@graphrefly/graphrefly 0.38.0 → 0.40.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/budget-gate-CmmVtasH.d.ts +115 -0
- package/dist/budget-gate-DiP_nK0n.d.cts +115 -0
- package/dist/{cascading-BsJ4GbnS.d.ts → cascading-BNfxffgc.d.ts} +2 -2
- package/dist/{cascading-B25wxpRa.d.cts → cascading-Cxs1eztH.d.cts} +2 -2
- package/dist/chunk-2BX4NB34.js +3 -0
- package/dist/{chunk-6VFC334U.js → chunk-2DMKW2AD.js} +1 -1
- package/dist/{chunk-4BDQXBXE.js → chunk-2QXRYP7Q.js} +1 -1
- package/dist/chunk-32N3JALT.js +1 -0
- package/dist/chunk-35JTVPOX.js +1 -0
- package/dist/chunk-3G5U5QNE.js +5 -0
- package/dist/{chunk-PHXZRR6C.js → chunk-4I45FVQS.js} +1 -1
- package/dist/{chunk-B5S7KTGP.js → chunk-6I726LZU.js} +1 -1
- package/dist/{chunk-NV63VQHI.js → chunk-6VWBPSSY.js} +1 -1
- package/dist/chunk-6XVD5TZV.js +1 -0
- package/dist/chunk-756D5TFD.js +1 -0
- package/dist/{chunk-DSOVKKTI.js → chunk-7Q4ZD3YW.js} +1 -1
- package/dist/{chunk-TMVY7OWG.js → chunk-B7LCDQEV.js} +1 -1
- package/dist/chunk-C72GO4IZ.js +1 -0
- package/dist/{chunk-RZ5HKPGI.js → chunk-CKFQS2CJ.js} +1 -1
- package/dist/chunk-D27JNOLZ.js +1 -0
- package/dist/chunk-ECQRP2UT.js +1 -0
- package/dist/{chunk-6773HURD.js → chunk-FHRBBHJN.js} +1 -1
- package/dist/{chunk-UVLZX2OU.js → chunk-I2DEVPMU.js} +1 -1
- package/dist/chunk-INQFTVZA.js +61 -0
- package/dist/{chunk-6KZZ6XQE.js → chunk-J63M5U46.js} +1 -1
- package/dist/{chunk-POCWFIJ7.js → chunk-JKBOIJ22.js} +1 -1
- package/dist/chunk-K2Z7UENB.js +1 -0
- package/dist/chunk-L6NSJVJZ.js +1 -0
- package/dist/{chunk-K5C67OGE.js → chunk-LCGAVGGV.js} +2 -2
- package/dist/chunk-LYM4PBMV.js +1 -0
- package/dist/{chunk-O2BLVQU4.js → chunk-MNZIKXK4.js} +1 -1
- package/dist/chunk-N43XM7BM.js +1 -0
- package/dist/{chunk-FWGIZP3W.js → chunk-OSZ22J7O.js} +1 -1
- package/dist/{chunk-FAYEMS5M.js → chunk-PPUYQ66A.js} +1 -1
- package/dist/{chunk-SP5O2MIX.js → chunk-QSK3RRII.js} +1 -1
- package/dist/chunk-RZJDIV2G.js +1 -0
- package/dist/chunk-SSCGRYJ2.js +1 -0
- package/dist/chunk-SVFKHUCW.js +1 -0
- package/dist/chunk-TSOYJ743.js +1 -0
- package/dist/{chunk-O245YLM5.js → chunk-UWA6D7UF.js} +1 -1
- package/dist/chunk-VMF23LGB.js +1 -0
- package/dist/chunk-WL6LFPJB.js +1 -0
- package/dist/chunk-WUT362QV.js +1 -0
- package/dist/chunk-XJLYLLIJ.js +1 -0
- package/dist/{chunk-IBGE62GZ.js → chunk-XW4YDF6G.js} +1 -1
- package/dist/chunk-YKD7WUYJ.js +43 -0
- package/dist/{chunk-7KZZLWZ6.js → chunk-YXDRGKXP.js} +1 -1
- package/dist/chunk-Z4F3DOWS.js +84 -0
- package/dist/compat/index.cjs +9 -13
- package/dist/compat/index.d.cts +16 -16
- package/dist/compat/index.d.ts +16 -16
- package/dist/compat/index.js +1 -1
- package/dist/compat/jotai/index.d.cts +2 -2
- package/dist/compat/jotai/index.d.ts +2 -2
- package/dist/compat/nanostores/index.d.cts +2 -2
- package/dist/compat/nanostores/index.d.ts +2 -2
- package/dist/compat/nestjs/index.cjs +7 -11
- package/dist/compat/nestjs/index.d.cts +8 -8
- package/dist/compat/nestjs/index.d.ts +8 -8
- package/dist/compat/nestjs/index.js +1 -1
- package/dist/compat/react/index.d.cts +2 -2
- package/dist/compat/react/index.d.ts +2 -2
- package/dist/compat/solid/index.d.cts +2 -2
- package/dist/compat/solid/index.d.ts +2 -2
- package/dist/compat/svelte/index.d.cts +2 -2
- package/dist/compat/svelte/index.d.ts +2 -2
- package/dist/compat/vue/index.d.cts +2 -2
- package/dist/compat/vue/index.d.ts +2 -2
- package/dist/compat/zustand/index.cjs +3 -7
- package/dist/compat/zustand/index.d.cts +4 -4
- package/dist/compat/zustand/index.d.ts +4 -4
- package/dist/compat/zustand/index.js +1 -1
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.d.cts +4 -4
- package/dist/core/index.d.ts +4 -4
- package/dist/core/index.js +1 -1
- package/dist/{composite-DTOlDuch.d.ts → decay-BnrlbxSv.d.ts} +39 -3
- package/dist/{composite-CgG0MqHm.d.cts → decay-C25AyNAj.d.cts} +39 -3
- package/dist/extra/browser.d.cts +1 -1
- package/dist/extra/browser.d.ts +1 -1
- package/dist/extra/index.cjs +16 -20
- package/dist/extra/index.d.cts +11 -9
- package/dist/extra/index.d.ts +11 -9
- package/dist/extra/index.js +1 -1
- package/dist/extra/node.cjs +2 -2
- package/dist/extra/node.d.cts +1 -1
- package/dist/extra/node.d.ts +1 -1
- package/dist/extra/node.js +1 -1
- package/dist/extra/operators.cjs +1 -1
- package/dist/extra/operators.d.cts +1 -1
- package/dist/extra/operators.d.ts +1 -1
- package/dist/extra/operators.js +1 -1
- package/dist/extra/reactive.cjs +1 -1
- package/dist/extra/reactive.d.cts +3 -3
- package/dist/extra/reactive.d.ts +3 -3
- package/dist/extra/reactive.js +1 -1
- package/dist/extra/render/index.cjs +5 -0
- package/dist/extra/render/index.d.cts +183 -0
- package/dist/extra/render/index.d.ts +183 -0
- package/dist/extra/render/index.js +1 -0
- package/dist/extra/sources.cjs +1 -1
- package/dist/extra/sources.d.cts +1 -1
- package/dist/extra/sources.d.ts +1 -1
- package/dist/extra/sources.js +1 -1
- package/dist/extra/storage-browser.d.cts +1 -1
- package/dist/extra/storage-browser.d.ts +1 -1
- package/dist/{fallback-axI2cXwt.d.cts → fallback-8JYU8tlT.d.cts} +1 -1
- package/dist/{fallback-DuEXfA4F.d.ts → fallback-CMZl39L5.d.ts} +1 -1
- package/dist/graph/index.cjs +7 -7
- package/dist/graph/index.d.cts +5 -5
- package/dist/graph/index.d.ts +5 -5
- package/dist/graph/index.js +1 -1
- package/dist/{graph-BjW1taJl.d.ts → graph-BkIkog4h.d.ts} +76 -100
- package/dist/{graph-CHsVwf9S.d.cts → graph-E6likq7w.d.cts} +76 -100
- package/dist/{index-CIcu6fIR.d.ts → index-2n8Eai6M.d.ts} +1 -1
- package/dist/{index-BwOsJfLJ.d.ts → index-3k4Gg6-n.d.ts} +3 -3
- package/dist/{index-BUFCHvOR.d.ts → index-40ZT4MHj.d.ts} +3 -3
- package/dist/index-8s-Qm-gz.d.ts +218 -0
- package/dist/index-A3U3CSve.d.cts +113 -0
- package/dist/{index-CDvC1m5p.d.ts → index-B2RUoIUz.d.ts} +1 -1
- package/dist/{index-Byp771zP.d.ts → index-B6iTqKtJ.d.ts} +2 -2
- package/dist/{index-D-B7U42V.d.cts → index-B72TQQHd.d.cts} +2 -2
- package/dist/{resilience-Bys63Cpd.d.ts → index-BAQrjuZF.d.ts} +202 -26
- package/dist/{index-BiomL7AW.d.ts → index-BJSZxSFX.d.ts} +1 -1
- package/dist/index-BQ1fR4li.d.ts +210 -0
- package/dist/{index-D7-RSD93.d.cts → index-BTHOTC0Q.d.cts} +4 -4
- package/dist/{index-CEVzBWeB.d.ts → index-BaA-xpSw.d.ts} +26 -19
- package/dist/{index-CAV-3RpJ.d.cts → index-Bd91Nmf4.d.cts} +4 -4
- package/dist/{index-BI1wMfyc.d.ts → index-BgjS2b8N.d.ts} +3 -3
- package/dist/{index-Bpr0Pwgl.d.cts → index-BiHUBEKq.d.cts} +3 -3
- package/dist/{index-UsU9ptzs.d.cts → index-BilOa6AE.d.cts} +55 -9
- package/dist/{index-DJVQ-t07.d.ts → index-BmSQLAZo.d.cts} +41 -48
- package/dist/{index-DTDVDzhA.d.ts → index-C-dkXOpB.d.cts} +56 -54
- package/dist/{index-B-ORMr3k.d.ts → index-C5cQ7Gfx.d.ts} +4 -4
- package/dist/{index-ML6vHKXK.d.ts → index-C6ZUaos7.d.ts} +1 -1
- package/dist/{index-Vz7KPfgz.d.ts → index-CAP3UGsq.d.ts} +1 -1
- package/dist/{index-BFaALJxR.d.ts → index-CD2dBMet.d.ts} +10 -8
- package/dist/index-CGhMJNHb.d.cts +128 -0
- package/dist/{index-B3D_z0Z6.d.cts → index-CL7oilfm.d.cts} +1 -1
- package/dist/{index-Bn0uZEL4.d.ts → index-CQtWm7jS.d.ts} +9 -9
- package/dist/{index-CM-i58FY.d.cts → index-CRm0YIzC.d.cts} +9 -9
- package/dist/index-CUIkE1l9.d.cts +230 -0
- package/dist/{index-CijfwEWx.d.ts → index-Cczxgd2D.d.ts} +2 -2
- package/dist/{index-CAbHN_rP.d.cts → index-CgnCFhr2.d.cts} +1 -1
- package/dist/{index-B2IUcH13.d.cts → index-Ck35nA-T.d.ts} +41 -48
- package/dist/{index-BpMZzX9P.d.cts → index-Cnr1WrlX.d.cts} +3 -3
- package/dist/{index-JYtN9uqM.d.ts → index-CoM4rzyB.d.ts} +1 -1
- package/dist/{index-Ckil6miL.d.cts → index-CtFNGe-m.d.cts} +2 -2
- package/dist/{index-BjWZARLy.d.ts → index-Ctb7_2sG.d.ts} +1 -1
- package/dist/index-CuPUehFa.d.cts +218 -0
- package/dist/index-D1Gc7wV5.d.ts +230 -0
- package/dist/{index-DqICM_I7.d.ts → index-D1IEZUsj.d.ts} +67 -9
- package/dist/{index-BFuVcqL8.d.cts → index-D3ayz3hy.d.cts} +1 -1
- package/dist/{index-CQsqqEVz.d.cts → index-D4uimgee.d.cts} +1 -1
- package/dist/{resilience-BWP2c7Af.d.cts → index-DGTo1yka.d.cts} +202 -26
- package/dist/{index-BmWuVdER.d.ts → index-DH4fm2Ck.d.ts} +2 -2
- package/dist/{index-BkQqf1EF.d.cts → index-DJ_MPOJ5.d.cts} +67 -9
- package/dist/{index-9xhIaM-w.d.cts → index-DOBLxOti.d.cts} +1 -1
- package/dist/{index-BqcgiSQg.d.cts → index-DQQCOIt8.d.cts} +10 -8
- package/dist/{index-DJNAWzcH.d.cts → index-DVAlsmEU.d.cts} +26 -19
- package/dist/index-DVDapw2k.d.cts +210 -0
- package/dist/{index-D_QQ_dTD.d.cts → index-DYTBbF8T.d.cts} +1 -1
- package/dist/{index-BgzPO43H.d.cts → index-DgJc8Zgc.d.cts} +6 -6
- package/dist/{index-Czk3r0yA.d.cts → index-DhLyOHYZ.d.ts} +56 -54
- package/dist/{index-CrlHFsiT.d.ts → index-DhnsQfa3.d.ts} +100 -118
- package/dist/{index-Bub6x_D4.d.cts → index-DktLSZOc.d.cts} +37 -90
- package/dist/{index-BaSy4L6w.d.cts → index-DpiGqtrs.d.cts} +100 -118
- package/dist/{index-D-HZ7sP4.d.ts → index-I1cCY3ZI.d.ts} +6 -6
- package/dist/{index-D9vBTuzo.d.ts → index-IUCY0OFN.d.ts} +4 -4
- package/dist/{index-DeSsvHDD.d.cts → index-MxYuWOrf.d.cts} +3 -3
- package/dist/index-N2MAxt7_.d.ts +128 -0
- package/dist/{index-CpZKtdMw.d.cts → index-PgwvGWa1.d.cts} +1 -1
- package/dist/{index-AUqWe_fX.d.ts → index-WSlcjhQF.d.ts} +55 -9
- package/dist/{index-Di7OdwlO.d.ts → index-bXXLSvor.d.ts} +37 -90
- package/dist/index-da2V5vPy.d.ts +113 -0
- package/dist/{index-DY2f2b9z.d.ts → index-eaQuGJnv.d.ts} +3 -3
- package/dist/{index-BsgxnHN8.d.cts → index-t6L2qpHh.d.cts} +3 -3
- package/dist/{index-C-3UXnHT.d.cts → index-tV3AA9hI.d.cts} +2 -2
- package/dist/{index-8OxXae3g.d.ts → index-yLt-aPMp.d.ts} +1 -1
- package/dist/{index-CqSJ25A9.d.cts → index-z8WFPVI8.d.cts} +1 -1
- package/dist/index.cjs +63 -59
- package/dist/index.d.cts +48 -47
- package/dist/index.d.ts +48 -47
- package/dist/index.js +1 -1
- package/dist/{meta-DreaEM_a.d.cts → meta-Ct9nqQS5.d.cts} +11 -7
- package/dist/{meta-BYqlATmg.d.ts → meta-D8OyedKp.d.ts} +11 -7
- package/dist/{node-fSc-hCv8.d.cts → node-BYInONRr.d.cts} +3 -3
- package/dist/{node-fSc-hCv8.d.ts → node-BYInONRr.d.ts} +3 -3
- package/dist/{observable-Cqty11jG.d.cts → observable-DMIlYJV1.d.cts} +1 -1
- package/dist/{observable-EAV_rNfM.d.ts → observable-DO8DDEzv.d.ts} +1 -1
- package/dist/patterns/ai/browser.cjs +5 -5
- package/dist/patterns/ai/browser.d.cts +4 -4
- package/dist/patterns/ai/browser.d.ts +4 -4
- package/dist/patterns/ai/browser.js +1 -1
- package/dist/patterns/ai/index.cjs +16 -20
- package/dist/patterns/ai/index.d.cts +17 -17
- package/dist/patterns/ai/index.d.ts +17 -17
- package/dist/patterns/ai/index.js +1 -1
- package/dist/patterns/ai/node.cjs +1 -1
- package/dist/patterns/ai/node.d.cts +4 -4
- package/dist/patterns/ai/node.d.ts +4 -4
- package/dist/patterns/ai/node.js +1 -1
- package/dist/patterns/audit/index.cjs +3 -7
- package/dist/patterns/audit/index.d.cts +6 -6
- package/dist/patterns/audit/index.d.ts +6 -6
- package/dist/patterns/audit/index.js +1 -1
- package/dist/patterns/cqrs/index.cjs +3 -7
- package/dist/patterns/cqrs/index.d.cts +6 -6
- package/dist/patterns/cqrs/index.d.ts +6 -6
- package/dist/patterns/cqrs/index.js +1 -1
- package/dist/patterns/demo-shell/index.cjs +5 -8
- package/dist/patterns/demo-shell/index.d.cts +5 -5
- package/dist/patterns/demo-shell/index.d.ts +5 -5
- package/dist/patterns/demo-shell/index.js +1 -1
- package/dist/patterns/domain-templates/index.cjs +3 -7
- package/dist/patterns/domain-templates/index.d.cts +4 -4
- package/dist/patterns/domain-templates/index.d.ts +4 -4
- package/dist/patterns/domain-templates/index.js +1 -1
- package/dist/patterns/graphspec/index.cjs +37 -37
- package/dist/patterns/graphspec/index.d.cts +5 -5
- package/dist/patterns/graphspec/index.d.ts +5 -5
- package/dist/patterns/graphspec/index.js +1 -1
- package/dist/patterns/guarded-execution/index.cjs +3 -7
- package/dist/patterns/guarded-execution/index.d.cts +7 -7
- package/dist/patterns/guarded-execution/index.d.ts +7 -7
- package/dist/patterns/guarded-execution/index.js +1 -1
- package/dist/patterns/harness/index.cjs +8 -12
- package/dist/patterns/harness/index.d.cts +12 -12
- package/dist/patterns/harness/index.d.ts +12 -12
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/job-queue/index.cjs +3 -7
- package/dist/patterns/job-queue/index.d.cts +6 -6
- package/dist/patterns/job-queue/index.d.ts +6 -6
- package/dist/patterns/job-queue/index.js +1 -1
- package/dist/patterns/lens/index.cjs +3 -7
- package/dist/patterns/lens/index.d.cts +5 -6
- package/dist/patterns/lens/index.d.ts +5 -6
- package/dist/patterns/lens/index.js +1 -1
- package/dist/patterns/memory/index.cjs +3 -7
- package/dist/patterns/memory/index.d.cts +6 -6
- package/dist/patterns/memory/index.d.ts +6 -6
- package/dist/patterns/memory/index.js +1 -1
- package/dist/patterns/messaging/index.cjs +3 -7
- package/dist/patterns/messaging/index.d.cts +5 -5
- package/dist/patterns/messaging/index.d.ts +5 -5
- package/dist/patterns/messaging/index.js +1 -1
- package/dist/patterns/orchestration/index.cjs +3 -7
- package/dist/patterns/orchestration/index.d.cts +8 -8
- package/dist/patterns/orchestration/index.d.ts +8 -8
- package/dist/patterns/orchestration/index.js +1 -1
- package/dist/patterns/process/index.cjs +1 -1
- package/dist/patterns/process/index.d.cts +7 -7
- package/dist/patterns/process/index.d.ts +7 -7
- package/dist/patterns/process/index.js +1 -1
- package/dist/patterns/reactive-layout/index.cjs +4 -8
- package/dist/patterns/reactive-layout/index.d.cts +5 -5
- package/dist/patterns/reactive-layout/index.d.ts +5 -5
- package/dist/patterns/reactive-layout/index.js +1 -1
- package/dist/patterns/reduction/index.cjs +3 -7
- package/dist/patterns/reduction/index.d.cts +4 -4
- package/dist/patterns/reduction/index.d.ts +4 -4
- package/dist/patterns/reduction/index.js +1 -1
- package/dist/patterns/refine-loop/index.cjs +5 -9
- package/dist/patterns/refine-loop/index.d.cts +6 -6
- package/dist/patterns/refine-loop/index.d.ts +6 -6
- package/dist/patterns/refine-loop/index.js +1 -1
- package/dist/patterns/resilient-pipeline/index.cjs +3 -1
- package/dist/patterns/resilient-pipeline/index.d.cts +6 -6
- package/dist/patterns/resilient-pipeline/index.d.ts +6 -6
- package/dist/patterns/resilient-pipeline/index.js +1 -1
- package/dist/patterns/surface/index.cjs +12 -16
- package/dist/patterns/surface/index.d.cts +6 -6
- package/dist/patterns/surface/index.d.ts +6 -6
- package/dist/patterns/surface/index.js +1 -1
- package/dist/{pipeline-graph-9JBbmRxA.d.ts → pipeline-graph-CB4La-UW.d.ts} +34 -17
- package/dist/{pipeline-graph-DuHpXSOn.d.cts → pipeline-graph-MWrQZXCq.d.cts} +34 -17
- package/dist/{reactive-layout-BMLDB4Vd.d.cts → reactive-layout-BtZfUKuL.d.cts} +2 -2
- package/dist/{reactive-layout-D-tRiNhg.d.ts → reactive-layout-KJj4E2dT.d.ts} +2 -2
- package/dist/{reactive-log-BgWSA1fg.d.ts → reactive-log-BlAsPLl2.d.ts} +2 -2
- package/dist/{reactive-log-C3IMAGpT.d.cts → reactive-log-_zeEnB9H.d.cts} +2 -2
- package/dist/{reactive-map-DmgeADH8.d.cts → reactive-map-6P_k3AQM.d.cts} +2 -2
- package/dist/{reactive-map-CHyeCf4D.d.ts → reactive-map-CjXByDV-.d.ts} +2 -2
- package/dist/resilience-S33JV6XC.js +1 -0
- package/dist/{sugar-D13E2M_z.d.ts → sugar-BhfjgetH.d.ts} +1 -1
- package/dist/{sugar-DgaGJcI6.d.cts → sugar-DzePN5-g.d.cts} +1 -1
- package/dist/{topology-tree-jrZue3ao.d.cts → topology-tree-3LBKFsUo.d.cts} +1 -1
- package/dist/{topology-tree-D47-nI6Z.d.ts → topology-tree-mF7Emqzm.d.ts} +1 -1
- package/dist/{types-BMSGPlpO.d.cts → types-1Dhoi7HM.d.cts} +1 -1
- package/dist/{types-CidcBDuk.d.ts → types-39jk0kaV.d.ts} +1 -1
- package/package.json +11 -1
- package/dist/chunk-2YFDSYEF.js +0 -1
- package/dist/chunk-5BGFS2XH.js +0 -1
- package/dist/chunk-CMTN3KPT.js +0 -80
- package/dist/chunk-DQJLC6YY.js +0 -1
- package/dist/chunk-G7JN6LCB.js +0 -1
- package/dist/chunk-KJEAIIIY.js +0 -43
- package/dist/chunk-LV3ACS5J.js +0 -1
- package/dist/chunk-NBGPXQSP.js +0 -1
- package/dist/chunk-NN3QPJ6U.js +0 -1
- package/dist/chunk-NSAZ6PR6.js +0 -1
- package/dist/chunk-O32GJOUJ.js +0 -1
- package/dist/chunk-QEVSIVSF.js +0 -1
- package/dist/chunk-QMC2PLNM.js +0 -7
- package/dist/chunk-QOJFR6GS.js +0 -1
- package/dist/chunk-SFK7MN7S.js +0 -1
- package/dist/chunk-TB7JKSVS.js +0 -61
- package/dist/chunk-UAXFKMAG.js +0 -1
- package/dist/chunk-XIMFHEKV.js +0 -1
- package/dist/chunk-XLMYQB6F.js +0 -1
- package/dist/chunk-XLYF4LBH.js +0 -1
- package/dist/imperative-audit-ahAE65a9.d.cts +0 -28
- package/dist/imperative-audit-ahAE65a9.d.ts +0 -28
- package/dist/index-5dNRlW7J.d.ts +0 -135
- package/dist/index-BWUMIt7J.d.cts +0 -135
- package/dist/index-BhzwpIJc.d.cts +0 -105
- package/dist/index-BsZk9T8y.d.ts +0 -105
- package/dist/index-C56XZiDe.d.cts +0 -163
- package/dist/index-CpdnP-0y.d.cts +0 -186
- package/dist/index-DKrIuF-r.d.ts +0 -163
- package/dist/index-DOU1Ee_k.d.ts +0 -186
- package/dist/resilience-LGBK236C.js +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,55 +1,55 @@
|
|
|
1
|
-
"use strict";var Yf=Object.create;var On=Object.defineProperty;var pu=Object.getOwnPropertyDescriptor;var Qf=Object.getOwnPropertyNames;var Xf=Object.prototype.hasOwnProperty;var fu=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),kr=t=>{throw TypeError(t)};var Zf=(t,e,n)=>e in t?On(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var uu=(t,e)=>On(t,"name",{value:e,configurable:!0});var Xe=(t,e)=>()=>(t&&(e=t(t=0)),e);var Se=(t,e)=>{for(var n in e)On(t,n,{get:e[n],enumerable:!0})},em=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qf(e))!Xf.call(t,o)&&o!==n&&On(t,o,{get:()=>e[o],enumerable:!(r=pu(e,o))||r.enumerable});return t};var tm=t=>em(On({},"__esModule",{value:!0}),t);var mu=t=>[,,,Yf(t?.[fu("metadata")]??null)],gu=["class","method","getter","setter","accessor","field","value","get","set"],wr=t=>t!==void 0&&typeof t!="function"?kr("Function expected"):t,nm=(t,e,n,r,o)=>({kind:gu[t],name:e,metadata:r,addInitializer:s=>n._?kr("Already initialized"):o.push(wr(s||null))}),rm=(t,e)=>Zf(e,fu("metadata"),t[3]),hu=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)e&1?s[o].call(n):r=s[o].call(n,r);return r},yu=(t,e,n,r,o,s)=>{var i,a,d,u,c,l=e&7,p=!!(e&8),f=!!(e&16),m=l>3?t.length+1:l?p?1:2:0,h=gu[l+5],g=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!f&&!p&&(o=o.prototype),l<5&&(l>3||!f)&&pu(l<4?o:{get[n](){return cu(this,s)},set[n](T){return lu(this,s,T)}},n));l?f&&l<4&&uu(s,(l>2?"set ":l>1?"get ":"")+n):uu(o,n);for(var v=r.length-1;v>=0;v--)u=nm(l,n,d={},t[3],y),l&&(u.static=p,u.private=f,c=u.access={has:f?T=>om(o,T):T=>n in T},l^3&&(c.get=f?T=>(l^1?cu:sm)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(c.set=f?(T,w)=>lu(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?f?s:b[h]:l>4?void 0:{get:b.get,set:b.set}:o,u),d._=1,l^4||a===void 0?wr(a)&&(l>4?g.unshift(a):l?f?s=a:b[h]=a:o=a):typeof a!="object"||a===null?kr("Object expected"):(wr(i=a.get)&&(b.get=i),wr(i=a.set)&&(b.set=i),wr(i=a.init)&&g.unshift(i));return l||rm(t,o),b&&On(o,n,b),f?l^4?s:b:o};var na=(t,e,n)=>e.has(t)||kr("Cannot "+n),om=(t,e)=>Object(e)!==e?kr('Cannot use the "in" operator on this value'):t.has(e),cu=(t,e,n)=>(na(t,e,"read from private field"),n?n.call(t):e.get(t));var lu=(t,e,n,r)=>(na(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),sm=(t,e,n)=>(na(t,e,"access private method"),n);var ft,M,oe,q,Qe,Ve,ze,le,P,I,Mt,An,Do,Cn,Go,Fo,Ln,xr,Rr,Sr,In,ae=Xe(()=>{"use strict";ft=Symbol.for("graphrefly/START"),M=Symbol.for("graphrefly/DATA"),oe=Symbol.for("graphrefly/DIRTY"),q=Symbol.for("graphrefly/RESOLVED"),Qe=Symbol.for("graphrefly/INVALIDATE"),Ve=Symbol.for("graphrefly/PAUSE"),ze=Symbol.for("graphrefly/RESUME"),le=Symbol.for("graphrefly/TEARDOWN"),P=Symbol.for("graphrefly/COMPLETE"),I=Symbol.for("graphrefly/ERROR"),Mt=Object.freeze([oe]),An=Object.freeze([q]),Do=Object.freeze([Qe]),Cn=Object.freeze([ft]),Go=Object.freeze([P]),Fo=Object.freeze([le]),Ln=Object.freeze([Mt]),xr=Object.freeze([An]),Rr=Object.freeze([Do]),Sr=Object.freeze([Go]),In=Object.freeze([Fo])});function ra(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function oa(t,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:n=>e.compressSync(t.encode(n)),decode:(n,r)=>t.decode(e.decompressSync(n))}}function Nr(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let o=2+n.length+2+e.length;if(o>4294967295)throw new Error(`encodeEnvelope: total envelope size ${o} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let s=new Uint8Array(o),i=0;return s[i++]=Pn,s[i++]=n.length,s.set(n,i),i+=n.length,s[i++]=r>>>8&255,s[i++]=r&255,s.set(e,i),s}function Er(t,e){if(t.length<bu)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${bu})`);let n=0,r=t[n++];if(r!==Pn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Pn})`);let o=t[n++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+o+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+o+2} bytes, have ${t.length})`);let s=new TextDecoder().decode(t.subarray(n,n+o));n+=o;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),d=e.lookupCodec(s);if(d==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function _r(t){t.registerCodec($o)}function sa(t){if(t.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=t[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let n=JSON.parse(JSON.stringify(e.snapshot)),r=e.seq;for(let o=1;o<t.length;o++){let s=t[o];if(s.seq<=r)throw new Error(`WAL chain broken at index ${o}: seq=${s.seq} must exceed prev seq=${r}`);if(s.mode==="full"){n=JSON.parse(JSON.stringify(s.snapshot)),r=s.seq;continue}let i=s.diff;for(let d of i.nodesRemoved)delete n.nodes[d];let a=i.nodesAddedFull;if(a!=null)for(let[d,u]of Object.entries(a))n.nodes[d]=JSON.parse(JSON.stringify(u));for(let d of i.nodesChanged){let u=n.nodes[d.path];u!=null&&(u[d.field]=d.to)}r=s.seq}return n}var $o,Pn,bu,jo=Xe(()=>{"use strict";$o={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}};Pn=1,bu=4});function Ot(t){if(t==null)return xt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var xt,Mr=Xe(()=>{"use strict";xt={type:"system",id:""}});function sn(){return Dn>0||Or}function vu(){return Dn>0}function Fn(t){Dn>0?Ar.push(t):t()}function Z(t){Dn+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Dn-=1,Dn===0)if(e){if(!Or){let n=Ar.splice(0);for(let r of n)try{r()}catch{}rn.length=0,on.length=0,Gn.length=0}}else im()}}function im(){let t=!Or;t&&(Or=!0);let e=[],n=0;try{for(;rn.length>0||on.length>0||Gn.length>0||t&&Ar.length>0;){if(t&&Ar.length>0){let s=Ar.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw rn.length=0,on.length=0,Gn.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(rn.length>0?rn:on.length>0?on:Gn).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(Or=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function At(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!sn()){t(e);return}(u>=5?Gn:u===4?on:rn).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let d=sn();if(o>0){let u=e.slice(0,o);t(u)}if(s>o){let u=e.slice(o,s);d?rn.push(()=>t(u)):t(u)}if(i>s){let u=e.slice(s,i);d?on.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?Gn.push(()=>t(u)):t(u)}}var Dn,Or,rn,on,Gn,Ar,Ae=Xe(()=>{"use strict";Dn=0,Or=!1,rn=[],on=[],Gn=[],Ar=[]});function V(){return Math.trunc(performance.now()*1e6)}function se(){return Date.now()*1e6}var Re=Xe(()=>{"use strict"});function Cr(t){t.registerMessageType(ft,{tier:0,wireCrossing:!1}),t.registerMessageType(oe,{tier:1,wireCrossing:!1}),t.registerMessageType(Qe,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Ve,{tier:2,wireCrossing:!1}),t.registerMessageType(ze,{tier:2,wireCrossing:!1}),t.registerMessageType(M,{tier:3,wireCrossing:!0}),t.registerMessageType(q,{tier:3,wireCrossing:!0}),t.registerMessageType(P,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(I,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(le,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var an,ia=Xe(()=>{"use strict";ae();an=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Tu(t){return Array.isArray(t)?[...t]:[t]}function am(t,e){return t.has(e)||t.has("*")}function Ct(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(Tu(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(Tu(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let d of e)am(d.actions,s)&&d.where(o)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function Lr(t){return Ct((e,n)=>{for(let r of t){let o=r.actorType==null?null:new Set(Array.isArray(r.actorType)?r.actorType:[r.actorType]),s=r.actorId==null?null:new Set(Array.isArray(r.actorId)?r.actorId:[r.actorId]),i=Object.entries(r.claims??{}),a=d=>{if(o!==null&&!o.has(String(d.type))||s!==null&&!s.has(String(d.id??"")))return!1;for(let[u,c]of i)if(d[u]!==c)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function Ir(t){let e=dm.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var dt,dm,Vt=Xe(()=>{"use strict";dt=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};dm=["human","llm","wallet","system"]});function aa(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(aa);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=aa(t[n]);return e}return null}function lm(t){let e=cm.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,c=2773480762,l=1359893119,p=2600822924,f=528734635,m=1541459225,h=new Uint32Array(64),g=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let _=0;_<16;_++)h[_]=i.getUint32(b+_*4,!1);for(let _=16;_<64;_++){let O=h[_-15],N=h[_-2],L=g(O,7)^g(O,18)^O>>>3,j=g(N,17)^g(N,19)^N>>>10;h[_]=h[_-16]+L+h[_-7]+j>>>0}let v=a,T=d,w=u,x=c,k=l,S=p,R=f,E=m;for(let _=0;_<64;_++){let O=g(k,6)^g(k,11)^g(k,25),N=k&S^~k&R,L=E+O+N+um[_]+h[_]>>>0,j=g(v,2)^g(v,13)^g(v,22),$=v&T^v&w^T&w,D=j+$>>>0;E=R,R=S,S=k,k=x+L>>>0,x=w,w=T,T=v,v=L+D>>>0}a=a+v>>>0,d=d+T>>>0,u=u+w>>>0,c=c+x>>>0,l=l+k>>>0,p=p+S>>>0,f=f+R>>>0,m=m+E>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(d)+y(u)+y(c)+y(l)+y(p)+y(f)+y(m)}function Kt(t){let e=aa(t??null),n=JSON.stringify(e);return lm(n).slice(0,16)}function pm(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function $n(t,e,n){let r=n?.id??pm();if(t===0)return{id:r,version:0};let s=(n?.hash??Kt)(e);return{id:r,version:0,cid:s,prev:null}}function Pr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function da(t){return"cid"in t}var um,cm,Bo=Xe(()=>{"use strict";um=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),cm=new TextEncoder});function xu(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function ua(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Vo(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function la(t){if(Fe._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");t(Fe)}function U(t,e,n){let r=Ru(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return Ru(t)?s=(ca(e)?e:n)??{}:ca(t)?s=t:s=(ca(e)?e:n)??{},new Oe(r,o,s)}var wu,ku,fm,mm,Fe,Oe,Ru,ca,Me=Xe(()=>{"use strict";jo();Mr();Ae();Re();ia();Vt();ae();Bo();wu=()=>{},ku=100;fm=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},mm=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[Cn]:[Cn,[M,s]];o._status==="dirty"&&i.push(Mt),At(e,i,o._config.tierOf)},Fe=new an({onMessage:fm,onSubscribe:mm});Cr(Fe);_r(Fe);Oe=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??Fe,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Kt;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?$n(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(xu);let s={};for(let[a,d]of Object.entries(r.meta??{})){let u={initial:d,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),s[a]=new t([],void 0,u)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[M,a]])},down(a){i._emit(Vo(a))},up(a){i._emitUp(Vo(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,d=i?.version??0,u=$n(e,s,{id:a,hash:o});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=Ot(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=Ot(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new dt({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new dt({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:se()}}down(e,n){let r=Vo(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[M,e]])}up(e,n){if(this._deps.length===0)return;let r=Vo(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let d=Ot(n);if(!this._guard(d,"observe"))throw new dt({actor:d,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)ua(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[n]=this._sinks;this._sinks=n}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,n=0;try{for(let r=0;r<e;r++){let o=r,s=this._deps[r];s.unsub=wu,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,d=!1;for(let u of i)a(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:o},this._actions);d&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}ua(s)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let n=this._deps.length,r=xu(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Ln),r.unsub=wu;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,i=!1;for(let a of o)s(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(o){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[I,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(o){this._emit([[I,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let r of this._deps){if(r.unsub!=null){let o=r.unsub;r.unsub=null;try{o()}catch{}}ua(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(s)}if(o!==ft){if(o===oe){this._depDirtied(r);return}if(o===Qe){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Rr);return}if(o===Ve||o===ze){this._emit([n]);return}if(o===le){this._emit(In);return}if(o===M)this._depSettledAsData(r,n[1]);else if(o===q)this._depSettledAsResolved(r);else if(o===P)this._depSettledAsTerminal(r,!0);else if(o===I)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===M||o===q)&&this._emit([n]),(o===P||o===I)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Ln))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(xr),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[I,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Sr)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[I,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[I,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let o=this._deps.map(i=>i.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,s);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[I,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>ku?(this._rerunDepth=0,this._emit([[I,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${ku} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[Mt,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let d of e){let u=n(d[0]);u<i&&(r=!1),u===3&&(o=!0),d[0]===oe&&(s=!0),i=u}let a=e;if(!r){let d=e.map((u,c)=>({m:u,i:c,tier:n(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),a=d.map(u=>u.m)}if(o&&!s&&this._status!=="dirty"){let d=0;for(;d<a.length&&n(a[d][0])===0;)d++;return d===0?[Mt,...a]:[...a.slice(0,d),Mt,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===I&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===le||d[0]===Qe);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let d=n[a],u=d[0];if(u!==Ve&&u!==ze){o?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===Ve?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let l=d[1];if(u===Ve)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))c=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?o?.push(d):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===le))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(In)}catch{}let{finalMessages:s,equalsError:i}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of s)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[I,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let c of e)n(c[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===M){d=c;break}}for(let c=0;c<e.length;c++){let l=e[c],p=l[0];if(p===M){if(l.length>=2){let f=!1;if(a&&this._cached!==void 0)try{f=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=c;break}if(f){r==null&&(r=e.slice(0,c)),r.push(An),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(d<0||c===d)&&Pr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===oe)this._status="dirty";else if(p===q)this._status="resolved";else if(p===P){this._status="completed";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===I){this._status="errored";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===Qe){if(this._cached!==void 0){let m=this._config.rigorRecorder;if(m!=null)try{m.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let m=f.invalidate;if(typeof m=="function")try{m()}catch{}}}else p===le&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:u,equalsError:o}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(vu()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Fn(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}At(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);At(this._deliverToSinks,n,this._config.tierOf)}},Ru=t=>Array.isArray(t),ca=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function A(t,e){return U([],{...e,initial:t})}function z(t,e){return U((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function C(t,e,n){return U(t,(o,s,i)=>{let a=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);s.emit(e(a,i))},{describeKind:"derived",...n})}function ge(t,e,n){return U(t,(o,s,i)=>{let a=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}function Dr(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),C(t,(o,s)=>e(a=>{let d=r.get(a);if(d==null)throw new Error(`dynamicNode: untracked dep "${a.name??"<unnamed>"}"`);return o[d]},s),n)}function dn(t,e){let n,r=new Map,o=(s,i,a)=>{let d=!1,u=c=>{let l=r.get(c);if(l!==void 0){if(l<s.length){let f=s[l];return f!=null&&f.length>0?f.at(-1):a.prevData[l]}return c.cache}d=!0;let p=n._addDep(c);return r.set(c,p),c.cache};try{let c=t(u,a);d||(i.emit(c),a.store.__autoTrackLastDiscoveryError!=null&&delete a.store.__autoTrackLastDiscoveryError)}catch(c){if(!d)throw c;a.store.__autoTrackLastDiscoveryError=c}};return n=new Oe([],o,{describeKind:"derived",...e}),n}function pa(t,...e){let n=t;for(let r of e)n=r(n);return n}var ne=Xe(()=>{"use strict";Me()});function $r(t,e,n){let r=new Set;for(let o of t.split(",")){let[s,i]=o.split("/"),a=i?Number.parseInt(i,10):1;if(Number.isNaN(a)||a<1)throw new Error(`Invalid cron step: ${o}`);let d,u;if(s==="*")d=e,u=n;else if(s.includes("-")){let[c,l]=s.split("-");d=Number.parseInt(c,10),u=Number.parseInt(l,10)}else d=Number.parseInt(s,10),u=d;if(Number.isNaN(d)||Number.isNaN(u))throw new Error(`Invalid cron field: ${t}`);if(d<e||u>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(d>u)throw new Error(`Invalid cron range: ${d}-${u} in ${t}`);for(let c=d;c<=u;c+=a)r.add(c)}return r}function Jo(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:$r(e[0],0,59),hours:$r(e[1],0,23),daysOfMonth:$r(e[2],1,31),months:$r(e[3],1,12),daysOfWeek:$r(e[4],0,6)}}function Yo(t,e){return t.minutes.has(e.getMinutes())&&t.hours.has(e.getHours())&&t.daysOfMonth.has(e.getDate())&&t.months.has(e.getMonth()+1)&&t.daysOfWeek.has(e.getDay())}var ga=Xe(()=>{"use strict"});function Lt(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta"]);default:return new Set(["type","deps"])}}function xm(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function st(t){let e=new WeakSet,n={};for(let[r,o]of ju(t))n[r]=ha(o,e);return n}function ha(t,e){if(t==null)return t;let n=typeof t;if(n==="boolean"||n==="number"||n==="string")return t;if(n==="function")return"<function>";if(Array.isArray(t))return e.has(t)?"<cycle>":(e.add(t),t.map(r=>ha(r,e)));if(n==="object"){let r=t;if(e.has(r))return"<cycle>";e.add(r);try{if(typeof r.subscribe=="function"&&"cache"in r)return"<Node>"}catch{return"<unserializable>"}let o={};for(let[s,i]of ju(r))o[s]=ha(i,e);return o}return"<unserializable>"}function ju(t){let e=[],n;try{n=Object.keys(t)}catch{return e}for(let r of n)try{e.push([r,t[r]])}catch{e.push([r,"<unserializable>"])}return e}function we(t,e){let n={factory:t};return e!==void 0&&(n.factoryArgs=e),n}function Rm(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function jr(t,e){let n=e==null,r=!n&&e!=null?[...e].filter(u=>u.startsWith("meta.")).map(u=>u.slice(5)):null,o=n||e.has("meta")||r!=null&&r.length>0,s="state",i=[];t instanceof Oe&&(s=xm(t),i=t._deps.map(u=>u.node.name??""));let a={type:s,deps:i};(n||e.has("status"))&&(a.status=t.status);let d=t instanceof Oe?t._guard:void 0;if(o){let u={...Rm(t)};if(d!=null&&u.access===void 0&&(u.access=Ir(d)),r!=null&&r.length>0&&!e.has("meta")){let c={};for(let l of r)l in u&&(c[l]=u[l]);a.meta=c}else a.meta=u}if(t.name!=null&&(a.name=t.name),n||e.has("value")){t.status==="sentinel"&&(a.sentinel=!0);try{a.value=t.cache}catch{}}if((n||e.has("v"))&&t.v!=null){let u={id:t.v.id,version:t.v.version};"cid"in t.v&&(u.cid=t.v.cid,u.prev=t.v.prev),a.v=u}return(n||e.has("guard"))&&d!=null&&(a.guard=Ir(d)),(n||e.has("lastMutation"))&&t.lastMutation!=null&&(a.lastMutation=t.lastMutation),a}var it=Xe(()=>{"use strict";Vt();Me()});var Bu={};Se(Bu,{NS_PER_MS:()=>He,NS_PER_SEC:()=>lt,constant:()=>Qo,decorrelatedJitter:()=>ts,exponential:()=>Zo,fibonacci:()=>es,linear:()=>Xo,resolveBackoffPreset:()=>qt,withMaxAttempts:()=>ya});function cn(t){return t<0?0:t}function Sm(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Nm(t,e){return t+Math.random()*(e-t)}function Qo(t){let e=cn(t);return()=>e}function Xo(t,e){let n=cn(t),r=e===void 0?n:cn(e);return o=>n+r*Math.max(0,o)}function Zo(t){let e=cn(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=cn(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,d=1;for(let u=0;u<Math.max(0,s);u++){if(d>=a){d=a;break}d*=n}i=e*d,i>r&&(i=r)}return Sm(i,o)}}function es(t=100*1e6,e=30*1e9){let n=cn(t),r=cn(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let d=1;d<s;d++){let u=i+a;i=a,a=u}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function ts(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return Nm(t,i)}}function ya(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function qt(t){if(t==="constant")return Qo(1*1e9);if(t==="linear")return Xo(1*1e9);if(t==="exponential")return Zo();if(t==="fibonacci")return es();if(t==="decorrelatedJitter")return ts();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var He,lt,Wn=Xe(()=>{"use strict";He=1e6,lt=1e9});var Ie,Rt=Xe(()=>{"use strict";Ie=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var qu={};Se(qu,{CircuitOpenError:()=>yt,RateLimiterOverflowError:()=>ln,TimeoutError:()=>pn,circuitBreaker:()=>Nt,fallback:()=>Yn,rateLimiter:()=>Jn,retry:()=>St,timeout:()=>Qn,tokenBucket:()=>zt,withBreaker:()=>Un,withStatus:()=>Ht});function fn(t){return{describeKind:"derived",...t}}function Em(t){return t<0?0:t}function ns(t){return t[1]}function Vu(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function St(t,e){return typeof t=="function"?Mm(t,e):_m(t,e)}function Ku(t){let e={};return t?.count!==void 0&&(e.count=t.count),typeof t?.backoff=="string"&&(e.backoff=t.backoff),Object.keys(e).length>0?e:void 0}function _m(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?qt(r):r;return z(i=>{let a=0,d=!1,u=null,c,l=new Ie;function p(){c?.(),c=void 0}function f(h){if(d)return;if(a>=o){p(),i.down([[I,h]]);return}let g=s===null?0:s(a,h,u);if(g==null){p(),i.down([[I,h]]);return}let y;try{y=Vu(g)}catch{p(),i.down([[I,h]]);return}u=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{d||m()})}function m(){l.cancel(),p(),c=t.subscribe(h=>{if(!d)for(let g of h){let y=g[0];if(y===oe)i.down([[oe]]);else if(y===M)a=0,u=null,i.emit(g[1]);else if(y===q)i.down([[q]]);else if(y===P)p(),i.down([[P]]);else if(y===I){f(ns(g));return}else i.down([g])}})}return m(),()=>{d=!0,l.cancel(),p()}},{...fn(),initial:t.cache,meta:{...we("retry",Ku(e))}})}function Mm(t,e){let n=e?.count,r=e?.backoff,o=n!==void 0?n:r===void 0?0:2147483647;if(o<0)throw new RangeError("retry count must be >= 0");let s=r===void 0?null:typeof r=="string"?qt(r):r;return z(i=>{let a=0,d=!1,u=null,c,l=new Ie;function p(){c?.(),c=void 0}function f(h){if(d)return;if(a>=o){p(),i.down([[I,h]]);return}let g=s===null?0:s(a,h,u);if(g==null){p(),i.down([[I,h]]);return}let y;try{y=Vu(g)}catch{p(),i.down([[I,h]]);return}u=y,a+=1,p();let b=y>0?y/1e6:1;l.start(b,()=>{d||m()})}function m(){l.cancel(),p();let h;try{h=t()}catch(g){f(g);return}c=h.subscribe(g=>{if(!d)for(let y of g){let b=y[0];if(b===oe)i.down([[oe]]);else if(b===M)a=0,u=null,i.emit(y[1]);else if(b===q)i.down([[q]]);else if(b===P)p(),i.down([[P]]);else if(b===I){f(ns(y));return}else i.down([y])}})}return m(),()=>{d=!0,l.cancel(),p()}},{...fn(),initial:e?.initial,meta:{...we("retry",Ku(e))}})}function Nt(t){let e=Math.max(1,t?.failureThreshold??5),n=Em(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??V,i="closed",a=0,d=0,u=0,c=n,l=0;function p(){if(!r)return n;let h=r(d);return h!==null?h:n}function f(){i="open",c=p(),u=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-u>=c?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,d=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){d++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,d=0,l=0}}}function Un(t,e){let n=e?.onOpen??"skip";return r=>{let o=U([],(s,i)=>{function a(){o.meta.breakerState.down([[M,t.state]])}let d=r.subscribe(u=>{for(let c of u){let l=c[0];l===oe?i.down([[oe]]):l===M?t.canExecute()?(a(),i.emit(c[1])):(a(),n==="error"?i.down([[I,new yt]]):i.down([[q]])):l===q?i.down([[q]]):l===P?(t.recordSuccess(),a(),i.down([[P]])):l===I?(t.recordFailure(ns(c)),a(),i.down([c])):i.down([c])}});return a(),d},{...fn(),meta:{breakerState:t.state,...we("withBreaker",{onOpen:n})},completeWhenDepsComplete:!1,initial:r.cache});return{node:o,breakerState:o.meta.breakerState}}}function zt(t,e){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let n=t,r=V();function o(s){if(e>0){let i=s-r;n=Math.min(t,n+i/1e9*e)}r=s}return{available(){return o(V()),n},tryConsume(s=1){if(s<=0)return!0;let i=V();return o(i),n>=s?(n-=s,!0):!1},putBack(s=1){s<=0||(o(V()),n=Math.min(t,n+s))}}}function Jn(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let o=e.maxBuffer;if(o!==void 0&&o<1)throw new RangeError("maxBuffer must be >= 1");let s=e.onOverflow??"drop-newest",i=n*1e9/r;return z(a=>{let d=zt(n,i),u=[],c=new Ie,l=!1,p=1e9/i;function f(){for(;u.length>0;)if(d.tryConsume(1))a.emit(u.shift());else{c.start(Math.max(1,p/1e6),f);return}}let m=t.subscribe(h=>{for(let g of h){if(l)return;let y=g[0];if(y===oe)a.down([[oe]]);else if(y===M){if(o!==void 0&&u.length>=o){if(s!=="drop-newest")if(s==="drop-oldest")u.shift(),u.push(g[1]);else{l=!0,c.cancel(),u.length=0,a.down([[I,new ln(o)]]);return}}else u.push(g[1]);f()}else if(y===q)a.down([[q]]);else if(y===P)l=!0,c.cancel(),u.length=0,a.down([[P]]);else if(y===I)l=!0,c.cancel(),u.length=0,a.down([g]);else if(y===le){l=!0,c.cancel(),u.length=0,a.down([g]);return}else a.down([g])}});return()=>{l=!0,c.cancel(),m()}},{...fn(),initial:t.cache,meta:{...we("rateLimiter",e)}})}function Ht(t,e){let n=e?.initialStatus??"pending",r=U([],(o,s)=>{let i=n;return r.meta.status.down([[M,n]]),r.meta.error.down([[M,null]]),t.subscribe(d=>{for(let u of d){let c=u[0];if(c===oe)s.down([[oe]]);else if(c===M)i==="errored"?Z(()=>{r.meta.error.down([[M,null]]),r.meta.status.down([[M,"active"]])}):r.meta.status.down([[M,"active"]]),i="active",s.emit(u[1]);else if(c===q)s.down([[q]]);else if(c===P)r.meta.status.down([[M,"completed"]]),i="completed",s.down([[P]]);else if(c===I){let l=ns(u);Z(()=>{r.meta.error.down([[M,l]]),r.meta.status.down([[M,"errored"]])}),i="errored",s.down([u])}else s.down([u])}})},{...fn(),meta:{status:n,error:null,...we("withStatus",{initialStatus:n})},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:r,status:r.meta.status,error:r.meta.error}}function Om(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Am(t){return t!=null&&typeof t.then=="function"}function Cm(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function Yn(t,e){return z(n=>{let r,o;function s(){o?.(),o=void 0,Om(e)||Am(e)||Cm(e)?r=Y(e).subscribe(a=>{n.down(a)}):(n.emit(e),n.down([[P]]))}return o=t.subscribe(i=>{for(let a of i){let d=a[0];if(d===oe)n.down([[oe]]);else if(d===M)n.emit(a[1]);else if(d===q)n.down([[q]]);else if(d===P)n.down([[P]]);else if(d===I){s();return}else if(d===le){r?.(),n.down([a]);return}else n.down([a])}}),()=>{o?.(),r?.()}},{...fn(),initial:t.cache,meta:{...we("fallback")}})}function Qn(t,e){if(e<=0)throw new RangeError("timeoutNs must be > 0");return z(n=>{let r=!1,o=new Ie;function s(){let a=e/1e6;o.start(a,()=>{r||(r=!0,i(),n.down([[I,new pn(e)]]))})}let i=t.subscribe(a=>{for(let d of a){if(r)return;let u=d[0];if(u===oe)n.down([[oe]]);else if(u===M)s(),n.emit(d[1]);else if(u===q)n.down([[q]]);else if(u===P){o.cancel(),r=!0,n.down([[P]]);return}else if(u===I){o.cancel(),r=!0,n.down([d]);return}else if(u===le){o.cancel(),r=!0,n.down([d]);return}else n.down([d])}});return s(),()=>{r=!0,o.cancel(),i()}},{...fn(),initial:t.cache,meta:{...we("timeout",{timeoutNs:e})}})}var yt,ln,pn,It=Xe(()=>{"use strict";Ae();Re();ae();it();Me();ne();Wn();ve();Rt();yt=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};ln=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};pn=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});function pt(t){return{describeKind:"producer",...t}}function va(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function Hu(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){t[n+1]==="*"?(e+=".*",n+=1):e+="[^/]*";continue}e+=va(r)}return e+="$",new RegExp(e)}function Wu(t,e){for(let n of e)if(n.test(t))return!0;return!1}function Lm(t,e){let n=U([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[q]]);return}for(let a of i)s.emit(a)},{describeKind:"derived",initial:t.cache}),r=n.subscribe.bind(n);return n.subscribe=(o,s)=>(e(o),r(o,s)),n}function Ze(t,e){let{signal:n,period:r,...o}=e??{};return z(s=>{let i=!1,a=0,d,u,c=()=>{i=!0,d!==void 0&&clearTimeout(d),u!==void 0&&clearInterval(u),n?.removeEventListener("abort",p)},l=()=>{i||(r!=null?(s.emit(a++),u=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",p),s.emit(a++),s.down([[P]])))},p=()=>{i||(c(),s.down([[I,n.reason]]))};if(n?.aborted){p();return}return d=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),c},pt(o))}function Uu(t){let{signal:e,...n}=t??{};return z(r=>{let o=!1,s,i,a=!1,d=!1,u=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,c=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,p=()=>{s!==void 0&&c&&c(s),i!==void 0&&clearTimeout(i),s=void 0,i=void 0},f=()=>{o=!0,p(),a&&(e?.removeEventListener("abort",m),a=!1),d&&l&&(l.removeEventListener("visibilitychange",y),d=!1)},m=()=>{o||(f(),r.down([[I,e.reason]]))},h=b=>{o||(r.emit(b),g())},g=()=>{o||(u&&(!l||l.visibilityState!=="hidden")?s=u(h):i=setTimeout(()=>h(performance.now()),16))},y=()=>{o||(p(),g())};return e?.aborted?(m(),f):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&u&&(l.addEventListener("visibilitychange",y),d=!0),g(),f)},pt(n))}function os(t,e){let n=Jo(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return z(d=>{let u=-1,c=()=>{let p=new Date,f=p.getFullYear()*1e8+(p.getMonth()+1)*1e6+p.getDate()*1e4+p.getHours()*100+p.getMinutes();f!==u&&Yo(n,p)&&(u=f,d.emit(a?p:se()))};c();let l=setInterval(c,i);return()=>clearInterval(l)},{...pt(s),name:s.name??`cron:${t}`})}function Ju(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return z(a=>{let d=c=>{a.emit(c)},u={capture:r,passive:o,once:s};return t.addEventListener(e,d,u),()=>t.removeEventListener(e,d,u)},pt(i))}function ss(t,e){return z(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[P]])}catch(o){r||n.down([[I,o]])}return()=>{r=!0}},pt(e))}function Im(t){return t!=null&&typeof t.then=="function"}function Xn(t,e){let{signal:n,...r}=e??{};return z(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[I,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{s||(s=!0,n?.removeEventListener("abort",i),o.emit(a),o.down([[P]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[I,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},pt(r))}function Br(t,e){let{signal:n,...r}=e??{};return z(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,d=!1,u=t[Symbol.asyncIterator](),c=()=>{d||a.aborted||Promise.resolve(u.next()).then(l=>{if(!(d||a.aborted)){if(l.done){o.down([[P]]);return}o.emit(l.value),c()}},l=>{!d&&!a.aborted&&o.down([[I,l]])})};return c(),()=>{d=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},pt(r))}function Pm(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Y(t,e){if(Pm(t))return t;if(Im(t))return Xn(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Br(t,e);if(typeof n[Symbol.iterator]=="function")return ss(t,e)}return Ta(t)}function Ta(...t){return ss(t,void 0)}function Yu(t){return z(e=>{e.down([[P]])},pt(t))}function Qu(t){return z(()=>{},pt(t))}function Xu(t,e){return z(n=>{n.down([[I,t]])},pt(e))}function Zu(t,e){let{signal:n,...r}=e??{},o=pt(r),s=o.resubscribable===void 0?{...o,resubscribable:!0}:o;return z(i=>{let a,d=!1;try{let u=t();a=Y(u,e).subscribe(l=>{if(!d)for(let p of l){let f=p[0];if(f!==ft)if(f===M)i.emit(p[1]);else if(f===P){d=!0,i.down([[P]]);break}else if(f===I){d=!0,i.down([[I,p[1]]]);break}else i.down([p])}})}catch(u){let c=u===void 0?new Error("defer: thunk threw undefined"):u;i.down([[I,c]])}return()=>{d=!0,a?.()}},s)}function Wt(t,e,n){return U([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function ec(t,e){return U([t],(n,r,o)=>{o.store.buf||(o.store.buf=[]);let s=o.store.buf,i=n[0];if(i!=null&&i.length>0)for(let a of i)s.push(a);if(o.terminalDeps[0]===!0){r.emit([...s]),r.down([[P]]);return}(i==null||i.length===0)&&r.down([[q]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function tc(t,e){return z(n=>t.subscribe(r=>{n.down(r)}),{...pt(e),initial:t.cache})}function is(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=z(s=>t.subscribe(i=>{for(let a of i)a[0]===M&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...pt(n),initial:t.cache});return Lm(o,s=>{for(let i of r)s([[M,i]])})}function nc(t,e){return is(t,1,e)}function et(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===M){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===I){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===P){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function rs(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,d=n?.skipCurrent===!0;a=t.subscribe(u=>{for(let c of u){if(s)return;if(!(d&&c[0]===M)){if(c[0]===M){let l=c[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(c[0]===I){s=!0,o(c[1]),a?(a(),a=void 0):i=!0;return}if(c[0]===P){s=!0,o(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),d=!1,i&&(a?.(),a=void 0)})}async function as(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await rs(t,n,{skipCurrent:r});if(ba===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(It(),qu)),Promise.resolve().then(()=>(Wn(),Bu))]);ba=s.timeout,zu=i.NS_PER_MS}let o=ba(t,e.timeoutMs*zu);return await rs(o,n,{skipCurrent:r})}function ds(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),o,s=!1,i=()=>{o?(o(),o=void 0):s=!0};return o=t.subscribe(a=>{if(!n.signal.aborted)for(let d of a){if(d[0]===M&&d[1]===!0){n.abort(r),i();return}if(d[0]===I){n.abort(d[1]),i();return}if(d[0]===P){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function te(t){return t.subscribe(()=>{})}function wa(t){let e=A(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[oe],[M,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var ba,zu,rc,ve=Xe(()=>{"use strict";Re();ae();Me();ne();ga();rc=is});var pv={};Se(pv,{COMPLETE:()=>P,COMPLETE_MSG:()=>Go,COMPLETE_ONLY_BATCH:()=>Sr,CircuitOpenError:()=>yt,ContentAddressedMissError:()=>ao,DATA:()=>M,DEFAULT_ACTOR:()=>xt,DIRTY:()=>oe,DIRTY_MSG:()=>Mt,DIRTY_ONLY_BATCH:()=>Ln,ENVELOPE_VERSION:()=>Pn,ERROR:()=>I,GRAPH_META_SEGMENT:()=>tt,Graph:()=>Q,GraphReFlyConfig:()=>an,GuardDenied:()=>dt,INVALIDATE:()=>Qe,INVALIDATE_MSG:()=>Do,INVALIDATE_ONLY_BATCH:()=>Rr,JsonCodec:()=>$o,NS_PER_MS:()=>He,NS_PER_SEC:()=>lt,NativeIndexBackend:()=>lo,NativeListBackend:()=>po,NativeLogBackend:()=>Hr,NativeMapBackend:()=>so,NativePubSubBackend:()=>co,NodeImpl:()=>Oe,PAUSE:()=>Ve,RESOLVED:()=>q,RESOLVED_MSG:()=>An,RESOLVED_ONLY_BATCH:()=>xr,RESUME:()=>ze,RateLimiterOverflowError:()=>ln,ResettableTimer:()=>Ie,SIZEOF_OVERHEAD:()=>$e,SIZEOF_SYMBOL:()=>hs,SNAPSHOT_VERSION:()=>bt,SNAPSHOT_WIRE_VERSION:()=>Io,START:()=>ft,START_MSG:()=>Cn,SurfaceError:()=>_e,TEARDOWN:()=>le,TEARDOWN_MSG:()=>Fo,TEARDOWN_ONLY_BATCH:()=>In,TimeoutError:()=>pn,accessHintForGuard:()=>Ir,accountability:()=>Si,advanceVersion:()=>Pr,ai:()=>ki,appendLogStorage:()=>ed,asSurfaceError:()=>Hi,audit:()=>al,autoTrackNode:()=>dn,awaitSettled:()=>as,batch:()=>Z,buffer:()=>dl,bufferCount:()=>ul,bufferTime:()=>ll,cached:()=>nc,canonicalJson:()=>uo,cascadingCache:()=>vp,catchError:()=>wl,checkpointToRedis:()=>lp,checkpointToS3:()=>cp,circuitBreaker:()=>Nt,combine:()=>Ka,combineLatest:()=>bl,compat:()=>Ba,concat:()=>el,concatMap:()=>rl,configure:()=>la,constant:()=>Qo,contentAddressedStorage:()=>Vs,core:()=>Ma,cqrs:()=>Es,createDagCborCodec:()=>ra,createDagCborZstdCodec:()=>oa,createGraph:()=>vr,createTransport:()=>Zt,createVersioning:()=>$n,createWatermarkController:()=>Zn,csvRows:()=>Hl,debounce:()=>za,debounceTime:()=>vl,decodeEnvelope:()=>Er,decorrelatedJitter:()=>ts,defaultConfig:()=>Fe,defaultHash:()=>Kt,defer:()=>Zu,delay:()=>sl,deleteSnapshot:()=>Zi,demoShell:()=>Ei,derived:()=>C,deserializeError:()=>wn,dictKv:()=>Cp,dictSnapshot:()=>Lp,diffForWAL:()=>Ts,diffSnapshots:()=>Qi,distill:()=>js,distinctUntilChanged:()=>Qc,domainTemplates:()=>_i,downWithBatch:()=>At,dynamicNode:()=>Dr,effect:()=>ge,elementAt:()=>Uc,empty:()=>Yu,encodeEnvelope:()=>Nr,escapeRegexChar:()=>va,exhaustMap:()=>nl,explainPath:()=>Kr,exponential:()=>Zo,externalBundle:()=>Gs,externalProducer:()=>bn,extra:()=>rd,factoryTag:()=>we,fallback:()=>Yn,fibonacci:()=>es,filter:()=>rt,find:()=>Wc,first:()=>Fs,firstValueFrom:()=>et,firstWhere:()=>rs,flatMap:()=>ol,forEach:()=>Wt,fromAny:()=>Y,fromAsyncIter:()=>Br,fromCSV:()=>zl,fromClickHouseWatch:()=>Yl,fromCron:()=>os,fromDrizzle:()=>hp,fromEvent:()=>Ju,fromHTTP:()=>Ya,fromHTTPPoll:()=>Al,fromHTTPStream:()=>Ol,fromIter:()=>ss,fromKafka:()=>Bl,fromKysely:()=>yp,fromMCP:()=>Il,fromNATS:()=>Zl,fromNDJSON:()=>Jl,fromOTel:()=>Pl,fromPrisma:()=>gp,fromPrometheus:()=>jl,fromPromise:()=>Xn,fromPulsar:()=>Ql,fromRabbitMQ:()=>tp,fromRaf:()=>Uu,fromRedisStream:()=>Kl,fromSSE:()=>Ml,fromSqlite:()=>pp,fromSqliteCursor:()=>fp,fromStatsD:()=>Fl,fromSyslog:()=>Dl,fromTimer:()=>Ze,fromWebSocket:()=>Ja,fromWebSocketReconnect:()=>Ll,fromWebhook:()=>kl,globToRegExp:()=>Hu,graph:()=>Ca,graphProfile:()=>hn,graphspec:()=>wi,guarded:()=>Oi,harness:()=>ji,interval:()=>ml,isBatching:()=>sn,isV1:()=>da,jobQueue:()=>Fi,jotai:()=>Ko,jsonCodec:()=>ar,jsonCodecFor:()=>Mp,keepalive:()=>te,kvStorage:()=>Ws,last:()=>Hc,layout:()=>qi,lens:()=>Vi,linear:()=>Xo,listSnapshots:()=>Xi,lru:()=>Za,makeHttpError:()=>wt,map:()=>eo,matchesAnyPattern:()=>Wu,matchesCron:()=>Yo,memory:()=>bi,memoryAppendLog:()=>Ap,memoryBackend:()=>mo,memoryKv:()=>go,memorySnapshot:()=>Op,merge:()=>Et,mergeMap:()=>qa,mergeReactiveLogs:()=>Lc,mermaidLiveUrl:()=>vs,messaging:()=>li,monotonicNs:()=>V,nameToSignal:()=>vn,nanostores:()=>Wo,ndjsonRows:()=>Wl,nestjs:()=>Ms,never:()=>Qu,node:()=>U,nodeSignal:()=>ds,normalizeActor:()=>Ot,of:()=>Ta,onFirstData:()=>no,orchestration:()=>pi,pairwise:()=>Xc,parseCron:()=>Jo,parsePrometheusText:()=>Qa,parseSSEStream:()=>$t,parseStatsD:()=>$l,parseSyslog:()=>Gl,patterns:()=>du,pausable:()=>hl,pipe:()=>pa,placeholderArgs:()=>st,policy:()=>Ct,policyFromRules:()=>Lr,process:()=>Ki,producer:()=>z,pubsub:()=>Rp,race:()=>tl,rateLimiter:()=>Jn,reachable:()=>yn,react:()=>Os,reactiveCounter:()=>wa,reactiveIndex:()=>Ep,reactiveList:()=>Ks,reactiveLog:()=>Ke,reactiveMap:()=>je,reactiveSink:()=>Ue,reduce:()=>Kc,reduction:()=>Ti,refine:()=>Li,registerBuiltinCodecs:()=>_r,registerBuiltins:()=>Cr,repeat:()=>gl,replay:()=>is,replayWAL:()=>sa,rescue:()=>ro,resilientPipeline:()=>zi,resolveBackoffPreset:()=>qt,resolveDescribeFields:()=>Lt,restoreSnapshot:()=>Yi,retry:()=>St,runReduction:()=>Wi,sample:()=>il,saveSnapshot:()=>Ji,scan:()=>Vc,serializeError:()=>Tn,share:()=>tc,shareReplay:()=>rc,signalToName:()=>Xt,signals:()=>Cs,singleFromAny:()=>qs,singleNodeFromAny:()=>_p,sizeof:()=>qr,skip:()=>Va,snapshotStorage:()=>Hs,solid:()=>Ls,sortJsonValue:()=>fo,stableJsonString:()=>zs,state:()=>A,stratify:()=>ho,surface:()=>ea,svelte:()=>Is,switchMap:()=>ke,take:()=>to,takeUntil:()=>zc,takeWhile:()=>qc,tap:()=>Jc,tapFirst:()=>Yc,throttle:()=>Ha,throttleTime:()=>Tl,throwError:()=>Xu,timeout:()=>Qn,toArray:()=>ec,toCSV:()=>rp,toClickHouse:()=>op,toFile:()=>Xa,toHTTP:()=>xl,toKafka:()=>Vl,toLoki:()=>dp,toMongo:()=>ap,toNATS:()=>ep,toObservable:()=>Uo,toPostgres:()=>ip,toPulsar:()=>Xl,toRabbitMQ:()=>np,toReadableStream:()=>_l,toRedisStream:()=>ql,toS3:()=>sp,toSSE:()=>Nl,toSSEBytes:()=>El,toSqlite:()=>mp,toTempo:()=>up,toWebSocket:()=>Cl,tokenBucket:()=>zt,topologyDiff:()=>er,validateGraphObservability:()=>Aa,valve:()=>yl,verifiable:()=>kp,version:()=>lv,vue:()=>Ps,wallClockNs:()=>se,watchTopologyTree:()=>Pt,window:()=>fl,windowCount:()=>cl,windowTime:()=>pl,withBreaker:()=>Un,withLatestFrom:()=>Ft,withMaxAttempts:()=>ya,withStatus:()=>Ht,workerBridge:()=>td,workerSelf:()=>nd,zip:()=>Zc,zustand:()=>Ds});module.exports=tm(pv);var Ba={};Se(Ba,{jotai:()=>Ko,nanostores:()=>Wo,nestjs:()=>Ms,react:()=>Os,signals:()=>Cs,solid:()=>Ls,svelte:()=>Is,vue:()=>Ps,zustand:()=>Ds});var Ko={};Se(Ko,{atom:()=>gm});ae();ne();function gm(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?Su(r,e,n):Su(r,void 0,e)}return hm(t,e)}function Gr(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===M&&(e=i),s===I&&(n=i)})(),n)throw n;return e}function hm(t,e){let n=A(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?Gr(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?Gr(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===M){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function Su(t,e,n){let r=dn(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&Gr(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?Gr(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[d,u]of a)if(d===M){if(i){i=!1;continue}s(u)}})},meta:r.meta,_node:r};if(e){let s=d=>d.get(),i=(d,u)=>d.set(u),a=o;return a.set=d=>e(s,i,d),a.update=d=>{let u=r.status==="sentinel"?Gr(r):r.cache;return e(s,i,d(u))},a}return o}var Wo={};Se(Wo,{action:()=>km,atom:()=>ym,computed:()=>bm,getValue:()=>Tm,map:()=>vm,onMount:()=>wm,onStart:()=>_u,onStop:()=>Mu});Ae();ae();ne();var zo=new WeakMap,Ho=new WeakMap;function qo(t,e){let n=e.get(t);if(n)for(let r of n)r()}function fa(t,e={}){let n=0;return{...e,get:()=>Eu(t),subscribe:o=>{n===0&&qo(t,zo),n++;let s=t.subscribe(i=>{for(let[a,d]of i)a===M&&o(d)});return()=>{s(),n--,n===0&&qo(t,Ho)}},listen:o=>{n===0&&qo(t,zo),n++;let s=!0,i=t.subscribe(a=>{for(let[d,u]of a)if(d===M){if(s){s=!1;continue}o(u)}});return()=>{i(),n--,n===0&&qo(t,Ho)}},_node:t}}function Nu(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===M&&(e=i),s===I&&(n=i)})(),n)throw n;return e}function Eu(t){return t.status==="sentinel"?Nu(t):t.cache}function ym(t){let e=A(t,{resubscribable:!0,resetOnTeardown:!0});return fa(e,{set:n=>e.emit(n)})}function bm(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=Dr(r,s=>{let i=n.map(a=>{let d=a._node;return d.status==="sentinel"&&Nu(d),s(d)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return fa(o)}function vm(t){let e=A(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return fa(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=Eu(e);e.emit({...o,[n]:r})}})}function Tm(t){return t.get()}function _u(t,e){let n=t._node,r=zo.get(n);r||(r=new Set,zo.set(n,r)),r.add(e)}function Mu(t,e){let n=t._node,r=Ho.get(n);r||(r=new Set,Ho.set(n,r)),r.add(e)}function wm(t,e){_u(t,()=>{let n=e();typeof n=="function"&&Mu(t,n)})}function km(t,e,n){return(...r)=>{let o;return Z(()=>{o=n(...r)}),o}}var Ms={};Se(Ms,{ACTOR_KEY:()=>cs,COMMAND_HANDLERS:()=>Kn,CQRS_EVENT_HANDLERS:()=>qn,CRON_HANDLERS:()=>Vn,CommandHandler:()=>Du,EVENT_HANDLERS:()=>jn,EventHandler:()=>Gu,GRAPHREFLY_REQUEST_GRAPH:()=>un,GRAPHREFLY_ROOT_GRAPH:()=>mt,GraphCron:()=>Pu,GraphInterval:()=>Iu,GraphReflyEventExplorer:()=>mn,GraphReflyGuard:()=>uc,GraphReflyGuardImpl:()=>Vr,GraphReflyModule:()=>_s,INTERVAL_HANDLERS:()=>Bn,InjectCqrsGraph:()=>Au,InjectGraph:()=>Ou,InjectNode:()=>Cu,ObserveGateway:()=>us,OnGraphEvent:()=>Lu,QUERY_HANDLERS:()=>zn,QueryHandler:()=>Fu,SAGA_HANDLERS:()=>Hn,SagaHandler:()=>$u,fromHeader:()=>ac,fromJwtPayload:()=>Ra,getActor:()=>dc,getGraphToken:()=>ut,getNodeToken:()=>ht,observeSSE:()=>sc,observeSubscription:()=>ic,toObservable:()=>Uo});var ma=require("rxjs");ae();function Uo(t,e){return e?.raw?new ma.Observable(n=>t.subscribe(o=>{if(!n.closed){n.next(o);for(let s of o){if(s[0]===I){n.error(s[1]);return}if(s[0]===P){n.complete();return}}}})):new ma.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===M)n.next(s[1]);else if(s[0]===I){n.error(s[1]);return}else if(s[0]===P){n.complete();return}}}))}var Fr=require("@nestjs/common");var mt=Symbol.for("graphrefly:root-graph");var un=Symbol.for("graphrefly:request-graph");function ut(t){return Symbol.for(`graphrefly:graph:${t}`)}function ht(t){return Symbol.for(`graphrefly:node:${t}`)}var jn=new Map,Bn=new Map,Vn=new Map,Kn=new Map,qn=new Map,zn=new Map,Hn=new Map;function Ou(t){return t==="request"?(0,Fr.Inject)(un):(0,Fr.Inject)(t?ut(t):mt)}function Au(t){return(0,Fr.Inject)(ut(t))}function Cu(t){return(0,Fr.Inject)(ht(t))}function Lu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=jn.get(o)??[];s.push({nodeName:t,methodKey:r}),jn.set(o,s)})}}function Iu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Bn.get(o)??[];s.push({ms:t,methodKey:r}),Bn.set(o,s)})}}function Pu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Vn.get(o)??[];s.push({expr:t,methodKey:r}),Vn.set(o,s)})}}function Du(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=Kn.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),Kn.set(s,i)})}}function Gu(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=qn.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),qn.set(s,i)})}}function Fu(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=zn.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),zn.set(s,i)})}}function $u(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=Hn.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),Hn.set(i,a)})}}ae();ve();var oc=0,mn=class{constructor(e,n){this.graph=e;this.moduleRef=n}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,n]of jn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireEventHandler(r,o)}}wireEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),i=this.observeNode(n.nodeName).subscribe(a=>{for(let d of a)d[0]===M&&o(d[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of Bn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireIntervalHandler(r,e,o)}}wireIntervalHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${oc++}`,d=Ze(r.ms,{period:r.ms,name:a});this.graph.add(d),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===M&&s(p[1])});this.disposers.push(c)}wireCrons(){for(let[e,n]of Vn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCronHandler(r,e,o)}}wireCronHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${oc++}`,d=os(r.expr,{name:a});this.graph.add(d),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===M&&s(p[1])});this.disposers.push(c)}wireCqrsCommands(){for(let[e,n]of Kn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsCommand(r,o)}}wireCqrsCommand(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.command(n.commandName,o)}wireCqrsEvents(){for(let[e,n]of qn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsEventHandler(r,o)}}wireCqrsEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;s.event(n.eventName);let a=s.resolve(n.eventName).cache,d=a&&a.length>0?a[a.length-1].seq:0,c=this.observeNodeOn(s,n.eventName).subscribe(l=>{for(let p of l)if(p[0]===M){let f=p[1];for(let m of f)m.seq>d&&(o(m),d=m.seq)}});this.disposers.push(c)}wireCqrsQueries(){for(let[e,n]of zn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsQuery(r,o)}}wireCqrsQuery(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;let a=this.observeNodeOn(s,n.projectionName).subscribe(d=>{for(let u of d)u[0]===M&&o(u[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of Hn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsSaga(r,o)}}wireCqrsSaga(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.saga(n.sagaName,n.eventNames,o)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,n){return e.observe(n)}resolveCqrsGraph(e){try{return this.moduleRef.get(ut(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};ae();ae();var Dm=0;function Zn(t,e){if(e.highWaterMark<1)throw new RangeError("highWaterMark must be >= 1");if(e.lowWaterMark<0)throw new RangeError("lowWaterMark must be >= 0");if(e.lowWaterMark>=e.highWaterMark)throw new RangeError("lowWaterMark must be < highWaterMark");let n=Symbol(`bp-${++Dm}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[Ve,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[ze,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[ze,n]]))}}}function sc(t,e,n){let{actor:r,serialize:o=Gm,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,d,u=n?.highWaterMark!=null,c,l,p=[],f=!1;return new ReadableStream({start(m){let h,g=()=>{},y=()=>{if(!f){f=!0,h!==void 0&&clearInterval(h),i?.removeEventListener("abort",b),g(),c?.dispose(),l?.(),l=void 0;for(let T of p)m.enqueue(T.frame);p.length=0,m.close()}};d=y;let b=()=>y(),v=t.observe(e,{actor:r});u&&(c=Zn(T=>v.up(T),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)})),g=v.subscribe(T=>{for(let w of T){if(f)return;let x=w[0];if(x===M){let k=a.encode(ka("data",o(w[1])));u?(p.push({frame:k,counted:!0}),c.onEnqueue(),l?.(),l=void 0):m.enqueue(k)}else if(x===I){let k=a.encode(ka("error",o(w[1])));u?(p.push({frame:k,counted:!1}),l?.(),l=void 0):m.enqueue(k),y();return}else if(x===P||x===le){if(x===P){let k=a.encode(ka("complete"));u?(p.push({frame:k,counted:!1}),l?.(),l=void 0):m.enqueue(k)}y();return}}}),s!==void 0&&s>0&&(h=setInterval(()=>{f||(u?(p.push({frame:a.encode(`: keepalive
|
|
1
|
+
"use strict";var Tm=Object.create;var Kn=Object.defineProperty;var Mu=Object.getOwnPropertyDescriptor;var wm=Object.getOwnPropertyNames;var km=Object.prototype.hasOwnProperty;var Ou=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Or=t=>{throw TypeError(t)};var xm=(t,e,n)=>e in t?Kn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Nu=(t,e)=>Kn(t,"name",{value:e,configurable:!0});var Ve=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ne=(t,e)=>{for(var n in e)Kn(t,n,{get:e[n],enumerable:!0})},Rm=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wm(e))!km.call(t,o)&&o!==n&&Kn(t,o,{get:()=>e[o],enumerable:!(r=Mu(e,o))||r.enumerable});return t};var Sm=t=>Rm(Kn({},"__esModule",{value:!0}),t);var Au=t=>[,,,Tm(t?.[Ou("metadata")]??null)],Cu=["class","method","getter","setter","accessor","field","value","get","set"],Mr=t=>t!==void 0&&typeof t!="function"?Or("Function expected"):t,Nm=(t,e,n,r,o)=>({kind:Cu[t],name:e,metadata:r,addInitializer:s=>n._?Or("Already initialized"):o.push(Mr(s||null))}),Em=(t,e)=>xm(e,Ou("metadata"),t[3]),Lu=(t,e,n,r)=>{for(var o=0,s=t[e>>1],i=s&&s.length;o<i;o++)e&1?s[o].call(n):r=s[o].call(n,r);return r},Iu=(t,e,n,r,o,s)=>{var i,a,d,u,c,l=e&7,p=!!(e&8),f=!!(e&16),m=l>3?t.length+1:l?p?1:2:0,h=Cu[l+5],g=l>3&&(t[m-1]=[]),y=t[m]||(t[m]=[]),b=l&&(!f&&!p&&(o=o.prototype),l<5&&(l>3||!f)&&Mu(l<4?o:{get[n](){return Eu(this,s)},set[n](T){return _u(this,s,T)}},n));l?f&&l<4&&Nu(s,(l>2?"set ":l>1?"get ":"")+n):Nu(o,n);for(var v=r.length-1;v>=0;v--)u=Nm(l,n,d={},t[3],y),l&&(u.static=p,u.private=f,c=u.access={has:f?T=>_m(o,T):T=>n in T},l^3&&(c.get=f?T=>(l^1?Eu:Mm)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(c.set=f?(T,w)=>_u(T,o,w,l^4?s:b.set):(T,w)=>T[n]=w)),a=(0,r[v])(l?l<4?f?s:b[h]:l>4?void 0:{get:b.get,set:b.set}:o,u),d._=1,l^4||a===void 0?Mr(a)&&(l>4?g.unshift(a):l?f?s=a:b[h]=a:o=a):typeof a!="object"||a===null?Or("Object expected"):(Mr(i=a.get)&&(b.get=i),Mr(i=a.set)&&(b.set=i),Mr(i=a.init)&&g.unshift(i));return l||Em(t,o),b&&Kn(o,n,b),f?l^4?s:b:o};var ma=(t,e,n)=>e.has(t)||Or("Cannot "+n),_m=(t,e)=>Object(e)!==e?Or('Cannot use the "in" operator on this value'):t.has(e),Eu=(t,e,n)=>(ma(t,e,"read from private field"),n?n.call(t):e.get(t));var _u=(t,e,n,r)=>(ma(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),Mm=(t,e,n)=>(ma(t,e,"access private method"),n);var mt,_,se,q,Ze,Ke,He,ce,I,L,Ct,qn,qo,zn,zo,Ho,Hn,Ar,Cr,Lr,Wn,ae=Ve(()=>{"use strict";mt=Symbol.for("graphrefly/START"),_=Symbol.for("graphrefly/DATA"),se=Symbol.for("graphrefly/DIRTY"),q=Symbol.for("graphrefly/RESOLVED"),Ze=Symbol.for("graphrefly/INVALIDATE"),Ke=Symbol.for("graphrefly/PAUSE"),He=Symbol.for("graphrefly/RESUME"),ce=Symbol.for("graphrefly/TEARDOWN"),I=Symbol.for("graphrefly/COMPLETE"),L=Symbol.for("graphrefly/ERROR"),Ct=Object.freeze([se]),qn=Object.freeze([q]),qo=Object.freeze([Ze]),zn=Object.freeze([mt]),zo=Object.freeze([I]),Ho=Object.freeze([ce]),Hn=Object.freeze([Ct]),Ar=Object.freeze([qn]),Cr=Object.freeze([qo]),Lr=Object.freeze([zo]),Wn=Object.freeze([Ho])});function ga(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function ha(t,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:n=>e.compressSync(t.encode(n)),decode:(n,r)=>t.decode(e.decompressSync(n))}}function Ir(t,e){let n=new TextEncoder().encode(t.name);if(n.length===0||n.length>255)throw new Error(`encodeEnvelope: codec name "${t.name}" encodes to ${n.length} bytes (must be 1\u2013255)`);let r=t.version;if(!Number.isInteger(r)||r<0||r>65535)throw new Error(`encodeEnvelope: codec.version ${r} out of u16 range (expected integer 0\u201365535)`);let o=2+n.length+2+e.length;if(o>4294967295)throw new Error(`encodeEnvelope: total envelope size ${o} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let s=new Uint8Array(o),i=0;return s[i++]=Un,s[i++]=n.length,s.set(n,i),i+=n.length,s[i++]=r>>>8&255,s[i++]=r&255,s.set(e,i),s}function Dr(t,e){if(t.length<Du)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Du})`);let n=0,r=t[n++];if(r!==Un)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Un})`);let o=t[n++];if(o===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(n+o+2>t.length)throw new Error(`decodeEnvelope: envelope truncated (need ${n+o+2} bytes, have ${t.length})`);let s=new TextDecoder().decode(t.subarray(n,n+o));n+=o;let i=(t[n]<<8|t[n+1])>>>0;n+=2;let a=t.subarray(n),d=e.lookupCodec(s);if(d==null)throw new Error(`decodeEnvelope: codec "${s}" not registered (envelope codec_v=${i})`);return{codec:d,codecVersion:i,payload:a}}function Pr(t){t.registerCodec(Wo)}function ya(t){if(t.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=t[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let n=JSON.parse(JSON.stringify(e.snapshot)),r=e.seq;for(let o=1;o<t.length;o++){let s=t[o];if(s.seq<=r)throw new Error(`WAL chain broken at index ${o}: seq=${s.seq} must exceed prev seq=${r}`);if(s.mode==="full"){n=JSON.parse(JSON.stringify(s.snapshot)),r=s.seq;continue}let i=s.diff;for(let d of i.nodesRemoved)delete n.nodes[d];let a=i.nodesAddedFull;if(a!=null)for(let[d,u]of Object.entries(a))n.nodes[d]=JSON.parse(JSON.stringify(u));for(let d of i.nodesChanged){let u=n.nodes[d.path];u!=null&&(u[d.field]=d.to)}r=s.seq}return n}var Wo,Un,Du,Uo=Ve(()=>{"use strict";Wo={name:"json",version:1,contentType:"application/json",encode(t){let e=JSON.stringify(t);return new TextEncoder().encode(e)},decode(t,e){let n=new TextDecoder().decode(t);return JSON.parse(n)}};Un=1,Du=4});function Lt(t){if(t==null)return Nt;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var Nt,Gr=Ve(()=>{"use strict";Nt={type:"system",id:""}});function mn(){return Jn>0||Fr}function Pu(){return Jn>0}function Qn(t){Jn>0?$r.push(t):t()}function Z(t){Jn+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Jn-=1,Jn===0)if(e){if(!Fr){let n=$r.splice(0);for(let r of n)try{r()}catch{}pn.length=0,fn.length=0,Yn.length=0}}else Om()}}function Om(){let t=!Fr;t&&(Fr=!0);let e=[],n=0;try{for(;pn.length>0||fn.length>0||Yn.length>0||t&&$r.length>0;){if(t&&$r.length>0){let s=$r.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw pn.length=0,fn.length=0,Yn.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(pn.length>0?pn:fn.length>0?fn:Yn).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(Fr=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function It(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!mn()){t(e);return}(u>=5?Yn:u===4?fn:pn).push(()=>t(e));return}let r=e.length,o=r,s=r,i=r,a=0;for(;a<r&&n(e[a][0])<3;)a++;for(o=a;a<r&&n(e[a][0])===3;)a++;for(s=a;a<r&&n(e[a][0])===4;)a++;i=a;let d=mn();if(o>0){let u=e.slice(0,o);t(u)}if(s>o){let u=e.slice(o,s);d?pn.push(()=>t(u)):t(u)}if(i>s){let u=e.slice(s,i);d?fn.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?Yn.push(()=>t(u)):t(u)}}var Jn,Fr,pn,fn,Yn,$r,Ae=Ve(()=>{"use strict";Jn=0,Fr=!1,pn=[],fn=[],Yn=[],$r=[]});function H(){return Math.trunc(performance.now()*1e6)}function oe(){return Date.now()*1e6}var Se=Ve(()=>{"use strict"});function jr(t){t.registerMessageType(mt,{tier:0,wireCrossing:!1}),t.registerMessageType(se,{tier:1,wireCrossing:!1}),t.registerMessageType(Ze,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(Ke,{tier:2,wireCrossing:!1}),t.registerMessageType(He,{tier:2,wireCrossing:!1}),t.registerMessageType(_,{tier:3,wireCrossing:!0}),t.registerMessageType(q,{tier:3,wireCrossing:!0}),t.registerMessageType(I,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(L,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(ce,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var gn,ba=Ve(()=>{"use strict";ae();gn=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=n=>{let r=this._messageTypes.get(n);return r!=null?r.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,n){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:n.tier,wireCrossing:n.wireCrossing??n.tier>=3,metaPassthrough:n.metaPassthrough??!0}),this}messageTier(e){let n=this._messageTypes.get(e);return n!=null?n.tier:1}isWireCrossing(e){let n=this._messageTypes.get(e);return n!=null?n.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let n=this._messageTypes.get(e);return n!=null?n.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}}});function Gu(t){return Array.isArray(t)?[...t]:[t]}function Am(t,e){return t.has(e)||t.has("*")}function Dt(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(Gu(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(Gu(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let d of e)Am(d.actions,s)&&d.where(o)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function Br(t){return Dt((e,n)=>{for(let r of t){let o=r.actorType==null?null:new Set(Array.isArray(r.actorType)?r.actorType:[r.actorType]),s=r.actorId==null?null:new Set(Array.isArray(r.actorId)?r.actorId:[r.actorId]),i=Object.entries(r.claims??{}),a=d=>{if(o!==null&&!o.has(String(d.type))||s!==null&&!s.has(String(d.id??"")))return!1;for(let[u,c]of i)if(d[u]!==c)return!1;return!0};r.effect==="deny"?n(r.action,{where:a}):e(r.action,{where:a})}})}function Vr(t){let e=Cm.filter(n=>t({type:n,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(n=>n==="human"||n==="llm"||n==="system")?"both":e.length===1?e[0]:e.join("+")}var ut,Cm,zt=Ve(()=>{"use strict";ut=class extends Error{actor;action;nodeName;constructor(e,n){super(n??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};Cm=["human","llm","wallet","system"]});function va(t){if(t===void 0)return null;if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError(`Cannot hash non-finite number: ${t}`);if(Number.isInteger(t)&&!Number.isSafeInteger(t))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${t}. Cross-language cid parity is not guaranteed for unsafe integers.`);return t}if(typeof t=="string"||typeof t=="boolean"||t===null)return t;if(Array.isArray(t))return t.map(va);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=va(t[n]);return e}return null}function Dm(t){let e=Im.encode(t),n=e.length,r=n*8,o=n+9+63&-64,s=new Uint8Array(o);s.set(e),s[n]=128;let i=new DataView(s.buffer);i.setUint32(o-4,r>>>0,!1),i.setUint32(o-8,Math.floor(r/4294967296)>>>0,!1);let a=1779033703,d=3144134277,u=1013904242,c=2773480762,l=1359893119,p=2600822924,f=528734635,m=1541459225,h=new Uint32Array(64),g=(b,v)=>b>>>v|b<<32-v;for(let b=0;b<o;b+=64){for(let E=0;E<16;E++)h[E]=i.getUint32(b+E*4,!1);for(let E=16;E<64;E++){let D=h[E-15],M=h[E-2],C=g(D,7)^g(D,18)^D>>>3,$=g(M,17)^g(M,19)^M>>>10;h[E]=h[E-16]+C+h[E-7]+$>>>0}let v=a,T=d,w=u,k=c,R=l,S=p,x=f,N=m;for(let E=0;E<64;E++){let D=g(R,6)^g(R,11)^g(R,25),M=R&S^~R&x,C=N+D+M+Lm[E]+h[E]>>>0,$=g(v,2)^g(v,13)^g(v,22),B=v&T^v&w^T&w,G=$+B>>>0;N=x,x=S,S=R,R=k+C>>>0,k=w,w=T,T=v,v=C+G>>>0}a=a+v>>>0,d=d+T>>>0,u=u+w>>>0,c=c+k>>>0,l=l+R>>>0,p=p+S>>>0,f=f+x>>>0,m=m+N>>>0}let y=b=>b.toString(16).padStart(8,"0");return y(a)+y(d)+y(u)+y(c)+y(l)+y(p)+y(f)+y(m)}function Ht(t){let e=va(t??null),n=JSON.stringify(e);return Dm(n).slice(0,16)}function Pm(){let t=globalThis.crypto;if(t?.randomUUID)return t.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),n=e()+e()+e()+e();return`${n.slice(0,8)}-${n.slice(8,12)}-4${n.slice(13,16)}-${(parseInt(n.slice(16,17),16)&3|8).toString(16)}${n.slice(17,20)}-${n.slice(20,32)}`}function Xn(t,e,n){let r=n?.id??Pm();if(t===0)return{id:r,version:0};let s=(n?.hash??Ht)(e);return{id:r,version:0,cid:s,prev:null}}function Kr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function Ta(t){return"cid"in t}var Lm,Im,Jo=Ve(()=>{"use strict";Lm=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Im=new TextEncoder});function ju(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function wa(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function Yo(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function xa(t){if($e._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");t($e)}function U(t,e,n){let r=Bu(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return Bu(t)?s=(ka(e)?e:n)??{}:ka(t)?s=t:s=(ka(e)?e:n)??{},new Ce(r,o,s)}var Fu,$u,Gm,Fm,$e,Ce,Bu,ka,Me=Ve(()=>{"use strict";Uo();Gr();Ae();Se();ba();zt();ae();Jo();Fu=()=>{},$u=100;Gm=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},Fm=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[zn]:[zn,[_,s]];o._status==="dirty"&&i.push(Ct),It(e,i,o._config.tierOf)},$e=new gn({onMessage:Gm,onSubscribe:Fm});jr($e);Pr($e);Ce=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??$e,this._config.onMessage,this._optsName=r.name,this._describeKind=r.describeKind,this._equals=r.equals??Object.is,this._resubscribable=r.resubscribable??!1,this._resetOnTeardown=r.resetOnTeardown??!1,this._autoComplete=r.completeWhenDepsComplete??!0,this._autoError=r.errorWhenDepsError??!0,this._pausable=r.pausable??!0,this._guard=r.guard,this._fn=n,this._partial=r.partial??!1,this._cached=r.initial!==void 0?r.initial:void 0,this._status=e.length===0&&n==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=r.versioningHash??this._config.defaultHashFn??Ht;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?Xn(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(ju);let s={};for(let[a,d]of Object.entries(r.meta??{})){let u={initial:d,name:`${r.name??"node"}:meta:${a}`,describeKind:"state",config:this._config};r.guard!=null&&(u.guard=r.guard),s[a]=new t([],void 0,u)}Object.freeze(s),this.meta=s,this._hasMeta=Object.keys(s).length>0;let i=this;this._actions={emit(a){i._emit([[_,a]])},down(a){i._emit(Yo(a))},up(a){i._emitUp(Yo(a))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,n){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let r=this._versioningLevel;if(r!=null&&e<=r)return;let o=n?.hash??this._hashFn;o!==this._hashFn&&(this._hashFn=o);let s=this._cached===void 0?void 0:this._cached,i=this._versioning,a=i?.id??n?.id,d=i?.version??0,u=Xn(e,s,{id:a,hash:o});u.version=d,this._versioning=u,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let n=Lt(e);if(this._guard!=null&&!this._guard(n,"observe"))return!1;if(this._extraGuards!=null){for(let r of this._extraGuards)if(!r(n,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let n=this._guard!=null||this._extraGuards!=null,r=e?.actor!=null;if(!n&&!r)return;let o=Lt(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new ut({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new ut({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:oe()}}down(e,n){let r=Yo(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[_,e]])}up(e,n){if(this._deps.length===0)return;let r=Yo(e);if(r.length===0)return;this._checkGuard(n);let o=n??{internal:!0};this._validateUpTiers(r);for(let s of this._deps)s.node.up?.(r,o)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let n of this._deps)n.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let n=this._config.tierOf;for(let r of e){let o=n(r[0]);if(o===3||o===4)throw new Error(`Node "${this.name}": tier-${o} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,n){if(n!=null&&this._guard!=null){let d=Lt(n);if(!this._guard(d,"observe"))throw new ut({actor:d,action:"observe",nodeName:this.name})}let o=this._isTerminal&&this._resubscribable;if(o){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)wa(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let s;try{s=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:o},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let i=this._isTerminal;if(this._sinkCount===1&&!i)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof s=="function")try{s()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let a=!1;return()=>{a||(a=!0,this._sinkCount-=1,this._removeSink(e),typeof s=="function"&&s(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[n]=this._sinks;this._sinks=n}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,n=0;try{for(let r=0;r<e;r++){let o=r,s=this._deps[r];s.unsub=Fu,s.unsub=s.node.subscribe(i=>{if(s.unsub===null)return;let a=this._config.tierOf,d=!1;for(let u of i)a(u[0])>=3&&(d=!0),this._config.onMessage(this,u,{direction:"down-in",depIndex:o},this._actions);d&&this._maybeRunFnOnSettlement()}),n++}}catch(r){this._deps[n].unsub=null;for(let o=0;o<n;o++){let s=this._deps[o];if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}wa(s)}}throw this._dirtyDepCount=0,r}}_addDep(e){for(let o=0;o<this._deps.length;o++)if(this._deps[o].node===e)return o;let n=this._deps.length,r=ju(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Hn),r.unsub=Fu;try{r.unsub=e.subscribe(o=>{if(r.unsub===null)return;let s=this._config.tierOf,i=!1;for(let a of o)s(a[0])>=3&&(i=!0),this._config.onMessage(this,a,{direction:"down-in",depIndex:n},this._actions);i&&this._maybeRunFnOnSettlement()})}catch(o){throw r.unsub=null,this._deps.pop(),this._dirtyDepCount--,o}return n}_deactivate(e=!1){let n=this._cleanup;if(this._cleanup=void 0,typeof n=="function")try{n()}catch(r){this._emit([[L,this._wrapFnError("cleanup threw",r)]])}else if(n!=null&&typeof n=="object"){let r=n.deactivate;if(typeof r=="function")try{r()}catch(o){this._emit([[L,this._wrapFnError("cleanup.deactivate threw",o)]])}}for(let r of this._deps){if(r.unsub!=null){let o=r.unsub;r.unsub=null;try{o()}catch{}}wa(r)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,n){let r=this._deps[e],o=n[0];if(this._inspectorHooks!=null){let s={kind:"dep_message",depIndex:e,message:n};for(let i of this._inspectorHooks)i(s)}if(o!==mt){if(o===se){this._depDirtied(r);return}if(o===Ze){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Cr);return}if(o===Ke||o===He){this._emit([n]);return}if(o===ce){this._emit(Wn);return}if(o===_)this._depSettledAsData(r,n[1]);else if(o===q)this._depSettledAsResolved(r);else if(o===I)this._depSettledAsTerminal(r,!0);else if(o===L)this._depSettledAsTerminal(r,n[1]);else{this._emit([n]);return}if(!this._fn){(o===_||o===q)&&this._emit([n]),(o===I||o===L)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Hn))}_depSettledAsData(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(n),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,n){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=n,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let n=this._deps[e];if(n.dataBatch.length===0&&n.prevData===void 0&&n.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(Ar),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(n=>n.terminal!==void 0&&n.terminal!==!0);if(e!=null){this._autoError&&this._emit([[L,e.terminal]]);return}this._autoComplete&&this._deps.every(n=>n.terminal!==void 0)&&this._emit(Lr)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(i){this._emit([[L,this._wrapFnError("cleanup threw",i)]]);return}}else if(e!=null&&typeof e=="object"){let i=e.beforeRun;if(typeof i=="function"){e.beforeRun=void 0;try{i()}catch(a){this._emit([[L,this._wrapFnError("cleanup.beforeRun threw",a)]]);return}}}let n=this._deps.map(i=>i.involvedThisWave?i.dataBatch.length>0?[...i.dataBatch]:[]:void 0),r=this._deps.map(i=>i.prevData);for(let i=0;i<this._deps.length;i++){let a=n[i];a!=null&&a.length>0&&(this._deps[i].prevData=a[a.length-1])}let o=this._deps.map(i=>i.terminal),s={prevData:r,terminalDeps:o,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let i={kind:"run",batchData:n,prevData:r};for(let a of this._inspectorHooks)a(i)}this._isExecutingFn=!0;try{let i=this._fn(n,this._actions,s);if(typeof i=="function")this._cleanup=i;else if(i!=null&&typeof i=="object"){let a=i;(typeof a.beforeRun=="function"||typeof a.deactivate=="function"||typeof a.invalidate=="function")&&(this._cleanup=i)}}catch(i){this._emit([[L,this._wrapFnError("fn threw",i)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>$u?(this._rerunDepth=0,this._emit([[L,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${$u} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,n){let r=n instanceof Error?n.message:String(n);return new Error(`Node "${this.name}": ${e}: ${r}`,{cause:n})}_frameBatch(e){let n=this._config.tierOf;if(e.length===1)return n(e[0][0])===3&&this._status!=="dirty"?[Ct,e[0]]:e;let r=!0,o=!1,s=!1,i=-1;for(let d of e){let u=n(d[0]);u<i&&(r=!1),u===3&&(o=!0),d[0]===se&&(s=!0),i=u}let a=e;if(!r){let d=e.map((u,c)=>({m:u,i:c,tier:n(u[0])}));d.sort((u,c)=>u.tier-c.tier||u.i-c.i),a=d.map(u=>u.m)}if(o&&!s&&this._status!=="dirty"){let d=0;for(;d<a.length&&n(a[d][0])===0;)d++;return d===0?[Ct,...a]:[...a.slice(0,d),Ct,...a.slice(d)]}return a}_emit(e){if(e.length===0)return;for(let a=0;a<e.length;a++){let d=e[a];if(d[0]===L&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let n=e;if(this._isTerminal&&!this._resubscribable){let a=e.filter(d=>d[0]===ce||d[0]===Ze);if(a.length===0)return;n=a}n=this._frameBatch(n);let o=null;for(let a=0;a<n.length;a++){let d=n[a],u=d[0];if(u!==Ke&&u!==He){o?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===Ke?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let l=d[1];if(u===Ke)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(l),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(l))c=!1;else if(this._pauseLocks.delete(l),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?o?.push(d):o==null&&(o=n.slice(0,a))}if(o!=null){if(o.length===0)return;n=o}if(this._hasMeta&&n.some(a=>a[0]===ce))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Wn)}catch{}let{finalMessages:s,equalsError:i}=this._updateState(n);if(s.length>0&&this._config.inspectorEnabled){let a=this._config.globalInspector;if(a!=null)try{a({kind:"emit",node:this,messages:s})}catch{}}if(s.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let a=this._config.tierOf,d=[];for(let u of s)a(u[0])===3?this._pauseBuffer.push(u):d.push(u);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(s);i!=null&&this._emit([[L,i]])}_updateState(e){let n=this._config.tierOf,r,o,s=-1,i=0;for(let c of e)n(c[0])===3&&i++;let a=i<=1,d=-1;if(this._versioning!=null&&i>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===_){d=c;break}}for(let c=0;c<e.length;c++){let l=e[c],p=l[0];if(p===_){if(l.length>=2){let f=!1;if(a&&this._cached!==void 0)try{f=this._equals(this._cached,l[1])}catch(m){o=this._wrapFnError("equals threw",m),s=c;break}if(f){r==null&&(r=e.slice(0,c)),r.push(qn),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(d<0||c===d)&&Kr(this._versioning,l[1],this._hashFn)}this._status="settled",r?.push(l)}else if(r?.push(l),p===se)this._status="dirty";else if(p===q)this._status="resolved";else if(p===I){this._status="completed";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===L){this._status="errored";{let f=this._config.rigorRecorder;if(f!=null)try{f.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===Ze){if(this._cached!==void 0){let m=this._config.rigorRecorder;if(m!=null)try{m.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let f=this._cleanup;if(typeof f=="function"){this._cleanup=void 0;try{f()}catch{}}else if(f!=null&&typeof f=="object"){let m=f.invalidate;if(typeof m=="function")try{m()}catch{}}}else p===ce&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:u,equalsError:o}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(Pu()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],Qn(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}It(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let n=this._frameBatch(e);It(this._deliverToSinks,n,this._config.tierOf)}},Bu=t=>Array.isArray(t),ka=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function O(t,e){return U([],{...e,initial:t})}function z(t,e){return U((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function A(t,e,n){return U(t,(o,s,i)=>{let a=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);s.emit(e(a,i))},{describeKind:"derived",...n})}function ye(t,e,n){return U(t,(o,s,i)=>{let a=o.map((d,u)=>d!=null&&d.length>0?d.at(-1):i.prevData[u]);return e(a,s,i)??void 0},{describeKind:"effect",...n})}function qr(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),A(t,(o,s)=>e(a=>{let d=r.get(a);if(d==null)throw new Error(`dynamicNode: untracked dep "${a.name??"<unnamed>"}"`);return o[d]},s),n)}function hn(t,e){let n,r=new Map,o=(s,i,a)=>{let d=!1,u=c=>{let l=r.get(c);if(l!==void 0){if(l<s.length){let f=s[l];return f!=null&&f.length>0?f.at(-1):a.prevData[l]}return c.cache}d=!0;let p=n._addDep(c);return r.set(c,p),c.cache};try{let c=t(u,a);d||(i.emit(c),a.store.__autoTrackLastDiscoveryError!=null&&delete a.store.__autoTrackLastDiscoveryError)}catch(c){if(!d)throw c;a.store.__autoTrackLastDiscoveryError=c}};return n=new Ce([],o,{describeKind:"derived",...e}),n}function Ra(t,...e){let n=t;for(let r of e)n=r(n);return n}var ne=Ve(()=>{"use strict";Me()});function Wr(t,e,n){let r=new Set;for(let o of t.split(",")){let[s,i]=o.split("/"),a=i?Number.parseInt(i,10):1;if(Number.isNaN(a)||a<1)throw new Error(`Invalid cron step: ${o}`);let d,u;if(s==="*")d=e,u=n;else if(s.includes("-")){let[c,l]=s.split("-");d=Number.parseInt(c,10),u=Number.parseInt(l,10)}else d=Number.parseInt(s,10),u=d;if(Number.isNaN(d)||Number.isNaN(u))throw new Error(`Invalid cron field: ${t}`);if(d<e||u>n)throw new Error(`Cron field out of range: ${t} (${e}-${n})`);if(d>u)throw new Error(`Invalid cron range: ${d}-${u} in ${t}`);for(let c=d;c<=u;c+=a)r.add(c)}return r}function rs(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:Wr(e[0],0,59),hours:Wr(e[1],0,23),daysOfMonth:Wr(e[2],1,31),months:Wr(e[3],1,12),daysOfWeek:Wr(e[4],0,6)}}function os(t,e){return t.minutes.has(e.getMinutes())&&t.hours.has(e.getHours())&&t.daysOfMonth.has(e.getDate())&&t.months.has(e.getMonth()+1)&&t.daysOfWeek.has(e.getDay())}var Ea=Ve(()=>{"use strict"});function xe(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}var at=Ve(()=>{"use strict"});function Wt(t,e,n){if(e.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=e.map(f=>f.node),o=[t,...r],s=new _a,i=!1,a=!1,d=Symbol("budget-gate"),u=new Array(e.length);function c(){return e.every((f,m)=>f.check(u[m]))}function l(f){for(;s.size>0&&c();){let m=s.shift();f.emit(m)}s.size===0&&a&&(a=!1,f.down([[q]]))}return U([],(f,m)=>{for(let g=0;g<e.length;g++)u[g]=e[g].node.cache;let h=[];for(let g=0;g<o.length;g++){let y=o[g];h.push(y.subscribe(b=>{for(let v of b)p(v,g,m)}))}return()=>{for(let g of h)g()}},{...n,describeKind:"derived",meta:xe("resilience","budget_gate",n?.meta)});function p(f,m,h){let g=f[0];if(m===0){if(g===_)return c()&&s.size===0?h.emit(f[1]):(s.push(f[1]),i||(i=!0,h.up([[Ke,d]]))),!0;if(g===se)return h.down([[se]]),!0;if(g===q)return s.size===0?h.down([[q]]):a=!0,!0;if(g===I||g===L){for(;s.size>0;)h.emit(s.shift());return a=!1,i&&(i=!1,h.up([[He,d]])),h.down([f]),!0}return!1}if(g===_&&(u[m-1]=f[1]),g===_||g===q){let y=c();return y&&s.size>0?(l(h),s.size===0&&i&&(i=!1,h.up([[He,d]]))):!y&&!i&&s.size>0&&(i=!0,h.up([[Ke,d]])),!0}return g===se?!0:g===L?(h.down([f]),!0):g===I}}var _a,rc=Ve(()=>{"use strict";ae();Me();at();_a=class{buf=[];head=0;get size(){return this.buf.length-this.head}push(e){this.buf.push(e)}shift(){if(this.head>=this.buf.length)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head++,this.head>32&&this.head*2>this.buf.length&&(this.buf=this.buf.slice(this.head),this.head=0),e}clear(){this.buf=[],this.head=0}}});function Ut(t,e){if(e!=null&&e.length>0)return new Set(e);switch(t){case"standard":return new Set(["type","status","value","deps","meta","v"]);case"full":return null;case"spec":return new Set(["type","deps","meta","value"]);default:return new Set(["type","deps"])}}function Wm(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function We(t){let e=new WeakSet,n={};for(let[r,o]of oc(t))n[r]=Ma(o,e);return n}function Ma(t,e){if(t==null)return t;let n=typeof t;if(n==="boolean"||n==="number"||n==="string")return t;if(n==="function")return"<function>";if(Array.isArray(t))return e.has(t)?"<cycle>":(e.add(t),t.map(r=>Ma(r,e)));if(n==="object"){let r=t;if(e.has(r))return"<cycle>";e.add(r);try{if(typeof r.subscribe=="function"&&"cache"in r)return"<Node>"}catch{return"<unserializable>"}let o={};for(let[s,i]of oc(r))o[s]=Ma(i,e);return o}return"<unserializable>"}function oc(t){let e=[],n;try{n=Object.keys(t)}catch{return e}for(let r of n)try{e.push([r,t[r]])}catch{e.push([r,"<unserializable>"])}return e}function be(t,e){let n={factory:t};return e!==void 0&&(n.factoryArgs=e),n}function Um(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Ur(t,e,n){let r=e==null,o=!r&&e!=null?[...e].filter(c=>c.startsWith("meta.")).map(c=>c.slice(5)):null,s=r||e.has("meta")||o!=null&&o.length>0,i="state",a=[];t instanceof Ce&&(i=Wm(t),a=t._deps.map(c=>c.node.name??""));let d={type:i,deps:a};(r||e.has("status"))&&(d.status=t.status);let u=t instanceof Ce?t._guard:void 0;if(s){let c={...Um(t)};if(u!=null&&c.access===void 0&&(c.access=Vr(u)),o!=null&&o.length>0&&!e.has("meta")){let l={};for(let p of o)p in c&&(l[p]=c[p]);d.meta=l}else d.meta=c}if(t.name!=null&&(d.name=t.name),(r||e.has("value"))&&(!n||i==="state")){t.status==="sentinel"&&(d.sentinel=!0);try{d.value=t.cache}catch{}}if((r||e.has("v"))&&t.v!=null){let c={id:t.v.id,version:t.v.version};"cid"in t.v&&(c.cid=t.v.cid,c.prev=t.v.prev),d.v=c}return(r||e.has("guard"))&&u!=null&&(d.guard=Vr(u)),(r||e.has("lastMutation"))&&t.lastMutation!=null&&(d.lastMutation=t.lastMutation),d}var et=Ve(()=>{"use strict";zt();Me()});var sc={};Ne(sc,{NS_PER_MS:()=>Ue,NS_PER_SEC:()=>pt,constant:()=>ss,decorrelatedJitter:()=>us,exponential:()=>as,fibonacci:()=>ds,linear:()=>is,resolveBackoffPreset:()=>vn,withMaxAttempts:()=>Oa});function bn(t){return t<0?0:t}function Jm(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function Ym(t,e){return t+Math.random()*(e-t)}function ss(t){let e=bn(t);return()=>e}function is(t,e){let n=bn(t),r=e===void 0?n:bn(e);return o=>n+r*Math.max(0,o)}function as(t){let e=bn(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=bn(t?.maxDelayNs??30*1e9),o=t?.jitter??"none";return s=>{let i;if(e===0)i=0;else if(n===1)i=e;else{let a=r/e,d=1;for(let u=0;u<Math.max(0,s);u++){if(d>=a){d=a;break}d*=n}i=e*d,i>r&&(i=r)}return Jm(i,o)}}function ds(t=100*1e6,e=30*1e9){let n=bn(t),r=bn(e);function o(s){if(s<=0)return 1;let i=1,a=2;for(let d=1;d<s;d++){let u=i+a;i=a,a=u}return a}return s=>{let i=o(s)*n;return i<=r?i:r}}function us(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return Ym(t,i)}}function Oa(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function vn(t){if(t==="constant")return ss(1*1e9);if(t==="linear")return is(1*1e9);if(t==="exponential")return as();if(t==="fibonacci")return ds();if(t==="decorrelatedJitter")return us();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var Ue,pt,ir=Ve(()=>{"use strict";Ue=1e6,pt=1e9});var De,Et=Ve(()=>{"use strict";De=class{_timer;_gen=0;start(e,n){this.cancel(),this._gen+=1;let r=this._gen;this._timer=setTimeout(()=>{this._timer=void 0,r===this._gen&&n()},e)}cancel(){this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0)}get pending(){return this._timer!==void 0}}});var Pt,cs=Ve(()=>{"use strict";Pt=class{constructor(e){this.capacity=e;if(!Number.isInteger(e)||e<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${e})`);this.buf=new Array(e)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(e){let n=(this.head+this._size)%this.capacity;this.buf[n]=e,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let e=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,e}at(e){if(this._size===0)return;let n=e<0?this._size+e:e;if(!(n<0||n>=this._size))return this.buf[(this.head+n)%this.capacity]}toArray(){let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this.buf[(this.head+n)%this.capacity];return e}clear(){for(let e=0;e<this._size;e++)this.buf[(this.head+e)%this.capacity]=void 0;this.head=0,this._size=0}}});function kn(t){return{describeKind:"derived",...t}}function Qm(t){return t<0?0:t}function Aa(t){return t[1]}function Xm(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function ic(t){let e=t?.count,n=t?.backoff;if(n!==void 0&&e===void 0)throw new RangeError("retry({ backoff }) requires explicit count to prevent unbounded retries; pass { count: <n>, backoff: ... }");let r=e!==void 0?e:0;if(r<0)throw new RangeError("retry count must be >= 0");let o=n===void 0?null:typeof n=="string"?vn(n):n;return{maxRetries:r,strategy:o}}function ac(t){let e={};return t?.count!==void 0&&(e.count=t.count),typeof t?.backoff=="string"&&(e.backoff=t.backoff),Object.keys(e).length>0?e:void 0}function dc(t,e,n){let r=0,o=!1,s=null,i,a=new De;function d(){i?.(),i=void 0}function u(l){if(o)return;if(r>=t.maxRetries){d(),n.down([[L,l]]);return}let p=t.strategy===null?0:t.strategy(r,l,s);if(p==null){d(),n.down([[L,l]]);return}let f;try{f=Xm(p)}catch{d(),n.down([[L,l]]);return}s=f,r+=1,d();let m=f>0?f/1e6:1;a.start(m,()=>{o||c()})}function c(){a.cancel(),d();let l;try{l=e()}catch(p){u(p);return}i=l.subscribe(p=>{if(!o)for(let f of p){let m=f[0];if(m===se)n.down([[se]]);else if(m===_)r=0,s=null,n.emit(f[1]);else if(m===q)n.down([[q]]);else if(m===I)d(),n.down([[I]]);else if(m===L){u(Aa(f));return}else n.down([f])}})}return c(),()=>{o=!0,a.cancel(),d()}}function vt(t,e){return typeof t=="function"?eg(t,e):Zm(t,e)}function Zm(t,e){let n=ic(e);return z(r=>dc(n,()=>t,r),{...kn(),initial:t.cache,meta:{...e?.meta??{},...be("retry",ac(e))}})}function eg(t,e){let n=ic(e);return z(r=>dc(n,t,r),{...kn(),initial:e?.initial,meta:{...e?.meta??{},...be("retry",ac(e))}})}function Tt(t){let e=Math.max(1,t?.failureThreshold??5),n=Qm(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??H,i="closed",a=0,d=0,u=0,c=n,l=0;function p(){if(!r)return n;let h=r(d);return h!==null?h:n}function f(){i="open",c=p(),u=s(),l=0}return{canExecute(){return i==="closed"?!0:i==="open"?s()-u>=c?(i="half-open",l=1,!0):!1:l<o?(l++,!0):!1},recordSuccess(){i==="half-open"?(i="closed",a=0,d=0):i==="closed"&&(a=0)},recordFailure(h){if(i==="half-open"){d++,f();return}i==="closed"&&(a++,a>=e&&f())},get state(){return i},get failureCount(){return a},reset(){i="closed",a=0,d=0,l=0}}}function xn(t,e){let n=e?.onOpen??"skip",r=e?.meta;return o=>{let s=U([],(i,a)=>{function d(){s.meta.breakerState.down([[_,t.state]])}let u=o.subscribe(c=>{for(let l of c){let p=l[0];p===se?a.down([[se]]):p===_?t.canExecute()?(d(),a.emit(l[1])):(d(),n==="error"?a.down([[L,new bt]]):a.down([[q]])):p===q?a.down([[q]]):p===I?(t.recordSuccess(),d(),a.down([[I]])):p===L?(t.recordFailure(Aa(l)),d(),a.down([l])):a.down([l])}});return d(),u},{...kn(),meta:{...r??{},breakerState:t.state,...be("withBreaker",{onOpen:n})},completeWhenDepsComplete:!1,initial:o.cache});return{node:s,breakerState:s.meta.breakerState}}}function Jt(t,e,n){if(t<=0)throw new RangeError("capacity must be > 0");if(e<0)throw new RangeError("refillPerSecond must be >= 0");let r=n?.clock??H,o=t,s=r();function i(a){if(e>0){let d=a-s;o=Math.min(t,o+d/1e9*e)}s=a}return{available(){return i(r()),o},tryConsume(a=1){if(a<=0)return!0;let d=r();return i(d),o>=a?(o-=a,!0):!1},putBack(a=1){a<=0||(i(r()),o=Math.min(t,o+a))}}}function tg(t,e){return t.droppedCount===e.droppedCount&&t.pendingCount===e.pendingCount&&t.paused===e.paused}function Rn(t,e){let{maxEvents:n,windowNs:r}=e;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let o=e.maxBuffer;if(o===void 0)throw new RangeError("rateLimiter requires explicit maxBuffer (use Infinity to opt in to unbounded)");let s=o===1/0;if(!s&&(!Number.isInteger(o)||o<1))throw new RangeError("maxBuffer must be a positive integer (or Infinity for unbounded)");let i=e.onOverflow??"drop-newest",a=n*1e9/r,d=z(u=>{let c=Jt(n,a),l=s?rg():ng(o),p=new De,f=!1,m=0,h=1e9/a,g=d.meta.droppedCount,y=d.meta.rateLimitState,b=ls;function v(){g.emit(m);let S={droppedCount:m,pendingCount:l.size,paused:l.size>0};tg(b,S)||(b=S,y.emit(S))}b=ls,g.emit(0),y.emit(ls);function T(){for(;l.size>0;)if(c.tryConsume(1))u.emit(l.shift()),v();else{p.start(Math.max(1,h/1e6),T);return}}function w(){m+=1,v()}function k(){for(f=!0,p.cancel();l.size>0;)l.shift();m=0}let R=t.subscribe(S=>{for(let x of S){if(f)return;let N=x[0];if(N===se)u.down([[se]]);else if(N===_){if(!s&&l.size>=o)if(i==="drop-newest")w();else if(i==="drop-oldest")l.shift(),l.push(x[1]),w();else{w(),k(),u.down([[L,new Tn(o)]]);return}else l.push(x[1]),v();T()}else if(N===q)u.down([[q]]);else if(N===I)k(),u.down([[I]]);else if(N===L)k(),u.down([x]);else if(N===ce){k(),u.down([x]);return}else u.down([x])}});return()=>{f=!0,p.cancel(),R()}},{...kn(),initial:t.cache,meta:{...e.meta??{},droppedCount:0,rateLimitState:ls,...be("rateLimiter",e)}});return{node:d,droppedCount:d.meta.droppedCount,rateLimitState:d.meta.rateLimitState}}function ng(t){let e=new Pt(t);return{push:n=>e.push(n),shift:()=>e.shift(),get size(){return e.size}}}function rg(){let t=[];return{push:e=>{t.push(e)},shift:()=>t.shift(),get size(){return t.length}}}function Yt(t,e){let n=e?.initialStatus??"pending",r=e?.meta,o=U([],(s,i)=>{let a=n;return o.meta.status.down([[_,n]]),o.meta.error.down([[_,null]]),t.subscribe(u=>{for(let c of u){let l=c[0];if(l===se)i.down([[se]]);else if(l===_)a==="errored"?Z(()=>{o.meta.error.down([[_,null]]),o.meta.status.down([[_,"running"]])}):o.meta.status.down([[_,"running"]]),a="running",i.emit(c[1]);else if(l===q)i.down([[q]]);else if(l===I)o.meta.status.down([[_,"completed"]]),a="completed",i.down([[I]]);else if(l===L){let p=Aa(c);Z(()=>{o.meta.error.down([[_,p]]),o.meta.status.down([[_,"errored"]])}),a="errored",i.down([c])}else i.down([c])}})},{...kn(),meta:{...r??{},status:n,error:null,...be("withStatus",{initialStatus:n})},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:o,status:o.meta.status,error:o.meta.error}}function og(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function sg(t){return t!=null&&typeof t.then=="function"}function ig(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function ar(t,e,n){let r=n?.meta;return z(o=>{let s,i;function a(){i?.(),i=void 0,og(e)||sg(e)||ig(e)?s=Y(e).subscribe(u=>{o.down(u);for(let c of u){let l=c[0];if(l===I||l===L||l===ce){s=void 0;return}}}):(o.emit(e),o.down([[I]]))}return i=t.subscribe(d=>{for(let u of d){let c=u[0];if(c===se)o.down([[se]]);else if(c===_)o.emit(u[1]);else if(c===q)o.down([[q]]);else if(c===I)o.down([[I]]);else if(c===L){a();return}else if(c===ce){s?.(),o.down([u]);return}else o.down([u])}}),()=>{i?.(),s?.()}},{...kn(),initial:t.cache,meta:{...r??{},...be("fallback")}})}function Sn(t,e,n){if(e<=0)throw new RangeError("timeoutNs must be > 0");let r=n?.meta;return z(o=>{let s=!1,i=new De;function a(){let u=e/1e6;i.start(u,()=>{s||(s=!0,d(),o.down([[L,new wn(e)]]))})}let d=t.subscribe(u=>{for(let c of u){if(s)return;let l=c[0];if(l===se)o.down([[se]]);else if(l===_)a(),o.emit(c[1]);else if(l===q)o.down([[q]]);else if(l===I){i.cancel(),s=!0,o.down([[I]]);return}else if(l===L){i.cancel(),s=!0,o.down([c]);return}else if(l===ce){i.cancel(),s=!0,o.down([c]);return}else o.down([c])}});return a(),()=>{s=!0,i.cancel(),d()}},{...kn(),initial:t.cache,meta:{...r??{},...be("timeout",{timeoutNs:e})}})}var bt,Tn,ls,wn,uc=Ve(()=>{"use strict";rc();Ae();Se();ae();et();Me();ne();ir();ue();Et();cs();bt=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};Tn=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};ls=Object.freeze({droppedCount:0,pendingCount:0,paused:!1});wn=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});var cc={};Ne(cc,{CircuitOpenError:()=>bt,RateLimiterOverflowError:()=>Tn,TimeoutError:()=>wn,budgetGate:()=>Wt,circuitBreaker:()=>Tt,fallback:()=>ar,rateLimiter:()=>Rn,retry:()=>vt,timeout:()=>Sn,tokenBucket:()=>Jt,withBreaker:()=>xn,withStatus:()=>Yt});var Gt=Ve(()=>{"use strict";uc()});function ft(t){return{describeKind:"producer",...t}}function La(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function pc(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){t[n+1]==="*"?(e+=".*",n+=1):e+="[^/]*";continue}e+=La(r)}return e+="$",new RegExp(e)}function fc(t,e){for(let n of e)if(n.test(t))return!0;return!1}function ag(t,e){let n=U([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[q]]);return}for(let a of i)s.emit(a)},{describeKind:"derived",initial:t.cache}),r=n.subscribe.bind(n);return n.subscribe=(o,s)=>(e(o),r(o,s)),n}function tt(t,e){let{signal:n,period:r,...o}=e??{};return z(s=>{let i=!1,a=0,d,u,c=()=>{i=!0,d!==void 0&&clearTimeout(d),u!==void 0&&clearInterval(u),n?.removeEventListener("abort",p)},l=()=>{i||(r!=null?(s.emit(a++),u=setInterval(()=>{i||s.emit(a++)},r)):(i=!0,n?.removeEventListener("abort",p),s.emit(a++),s.down([[I]])))},p=()=>{i||(c(),s.down([[L,n.reason]]))};if(n?.aborted){p();return}return d=setTimeout(l,t),n?.addEventListener("abort",p,{once:!0}),c},ft(o))}function mc(t){let{signal:e,...n}=t??{};return z(r=>{let o=!1,s,i,a=!1,d=!1,u=typeof requestAnimationFrame=="function"?requestAnimationFrame:void 0,c=typeof cancelAnimationFrame=="function"?cancelAnimationFrame:void 0,l=typeof document<"u"?document:void 0,p=()=>{s!==void 0&&c&&c(s),i!==void 0&&clearTimeout(i),s=void 0,i=void 0},f=()=>{o=!0,p(),a&&(e?.removeEventListener("abort",m),a=!1),d&&l&&(l.removeEventListener("visibilitychange",y),d=!1)},m=()=>{o||(f(),r.down([[L,e.reason]]))},h=b=>{o||(r.emit(b),g())},g=()=>{o||(u&&(!l||l.visibilityState!=="hidden")?s=u(h):i=setTimeout(()=>h(performance.now()),16))},y=()=>{o||(p(),g())};return e?.aborted?(m(),f):(e?.addEventListener("abort",m,{once:!0}),a=e!==void 0,l&&u&&(l.addEventListener("visibilitychange",y),d=!0),g(),f)},ft(n))}function fs(t,e){let n=rs(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return z(d=>{let u=-1,c=()=>{let p=new Date,f=p.getFullYear()*1e8+(p.getMonth()+1)*1e6+p.getDate()*1e4+p.getHours()*100+p.getMinutes();f!==u&&os(n,p)&&(u=f,d.emit(a?p:oe()))};c();let l=setInterval(c,i);return()=>clearInterval(l)},{...ft(s),name:s.name??`cron:${t}`})}function gc(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return z(a=>{let d=c=>{a.emit(c)},u={capture:r,passive:o,once:s};return t.addEventListener(e,d,u),()=>t.removeEventListener(e,d,u)},ft(i))}function ms(t,e){return z(n=>{let r=!1;try{for(let o of t){if(r)return;n.emit(o)}r||n.down([[I]])}catch(o){r||n.down([[L,o]])}return()=>{r=!0}},ft(e))}function dg(t){return t!=null&&typeof t.then=="function"}function dr(t,e){let{signal:n,...r}=e??{};return z(o=>{let s=!1,i=()=>{s||(s=!0,o.down([[L,n.reason]]))};if(n?.aborted){i();return}return n?.addEventListener("abort",i,{once:!0}),Promise.resolve(t).then(a=>{s||(s=!0,n?.removeEventListener("abort",i),o.emit(a),o.down([[I]]))},a=>{s||(s=!0,n?.removeEventListener("abort",i),o.down([[L,a]]))}),()=>{s=!0,n?.removeEventListener("abort",i)}},ft(r))}function Jr(t,e){let{signal:n,...r}=e??{};return z(o=>{let s=new AbortController,i=()=>s.abort(n?.reason);n?.aborted?s.abort(n.reason):n?.addEventListener("abort",i,{once:!0});let a=n??s.signal,d=!1,u=t[Symbol.asyncIterator](),c=()=>{d||a.aborted||Promise.resolve(u.next()).then(l=>{if(!(d||a.aborted)){if(l.done){o.down([[I]]);return}o.emit(l.value),c()}},l=>{!d&&!a.aborted&&o.down([[L,l]])})};return c(),()=>{d=!0,n?.removeEventListener("abort",i),s.abort(),Promise.resolve(u.return?.()).catch(()=>{})}},ft(r))}function ug(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Y(t,e){if(ug(t))return t;if(dg(t))return dr(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return Jr(t,e);if(typeof n[Symbol.iterator]=="function")return ms(t,e)}return Ia(t)}function Ia(...t){return ms(t,void 0)}function hc(t){return z(e=>{e.down([[I]])},ft(t))}function yc(t){return z(()=>{},ft(t))}function bc(t,e){return z(n=>{n.down([[L,t]])},ft(e))}function vc(t,e){let{signal:n,...r}=e??{},o=ft(r),s=o.resubscribable===void 0?{...o,resubscribable:!0}:o;return z(i=>{let a,d=!1;try{let u=t();a=Y(u,e).subscribe(l=>{if(!d)for(let p of l){let f=p[0];if(f!==mt)if(f===_)i.emit(p[1]);else if(f===I){d=!0,i.down([[I]]);break}else if(f===L){d=!0,i.down([[L,p[1]]]);break}else i.down([p])}})}catch(u){let c=u===void 0?new Error("defer: thunk threw undefined"):u;i.down([[L,c]])}return()=>{d=!0,a?.()}},s)}function Qt(t,e,n){return U([t],(o,s)=>{let i=o[0];if(i!=null&&i.length>0)for(let a of i)e(a)},{describeKind:"effect",...n}).subscribe(()=>{})}function Tc(t,e){return U([t],(n,r,o)=>{o.store.buf||(o.store.buf=[]);let s=o.store.buf,i=n[0];if(i!=null&&i.length>0)for(let a of i)s.push(a);if(o.terminalDeps[0]===!0){r.emit([...s]),r.down([[I]]);return}(i==null||i.length===0)&&r.down([[q]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function wc(t,e){return z(n=>t.subscribe(r=>{n.down(r)}),{...ft(e),initial:t.cache})}function gs(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=z(s=>t.subscribe(i=>{for(let a of i)a[0]===_&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...ft(n),initial:t.cache});return ag(o,s=>{for(let i of r)s([[_,i]])})}function kc(t,e){return gs(t,1,e)}function nt(t){return new Promise((e,n)=>{let r=!1,o=!1,s;s=t.subscribe(i=>{for(let a of i){if(r)return;if(a[0]===_){r=!0,e(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===L){r=!0,n(a[1]),s?(s(),s=void 0):o=!0;return}if(a[0]===I){r=!0,n(new Error("completed without DATA")),s?(s(),s=void 0):o=!0;return}}}),o&&(s?.(),s=void 0)})}function ps(t,e,n){return new Promise((r,o)=>{let s=!1,i=!1,a,d=n?.skipCurrent===!0;a=t.subscribe(u=>{for(let c of u){if(s)return;if(!(d&&c[0]===_)){if(c[0]===_){let l=c[1];if(e(l)){s=!0,r(l),a?(a(),a=void 0):i=!0;return}}if(c[0]===L){s=!0,o(c[1]),a?(a(),a=void 0):i=!0;return}if(c[0]===I){s=!0,o(new Error("completed without matching value")),a?(a(),a=void 0):i=!0;return}}}}),d=!1,i&&(a?.(),a=void 0)})}async function hs(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await ps(t,n,{skipCurrent:r});if(Ca===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(Gt(),cc)),Promise.resolve().then(()=>(ir(),sc))]);Ca=s.timeout,lc=i.NS_PER_MS}let o=Ca(t,e.timeoutMs*lc);return await ps(o,n,{skipCurrent:r})}function ys(t,e){let n=new AbortController,r=e?.reason??new Error("cancelled via nodeSignal"),o,s=!1,i=()=>{o?(o(),o=void 0):s=!0};return o=t.subscribe(a=>{if(!n.signal.aborted)for(let d of a){if(d[0]===_&&d[1]===!0){n.abort(r),i();return}if(d[0]===L){n.abort(d[1]),i();return}if(d[0]===I){i();return}}}),s&&(o?.(),o=void 0),{signal:n.signal,dispose:()=>{o&&(o(),o=void 0)}}}function te(t){return t.subscribe(()=>{})}function Rc(t){let e=O(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[se],[_,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var Ca,lc,xc,Sc=Ve(()=>{"use strict";Se();ae();Me();ne();Ea();xc=gs});var ue=Ve(()=>{"use strict";Sc()});var Nv={};Ne(Nv,{COMPLETE:()=>I,COMPLETE_MSG:()=>zo,COMPLETE_ONLY_BATCH:()=>Lr,CircuitOpenError:()=>bt,ContentAddressedMissError:()=>fo,DATA:()=>_,DEFAULT_ACTOR:()=>Nt,DEFAULT_AUDIT_GUARD:()=>Ka,DIRTY:()=>se,DIRTY_MSG:()=>Ct,DIRTY_ONLY_BATCH:()=>Hn,ENVELOPE_VERSION:()=>Un,ERROR:()=>L,GRAPH_META_SEGMENT:()=>rt,Graph:()=>Q,GraphReFlyConfig:()=>gn,GuardDenied:()=>ut,INVALIDATE:()=>Ze,INVALIDATE_MSG:()=>qo,INVALIDATE_ONLY_BATCH:()=>Cr,JsonCodec:()=>Wo,NS_PER_MS:()=>Ue,NS_PER_SEC:()=>pt,NativeIndexBackend:()=>ho,NativeListBackend:()=>yo,NativeLogBackend:()=>eo,NativeMapBackend:()=>lo,NativePubSubBackend:()=>go,NodeImpl:()=>Ce,PAUSE:()=>Ke,RESOLVED:()=>q,RESOLVED_MSG:()=>qn,RESOLVED_ONLY_BATCH:()=>Ar,RESUME:()=>He,RateLimiterOverflowError:()=>Tn,ResettableTimer:()=>De,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>xs,SNAPSHOT_VERSION:()=>wt,SNAPSHOT_WIRE_VERSION:()=>Vo,START:()=>mt,START_MSG:()=>zn,SurfaceError:()=>Oe,TEARDOWN:()=>ce,TEARDOWN_MSG:()=>Ho,TEARDOWN_ONLY_BATCH:()=>Wn,TimeoutError:()=>wn,accessHintForGuard:()=>Vr,accountability:()=>Gi,advanceVersion:()=>Kr,ai:()=>Ii,appendAudit:()=>lr,appendLogStorage:()=>vd,asSurfaceError:()=>oa,audit:()=>Al,autoTrackNode:()=>hn,awaitSettled:()=>hs,batch:()=>Z,budgetGate:()=>Wt,buffer:()=>Cl,bufferCount:()=>Ll,bufferTime:()=>Dl,bumpCursor:()=>An,cached:()=>kc,canonicalJson:()=>mo,cascadingCache:()=>Kp,catchError:()=>zl,checkpointToRedis:()=>Dp,checkpointToS3:()=>Ip,circuitBreaker:()=>Tt,combine:()=>dd,combineLatest:()=>Vl,compat:()=>id,concat:()=>Rl,concatMap:()=>El,configure:()=>xa,constant:()=>ss,contentAddressedStorage:()=>Xs,core:()=>Ba,cqrs:()=>Gs,createAuditLog:()=>ot,createDagCborCodec:()=>ga,createDagCborZstdCodec:()=>ha,createGraph:()=>Er,createTransport:()=>sn,createVersioning:()=>Xn,createWatermarkController:()=>ur,csvRows:()=>hp,debounce:()=>cd,debounceTime:()=>Kl,decay:()=>Ot,decodeEnvelope:()=>Dr,decorrelatedJitter:()=>us,defaultConfig:()=>$e,defaultHash:()=>Ht,defer:()=>vc,delay:()=>Ml,deleteSnapshot:()=>la,demoShell:()=>$i,derived:()=>A,deserializeError:()=>Pn,dictKv:()=>nf,dictSnapshot:()=>rf,diffForWAL:()=>Ss,diffSnapshots:()=>ua,distill:()=>Ys,distinctUntilChanged:()=>wl,domainMeta:()=>xe,domainTemplates:()=>ji,downWithBatch:()=>It,dynamicNode:()=>qr,effect:()=>ye,elementAt:()=>bl,empty:()=>hc,encodeEnvelope:()=>Ir,escapeRegexChar:()=>La,exhaustMap:()=>Nl,explainPath:()=>Qr,exponential:()=>as,externalBundle:()=>Ws,externalProducer:()=>Ln,extra:()=>kd,factoryTag:()=>be,fallback:()=>ar,fibonacci:()=>ds,filter:()=>st,find:()=>yl,first:()=>Us,firstValueFrom:()=>nt,firstWhere:()=>ps,flatMap:()=>_l,forEach:()=>Qt,fromAny:()=>Y,fromAsyncIter:()=>Jr,fromCSV:()=>gp,fromClickHouseWatch:()=>Tp,fromCron:()=>fs,fromDrizzle:()=>jp,fromEvent:()=>gc,fromHTTP:()=>gd,fromHTTPPoll:()=>tp,fromHTTPStream:()=>ep,fromIter:()=>ms,fromKafka:()=>lp,fromKysely:()=>Bp,fromMCP:()=>op,fromNATS:()=>xp,fromNDJSON:()=>vp,fromOTel:()=>sp,fromPrisma:()=>$p,fromPrometheus:()=>cp,fromPromise:()=>dr,fromPulsar:()=>wp,fromRabbitMQ:()=>Sp,fromRaf:()=>mc,fromRedisStream:()=>fp,fromSSE:()=>Zl,fromSqlite:()=>Pp,fromSqliteCursor:()=>Gp,fromStatsD:()=>dp,fromSyslog:()=>ip,fromTimer:()=>tt,fromWebSocket:()=>md,fromWebSocketReconnect:()=>rp,fromWebhook:()=>Hl,globToRegExp:()=>pc,graph:()=>Xa,graphProfile:()=>En,graphspec:()=>Li,guarded:()=>Vi,harness:()=>Xi,interval:()=>Fl,isBatching:()=>mn,isV1:()=>Ta,jobQueue:()=>Yi,jotai:()=>Qo,jsonCodec:()=>yr,jsonCodecFor:()=>Zp,keepalive:()=>te,kvStorage:()=>ri,last:()=>hl,layout:()=>ta,lens:()=>Zi,lightMutation:()=>dt,linear:()=>is,listSnapshots:()=>ca,lru:()=>bd,makeHttpError:()=>xt,map:()=>so,matchesAnyPattern:()=>fc,matchesCron:()=>os,memory:()=>Mi,memoryAppendLog:()=>tf,memoryBackend:()=>vo,memoryKv:()=>To,memorySnapshot:()=>ef,merge:()=>Mt,mergeMap:()=>ud,mergeReactiveLogs:()=>Kc,messaging:()=>ki,monotonicNs:()=>H,nameToSignal:()=>In,nanostores:()=>ts,ndjsonRows:()=>yp,nestjs:()=>$s,never:()=>yc,node:()=>U,nodeSignal:()=>ys,normalizeActor:()=>Lt,of:()=>Ia,onFirstData:()=>ao,orchestration:()=>xi,pairwise:()=>kl,parseCron:()=>rs,parsePrometheusText:()=>hd,parseSSEStream:()=>Bt,parseStatsD:()=>up,parseSyslog:()=>ap,patterns:()=>Su,pausable:()=>jl,pipe:()=>Ra,placeholderArgs:()=>We,policy:()=>Dt,policyFromRules:()=>Br,process:()=>ea,producer:()=>z,pubsub:()=>Up,race:()=>Sl,rateLimiter:()=>Rn,reachable:()=>Mn,react:()=>js,reactiveCounter:()=>Rc,reactiveIndex:()=>Qp,reactiveList:()=>Zs,reactiveLog:()=>qe,reactiveMap:()=>Ye,reactiveSink:()=>Je,reduce:()=>fl,reduction:()=>Oi,refine:()=>zi,registerBuiltinCodecs:()=>Pr,registerBuiltins:()=>jr,registerCursor:()=>_t,registerCursorMap:()=>Ns,repeat:()=>$l,replay:()=>gs,replayWAL:()=>ya,rescue:()=>uo,resilientPipeline:()=>ra,resolveBackoffPreset:()=>vn,resolveDescribeFields:()=>Ut,restoreSnapshot:()=>da,retry:()=>vt,runReduction:()=>sa,sample:()=>Ol,saveSnapshot:()=>aa,scan:()=>pl,serializeError:()=>Dn,share:()=>wc,shareReplay:()=>xc,signalToName:()=>on,signals:()=>Vs,singleFromAny:()=>ei,singleNodeFromAny:()=>Xp,sizeof:()=>Xr,skip:()=>ad,snapshotStorage:()=>ni,solid:()=>Ks,sortJsonValue:()=>bo,stableJsonString:()=>ti,state:()=>O,stratify:()=>wo,surface:()=>pa,svelte:()=>qs,switchMap:()=>me,take:()=>io,takeUntil:()=>gl,takeWhile:()=>ml,tap:()=>vl,tapFirst:()=>Tl,throttle:()=>ld,throttleTime:()=>ql,throwError:()=>bc,timeout:()=>Sn,toArray:()=>Tc,toCSV:()=>Ep,toClickHouse:()=>_p,toFile:()=>yd,toHTTP:()=>Wl,toKafka:()=>pp,toLoki:()=>Cp,toMongo:()=>Ap,toNATS:()=>Rp,toObservable:()=>ns,toPostgres:()=>Op,toPulsar:()=>kp,toRabbitMQ:()=>Np,toReadableStream:()=>Xl,toRedisStream:()=>mp,toS3:()=>Mp,toSSE:()=>Yl,toSSEBytes:()=>Ql,toSqlite:()=>Fp,toTempo:()=>Lp,toWebSocket:()=>np,tokenBucket:()=>Jt,topologyDiff:()=>cr,tryIncrementBounded:()=>On,validateGraphObservability:()=>Qa,valve:()=>Bl,verifiable:()=>Hp,version:()=>Sv,vue:()=>zs,wallClockNs:()=>oe,watchTopologyTree:()=>Cn,window:()=>Gl,windowCount:()=>Il,windowTime:()=>Pl,withBreaker:()=>xn,withLatestFrom:()=>jt,withMaxAttempts:()=>Oa,withStatus:()=>Yt,workerBridge:()=>Td,workerSelf:()=>wd,wrapMutation:()=>Zt,zip:()=>xl,zustand:()=>Hs});module.exports=Sm(Nv);var id={};Ne(id,{jotai:()=>Qo,nanostores:()=>ts,nestjs:()=>$s,react:()=>js,signals:()=>Vs,solid:()=>Ks,svelte:()=>qs,vue:()=>zs,zustand:()=>Hs});var Qo={};Ne(Qo,{atom:()=>$m});ae();ne();function $m(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?Vu(r,e,n):Vu(r,void 0,e)}return jm(t,e)}function zr(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===_&&(e=i),s===L&&(n=i)})(),n)throw n;return e}function jm(t,e){let n=O(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?zr(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?zr(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===_){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function Vu(t,e,n){let r=hn(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&zr(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?zr(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[d,u]of a)if(d===_){if(i){i=!1;continue}s(u)}})},meta:r.meta,_node:r};if(e){let s=d=>d.get(),i=(d,u)=>d.set(u),a=o;return a.set=d=>e(s,i,d),a.update=d=>{let u=r.status==="sentinel"?zr(r):r.cache;return e(s,i,d(u))},a}return o}var ts={};Ne(ts,{action:()=>Hm,atom:()=>Bm,computed:()=>Vm,getValue:()=>qm,map:()=>Km,onMount:()=>zm,onStart:()=>zu,onStop:()=>Hu});Ae();ae();ne();var Zo=new WeakMap,es=new WeakMap;function Xo(t,e){let n=e.get(t);if(n)for(let r of n)r()}function Sa(t,e={}){let n=0;return{...e,get:()=>qu(t),subscribe:o=>{n===0&&Xo(t,Zo),n++;let s=t.subscribe(i=>{for(let[a,d]of i)a===_&&o(d)});return()=>{s(),n--,n===0&&Xo(t,es)}},listen:o=>{n===0&&Xo(t,Zo),n++;let s=!0,i=t.subscribe(a=>{for(let[d,u]of a)if(d===_){if(s){s=!1;continue}o(u)}});return()=>{i(),n--,n===0&&Xo(t,es)}},_node:t}}function Ku(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===_&&(e=i),s===L&&(n=i)})(),n)throw n;return e}function qu(t){return t.status==="sentinel"?Ku(t):t.cache}function Bm(t){let e=O(t,{resubscribable:!0,resetOnTeardown:!0});return Sa(e,{set:n=>e.emit(n)})}function Vm(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=qr(r,s=>{let i=n.map(a=>{let d=a._node;return d.status==="sentinel"&&Ku(d),s(d)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return Sa(o)}function Km(t){let e=O(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return Sa(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=qu(e);e.emit({...o,[n]:r})}})}function qm(t){return t.get()}function zu(t,e){let n=t._node,r=Zo.get(n);r||(r=new Set,Zo.set(n,r)),r.add(e)}function Hu(t,e){let n=t._node,r=es.get(n);r||(r=new Set,es.set(n,r)),r.add(e)}function zm(t,e){zu(t,()=>{let n=e();typeof n=="function"&&Hu(t,n)})}function Hm(t,e,n){return(...r)=>{let o;return Z(()=>{o=n(...r)}),o}}var $s={};Ne($s,{ACTOR_KEY:()=>vs,COMMAND_HANDLERS:()=>nr,CQRS_EVENT_HANDLERS:()=>rr,CRON_HANDLERS:()=>tr,CommandHandler:()=>Zu,EVENT_HANDLERS:()=>Zn,EventHandler:()=>ec,GRAPHREFLY_REQUEST_GRAPH:()=>yn,GRAPHREFLY_ROOT_GRAPH:()=>gt,GraphCron:()=>Xu,GraphInterval:()=>Qu,GraphReflyEventExplorer:()=>Nn,GraphReflyGuard:()=>Ac,GraphReflyGuardImpl:()=>Yr,GraphReflyModule:()=>Fs,INTERVAL_HANDLERS:()=>er,InjectCqrsGraph:()=>Uu,InjectGraph:()=>Wu,InjectNode:()=>Ju,ObserveGateway:()=>bs,OnGraphEvent:()=>Yu,QUERY_HANDLERS:()=>or,QueryHandler:()=>tc,SAGA_HANDLERS:()=>sr,SagaHandler:()=>nc,fromHeader:()=>Mc,fromJwtPayload:()=>Ga,getActor:()=>Oc,getGraphToken:()=>ct,getNodeToken:()=>yt,observeSSE:()=>Ec,observeSubscription:()=>_c,toObservable:()=>ns});var Na=require("rxjs");ae();function ns(t,e){return e?.raw?new Na.Observable(n=>t.subscribe(o=>{if(!n.closed){n.next(o);for(let s of o){if(s[0]===L){n.error(s[1]);return}if(s[0]===I){n.complete();return}}}})):new Na.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===_)n.next(s[1]);else if(s[0]===L){n.error(s[1]);return}else if(s[0]===I){n.complete();return}}}))}var Hr=require("@nestjs/common");var gt=Symbol.for("graphrefly:root-graph");var yn=Symbol.for("graphrefly:request-graph");function ct(t){return Symbol.for(`graphrefly:graph:${t}`)}function yt(t){return Symbol.for(`graphrefly:node:${t}`)}var Zn=new Map,er=new Map,tr=new Map,nr=new Map,rr=new Map,or=new Map,sr=new Map;function Wu(t){return t==="request"?(0,Hr.Inject)(yn):(0,Hr.Inject)(t?ct(t):gt)}function Uu(t){return(0,Hr.Inject)(ct(t))}function Ju(t){return(0,Hr.Inject)(yt(t))}function Yu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=Zn.get(o)??[];s.push({nodeName:t,methodKey:r}),Zn.set(o,s)})}}function Qu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=er.get(o)??[];s.push({ms:t,methodKey:r}),er.set(o,s)})}}function Xu(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=tr.get(o)??[];s.push({expr:t,methodKey:r}),tr.set(o,s)})}}function Zu(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=nr.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),nr.set(s,i)})}}function ec(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=rr.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),rr.set(s,i)})}}function tc(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=or.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),or.set(s,i)})}}function nc(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=sr.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),sr.set(i,a)})}}ae();ue();var Nc=0,Nn=class{constructor(e,n){this.graph=e;this.moduleRef=n}disposers=[];scheduleNodeNames=[];onModuleInit(){this.wireEvents(),this.wireIntervals(),this.wireCrons(),this.wireCqrsCommands(),this.wireCqrsEvents(),this.wireCqrsQueries(),this.wireCqrsSagas()}onModuleDestroy(){for(let e of this.disposers)e();this.disposers.length=0;for(let e of this.scheduleNodeNames)try{this.graph.remove(e)}catch{}this.scheduleNodeNames.length=0}wireEvents(){for(let[e,n]of Zn){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireEventHandler(r,o)}}wireEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),i=this.observeNode(n.nodeName).subscribe(a=>{for(let d of a)d[0]===_&&o(d[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of er){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireIntervalHandler(r,e,o)}}wireIntervalHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${Nc++}`,d=tt(r.ms,{period:r.ms,name:a});this.graph.add(d),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===_&&s(p[1])});this.disposers.push(c)}wireCrons(){for(let[e,n]of tr){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCronHandler(r,e,o)}}wireCronHandler(e,n,r){let o=e[r.methodKey];if(typeof o!="function")return;let s=o.bind(e),a=`__schedule__.${n.name??"anonymous"}.${String(r.methodKey)}.${Nc++}`,d=fs(r.expr,{name:a});this.graph.add(d),this.scheduleNodeNames.push(a);let c=this.observeNode(a).subscribe(l=>{for(let p of l)p[0]===_&&s(p[1])});this.disposers.push(c)}wireCqrsCommands(){for(let[e,n]of nr){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsCommand(r,o)}}wireCqrsCommand(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.command(n.commandName,o)}wireCqrsEvents(){for(let[e,n]of rr){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsEventHandler(r,o)}}wireCqrsEventHandler(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;s.event(n.eventName);let a=s.resolve(n.eventName).cache,d=a&&a.length>0?a[a.length-1].seq:0,c=this.observeNodeOn(s,n.eventName).subscribe(l=>{for(let p of l)if(p[0]===_){let f=p[1];for(let m of f)m.seq>d&&(o(m),d=m.seq)}});this.disposers.push(c)}wireCqrsQueries(){for(let[e,n]of or){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsQuery(r,o)}}wireCqrsQuery(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);if(!s)return;let a=this.observeNodeOn(s,n.projectionName).subscribe(d=>{for(let u of d)u[0]===_&&o(u[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of sr){let r=this.resolveInstance(e);if(r)for(let o of n)this.wireCqrsSaga(r,o)}}wireCqrsSaga(e,n){let r=e[n.methodKey];if(typeof r!="function")return;let o=r.bind(e),s=this.resolveCqrsGraph(n.cqrsName);s&&s.saga(n.sagaName,n.eventNames,o)}observeNode(e){return this.graph.observe(e)}observeNodeOn(e,n){return e.observe(n)}resolveCqrsGraph(e){try{return this.moduleRef.get(ct(e),{strict:!1})}catch{return console.warn(`[GraphReFly] CqrsGraph "${e}" not found in DI \u2014 did you import GraphReflyModule.forCqrs({ name: "${e}" })?`),null}}resolveInstance(e){try{return this.moduleRef.get(e,{strict:!1})}catch{return null}}};ae();ae();var cg=0;function ur(t,e){if(e.highWaterMark<1)throw new RangeError("highWaterMark must be >= 1");if(e.lowWaterMark<0)throw new RangeError("lowWaterMark must be >= 0");if(e.lowWaterMark>=e.highWaterMark)throw new RangeError("lowWaterMark must be < highWaterMark");let n=Symbol(`bp-${++cg}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[Ke,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[He,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[He,n]]))}}}function Ec(t,e,n){let{actor:r,serialize:o=lg,keepAliveMs:s,signal:i}=n??{},a=new TextEncoder,d,u=n?.highWaterMark!=null,c,l,p=[],f=!1;return new ReadableStream({start(m){let h,g=()=>{},y=()=>{if(!f){f=!0,h!==void 0&&clearInterval(h),i?.removeEventListener("abort",b),g(),c?.dispose(),l?.(),l=void 0;for(let T of p)m.enqueue(T.frame);p.length=0,m.close()}};d=y;let b=()=>y(),v=t.observe(e,{actor:r});u&&(c=ur(T=>v.up(T),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)})),g=v.subscribe(T=>{for(let w of T){if(f)return;let k=w[0];if(k===_){let R=a.encode(Da("data",o(w[1])));u?(p.push({frame:R,counted:!0}),c.onEnqueue(),l?.(),l=void 0):m.enqueue(R)}else if(k===L){let R=a.encode(Da("error",o(w[1])));u?(p.push({frame:R,counted:!1}),l?.(),l=void 0):m.enqueue(R),y();return}else if(k===I||k===ce){if(k===I){let R=a.encode(Da("complete"));u?(p.push({frame:R,counted:!1}),l?.(),l=void 0):m.enqueue(R)}y();return}}}),s!==void 0&&s>0&&(h=setInterval(()=>{f||(u?(p.push({frame:a.encode(`: keepalive
|
|
2
2
|
|
|
3
3
|
`),counted:!1}),l?.(),l=void 0):m.enqueue(a.encode(`: keepalive
|
|
4
4
|
|
|
5
|
-
`)))},s)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(u&&!f){if(p.length>0){let h=p.shift();m.enqueue(h.frame),h.counted&&c.onDequeue();return}return new Promise(h=>{l=h})}},cancel(){try{d?.()}catch{}}})}function
|
|
5
|
+
`)))},s)),i?.aborted?b():i?.addEventListener("abort",b,{once:!0})},pull(m){if(u&&!f){if(p.length>0){let h=p.shift();m.enqueue(h.frame),h.counted&&c.onDequeue();return}return new Promise(h=>{l=h})}},cancel(){try{d?.()}catch{}}})}function _c(t,e,n){let{actor:r,filter:o}=n??{},s=[],i=[],a=!1,d=t.observe(e,{actor:r}),u=n?.highWaterMark!=null?ur(m=>d.up(m),{highWaterMark:n.highWaterMark,lowWaterMark:n.lowWaterMark??Math.floor(n.highWaterMark/2)}):void 0,c=()=>{a||(a=!0,u?.dispose(),p())},l=m=>{if(!a)if(i.length>0){let h=i.shift();m.done&&m.error?h.reject(m.error):m.done?h.resolve({done:!0,value:void 0}):h.resolve({done:!1,value:m.value})}else s.push(m),m.done||u?.onEnqueue()},p=d.subscribe(m=>{for(let h of m){let g=h[0];if(g===_){let y=h[1];if(o&&!o(y))continue;l({done:!1,value:y})}else if(g===L){let y=h[1]instanceof Error?h[1]:new Error(String(h[1]));l({done:!0,error:y}),c();return}else if(g===I||g===ce){l({done:!0}),c();return}}});return{next(){if(s.length>0){let m=s.shift();return m.done||u?.onDequeue(),m.done&&m.error?Promise.reject(m.error):Promise.resolve(m.done?{done:!0,value:void 0}:{done:!1,value:m.value})}return a?Promise.resolve({done:!0,value:void 0}):new Promise((m,h)=>{i.push({resolve:m,reject:h})})},return(){c();for(let m of i)m.resolve({done:!0,value:void 0});return i.length=0,Promise.resolve({done:!0,value:void 0})},throw(m){return c(),Promise.reject(m)},[Symbol.asyncIterator](){return this}}}var bs=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??pg,this.highWaterMark=n?.highWaterMark,this.lowWaterMark=n?.lowWaterMark}clients=new Map;extractActor;parse;highWaterMark;lowWaterMark;handleConnection(e){this.clients.has(e)||this.clients.set(e,new Map)}handleDisconnect(e){let n=this.clients.get(e);if(n){for(let r of n.values())r.wm?.dispose(),r.unsub();this.clients.delete(e)}}handleMessage(e,n,r){let o=r??fg.bind(null,e),s;try{s=typeof n=="string"?this.parse(n):n}catch{o({type:"err",message:"invalid command"});return}s.type==="subscribe"?this.subscribe(e,s.path,o):s.type==="unsubscribe"?this.unsubscribe(e,s.path,o):s.type==="ack"?this.ack(e,s.path,s.count??1):o({type:"err",message:`unknown command type: ${s.type}`})}subscriptionCount(e){return this.clients.get(e)?.size??0}destroy(){for(let[e]of this.clients)this.handleDisconnect(e)}subscribe(e,n,r){let o=this.clients.get(e);if(o||(o=new Map,this.clients.set(e,o)),o.has(n)){r({type:"subscribed",path:n});return}let s=this.extractActor(e),i;try{i=this.graph.observe(n,{actor:s})}catch(c){let l=c instanceof Error?c.message:String(c);r({type:"err",message:l});return}let a=this.highWaterMark!=null?ur(c=>i.up(c),{highWaterMark:this.highWaterMark,lowWaterMark:this.lowWaterMark??Math.floor(this.highWaterMark/2)}):void 0,d=()=>{a?.dispose(),u(),o.delete(n)},u=i.subscribe(c=>{for(let l of c){let p=l[0];if(p===_)a?.onEnqueue(),Pa(r,{type:"data",path:n,value:l[1]});else if(p===L){let f=l[1]instanceof Error?l[1].message:String(l[1]);Pa(r,{type:"error",path:n,error:f}),d();return}else if(p===I||p===ce){Pa(r,{type:"complete",path:n}),d();return}}});o.set(n,{unsub:u,wm:a}),r({type:"subscribed",path:n})}unsubscribe(e,n,r){let o=this.clients.get(e),s=o?.get(n);s&&(s.wm?.dispose(),s.unsub(),o.delete(n)),r({type:"unsubscribed",path:n})}ack(e,n,r){let o=this.clients.get(e)?.get(n);if(!o?.wm)return;let s=Math.min(Math.max(0,Math.floor(r)),1024);for(let i=0;i<s;i++)o.wm.onDequeue()}};function lg(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function Da(t,e){let n=`event: ${t}
|
|
6
6
|
`;if(e!==void 0)for(let r of e.split(`
|
|
7
7
|
`))n+=`data: ${r}
|
|
8
8
|
`;return n+=`
|
|
9
|
-
`,n}function
|
|
10
|
-
`)}function Vm(t,e,n,r,o){let{x:s,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&pc(t,e,s,i,a,o);return}Ut(t,e,s,i,n.boxTL);for(let c=s+1;c<s+a-1;c+=1)Ut(t,e,c,i,n.boxH);Ut(t,e,s+a-1,i,n.boxTR);for(let c=i+1;c<i+d-1;c+=1){Ut(t,e,s,c,n.boxV);for(let l=s+1;l<s+a-1;l+=1)hc(t,e,l,c," ","empty");Ut(t,e,s+a-1,c,n.boxV)}Ut(t,e,s,i+d-1,n.boxBL);for(let c=s+1;c<s+a-1;c+=1)Ut(t,e,c,i+d-1,n.boxH);Ut(t,e,s+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);pc(t,e,s+1,u,a-2,o)}function Ut(t,e,n,r,o){hc(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function hc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=o,e[r][n]=s)}function pc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let d of s){let u=tr(d);if(u!==0){if(a<u)break;i>=0&&i<t[r].length&&(t[r][i]=d,e[r][i]="label",u===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function Km(t,e,n,r){let o=r.points;if(o.length<2)return;for(let d=0;d+1<o.length;d+=1)qm(t,e,n,o[d],o[d+1]);for(let d=1;d+1<o.length;d+=1){let u=o[d-1],c=o[d],l=o[d+1],p=zm(u,c,l,n);p&&mc(t,e,c.x,c.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=Hm(i,s,n);a&&mc(t,e,s.x,s.y,a,"arrow")}function qm(t,e,n,r,o){if(!(r.x===o.x&&r.y===o.y)){if(r.y===o.y){let s=r.y,i=Math.min(r.x,o.x),a=Math.max(r.x,o.x);for(let d=i;d<=a;d+=1)fc(t,e,d,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 d=i;d<=a;d+=1)fc(t,e,s,d,n,"v")}}}function fc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=s==="h"?o.horizontal:o.vertical,e[r][n]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[n]=o.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[n]=o.cross,e[r][n]="edgeCorner";return}}}function mc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,e[r][n]=s)}function zm(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let d=t.x<e.x,u=n.y>e.y;return d&&u?r.cornerTR:d&&!u?r.cornerBR:!d&&u?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function Hm(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function Wm(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function vc(t){let e=Um(t);Jm(e),Ym(e),Qm(e),Xm(e,t);let n=tg(e,t),{width:r,height:o}=rg(e),s=[];for(let i of e.layers)for(let a of i)a.isVirtual||s.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:s,edges:n,width:r,height:o}}function Um(t){let e=new Map;for(let o of t.nodes)e.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(o),h:t.heightCells(o),in:[],out:[]});let n=[],r=0;for(let o of t.edges){if(o.from===o.to)continue;let s=e.get(o.from),i=e.get(o.to);if(!s||!i)continue;let a={chainId:r++,chainFrom:o.from,chainTo:o.to,fromId:o.from,toId:o.to,hopIndex:0,chainLen:1};s.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function Jm(t){let e=new Map;for(let s of t.nodes.values())e.set(s.id,s.in.length);let n=[];for(let s of t.nodes.values())(e.get(s.id)??0)===0&&(s.layer=0,n.push(s));let r=new Set,o=0;for(;o<n.length;){let s=n[o++];if(!r.has(s.id)){r.add(s.id);for(let i of s.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let d=(e.get(a.id)??0)-1;e.set(a.id,d),d<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function Ym(t){let e=Math.max(0,...Array.from(t.nodes.values(),s=>s.layer)),n=Array.from({length:e+1},()=>[]);for(let s of t.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of t.hops){let i=t.nodes.get(s.fromId),a=t.nodes.get(s.toId),d=a.layer-i.layer;if(d<=0){i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);continue}if(d===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);let u=i;for(let l=1;l<d;l+=1){let p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+l,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(p,f),n[f.layer].push(f);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:p,hopIndex:l-1,chainLen:d};u.out.push(m),f.in.push(m),r.push(m),u=f}let c={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:a.id,hopIndex:d-1,chainLen:d};u.out.push(c),a.in.push(c),r.push(c)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function Qm(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)yc(t,t.layers[r],"in"),ls(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)yc(t,t.layers[r],"out"),ls(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<t.layers.length;o+=1){let s=t.layers[o];for(let i=0;i+1<s.length;i+=1){let a=bc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],ls(s),bc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],ls(s))}}if(!r)break}}function yc(t,e,n){let r=new Map;for(let o of e){let s=n==="in"?o.in:o.out;if(s.length===0){r.set(o.id,o.order);continue}let i=0,a=0;for(let d of s){let u=t.nodes.get(n==="in"?d.fromId:d.toId);u&&(i+=u.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}e.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function ls(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function bc(t,e,n,r){let o=r==="in"?e.in:e.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let d of s){let u=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,c=t.nodes.get(r==="in"?d.fromId:d.toId)?.order??0;(e.order<n.order&&u>c||e.order>n.order&&u<c)&&(i+=1)}return i}function Xm(t,e){e.direction==="LR"?Zm(t,e):eg(t,e)}function Zm(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.w);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.x=n[o];for(let o of t.layers){let s=0;for(let i of o)i.y=s,s+=i.h+e.nodeGap}Tc(t,e,"y")}function eg(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.h);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.y=n[o];for(let o of t.layers){let s=0;for(let i of o)i.x=s,s+=i.w+e.nodeGap}Tc(t,e,"x")}function Tc(t,e,n){let r=s=>n==="y"?s.h:s.w,o=e.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let d=new Map;for(let c of a){let l=s===0?c.in:c.out;if(l.length===0)continue;let p=[];for(let m of l){let h=t.nodes.get(s===0?m.fromId:m.toId);if(!h)continue;let g=n==="y"?h.y:h.x;p.push(g+Math.floor(r(h)/2))}if(p.length===0)continue;p.sort((m,h)=>m-h);let f=p[Math.floor(p.length/2)];d.set(c.id,f-Math.floor(r(c)/2))}let u=0;for(let c of a){let l=d.get(c.id),p=n==="y"?c.y:c.x,m=Math.max(l??p,u);n==="y"?c.y=m:c.x=m,u=m+r(c)+o}}}}function tg(t,e){let n=new Map;for(let u of t.hops){let c=n.get(u.chainId);c?c.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((c,l)=>c.hopIndex-l.hopIndex);let r=e.direction==="LR",o=u=>r?u.x:u.y,s=u=>r?u.w:u.h,i=u=>r?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<t.layers.length;u+=1){let c=t.layers[u],l=t.layers[u+1],p=0;for(let S of c)p=Math.max(p,o(S)+s(S));let f=Number.POSITIVE_INFINITY;for(let S of l)f=Math.min(f,o(S));let m=Number.isFinite(f)?f-1:p,h=Math.max(1,m-p+1),g=[];for(let S of c)for(let R of S.out)g.push(R);g.sort((S,R)=>{let E=i(t.nodes.get(S.fromId)),_=i(t.nodes.get(R.fromId));if(E!==_)return E-_;let O=i(t.nodes.get(S.toId)),N=i(t.nodes.get(R.toId));return O-N});let y=[],b=new Map;for(let S of g){let R=i(t.nodes.get(S.fromId)),E=i(t.nodes.get(S.toId)),_=Math.min(R,E),O=Math.max(R,E),N=-1;for(let L=0;L<y.length;L+=1){let j=y[L],$=!0;for(let D of j)if(D.lo<=O&&_<=D.hi){$=!1;break}if($){j.push({lo:_,hi:O}),N=L;break}}N<0&&(y.push([{lo:_,hi:O}]),N=y.length-1),b.set(S,N)}let v=y.length,T=h>=Math.max(3,v+2),w=T?p+1:p,x=T?m-1:m,k=Math.max(1,x-w+1);for(let S of g){let R=b.get(S),E;if(v<=1)E=w+Math.floor(k/2);else{let _=(k-1)/(v-1);E=w+Math.floor(R*_)}a.set(S,Math.max(p,Math.min(m,E)))}}let d=[];for(let[,u]of n){let c=[];for(let p=0;p<u.length;p+=1){let f=u[p],m=t.nodes.get(f.fromId),h=t.nodes.get(f.toId),g=a.get(f),y=m.isVirtual?o(m):o(m)+s(m),b=h.isVirtual?o(h):o(h)-1,v=i(m),T=i(h);p===0&&ps(c,r,y,v),v!==T&&(ps(c,r,g,v),ps(c,r,g,T)),ps(c,r,b,T)}let l=u[0];d.push({from:l.chainFrom,to:l.chainTo,points:ng(c)})}return d}function ps(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function ng(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function rg(t){let e=0,n=0;for(let r of t.layers)for(let o of r)e=Math.max(e,o.x+o.w),n=Math.max(n,o.y+o.h);return{width:e,height:n}}var og=24,sg=4,ig=1,ag=3;function wc(t,e){let n=dg(e.direction),r=Math.max(3,e.maxLabelWidth??og),o=e.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(f=>i.has(f.from)&&i.has(f.to)),d=new Map,u=new Map;for(let f of s){let m=lc(f,r);d.set(f,m),u.set(f,tr(m)+4)}let c=vc({nodes:s,edges:a,widthCells:f=>u.get(f)??3,heightCells:()=>ag,layerGap:sg,nodeGap:ig,direction:n}),l=gc(c,{charset:o,labelOf:f=>d.get(f)??f}),p=e.logger;return p&&p(l),l}function dg(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}function Kr(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return fs(e,n,"no-such-from");if(!s)return fs(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let u=ug(t,e,r);if(u!=null)return u}let d=ms(e,t.nodes[e],0,r);return gs(e,n,[d])}if(i===0)return fs(e,n,"no-path");let a=kc(t,e,n,i);return a.found?gs(e,n,xc(t,a.pathOrder,r)):fs(e,n,a.truncated?"max-depth-exceeded":"no-path")}function kc(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,d=!1;for(;a<s.length;){let l=s[a++];if(l.path===e)break;if(r!=null&&l.depth>=r){let h=t.nodes[l.path];h?.deps&&h.deps.length>0&&(d=!0);continue}let p=t.nodes[l.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let h=0;h<f.length;h++){let g=f[h];if(!g)continue;let y=m.get(g);y==null&&(y=[],m.set(g,y)),y.push(h)}for(let[h,g]of m)i.has(h)||(i.add(h),o.set(h,{from:l.path,depIndices:g}),s.push({path:h,depth:l.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==n;){let l=o.get(c);if(l==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=l.depIndices,u.push({path:l.from}),c=l.from}return{found:!0,pathOrder:u,truncated:!1}}function ug(t,e,n){let r=t.nodes[e];if(r==null)return null;let o=r.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===e&&s.push(a);if(s.length>0){let a=ms(e,r,0,n);a.dep_index=s[0];let d=ms(e,r,1,n);return gs(e,e,[a,d])}let i=null;for(let a=0;a<o.length;a++){let d=o[a];if(!d||d===e)continue;let u=kc(t,d,e,n.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:gs(e,e,xc(t,i.pathOrder,n))}function xc(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=ms(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 ms(t,e,n,r){let o={path:t,type:e.type,hop:n};e.status!==void 0&&(o.status=e.status),"value"in e&&(o.value=e.value),e.v!=null&&(o.v=e.v);let s=r.annotations?.get(t)??e.annotation;s!=null&&(o.annotation=s);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(o.lastMutation=i),o}function gs(t,e,n){return Rc(t,e,!0,"ok",n)}function fs(t,e,n){return Rc(t,e,!1,n,[])}function Rc(t,e,n,r,o){let s=cg(t,e,n,r,o);return{from:t,to:e,found:n,reason:r,steps:o,text:s,toJSON(){return{from:t,to:e,found:n,reason:r,steps:o}}}}function cg(t,e,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let s=[`Causal path: ${t} \u2192 ${e} (${o.length} step(s))`];for(let i of o){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(d),"value"in i&&s.push(` value: ${lg(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(`
|
|
11
|
-
`)}function lg(t){if(t===void 0)return"<sentinel>";if(t===null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(t)}}Me();var $e={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},hs=Symbol.for("sizeof");function qr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=pg(s,e,n,r)}return o}function pg(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return $e.number;case"boolean":return $e.boolean;case"string":return $e.string+t.length*2;case"bigint":return $e.bigint+fg(t);case"symbol":return $e.symbol;case"function":return e.has(t)?0:(e.add(t),$e.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[hs];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 $e.date;if(s instanceof RegExp)return $e.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,c=s.stack?s.stack.length*2:0;return $e.error+u+c}if(typeof URL<"u"&&s instanceof URL)return $e.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return $e.promise;if(s instanceof WeakMap)return $e.weakmap;if(s instanceof WeakSet)return $e.weakset;if(s instanceof Map){let u=$e.map;for(let[c,l]of s)u+=$e.mapEntry,r.push(c),r.push(l);return u}if(s instanceof Set){let u=$e.set;for(let c of s)u+=$e.setEntry,r.push(c);return u}if(Array.isArray(s)){let u=$e.array+s.length*8;for(let c of s)r.push(c);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=$e.object,d=Object.keys(s);for(let u of d){a+=$e.string+u.length*2;try{r.push(s[u])}catch{}}return a}function fg(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function hn(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let i=new Map;for(let[p,f]of o)i.set(p,f);let a=[];for(let[p,f]of Object.entries(r.nodes)){let m=i.get(p),h=m instanceof Oe?m:null,g=h?qr(h.cache):0,y=h?h._sinkCount:0,b=f.deps?.length??0,v=f.type==="effect"&&y===0,T=y===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:g,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let d=a.reduce((p,f)=>p+f.valueSizeBytes,0),u=(p,f)=>[...a].sort(f??((m,h)=>h[p]-m[p])).slice(0,n),c=a.filter(p=>p.orphanKind!=null),l=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:l}}var Ge="::",tt="__meta__",bt=1;function Sc(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let o=t.values().next();if(o.done)return;let s=o.value;t.delete(s);try{s()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function _c(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function mg(t){if(t!=null)return _c(t)?t.cache:t}function gg(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
|
|
12
|
-
`)}function Nc(t){if(t.version!==bt)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${bt})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function hg(t,e){let n=new WeakMap,r=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let i=n.get(o);if(i==null&&(i=new WeakSet,n.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,d=s.constructor;if(a!==d)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,m]of o)if(!p.has(f)||!r(m,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 m=!1;for(let h of p)if(r(f,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let m=0;m<p.length;m++)if(p[m]!==f[m])return!1;return!0}let u=Object.keys(o),c=Object.keys(s);if(u.length!==c.length)return!1;let l=new Set(c);for(let p of u)if(!l.has(p)||!r(o[p],s[p]))return!1;return!0};return r(t,e)}function _a(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(_a);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=_a(e[o]);return r}function yg(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function bg(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function vg(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Mc(t){let e=new Set,n=[];function r(o,s){let i=`${o}\0${s}`;e.has(i)||(e.add(i),n.push([o,s]))}for(let[o,s]of Object.entries(t.nodes)){let i=s.deps;if(i)for(let a of i)r(a,o)}for(let o of t.edges)r(o.from,o.to);return n}function Oc(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function Tg(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,{expand:o,...s}=t,i={...s,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(_a(i),null,e.indent??2);return e.logger?.(a),a}function wg(t,e){let n=e.includeEdges??!0,r=e.includeSubgraphs??!0,o=[];o.push(`Graph ${t.name}`),o.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${bs(a.value)}`)}if(n){o.push("Edges:");for(let i of t.edges)o.push(`- ${i.from} -> ${i.to}`)}if(r){o.push("Subgraphs:");for(let i of t.subgraphs)o.push(`- ${i}`)}let s=o.join(`
|
|
13
|
-
`);return e
|
|
14
|
-
`)}function
|
|
15
|
-
`)}function Rg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ys(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let o=t.indexOf("]",n+1);if(o<=n+1){e+="\\[";continue}let s=t.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,n=o;continue}e+=Rg(r)}return e+="$",new RegExp(e)}var Sg={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"},Ng={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function bs(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function Eg(t){return t==="none"?Ng:t==="ansi"||t==null?Sg:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function Ec(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function _g(t,e,n){for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function Ea(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(Ge))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${Ge}' (path separator)`);if(t===tt)throw new Error(`Graph "${e}": ${n} name "${tt}" is reserved for meta companion paths`);_g(t,e,n)}function Mg(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(Ge);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function Og(t,e){let n=!1;for(let o of t)if(!e.isMetaPassthrough(o[0])){n=!0;break}return n?t.filter(o=>e.isMetaPassthrough(o[0])):t}function Cc(t){for(let e of t._mounts.values())Cc(e);for(let e of t._nodes.values())try{e.down([[le]],{internal:!0})}catch{}}var Q=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(Ge))throw new Error(`Graph name must not contain '${Ge}' (got "${e}")`);if(e===tt)throw new Error(`Graph name "${tt}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??Fe,this._traceRing=new gn(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning),typeof n?.factory=="string"&&(this._factory=n.factory,n.factoryArgs!==void 0&&(this._factoryArgs=n.factoryArgs))}tagFactory(e,n){return this._factory=e,this._factoryArgs=n,this}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=z(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}nameOf(e){return this._nodeToName.get(e)}add(e,n){let r=e.name,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(Ea(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:V()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Oe&&n._applyVersioning(e)}remove(e){Ea(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${Ge}${tt}${Ge}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${Ge}`)),this._mounts.delete(e),n._parent=void 0,Cc(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[le]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=ys(e);return i=>s.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let i=this.remove(s);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let o=e[r++];return{value:[o,n.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(Ge))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[M,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);Z(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Qe]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[I,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[P]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[d,u]of this._nodes)r.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof Oe)for(let c of u._deps){let l=r.get(c.node);l!=null&&a.push([l,d])}return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,d]of o)s.set(d,a);let i=[];for(let[a,d]of o)if(d instanceof Oe)for(let u of d._deps){let c=s.get(u.node);c!=null&&i.push([c,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,n){if(n===void 0){let o=new t(e);return this.mount(e,o)}if(typeof n=="function"){let o=new t(e);return n(o),this.mount(e,o)}let r=n;if(Ea(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let o=this;o!=null;o=o._parent)if(o===r)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,r),r._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),r}resolve(e){let n=Mg(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===tt)return this._resolveMetaChainFromNode(s,o,n.join(Ge));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(Ge)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(Ge))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==tt)throw new Error(`Graph "${this.name}": expected ${tt} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${tt} in "${r}"`);let a=i[s+1],d=o.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=d,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let d of this._mounts.values())d._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=Og(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!r.has(u)){r.add(u);try{u.down(e,i)}catch(c){if(c instanceof dt)throw c;o.push(c)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(d){if(d instanceof dt)throw d;s.push(d)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let n=mg(e?.actor),r=e?.filter,o=Lt(e?.detail,e?.fields),s=e?.format==="spec",i=s?Lt("minimal"):o,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[x,k]of a)d.set(k,x);let u=[];{let x=a.map(([,R])=>R),k=new Set(d.values()),S=0;for(;x.length>0;){let R=x.shift();if(R instanceof Oe)for(let E of R._deps){let _=E.node;if(d.has(_))continue;let O=_.name??"",N=O;if(!N||k.has(N))if(O){let L=2;for(;k.has(`${O}#${L}`);)L++;N=`${O}#${L}`}else for(N=`__internal__/${S++}`;k.has(N);)N=`__internal__/${S++}`;d.set(_,N),k.add(N),u.push([N,_]),x.push(_)}}}let c=[...a,...u],l={};for(let[x,k]of c){if(n!=null&&!k.allowsObserve(n))continue;let S=jr(k,i),R=k instanceof Oe?k._deps.map(N=>d.get(N.node)??N.node.name??""):[],{name:E,..._}=S,O={..._,deps:R};if(!s){let N=this._annotations.get(x);N!=null&&(O.annotation=N)}if(r!=null)if(typeof r=="function"){let N=r;if(!(N.length>=2?N(x,O):N(O)))continue}else{let N=!0;for(let[L,j]of Object.entries(r)){let $=L==="deps_includes"?"depsIncludes":L==="meta_has"?"metaHas":L;if($==="depsIncludes"){if(!O.deps.includes(String(j))){N=!1;break}continue}if($==="metaHas"){if(!Object.hasOwn(O.meta??{},String(j))){N=!1;break}continue}if(O[$]!==j){N=!1;break}}if(!N)continue}l[x]=O}let p=new Set(Object.keys(l)),f=[];for(let[x,k]of c)if(k instanceof Oe)for(let S of k._deps){let R=d.get(S.node);R!=null&&f.push([R,x])}f.sort((x,k)=>x[0]<k[0]?-1:x[0]>k[0]?1:x[1]<k[1]?-1:x[1]>k[1]?1:0);let m=f.map(([x,k])=>({from:x,to:k}));(n!=null||r!=null)&&(m=m.filter(x=>p.has(x.from)&&p.has(x.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(x=>{let k=`${x}${Ge}`;return[...p].some(S=>S===x||S.startsWith(k))}):h,y=this,b=e,v={name:this.name,nodes:l,edges:m,subgraphs:g,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(x){let k={...b,format:void 0};return Array.isArray(x)?(k.fields=x,k.detail=void 0):(k.detail=x,k.fields=void 0),y.describe(k)}},T=e??{},w=T.format;return w==="json"?Tg(v,T):w==="pretty"?wg(v,T):w==="mermaid"?Ac(v,T):w==="mermaid-url"?kg(v,T):w==="d2"?xg(v,T):w==="ascii"?wc(v,T):v}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${Ge}`))}return n}resourceProfile(e){return hn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?yn(this.describe(),e,n,{...r,withDetail:!0}):yn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(e,n,r)}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(o.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return Kr(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=A(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,Fn(()=>{a=!1,!d&&(o+=1,s.emit(o))}))},c=i.onEvent(b=>{let v=b.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||u()}),l=[],p=new WeakSet,f=b=>{if(p.has(b)||d)return;p.add(b);let v=b.topology.subscribe(T=>{for(let w of T){if(w[0]!==M)continue;let x=w[1];if(u(),x.kind==="added"&&x.nodeKind==="mount"){let k=b._mounts.get(x.name);k!=null&&f(k)}}});l.push(v);for(let T of b._mounts.keys()){let w=b._mounts.get(T);w!=null&&f(w)}};f(this);let m,h=e.actor;_c(h)&&(m=h.subscribe(b=>{let v=!1,T=!1;for(let w of b){let x=w[0];x===M?v=!0:(x===P||x===I||x===le)&&(T=!0)}v&&u(),T&&(m?.(),m=void 0,u())}));let g;try{g=C([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(b,v)=>b===v})}catch(b){c(),m?.();for(let v of l)v();throw i.dispose(),b}let y=te(g);return{node:g,dispose(){d=!0,c(),m?.();for(let b of l)b();l.length=0,i.dispose(),y()}}}_describeReactiveDiff(e){let n={...e,format:void 0,reactive:!1},r=e.reactiveName??"describe-diff",o={name:this.name,nodes:{},edges:[],subgraphs:[]},s=this.describe(n),i=er(o,s),a=A(i,{name:r,meta:{domain:"audit",kind:"describe-diff"},equals:(p,f)=>p===f}),d=this._describeReactive({...e,format:void 0,reactiveName:void 0}),u=!1,c=d.node.subscribe(p=>{if(!u)for(let f of p){if(f[0]!==M)continue;let m=f[1],h=er(s,m);s=m,h.events.length!==0&&a.emit(h)}}),l=te(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[le,"describe-diff disposed"]]),l()}}}_explainReactive(e,n,r){let o=0,s=A(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=i.onEvent(f=>{let m=f.type;m!=="data"&&m!=="error"&&m!=="complete"&&m!=="teardown"||a||d||(a=!0,Fn(()=>{a=!1,!d&&(o+=1,s.emit(o))}))}),c={...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{}},l;try{l=C([s],()=>this._explainStatic(e,n,c),{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:e,to:n},equals:(f,m)=>f.found===m.found&&f.reason===m.reason&&f.steps.length===m.steps.length&&Ag(f.steps,m.steps)})}catch(f){throw u(),i.dispose(),f}let p=te(l);return{node:l,dispose(){d=!0,u(),i.dispose(),p()}}}_pathsMatching(e){let n=ys(e),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${Ge}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=e===""?r:`${e}${Ge}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(e,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],i=`${e}${Ge}${tt}${Ge}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Ec(r?n:e);if(s.reactive===!0)return this._observeReactive(r?e:void 0,s);let 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 c=e,l=this.resolve(c);if(a!=null&&!l.allowsObserve(a))throw new dt({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof dt)return;throw f}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,s,"all"):{subscribe:c=>{let l=u.map(([p,f])=>f.subscribe(m=>{c(p,m)}));return()=>{for(let p of l)p()}},up:(c,l)=>{try{this.resolve(c).up?.(l)}catch(p){if(p instanceof dt)return;throw p}}}}_observeReactive(e,n){let r=n.tiers,o=r!=null?new Set(r):null,s=n.reactiveName??"observe";return z(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let h={events:a.slice(),flushedAt_ns:V()};a.length=0,i.emit(h)},l={...n,reactive:!1,structured:!0,timeline:!0},p=e!=null?this.observe(e,l):this.observe(l),f=h=>{u||(a.push(h),!d&&(d=!0,Fn(()=>{d=!1,c()})))};for(let h of p.events)f(h);let m=p.onEvent(f);return()=>{u=!0,m(),p.dispose()}},{name:s,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let c=this.resolve(o);return this._buildStructuredObserver([[o,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",d=this.config.inspectorEnabled,u=(s||i)&&d,c=n.maxEvents,l=c!=null&&c>0?new gn(c):null,p=[],f=new Set,m=n.tiers!=null?new Set(n.tiers):null,h={},g=new Set,y=0,b=0,v=0,T=0,w=0,x=0,k=!1,S=!1,R=0,E=new Map,_=new Map,O=new Map,N=ee=>{if(!(m!=null&&!m.has(ee.type))){l?l.push(ee):p.push(ee);for(let ue of f)ue(ee)}},L=ee=>m==null||m.has(ee),j=()=>o?{timestamp_ns:V(),in_batch:sn(),batch_id:R}:{},$=(ee,ue)=>{if(!(!u||!(ee instanceof Oe)))return ee._setInspectorHook(Ce=>{if(Ce.kind==="dep_message")E.set(ee,Ce.depIndex);else if(Ce.kind==="run"){let Ye=Ce.batchData.map((J,de)=>J!=null&&J.length>0?J.at(-1):Ce.prevData[de]);_.set(ee,Ye);let Be=Ce.batchData.map(J=>J!=null?[...J]:void 0);O.set(ee,Be),i&&N({type:"derived",path:ue,dep_values:Ye,dep_batches:Be,...j()})}})},D=ee=>{let ue=E.get(ee),Ce=_.get(ee);if(!s||Ce==null)return{};let Be=(ue!=null&&ue>=0&&ee instanceof Oe?ee._deps[ue]:void 0)?.node,J=Be?.v,de=O.get(ee);return{trigger_dep_index:ue,trigger_dep_name:Be?.name,...J!=null?{trigger_version:{id:J.id,version:J.version}}:{},dep_values:[...Ce],...de!=null?{dep_batches:de}:{}}},K=[],F=[];for(let[ee,ue]of e){let Ce=$(ue,ee);Ce&&K.push(Ce),F.push(ue.subscribe(Ye=>{R++;for(let Be of Ye){let J=Be[0],de=j();if(J===M){h[ee]=Be[1];let Le=ue instanceof Oe?ue.lastMutation?.actor??xt:xt;N({type:"data",path:ee,data:Be[1],actor:Le,...de,...D(ue)})}else if(a)J===oe?L("dirty")&&y++:J===q?L("resolved")&&b++:J===Qe?L("invalidate")&&v++:J===Ve?L("pause")&&T++:J===ze?L("resume")&&w++:J===le?L("teardown")&&x++:J===P&&!g.has(ee)?L("complete")&&(k=!0):J===I&&L("error")&&(S=!0,g.add(ee));else if(J===oe)L("dirty")&&y++,N({type:"dirty",path:ee,...de});else if(J===q)L("resolved")&&b++,N({type:"resolved",path:ee,...de,...D(ue)});else if(J===Qe)L("invalidate")&&v++,N({type:"invalidate",path:ee,...de});else if(J===Ve)L("pause")&&T++,N({type:"pause",path:ee,lockId:Be[1],...de});else if(J===ze)L("resume")&&w++,N({type:"resume",path:ee,lockId:Be[1],...de});else if(J===P)L("complete")&&!g.has(ee)&&(k=!0),N({type:"complete",path:ee,...de});else if(J===I){L("error")&&(S=!0,g.add(ee));let Le=ue instanceof Oe?ue.lastMutation?.actor??xt:xt;N({type:"error",path:ee,data:Be[1],actor:Le,...de})}else J===le&&(L("teardown")&&x++,N({type:"teardown",path:ee,...de}))}}))}let H=!1,G=()=>{if(!H){H=!0;for(let ee of F)ee();for(let ee of K)ee();for(let ee of re)ee({value:void 0,done:!0});re.length=0}},B=[],re=[];f.add(ee=>{let ue=re.shift();ue?ue({value:ee,done:!1}):B.push(ee)});let pe={get values(){return h},get dirtyCount(){return y},get resolvedCount(){return b},get invalidateCount(){return v},get pauseCount(){return T},get resumeCount(){return w},get teardownCount(){return x},get events(){return l?l.toArray():[...p]},get anyCompletedCleanly(){return k},get anyErrored(){return S},get completedWithoutErrors(){return k&&!S},onEvent(ee){return f.add(ee),()=>f.delete(ee)},dispose:G,expand(ee){G();let ue={...n};return typeof ee=="string"?ue.detail=ee:Object.assign(ue,ee),r(Ec(ue))},[Symbol.asyncIterator](){return{next(){return B.length>0?Promise.resolve({value:B.shift(),done:!1}):H?Promise.resolve({value:void 0,done:!0}):new Promise(ee=>re.push(ee))},return(){return G(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(pe,n),pe}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let o=n.logger??(m=>console.log(m)),s=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:m=>(s==null||s.has(m))&&(i==null||!i.has(m)),d=Eg(n.theme),u=r==="stage-log"?V():0,c=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l(bs(m.data),120):"",f=m=>{if(r==="stage-log"){let k=(V()-u)/1e9,S=c(m.path).padEnd(9);if(m.type==="data"){let R=p(m);return`[${k.toFixed(3)}s] ${S} \u2190${R?` ${R}`:""}`}if(m.type==="error"){let R=p(m);return`[${k.toFixed(3)}s] ${S} \u2717${R?` ${R}`:""}`}return m.type==="complete"?`[${k.toFixed(3)}s] ${S} \u25A0 complete`:`[${k.toFixed(3)}s] ${S} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=d[m.type]??"",g=m.path?`${d.path}${m.path}${d.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${bs(m.data)}`:b?` ${bs(m.lockId)}`:"",T=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",x=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${d.reset}${v}${w}${x}`};e.onEvent(m=>{a(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Sc(this._disposers,this.name),this.signal([[le]],{internal:!0}),Sc(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...c}=r.nodes[a];o[a]=c}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return Nr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??Fe,{codec:o,codecVersion:s,payload:i}=Er(e,r);return o.decode(i,s)}restore(e,n){if(Nc(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>ys(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=e.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let d=this.tryResolve(s)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){Nc(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((m,h)=>{let g=m.split(Ge).length,y=h.split(Ge).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=f.split(Ge),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let i=o?Object.entries(o).map(([f,m])=>({re:ys(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},d=f=>{let m=f.split(Ge),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${f}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${f}"`);g=b}return[g,h]},u=Object.entries(e.nodes).filter(([f])=>!f.includes(`${Ge}${tt}${Ge}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),c=new Map(u),l=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[f,m]of[...c.entries()]){let h=m?.deps??[];if(!h.every(w=>l.has(w)))continue;let[g,y]=d(f),b={...m?.meta??{}},v=a(f),T;if(m?.type==="state")T=A(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:f,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>l.get(w))})}g.add(T,{name:y}),l.set(f,T),c.delete(f),p=!0}}if(c.size>0){let f=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachSnapshotStorage(e,n={}){let r=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(u,c)=>{if(u.disposed)return;let l=gg(c.nodes);if(u.lastSnapshot!=null&&l!==""&&l===u.lastFingerprint)return;let p=u.seq+1,f=se(),g=u.lastSnapshot==null||p%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:f,format_version:bt}:{name:this.name,mode:"diff",diff:Ts(u.lastSnapshot,c),seq:p,timestamp_ns:f,format_version:bt};if(u.tier.filter&&!u.tier.filter(g))return;let y;try{y=u.tier.save(g)}catch(b){n.onError?.(b,u.tier);return}if(y&&typeof y.then=="function"){let T=(u.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l)},w=>{n.onError?.(w,u.tier)});u.savePending=T.finally(()=>{u.savePending===T&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l},s=(u,c)=>{try{o(u,c)}catch(l){n.onError?.(l,u.tier)}},i=(u,c)=>{if(!c.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(u);if(m==null)return;let h=jr(m,Lt("standard"));if(!n.filter(u,h))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?s(m,f()):(m.timer==null&&(m.timer=new Ie),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(f=>i(l,f))});a=()=>{for(let l of c)l()}}else a=this.observe().subscribe((u,c)=>i(u,c));let d=()=>{a();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load?.()}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===bt&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load?.()}catch(d){r?.onError?.(d,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===bt&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(d){r?.onError?.(d,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:V(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],d=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],T=n.nodes[b],w=v.v,x=T.v;w!=null&&x!=null&&w.id===x.id&&w.version!==x.version&&d.push({path:b,id:w.id,from:w.version,to:x.version});let k=w!=null&&x!=null&&w.id===x.id&&w.version===x.version;for(let S of["type","status","sentinel"]){let R=v[S],E=T[S];R!==E&&a.push({path:b,field:S,from:R,to:E})}if(!k)for(let S of["value","meta"]){let R=v[S],E=T[S];hg(R,E)||a.push({path:b,field:S,from:R,to:E})}}let u=b=>`${b.from} ${b.to}`,c=new Set(e.edges.map(u)),l=new Set(n.edges.map(u)),p=n.edges.filter(b=>!c.has(u(b))),f=e.edges.filter(b=>!l.has(u(b))),m=new Set(e.subgraphs),h=new Set(n.subgraphs),g=[...h].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!h.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:y}}};function Ts(t,e){let n=Q.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function yn(t,e,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?o:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=r.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return r.withDetail?o:[];let i=new Map,a=new Map,d=new Map,u=new Map,c=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;c.add(v);let w=T.deps??[];i.set(v,w);for(let x of w)x&&(c.add(x),a.has(x)||a.set(x,new Set),a.get(x).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let T=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!T||!w||(c.add(T),c.add(w),u.has(T)||u.set(T,new Set),u.get(T).add(w),d.has(w)||d.set(w,new Set),d.get(w).add(T))}if(!c.has(e))return r.withDetail?o:[];let l=r.both===!0,p=v=>{if(l){let k=i.get(v)??[],S=d.get(v),R=a.get(v),E=u.get(v),_=[...k];return S&&_.push(...S),R&&_.push(...R),E&&_.push(...E),_}if(n==="upstream"){let k=i.get(v)??[],S=d.get(v);return S?[...k,...S]:k}let T=a.get(v),w=u.get(v),x=T?[...T]:[];return w&&x.push(...w),x},f=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,y=!1;for(;g<h.length;){let v=h[g++];if(s!=null&&v.depth>=s){p(v.path).length>0&&(y=!0);continue}for(let T of p(v.path))!T||f.has(T)||(f.add(T),m.set(T,v.depth+1),h.push({path:T,depth:v.depth+1}))}let b=[...m.keys()].sort((v,T)=>v<T?-1:v>T?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function Ag(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.path!==o.path||r.type!==o.type||r.status!==o.status||r.hop!==o.hop||r.dep_index!==o.dep_index||r.annotation!==o.annotation||r.value!==o.value||r.lastMutation!==o.lastMutation)return!1;let s=r.v,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}var Es={};Se(Es,{CqrsGraph:()=>Ns,cqrs:()=>Pa,cqrsEventKeyOf:()=>Dg,dispatchKeyOf:()=>Gg,sagaInvocationKeyOf:()=>Fg});Ae();Re();Vt();var Ma={};Se(Ma,{COMPLETE:()=>P,COMPLETE_MSG:()=>Go,COMPLETE_ONLY_BATCH:()=>Sr,DATA:()=>M,DEFAULT_ACTOR:()=>xt,DIRTY:()=>oe,DIRTY_MSG:()=>Mt,DIRTY_ONLY_BATCH:()=>Ln,ERROR:()=>I,GraphReFlyConfig:()=>an,GuardDenied:()=>dt,INVALIDATE:()=>Qe,INVALIDATE_MSG:()=>Do,INVALIDATE_ONLY_BATCH:()=>Rr,NodeImpl:()=>Oe,PAUSE:()=>Ve,RESOLVED:()=>q,RESOLVED_MSG:()=>An,RESOLVED_ONLY_BATCH:()=>xr,RESUME:()=>ze,START:()=>ft,START_MSG:()=>Cn,TEARDOWN:()=>le,TEARDOWN_MSG:()=>Fo,TEARDOWN_ONLY_BATCH:()=>In,accessHintForGuard:()=>Ir,advanceVersion:()=>Pr,autoTrackNode:()=>dn,batch:()=>Z,configure:()=>la,createVersioning:()=>$n,defaultConfig:()=>Fe,defaultHash:()=>Kt,derived:()=>C,downWithBatch:()=>At,dynamicNode:()=>Dr,effect:()=>ge,factoryTag:()=>we,isBatching:()=>sn,isV1:()=>da,monotonicNs:()=>V,node:()=>U,normalizeActor:()=>Ot,pipe:()=>pa,placeholderArgs:()=>st,policy:()=>Ct,policyFromRules:()=>Lr,producer:()=>z,registerBuiltins:()=>Cr,resolveDescribeFields:()=>Lt,state:()=>A,wallClockNs:()=>se});Mr();Ae();Re();ia();Vt();ae();it();Me();ne();Bo();Ae();ae();Me();ne();ve();var Hr=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let n=0;n<e.length;n++)this._buf.push(e[n]);this._size=this._buf.length}else{let n=this._maxSize;for(let s=0;s<n;s++)this._buf[s]=void 0;this._head=0;let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function zr(t){return t.subscribe(()=>{})}var Cg=64;function Ke(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:i}=e,a=i??new Hr(t,r),d=A(a.toArray(),{name:n,describeKind:"state",equals:(k,S)=>k===S,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function u(){let k=a.toArray();Z(()=>{d.down([[oe]],{internal:!0}),d.down([[M,k]],{internal:!0})})}let c=new Map,l=new Map,p=new Map;function f(k,S){return`${k}:${S===void 0?"END":S}`}function m(k){if(k.size<Cg)return;let S=k.keys().next();if(S.done)return;let R=k.get(S.value);R!==void 0&&R.dispose(),k.delete(S.value)}function h(k){let S=a.version;try{return k()}finally{a.version!==S&&u()}}function g(k){if(!Number.isInteger(k)||k<0)throw new RangeError(`tail: n must be a non-negative integer (got ${k})`);let S=c.get(k);if(S!==void 0)return c.delete(k),c.set(k,S),S.node;m(c);let R=C([d],([_])=>{let O=_;return k===0||O.length===0?[]:O.slice(Math.max(0,O.length-k))},{initial:a.tail(k),describeKind:"derived"}),E=zr(R);return c.set(k,{node:R,dispose:E}),R}function y(k,S){if(!Number.isInteger(k)||k<0)throw new RangeError(`slice: start must be a non-negative integer (got ${k})`);if(S!==void 0&&(!Number.isInteger(S)||S<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${S})`);let R=f(k,S),E=l.get(R);if(E!==void 0)return l.delete(R),l.set(R,E),E.node;m(l);let _=C([d],([N])=>{let L=N;return S===void 0?L.slice(k):L.slice(k,S)},{initial:a.slice(k,S),describeKind:"derived"}),O=zr(_);return l.set(R,{node:_,dispose:O}),_}function b(k){let S=p.get(k);if(S!==void 0)return S.node;let R=C([d,k],([_,O])=>{let N=_,L=Math.max(0,Math.trunc(O??0));return N.slice(L)},{initial:[],describeKind:"derived"}),E=zr(R);return p.set(k,{node:R,dispose:E}),R}let v,T;function w(){v===void 0&&(v=U([d],(k,S,R)=>{let E=k[0],O=E!=null&&E.length>0?E.at(-1):R.prevData[0];if(O==null||O.length===0){S.down([[q]]);return}S.emit(O[O.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),T=C([d],([k])=>k.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),zr(v),zr(T))}let x={entries:d,get size(){return a.size},at(k){return a.at(k)},append(k){h(()=>a.append(k))},appendMany(k){k.length!==0&&h(()=>a.appendMany(k))},clear(){h(()=>a.clear())},trimHead(k){h(()=>a.trimHead(k))},withLatest(){return w(),d},get lastValue(){return w(),v},get hasLatest(){return w(),T},view(k){switch(k.kind){case"tail":return g(k.n);case"slice":return y(k.start,k.stop);case"fromCursor":return b(k.cursor)}},attach(k){let S=k.subscribe(R=>{for(let E of R)E[0]===M&&x.append(E[1])});return()=>S()},attachStorage(k){if(k.length===0)return()=>{};let S=new Map;for(let E of k)S.set(E,a.size);(async()=>{for(let E of k)if(typeof E.loadEntries=="function")try{let _=await Promise.resolve(E.loadEntries());_.entries.length>0&&a.size===0&&(a.restore(_.entries),S.set(E,_.entries.length),u());break}catch{}})();let R=d.subscribe(E=>{for(let _ of E){if(_[0]!==M)continue;let O=_[1];for(let N of k){let L=S.get(N)??0;if(O.length<L){try{let $=N.appendEntries(O);$ instanceof Promise&&$.catch(()=>{})}catch{}S.set(N,O.length);continue}if(O.length===L)continue;let j=O.slice(L);S.set(N,O.length);try{let $=N.appendEntries(j);$ instanceof Promise&&$.catch(()=>{})}catch{}}}});return()=>R()},disposeAllViews(){for(let k of c.values())k.dispose();c.clear();for(let k of l.values())k.dispose();l.clear();for(let k of p.values())k.dispose();p.clear()},dispose(){for(let k of c.values())k.dispose();c.clear();for(let k of l.values())k.dispose();l.clear();for(let k of p.values())k.dispose();p.clear()}};return x}var Oa=new WeakMap;function Lc(t){let e=Oa.get(t);if(e)return e;let n=t.map(c=>c.cache??[]),r=n.flat(),o=A(r,{name:"mergeReactiveLogs",describeKind:"state",equals:(c,l)=>c===l}),s=t.map((c,l)=>[...n[l]??[]]),i=[];for(let c=0;c<t.length;c++){let l=c,p=t[l].subscribe(f=>{for(let m of f)if(m[0]===M)s[l]=[...m[1]],o.emit(s.flat());else if(m[0]===P){s[l]=[];let h=i[l];h!==void 0&&(i[l]=void 0,h())}else m[0]===I&&o.down([[I,m[1]]])});i.push(p)}let a=te(o),d=!1,u={node:o,dispose(){if(!d){d=!0;for(let c of i)c?.();i.length=0,a(),Oa.delete(t)}}};return Oa.set(t,u),u}var Ca={};Se(Ca,{ENVELOPE_VERSION:()=>Pn,GRAPH_META_SEGMENT:()=>tt,Graph:()=>Q,JsonCodec:()=>$o,SIZEOF_OVERHEAD:()=>$e,SIZEOF_SYMBOL:()=>hs,SNAPSHOT_VERSION:()=>bt,createDagCborCodec:()=>ra,createDagCborZstdCodec:()=>oa,decodeEnvelope:()=>Er,diffForWAL:()=>Ts,encodeEnvelope:()=>Nr,explainPath:()=>Kr,graphProfile:()=>hn,mermaidLiveUrl:()=>vs,reachable:()=>yn,registerBuiltinCodecs:()=>_r,replayWAL:()=>sa,sizeof:()=>qr,validateGraphObservability:()=>Aa,watchTopologyTree:()=>Pt});jo();ae();function Pt(t,e){let n=new Map,r=(o,s)=>{if(n.has(o))return;let i={off:()=>{},prefix:s};n.set(o,i);let a=o.topology.subscribe(d=>{for(let u of d){if(u[0]!==M)continue;let c=u[1];if(e(c,o,s),c.kind==="added"&&c.nodeKind==="mount"){let l=o._mounts.get(c.name);if(l instanceof Q){let p=`${s}${c.name}::`;r(l,p)}}else if(c.kind==="removed"&&c.nodeKind==="mount"){let l=`${s}${c.name}::`;for(let[p,f]of Array.from(n.entries()))p!==t&&f.prefix.startsWith(l)&&(f.off(),n.delete(p))}}});i.off=a;for(let[d,u]of o._mounts)if(u instanceof Q){let c=`${s}${d}::`;r(u,c)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}function Aa(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let u=t.describe(),c=new Set(Object.keys(u.nodes)),l=[];for(let[p,f]of Object.entries(u.nodes))for(let m of f.deps)m!==""&&!c.has(m)&&l.push(`${p} \u2192 ${m}`);for(let p of u.edges)c.has(p.from)||l.push(`edge.from: ${p.from}`),c.has(p.to)||l.push(`edge.to: ${p.to}`);l.length>0?n.push({kind:"describe",ok:!1,reason:`describe() has ${l.length} dangling pointer(s); nodes \u2289 deps`,danglingDeps:l}):n.push({kind:"describe",ok:!0,nodeCount:c.size,edgeCount:u.edges.length})}catch(u){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${u instanceof Error?u.message:String(u)}`})}for(let u of e.formats??[])try{let c=t.describe({format:u});typeof c!="string"||c.length===0?n.push({kind:"describe-format",ok:!1,format:u,reason:`describe({ format: "${u}" }) returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:u,length:c.length})}catch(c){n.push({kind:"describe-format",ok:!1,format:u,reason:c instanceof Error?c.message:String(c)})}for(let u of e.paths??[])try{t.resolve(u),n.push({kind:"observe",ok:!0,path:u})}catch(c){n.push({kind:"observe",ok:!1,path:u,reason:c instanceof Error?c.message:String(c)})}for(let[u,c]of e.pairs??[])try{let l=t.explain(u,c);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:u,to:c,reason:`explain(${u} \u2192 ${c}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:u,to:c,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:u,to:c,reason:l instanceof Error?l.message:String(l)})}let o=n.filter(u=>!u.ok),s=o.length===0,i=e.paths?.length??0,a=e.pairs?.length??0,d=e.formats?.length??0;return{ok:s,checks:n,failures:o,summary(){let u=[e.skipDescribe===!0?null:"describe",d>0?`${d} format${d===1?"":"s"}`:null,i>0?`${i} observe path${i===1?"":"s"}`:null,a>0?`${a} explain pair${a===1?"":"s"}`:null].filter(l=>l!=null),c=u.length>0?u.join(", "):"describe-only";return s?`validateGraphObservability: OK (${c})`:`validateGraphObservability: ${o.length} failure(s) across ${c}`}}}var Jt=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},ws=class extends Jt{constructor(n,r){super(`Duplicate ${n} registration: "${r}"`);this.kind=n;this.registrationName=r}},ks=class extends Jt{constructor(n,r,o){super(`Command "${n}" emitted undeclared event "${r}". Declared emits: [${o.join(", ")}]`);this.commandName=n;this.eventName=r;this.declaredEmits=o}},xs=class extends Jt{constructor(n,r,o){super(`Optimistic concurrency conflict on aggregate "${n}": expected version ${r}, got ${o}`);this.aggregateId=n;this.expected=r;this.actual=o}},Rs=class extends Jt{constructor(n){super(`Unknown command: "${n}". Register with command() first.`);this.commandName=n}},Wr=class extends Jt{constructor(n,r){super(`Command handler "${n}" threw: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.commandName=n}};var Ur=class extends Jt{constructor(n,r){super(`Projection "${n}" rebuild failed: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.projectionName=n}};Ae();Re();Vt();ae();ne();var Lg=Ct((t,e)=>{t("observe"),t("signal"),e("write")});function at(t){let e=Ke([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??Lg,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function La(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))La(t[e]);return Object.freeze(t)}function Jr(t){let e=t.cache,r=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return t.down([[oe],[M,r]]),r}function Ss(t,e,n,r,o,s){let i=e(n,r,o);if(i===void 0)return;let a=s!=null?{...i,handlerVersion:s}:i;t.append(a)}function nt(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(La):o,i=se(),a=e.seq?Jr(e.seq):void 0;try{let d=t(...s);return e.onSuccess&&Ss(e.audit,e.onSuccess,s,d,{t_ns:i,seq:a},e.handlerVersion),d}catch(d){if(e.onFailure){let u=d instanceof Error?d.name:typeof d;Ss(e.audit,e.onFailure,s,d,{t_ns:i,seq:a,errorType:u},e.handlerVersion)}throw d}}}function nr(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(La):o,i=se(),a,d,u=!1,c;try{Z(()=>{e.seq&&(c=Jr(e.seq));try{a=t(...s),e.onSuccess&&Ss(e.audit,e.onSuccess,s,a,{t_ns:i,seq:c},e.handlerVersion)}catch(l){throw d=l,u=!0,l}})}catch(l){if(u&&e.onFailure){let p=d instanceof Error?d.name:typeof d;Ss(e.audit,e.onFailure,s,d,{t_ns:i,seq:c,errorType:p},e.handlerVersion)}throw u?d:l}return a}}function Yt(t,e,n=0){let r=A(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function Ic(t,e,n,r=0){let o={},s=new Q(e);for(let i of n){let a=A(r,{name:i,describeKind:"state"});s.add(a,{name:i}),o[i]=a}return t.mount(e,s),o}Ae();ae();Me();ve();function vt(t,e){t!=null&&At(n=>t.down(n),[[M,e]],Fe.tierOf)}function Yr(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[oe],[M,n+1]]),!0)}function We(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}function Qr(t){return t.relatedTo?.[0]??t.summary}var Ig=Ct((t,e)=>{t("write"),t("signal"),e("observe")}),Pg=Ct((t,e)=>{t("observe"),t("signal"),e("write")}),Pc=Ct((t,e)=>{t("observe"),t("signal"),e("write")});function Xr(t,e){return We("cqrs",t,e)}function Ia(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))Ia(t[e]);return Object.freeze(t)}var Dg=t=>`${t.type}::${t.aggregateId??"__default__"}`,Gg=t=>t.commandName,Fg=t=>t.eventType,Ns=class extends Q{_eventLogs=new Map;_eventLogsByAggregate=new Map;_aggregateVersions=new Map;_aggregateLru=new Map;_commandRegs=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_seq=0;_retainedLimit;_freezeCommandPayload;_freezeEventPayload;_maxAggregates;_dispatchSeqCursor;dispatches;audit;aggregateEvictions;constructor(e,n={}){super(e,n.graph),this._retainedLimit=n.retainedLimit??1024,this._freezeCommandPayload=n.freezeCommandPayload??!0,this._freezeEventPayload=n.freezeEventPayload??!0,this._maxAggregates=n.maxAggregates??1e4,this.dispatches=at({name:"dispatches",retainedLimit:this._retainedLimit,graph:this}),this.audit=this.dispatches,this.aggregateEvictions=at({name:"aggregateEvictions",retainedLimit:this._retainedLimit,graph:this}),this._dispatchSeqCursor=Yt(this,"dispatch_seq",0)}aggregateVersion(e,n){return this._aggregateVersions.get(`${e}::${n}`)??0}_touchAggregate(e){this._aggregateLru.delete(e),this._aggregateLru.set(e,!0)}_enforceAggregateLru(){for(;this._aggregateLru.size>this._maxAggregates;){let e=this._aggregateLru.keys().next();if(e.done)break;let n=e.value;this._aggregateLru.delete(n);let r=n.indexOf("::");if(r<0)continue;let o=n.slice(0,r),s=n.slice(r+2),i=this._aggregateVersions.get(n)??0;this._aggregateVersions.delete(n);let a=this._eventLogsByAggregate.get(o);a&&(a.delete(s),a.size===0&&this._eventLogsByAggregate.delete(o)),this.aggregateEvictions.append({aggregateId:s,type:o,lastVersion:i,t_ns:se()})}}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}_attachedEventTiers=[];_attachedTierDisposers=new Map;attachEventStorage(e){this._attachedEventTiers.push(e);for(let[n,r]of this._eventLogs){let o=r.log.attachStorage(e),s=this._attachedTierDisposers.get(n);s||(s=[],this._attachedTierDisposers.set(n,s)),s.push(o)}for(let[n,r]of this._eventLogsByAggregate)for(let[o,s]of r){let i=`${n}::${o}`,a=s.log.attachStorage(e),d=this._attachedTierDisposers.get(i);d||(d=[],this._attachedTierDisposers.set(i,d)),d.push(a)}return()=>{let n=this._attachedEventTiers.indexOf(e);n>=0&&this._attachedEventTiers.splice(n,1)}}_autoWireStreamStorage(e,n){if(this._attachedEventTiers.length===0)return;let r=this._attachedTierDisposers.get(e);r||(r=[],this._attachedTierDisposers.set(e,r));for(let o of this._attachedEventTiers)r.push(n.attachStorage(o))}_bumpDispatchSeq(){let n=(this._dispatchSeqCursor.cache??0)+1;return this._dispatchSeqCursor.emit(n),n}event(e,n){if(n!==void 0)return this._ensureAggregateStream(e,n).node;let r=this._eventLogs.get(e);if(r)return r.node;let o=Ke([],{name:e,versioning:0,maxSize:this._retainedLimit});o.withLatest();let s=o.entries,i=C([s],([a])=>a,{name:e,describeKind:"state",meta:Xr("event",{event_name:e}),guard:Pc,initial:s.cache});return this.add(i,{name:e}),this._keepaliveDisposers.push(te(i)),this._eventLogs.set(e,{log:o,node:i}),this._autoWireStreamStorage(e,o),i}_ensureAggregateStream(e,n){this._eventLogs.has(e)||this.event(e);let r=this._eventLogsByAggregate.get(e);r||(r=new Map,this._eventLogsByAggregate.set(e,r));let o=`${e}::${n}`;this._touchAggregate(o);let s=r.get(n);if(s)return s;let i=`${e}_${n.replace(/[^a-zA-Z0-9_-]/g,"_")}`,a=Ke([],{name:i,versioning:0,maxSize:this._retainedLimit});a.withLatest();let d=a.entries,u=C([d],([f])=>f,{name:i,describeKind:"state",meta:Xr("event_aggregate",{event_name:e,aggregate_id:n}),guard:Pc,initial:d.cache}),c=i,l=0;for(;this.nameOf(this.resolveOptional(c)??u)===c&&(l+=1,c=`${i}_${l}`,this.resolveOptional(c)!==void 0););try{this.add(u,{name:c})}catch{}this._keepaliveDisposers.push(te(u));let p={log:a,node:u};return r.set(n,p),this._autoWireStreamStorage(`${e}::${n}`,a),this._enforceAggregateLru(),p}resolveOptional(e){try{return this.resolve(e)}catch{return}}_appendEvent(e,n,r){let o=this._eventLogs.get(e);if(o||(this.event(e),o=this._eventLogs.get(e)),o.node.status==="completed"||o.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${o.node.status}).`);let s,i;if(r?.aggregateId!==void 0){let c=`${e}::${r.aggregateId}`;s=(this._aggregateVersions.get(c)??0)+1,this._aggregateVersions.set(c,s),i=this._ensureAggregateStream(e,r.aggregateId)}let a=o.log.entries.v,d=this._freezeEventPayload?Ia(n):n,u={type:e,payload:d,timestampNs:se(),seq:++this._seq,...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...s!==void 0?{aggregateVersion:s}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...r?.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{},...a!=null?{v0:{id:a.id,version:a.version}}:{}};return o.log.append(u),i&&i.log.append(u),u}command(e,n){if(this._commandRegs.has(e))throw new ws("command",e);let r=typeof n=="function"?{handler:n}:n,o=A(void 0,{name:e,describeKind:"state",meta:{...Xr("command",{command_name:e}),error:null},guard:Ig});if(this.add(o,{name:e}),this._commandRegs.set(e,{handler:r.handler,...r.emits!==void 0?{emits:r.emits}:{},...r.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{}}),r.emits)for(let s of r.emits)this._eventLogs.has(s)||this.event(s);return o}dispatch(e,n,r){let o=this._commandRegs.get(e);if(!o)throw new Rs(e);if(r?.aggregateId!==void 0&&r.expectedAggregateVersion!==void 0&&o.emits!==void 0){let p=0;for(let f of o.emits){let m=this._aggregateVersions.get(`${f}::${r.aggregateId}`);m!==void 0&&m>p&&(p=m)}if(p!==r.expectedAggregateVersion)throw new xs(r.aggregateId,r.expectedAggregateVersion,p)}let s=this.resolve(e),i=this._freezeCommandPayload?Ia(n):n,a=[],d=se(),u=0,c,l=!1;try{Z(()=>{u=this._bumpDispatchSeq(),s.emit(i,{internal:!0});try{o.handler(i,{emit:(p,f)=>{if(o.emits!==void 0&&!o.emits.includes(p))throw new ks(e,p,o.emits);a.push(p),this._appendEvent(p,f,{...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}}),s.meta.error.emit(null,{internal:!0}),this.dispatches.append({commandName:e,payload:i,status:"success",emittedEvents:[...a],t_ns:d,seq:u,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}catch(p){throw c=p,l=!0,p}})}catch(p){if(l){s.meta.error.emit(c,{internal:!0});let f=c instanceof Error?c.name:typeof c,m=c instanceof Wr?c:new Wr(e,c);this.dispatches.append({commandName:e,payload:i,status:"failed",error:m,errorType:f,emittedEvents:[...a],t_ns:d,seq:u,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}throw l?c:p}}projection(e){let{name:n,events:r,reducer:o,initial:s}=e,i=e.mode??"scan",a=e.freezeInputs??!0,d=e.snapshot,u=r.map(E=>(this._eventLogs.has(E)||this.event(E),this._eventLogs.get(E).node));function c(E){E.sort((_,O)=>_.timestampNs-O.timestampNs||_.seq-O.seq||(_.aggregateId??"").localeCompare(O.aggregateId??""))}function l(E){let _=[];for(let O of E)_.push(...O);return c(_),_}let p=u.map(E=>E.cache??[]),f=l(p),m=a?Object.freeze(f):f,h=0,g=s;i==="scan"&&f.length>0&&(g=o(s,m),h=f.length);let y=i==="replay"?o(s,m):g,b=d?.saveDebounceMs??1e3,v=d?.saveEvery??1e3,T,w=0;function x(E){if(d?.save){if(w+=1,w>=v){w=0,T!==void 0&&(clearTimeout(T),T=void 0);let _=d.save(E);_ instanceof Promise&&_.catch(()=>{});return}T!==void 0&&clearTimeout(T),T=setTimeout(()=>{T=void 0,w=0;let _=d.save(E);_ instanceof Promise&&_.catch(()=>{})},b)}}let k=C(u,E=>{let _=l(E),O;if(i==="replay"){let N=a?Object.freeze(_):_;O=o(s,N)}else{let N=_.slice(h);h=_.length;let L=a?Object.freeze(N):N;O=o(g,L),g=O}return x(O),O},{name:n,describeKind:"derived",meta:Xr("projection",{projection_name:n,source_events:r}),guard:Pg,initial:y});return this.add(k,{name:n}),this._keepaliveDisposers.push(te(k)),this._keepaliveDisposers.push(()=>{T!==void 0&&(clearTimeout(T),T=void 0)}),this._projections.add(n),{node:k,rebuild:async E=>{try{let _=E?.pageSize??1e3,O=E?.fromTier??this._attachedEventTiers[0]?.[0],N=l(u.map(j=>j.cache??[])).length,L=s;if(d?.load){let j=await d.load();j!==void 0&&(L=j)}if(!O||!O.loadEntries){let j=l(u.map(D=>D.cache??[])),$=a?Object.freeze(j):j;L=o(L,$)}else{let j=new Set(r),$,D=!1;for(;!D;){let K=await O.loadEntries({cursor:$,pageSize:_}),F=[...K.entries].filter(G=>j.has(G.type));c(F);let H=a?Object.freeze(F):F;L=o(L,H),$=K.cursor,D=!$||K.entries.length===0}}if(i==="scan"){let j=l(u.map(D=>D.cache??[])),$=j.slice(N);if($.length>0){let D=a?Object.freeze($):$;L=o(L,D)}g=L,h=j.length}return k.emit(L,{internal:!0}),L}catch(_){throw new Ur(n,_)}},reset:async()=>{try{let E=s;if(d?.load){let L=await d.load();L!==void 0&&(E=L)}let _=l(u.map(L=>L.cache??[])),O=a?Object.freeze(_):_,N=o(E,O);return i==="scan"&&(g=N,h=_.length),k.emit(N,{internal:!0}),N}catch(E){throw new Ur(n,E)}}}}saga(e,n,r,o={}){let s=n.map(f=>(this._eventLogs.has(f)||this.event(f),this._eventLogs.get(f).node)),i=Ic(this,`${e}_cursor`,n,0),a=at({name:`${e}_invocations`,retainedLimit:this._retainedLimit,graph:this}),d=o.aggregateId,u=o.errorPolicy??"advance",c=new Map;for(let f of n){let m=i[f];c.set(f,m.cache??0);let h=m.subscribe(g=>{for(let y of g)y[0]===M&&c.set(f,y[1])});this._keepaliveDisposers.push(h)}let l={},p=U(s,(f,m)=>{let h=l.n.meta.error;for(let g=0;g<f.length;g++){let y=f[g];if(y==null||y.length===0)continue;let b=y.at(-1);if(!b)continue;let v=n[g],T=i[v],w=c.get(v)??0;if(b.length>w){let x=b.slice(w),k=w;for(let S of x){let R=S;if(d!==void 0&&R.aggregateId!==d){k+=1;continue}try{r(R),h.emit(null,{internal:!0}),a.append({eventType:v,status:"success",aggregateId:R.aggregateId,event:R,t_ns:se(),...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),k+=1}catch(E){if(h.emit(E,{internal:!0}),a.append({eventType:v,status:"failed",error:E,errorType:E instanceof Error?E.name:typeof E,aggregateId:R.aggregateId,event:R,t_ns:se(),...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),u==="hold")break;k+=1}}T.emit(k)}}},{name:e,describeKind:"effect",meta:{...Xr("saga",{saga_name:e,source_events:n}),error:null}});return l.n=p,this.add(p,{name:e}),this._keepaliveDisposers.push(te(p)),this._sagas.add(e),{node:p,invocations:a,audit:a,cursors:i}}};function Pa(t,e){let n=new Ns(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("cqrs",st(s)),n}var Ga=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},Fa=class{graph=new Q("request");onModuleDestroy(){this.graph.destroy()}},Dc,Da;Dc=[(0,Zr.Module)({})];var Qt=class Qt{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:mt,useFactory:()=>{let s=new Q(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new Ga(s),inject:[mt]},{provide:mn,useFactory:(s,i)=>new mn(s,i),inject:[mt,Gc.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:ht(s),useFactory:i=>i.resolve(s),inject:[mt]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new Fa,scope:Zr.Scope.REQUEST},{provide:un,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:Zr.Scope.REQUEST}),{module:Qt,global:!0,providers:o,exports:[mt,...(n.nodes??[]).map(ht),...n.requestScope?[un]:[]]}}static forFeature(e){let n=[{provide:ut(e.name),useFactory:r=>{let o=new Q(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),r.mount(e.name,o),o},inject:[mt]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ht(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[ut(e.name)]});return{module:Qt,providers:n,exports:[ut(e.name),...(e.nodes??[]).map(r=>ht(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:ut(e.name),useFactory:r=>{let o=Pa(e.name,e.cqrs);return e.eventStorage&&o.attachEventStorage(e.eventStorage),e.build&&e.build(o),r.mount(e.name,o),o},inject:[mt]}];if(e.nodes)for(let r of e.nodes)n.push({provide:ht(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[ut(e.name)]});return{module:Qt,providers:n,exports:[ut(e.name),...(e.nodes??[]).map(r=>ht(`${e.name}::${r}`))]}}};Da=mu(null),Qt=yu(Da,0,"GraphReflyModule",Dc,Qt),hu(Da,1,Qt);var _s=Qt;var Os={};Se(Os,{useStore:()=>$g,useSubscribe:()=>Fc,useSubscribeRecord:()=>jg});var Dt=require("react");ae();function Fc(t){return(0,Dt.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function $g(t){let e=Fc(t),n=(0,Dt.useCallback)(r=>{t.down([[oe],[M,r]])},[t]);return[e,n]}function jg(t,e){let n=(0,Dt.useRef)(e);n.current=e;let r=(0,Dt.useMemo)(()=>{let o=()=>{let i={},a=t.cache??[];for(let d of a){let u=n.current(d),c={};for(let l of Object.keys(u))c[l]=u[l].cache;i[d]=c}return i},s=o();return{subscribe:i=>{let a=!1,d=[],u=()=>{for(let p of d)p();d=[]},c=p=>{u();for(let f of p){let m=n.current(f);for(let h of Object.keys(m)){let g=m[h].subscribe(()=>{s=o(),a||i()});d.push(g)}}s=o(),a||i()},l=t.subscribe(p=>{let f=p.some(m=>m[0]===M||m[0]===q);!a&&f&&c(t.cache??[])});return c(t.cache??[]),()=>{a=!0,l(),u()}},getSnapshot:()=>s}},[t]);return(0,Dt.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var Cs={};Se(Cs,{Signal:()=>Bg});Ae();ae();ne();var rr=[];function As(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===M&&(e=s)})(),e}var $a=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=A(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=rr[rr.length-1];return e?(this._node.status==="sentinel"&&As(this._node),e(this._node)):this._node.status==="sentinel"?As(this._node):this._node.cache}set(e){this._equals(this.get(),e)||Z(()=>{this._node.down([[oe],[M,e]])})}},ja=class{_node;constructor(e,n){this._node=dn(r=>{rr.push(r);try{return e()}finally{rr.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=rr[rr.length-1];return e?(this._node.status==="sentinel"&&As(this._node),e(this._node)):this._node.status==="sentinel"?As(this._node):this._node.cache}},Bg={State:$a,Computed:ja,sub:(t,e)=>{let n=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,r=!0;return t._node.subscribe(o=>{for(let[s,i]of o){if(s===M){if(r){r=!1;continue}n.data?.(i)}s===I&&n.error?.(i),s===P&&n.complete?.()}})}};var Ls={};Se(Ls,{useStore:()=>Vg,useSubscribe:()=>$c,useSubscribeRecord:()=>Kg});var Gt=require("solid-js");ae();function $c(t){let[e,n]=(0,Gt.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,Gt.getOwner)()?(0,Gt.onCleanup)(()=>r()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),e}function Vg(t){return[$c(t),r=>{t.down([[oe],[M,r]])}]}function Kg(t,e){let[n,r]=(0,Gt.createSignal)({},{equals:!1}),o=[],s=()=>{for(let u of o)u();o=[]},i=()=>{let u={};for(let c of t.cache??[]){let l=e(c),p={};for(let f of Object.keys(l))p[f]=l[f].cache;u[c]=p}return u},a=u=>{s();for(let c of u){let l=e(c);for(let p of Object.keys(l)){let f=l[p].subscribe(()=>{r(()=>i())});o.push(f)}}r(()=>i())},d=t.subscribe(u=>{u.some(c=>c[0]===M||c[0]===q)&&a(t.cache??[])});return a(t.cache??[]),(0,Gt.getOwner)()?(0,Gt.onCleanup)(()=>{d(),s()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),n}var Is={};Se(Is,{useStore:()=>zg,useSubscribe:()=>qg,useSubscribeRecord:()=>Hg});ae();function qg(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function zg(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[oe],[M,e]])},update(e){let n=e(t.cache);t.down([[oe],[M,n]])}}}function Hg(t,e){return{subscribe(n){let r=[],o=()=>{for(let d of r)d();r=[]},s=()=>{let d={};for(let u of t.cache??[]){let c=e(u),l={};for(let p of Object.keys(c))l[p]=c[p].cache;d[u]=l}return d},i=d=>{o();for(let u of d){let c=e(u);for(let l of Object.keys(c)){let p=c[l].subscribe(()=>{n(s())});r.push(p)}}n(s())},a=t.subscribe(d=>{d.some(u=>u[0]===M||u[0]===q)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var Ps={};Se(Ps,{useStore:()=>Ug,useSubscribe:()=>Wg,useSubscribeRecord:()=>Jg});var qe=require("vue");ae();function Wg(t){let e=(0,qe.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,qe.getCurrentScope)()?(0,qe.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,qe.readonly)(e)}function Ug(t){let e=(0,qe.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,qe.getCurrentScope)()?(0,qe.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,qe.computed)({get:()=>e.value,set:r=>{t.down([[oe],[M,r]])}})}function Jg(t,e){let n=(0,qe.shallowRef)({}),r=new Map;function o(){let a={};for(let[d,u]of r)a[d]={...u.values};n.value=a}function s(a){for(let u of r.values())for(let c of u.subs)c();r.clear();for(let u of a){let c=e(u),l=Object.keys(c),p={},f=[];for(let m of l){let h=c[m];p[m]=h.cache;let g=h.subscribe(()=>{p[m]=h.cache,o()});f.push(g)}r.set(u,{subs:f,values:p})}let d={};for(let[u,c]of r)d[u]={...c.values};n.value=d}return(0,qe.watch)(()=>[...(typeof t=="function"?t():(0,qe.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,qe.getCurrentScope)()?(0,qe.onScopeDispose)(()=>{for(let a of r.values())for(let d of a.subs)d();r.clear()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,qe.readonly)(n)}var Ds={};Se(Ds,{create:()=>Qg});ae();ne();var Yg=()=>!1;function Qg(t){let e=new Q("zustand"),n=A(void 0,{name:"state",equals:Yg});e.add(n,{name:"state"});let r=()=>n.cache,o=(a,d)=>{let u=n.cache,c=typeof a=="function"?a(u):a;n.emit(d?c:{...u,...c})},s={getState:r,setState:o,getInitialState:()=>i,subscribe:a=>{let d=!0,u=n.cache;return n.subscribe(c=>{for(let[l,p]of c)if(l===M){if(d){d=!1;continue}a(p,u),u=p}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var rd={};Se(rd,{CircuitOpenError:()=>yt,ContentAddressedMissError:()=>ao,NS_PER_MS:()=>He,NS_PER_SEC:()=>lt,NativeIndexBackend:()=>lo,NativeListBackend:()=>po,NativeLogBackend:()=>Hr,NativeMapBackend:()=>so,NativePubSubBackend:()=>co,RateLimiterOverflowError:()=>ln,ResettableTimer:()=>Ie,TimeoutError:()=>pn,appendLogStorage:()=>ed,audit:()=>al,awaitSettled:()=>as,buffer:()=>dl,bufferCount:()=>ul,bufferTime:()=>ll,cached:()=>nc,canonicalJson:()=>uo,cascadingCache:()=>vp,catchError:()=>wl,checkpointToRedis:()=>lp,checkpointToS3:()=>cp,circuitBreaker:()=>Nt,combine:()=>Ka,combineLatest:()=>bl,concat:()=>el,concatMap:()=>rl,constant:()=>Qo,contentAddressedStorage:()=>Vs,createTransport:()=>Zt,createWatermarkController:()=>Zn,csvRows:()=>Hl,debounce:()=>za,debounceTime:()=>vl,decorrelatedJitter:()=>ts,defer:()=>Zu,delay:()=>sl,deserializeError:()=>wn,dictKv:()=>Cp,dictSnapshot:()=>Lp,distill:()=>js,distinctUntilChanged:()=>Qc,elementAt:()=>Uc,empty:()=>Yu,escapeRegexChar:()=>va,exhaustMap:()=>nl,exponential:()=>Zo,externalBundle:()=>Gs,externalProducer:()=>bn,fallback:()=>Yn,fibonacci:()=>es,filter:()=>rt,find:()=>Wc,first:()=>Fs,firstValueFrom:()=>et,firstWhere:()=>rs,flatMap:()=>ol,forEach:()=>Wt,fromAny:()=>Y,fromAsyncIter:()=>Br,fromCSV:()=>zl,fromClickHouseWatch:()=>Yl,fromCron:()=>os,fromDrizzle:()=>hp,fromEvent:()=>Ju,fromHTTP:()=>Ya,fromHTTPPoll:()=>Al,fromHTTPStream:()=>Ol,fromIter:()=>ss,fromKafka:()=>Bl,fromKysely:()=>yp,fromMCP:()=>Il,fromNATS:()=>Zl,fromNDJSON:()=>Jl,fromOTel:()=>Pl,fromPrisma:()=>gp,fromPrometheus:()=>jl,fromPromise:()=>Xn,fromPulsar:()=>Ql,fromRabbitMQ:()=>tp,fromRaf:()=>Uu,fromRedisStream:()=>Kl,fromSSE:()=>Ml,fromSqlite:()=>pp,fromSqliteCursor:()=>fp,fromStatsD:()=>Fl,fromSyslog:()=>Dl,fromTimer:()=>Ze,fromWebSocket:()=>Ja,fromWebSocketReconnect:()=>Ll,fromWebhook:()=>kl,globToRegExp:()=>Hu,interval:()=>ml,jsonCodec:()=>ar,jsonCodecFor:()=>Mp,keepalive:()=>te,kvStorage:()=>Ws,last:()=>Hc,linear:()=>Xo,lru:()=>Za,makeHttpError:()=>wt,map:()=>eo,matchesAnyPattern:()=>Wu,matchesCron:()=>Yo,memoryAppendLog:()=>Ap,memoryBackend:()=>mo,memoryKv:()=>go,memorySnapshot:()=>Op,merge:()=>Et,mergeMap:()=>qa,mergeReactiveLogs:()=>Lc,nameToSignal:()=>vn,ndjsonRows:()=>Wl,never:()=>Qu,nodeSignal:()=>ds,of:()=>Ta,onFirstData:()=>no,pairwise:()=>Xc,parseCron:()=>Jo,parsePrometheusText:()=>Qa,parseSSEStream:()=>$t,parseStatsD:()=>$l,parseSyslog:()=>Gl,pausable:()=>hl,pubsub:()=>Rp,race:()=>tl,rateLimiter:()=>Jn,reactiveCounter:()=>wa,reactiveIndex:()=>Ep,reactiveList:()=>Ks,reactiveLog:()=>Ke,reactiveMap:()=>je,reactiveSink:()=>Ue,reduce:()=>Kc,repeat:()=>gl,replay:()=>is,rescue:()=>ro,resolveBackoffPreset:()=>qt,retry:()=>St,sample:()=>il,scan:()=>Vc,serializeError:()=>Tn,share:()=>tc,shareReplay:()=>rc,signalToName:()=>Xt,singleFromAny:()=>qs,singleNodeFromAny:()=>_p,skip:()=>Va,snapshotStorage:()=>Hs,sortJsonValue:()=>fo,stableJsonString:()=>zs,stratify:()=>ho,switchMap:()=>ke,take:()=>to,takeUntil:()=>zc,takeWhile:()=>qc,tap:()=>Jc,tapFirst:()=>Yc,throttle:()=>Ha,throttleTime:()=>Tl,throwError:()=>Xu,timeout:()=>Qn,toArray:()=>ec,toCSV:()=>rp,toClickHouse:()=>op,toFile:()=>Xa,toHTTP:()=>xl,toKafka:()=>Vl,toLoki:()=>dp,toMongo:()=>ap,toNATS:()=>ep,toObservable:()=>Uo,toPostgres:()=>ip,toPulsar:()=>Xl,toRabbitMQ:()=>np,toReadableStream:()=>_l,toRedisStream:()=>ql,toS3:()=>sp,toSSE:()=>Nl,toSSEBytes:()=>El,toSqlite:()=>mp,toTempo:()=>up,toWebSocket:()=>Cl,tokenBucket:()=>zt,topologyDiff:()=>er,valve:()=>yl,verifiable:()=>kp,window:()=>fl,windowCount:()=>cl,windowTime:()=>pl,withBreaker:()=>Un,withLatestFrom:()=>Ft,withMaxAttempts:()=>ya,withStatus:()=>Ht,workerBridge:()=>td,workerSelf:()=>nd,zip:()=>Zc});Ae();Re();ae();Me();ne();Ae();ae();ne();function jc(t){return{describeKind:"producer",...t}}function bn(t,e){return z(n=>{let r=!0,o={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[I,i]]))},complete(){r&&(r=!1,n.down([[P]]))}},s;try{let i=t(o);s=typeof i=="function"?i:void 0}catch(i){return o.error(i),()=>{r=!1}}return()=>{r=!1;try{s?.()}catch{}}},jc(e))}function Gs(t,e,n){let r=!0,o,s=0,i=0,a={},d=[],u=()=>{let f=o;o=void 0;try{f?.()}catch{}};for(let f of e){let m=n?.name?`${n.name}::${f}`:f,h=n?.channelOpts?.[f],g=z(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&u()}),jc({...h,name:m}));a[f]=g,d.push(g)}let c={};for(let f of e)c[f]=m=>{r&&a[f].down([[M,m]])};c.error=f=>{r&&(r=!1,Z(()=>{for(let m of d)m.down([[I,f]])}),u())},c.complete=()=>{r&&(r=!1,Z(()=>{for(let f of d)f.down([[P]])}),u())};let l=t(c);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,Z(()=>{for(let f of d)try{f.down([[P]])}catch{}}),u())}})}Re();ae();it();Me();ne();ve();function ce(t){return{describeKind:"derived",...t}}function Bc(t){return{describeKind:"derived",partial:!0,...t}}function eo(t,e,n){return U([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[q]]);return}for(let i of s)o.emit(e(i))},{...ce(n),meta:{...we("map"),...n?.meta??{}}})}function rt(t,e,n){return U([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[q]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[q]])},{...ce(n),meta:{...we("filter"),...n?.meta??{}}})}function Vc(t,e,n,r){return U([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[q]]);return}for(let d of a)i.store.acc=e(i.store.acc,d),s.emit(i.store.acc)},{...ce(r),initial:n,resetOnTeardown:!0,meta:{...we("scan",{initial:n}),...r?.meta??{}}})}function Kc(t,e,n,r){return U([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[P]]);return}let a=o[0];if(a==null||a.length===0){s.down([[q]]);return}for(let d of a)i.store.acc=e(i.store.acc,d)},{...ce(r),completeWhenDepsComplete:!1,meta:{...we("reduce",{initial:n}),...r?.meta??{}}})}function to(t,e,n){return e<=0?U([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[P]]))},{...ce(n),completeWhenDepsComplete:!1,meta:{...we("take",{count:e}),...n?.meta??{}}}):U([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[q]]);return}if(s.terminalDeps[0]===!0){s.store.done=!0,o.down([[P]]);return}let i=r[0];if(i==null||i.length===0){o.down([[q]]);return}for(let a of i)if(s.store.taken++,o.emit(a),s.store.taken>=e){s.store.done=!0,o.down([[P]]);return}},{...ce(n),completeWhenDepsComplete:!1,meta:{...we("take",{count:e}),...n?.meta??{}}})}function Va(t,e,n){return U([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[q]]);return}let a=!1;for(let d of i)s.store.skipped++,s.store.skipped<=e||(o.emit(d),a=!0);a||o.down([[q]])},ce(n))}function qc(t,e,n){return U([t],(r,o,s)=>{if(s.store.done){o.down([[q]]);return}let i=r[0];if(i==null||i.length===0){o.down([[q]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[P]]);return}o.emit(a)}},{...ce(n),completeWhenDepsComplete:!1})}function zc(t,e,n){let r=n?.predicate??(i=>i[0]===M),{predicate:o,...s}=n??{};return z(i=>{let a=!1,d=t.subscribe(c=>{if(!a)for(let l of c){if(a)return;l[0]===M?i.emit(l[1]):(l[0]===P||l[0]===I)&&(a=!0,i.down([l]))}}),u=e.subscribe(c=>{if(!a)for(let l of c){if(a)return;if(r(l)){a=!0,i.down([[P]]);return}}});return()=>{d(),u()}},ce(s))}function Fs(t,e){return to(t,1,e)}function Hc(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return U([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[P]]);return}let d=s[0];if(d==null||d.length===0){i.down([[q]]);return}a.store.latest=d.at(-1),a.store.has=!0},{...ce(r),completeWhenDepsComplete:!1})}function Wc(t,e,n){return to(rt(t,e,n),1,n)}function Uc(t,e,n){return to(Va(t,e,n),1,n)}function Jc(t,e,n){if(typeof e=="function")return U([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[q]]);return}for(let a of i)e(a),s.emit(a)},{...ce(n),meta:{...we("tap"),...n?.meta??{}}});let r=e;return U([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[P]])):(r.error?.(i.terminalDeps[0]),s.down([[I,i.terminalDeps[0]]]));return}let a=o[0];if(a==null||a.length===0){s.down([[q]]);return}for(let d of a)r.data?.(d),s.emit(d)},{...ce(n),completeWhenDepsComplete:!1,meta:{...we("tap"),...n?.meta??{}}})}function no(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return U([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[q]]);return}for(let d of a)!o&&r(d)&&(o=!0,e(d)),i.emit(d)},ce(n))}var Yc=no;function Qc(t,e=Object.is,n){return U([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[q]]);return}let a=!1;for(let d of i)s.store.hasPrev&&e(s.store.prev,d)||(s.store.prev=d,s.store.hasPrev=!0,o.emit(d),a=!0);a||o.down([[q]])},{...ce(n),meta:{...we("distinctUntilChanged"),...n?.meta??{}}})}function Xc(t,e){return U([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[q]]);return}let i=!1;for(let a of s)if(!o.store.hasPrev)o.store.prev=a,o.store.hasPrev=!0;else{let d=[o.store.prev,a];o.store.prev=a,r.emit(d),i=!0}i||r.down([[q]])},ce(e))}function Ka(...t){let e=[...t];return C(e,n=>n,{...ce(),equals:(n,r)=>{if(n.length!==r.length)return!1;for(let o=0;o<n.length;o++)if(!Object.is(n[o],r[o]))return!1;return!0}})}function Ft(t,e,n){return U([t,e],(r,o,s)=>{let i=r[0],a=r[1],d=a!=null&&a.length>0?a.at(-1):s.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&s.prevData[1]===void 0){o.down([[q]]);return}for(let u of i)o.emit([u,d])}else o.down([[q]])},{...Bc(n),meta:{...we("withLatestFrom"),...n?.meta??{}}})}function Et(...t){return t.length===0?z(e=>{e.down([[P]])},{...ce(),meta:{...we("merge")}}):z(e=>{let n=t.length,r=0,o=[];for(let s of t){let i=s.subscribe(a=>{for(let d of a)d[0]===M?e.emit(d[1]):d[0]===P?(r+=1,r>=n&&e.down([[P]])):d[0]===I&&e.down([d])});o.push(i)}return()=>{for(let s of o)s()}},{...ce(),meta:{...we("merge")}})}function Zc(...t){let e=t.length;return e===0?z(n=>{n.emit([]),n.down([[P]])},ce()):z(n=>{let r=Array.from({length:e},()=>[]),o=e;function s(){for(;r.every(a=>a.length>0);){let a=r.map(d=>d.shift());n.emit(a)}}let i=[];for(let a=0;a<e;a++){let d=a,u=t[a].subscribe(c=>{for(let l of c)l[0]===M?(r[d].push(l[1]),s()):l[0]===P?(o-=1,(o===0||r[d].length===0)&&n.down([[P]])):l[0]===I&&n.down([l])});i.push(u)}return()=>{for(let a of i)a()}},ce())}function el(t,e,n){return z(r=>{let o=0,s=[],i,a;return a=e.subscribe(d=>{for(let u of d)o===0?u[0]===M?s.push(u[1]):u[0]===I&&r.down([u]):u[0]===M?r.emit(u[1]):(u[0]===P||u[0]===I)&&r.down([u])}),i=t.subscribe(d=>{for(let u of d)if(o===0)if(u[0]===M)r.emit(u[1]);else if(u[0]===P){o=1;for(let c of s)r.emit(c);s.length=0}else u[0]===I&&r.down([u])}),()=>{i?.(),a?.()}},ce(n))}function tl(...t){return t.length===0?z(e=>{e.down([[P]])},ce()):t.length===1?U([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[q]]);return}for(let o of r)n.emit(o)},ce()):z(e=>{let n=null,r=[];for(let o=0;o<t.length;o++){let s=o,i=t[o].subscribe(a=>{for(let d of a){if(n!==null&&s!==n)return;d[0]===M?(n===null&&(n=s),e.emit(d[1])):(d[0]===P||d[0]===I)&&(n===null||s===n)&&e.down([d])}});r.push(i)}return()=>{for(let o of r)o()}},ce())}function $s(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==ft&&(u[0]===M?e.emit(u[1]):u[0]===P?a=!0:u[0]===I?(d=!0,e.down([u])):(u[0]===oe||u[0]===q)&&e.down([u]));d?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function ke(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return U([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){s();return}if(d.terminalDeps[0]===!0){o=!0,r||a.down([[P]]);return}let u=i[0];if(!(u==null||u.length===0))return s(),r=$s(Y(e(u[u.length-1])),a,()=>{s(),o&&a.down([[P]])}),{deactivate:()=>{s(),o=!1}}},{...ce(n),completeWhenDepsComplete:!1,meta:{...we("switchMap"),...n?.meta??{}}})}function nl(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return U([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){s();return}if(d.terminalDeps[0]===!0){o=!0,r||a.down([[P]]);return}let u=i[0];if(!(u==null||u.length===0))return r===void 0?r=$s(Y(e(u[0])),a,()=>{s(),o&&a.down([[P]])}):a.down([[q]]),{deactivate:()=>{s(),o=!1}}},{...ce(n),completeWhenDepsComplete:!1})}function rl(t,e,n){let{maxBuffer:r,...o}=n??{},s=[],i,a=!1,d;function u(){i?.(),i=void 0}function c(){if(!d||i!==void 0)return;if(s.length===0){a&&d.down([[P]]);return}let p=s.shift();i=$s(Y(e(p)),d,()=>{u(),c()})}function l(p){r&&r>0&&s.length>=r&&s.shift(),s.push(p),c()}return U([t],(p,f,m)=>{if(d=f,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){u(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,c();return}let h=p[0];if(!(h==null||h.length===0)){for(let g of h)l(g);return{deactivate:()=>{u(),s.length=0,a=!1}}}},{...ce(o),completeWhenDepsComplete:!1})}function qa(t,e,n){let{concurrent:r,...o}=n??{},s=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,d=new Set,u=[],c;function l(){a&&i===0&&u.length===0&&c&&c.down([[P]])}function p(g){if(!c)return;i++;let y;y=$s(Y(e(g)),c,()=>{y&&d.delete(y),i--,f(),l()}),d.add(y)}function f(){for(;u.length>0&&i<s;)p(u.shift())}function m(g){i<s?p(g):u.push(g)}function h(){for(let g of d)g();d.clear(),i=0,u.length=0}return U([t],(g,y,b)=>{if(c=y,b.terminalDeps[0]!=null&&b.terminalDeps[0]!==!0){h();return}if(b.terminalDeps[0]===!0){a=!0,l();return}let v=g[0];if(!(v==null||v.length===0)){for(let T of v)m(T);return{deactivate:()=>{h(),a=!1}}}},{...ce(o),completeWhenDepsComplete:!1})}var ol=qa;function sl(t,e,n){return z(r=>{let o=new Set;function s(){for(let a of o)clearTimeout(a);o.clear()}let i=t.subscribe(a=>{for(let d of a)if(d[0]===M){let u=setTimeout(()=>{o.delete(u),r.emit(d[1])},e);o.add(u)}else if(d[0]===P){let u=setTimeout(()=>{o.delete(u),r.down([[P]])},e);o.add(u)}else d[0]===I&&(s(),r.down([d]))});return()=>{i(),s()}},ce(n))}function za(t,e,n){return z(r=>{let o,s;function i(){o!==void 0&&(clearTimeout(o),o=void 0)}let a=t.subscribe(d=>{for(let u of d)u[0]===M?(i(),s=u[1],o=setTimeout(()=>{o=void 0,r.emit(s)},e)):u[0]===P?(o!==void 0&&(i(),r.emit(s)),r.down([[P]])):u[0]===I&&(i(),r.down([u]))});return()=>{a(),i()}},{...ce(n),meta:{...we("debounce",{ms:e}),...n?.meta??{}}})}function Ha(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,d=e*1e6;return z(u=>{let c,l=-1/0,p,f=!1;function m(){c!==void 0&&(clearTimeout(c),c=void 0)}let h=t.subscribe(g=>{for(let y of g)if(y[0]===M){let b=y[1],v=V();if(i&&v-l>=d)l=v,u.emit(b),m(),a&&(c=setTimeout(()=>{c=void 0,f&&(l=V(),u.emit(p),f=!1)},e));else if(a&&(p=b,f=!0,c===void 0)){let T=(v-l)/1e6;c=setTimeout(()=>{c=void 0,f&&(l=V(),u.emit(p),f=!1)},Math.max(0,e-T))}}else(y[0]===P||y[0]===I)&&(m(),u.down([y]))});return()=>{h(),m()}},{...ce(s),meta:{...we("throttle",{ms:e,leading:i,trailing:a}),...s.meta??{}}})}function il(t,e,n){return z(r=>{let o,s=!1,i=!1,a=t.subscribe(u=>{if(!s)for(let c of u){if(s)return;c[0]===M?o={v:c[1]}:c[0]===I?(s=!0,r.down([c])):c[0]===P&&(i=!0,o=void 0)}}),d=e.subscribe(u=>{if(!s)for(let c of u){if(s)return;c[0]===M?o!==void 0&&!i&&r.emit(o.v):c[0]===I?(s=!0,r.down([c])):c[0]===P&&(s=!0,r.down([[P]]))}});return()=>{a(),d()}},ce(n))}function al(t,e,n){return z(r=>{let o,s,i=!1;function a(){o!==void 0&&(clearTimeout(o),o=void 0)}let d=t.subscribe(u=>{for(let c of u)c[0]===M?(s=c[1],i=!0,a(),o=setTimeout(()=>{o=void 0,i&&(i=!1,r.emit(s))},e)):(c[0]===P||c[0]===I)&&(a(),r.down([c]))});return()=>{d(),a()}},ce(n))}function dl(t,e,n){return z(r=>{let o=[],s=t.subscribe(a=>{for(let d of a)d[0]===M?o.push(d[1]):d[0]===P?(o.length>0&&r.emit([...o]),o.length=0,r.down([[P]])):d[0]===I&&r.down([d])}),i=e.subscribe(a=>{for(let d of a)d[0]===M?o.length>0&&(r.emit([...o]),o.length=0):d[0]===P?r.down([[P]]):d[0]===I&&r.down([d])});return()=>{s(),i(),o.length=0}},ce(n))}function ul(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return z(r=>{let o=[],s=t.subscribe(i=>{for(let a of i)a[0]===M?(o.push(a[1]),o.length>=e&&r.emit(o.splice(0,o.length))):a[0]===P?(o.length>0&&r.emit([...o]),o.length=0,r.down([[P]])):a[0]===I&&r.down([a])});return()=>{s(),o.length=0}},ce(n))}function cl(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return z(r=>{let o,s=0;function i(){let d=z(u=>(o=u.down.bind(u),()=>{o=void 0}),ce());s=0,r.emit(d)}let a=t.subscribe(d=>{for(let u of d)u[0]===M?(o||i(),o?.([[M,u[1]]]),s+=1,s>=e&&(o?.([[P]]),o=void 0)):u[0]===P?(o?.([[P]]),o=void 0,r.down([[P]])):u[0]===I&&(o?.([u]),o=void 0,r.down([u]))});return()=>{a(),o?.([[P]]),o=void 0}},ce(n))}function ll(t,e,n){return z(r=>{let o=[],s=setInterval(()=>{o.length>0&&(r.emit([...o]),o.length=0)},e),i=t.subscribe(a=>{for(let d of a)d[0]===M?o.push(d[1]):d[0]===P?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[P]])):d[0]===I&&(clearInterval(s),r.down([d]))});return()=>{i(),clearInterval(s),o.length=0}},{...ce(n),meta:{...we("bufferTime",{ms:e}),...n?.meta??{}}})}function pl(t,e,n){return z(r=>{let o;function s(){o?.([[P]]),o=void 0}function i(){let u=z(c=>(o=c.down.bind(c),()=>{o=void 0}),ce());r.emit(u)}i();let a=setInterval(()=>{s(),i()},e),d=t.subscribe(u=>{for(let c of u)c[0]===M?o?.([[M,c[1]]]):c[0]===P?(clearInterval(a),s(),r.down([[P]])):c[0]===I&&(clearInterval(a),o?.([c]),s(),r.down([c]))});return()=>{d(),clearInterval(a),s()}},ce(n))}function fl(t,e,n){return z(r=>{let o;function s(){o?.([[P]]),o=void 0}function i(){let u=z(c=>(o=c.down.bind(c),()=>{o=void 0}),ce());r.emit(u)}let a=t.subscribe(u=>{for(let c of u)c[0]===M?(o||i(),o?.([[M,c[1]]])):c[0]===P?(s(),r.down([[P]])):c[0]===I&&(o?.([c]),o=void 0,r.down([c]))}),d=e.subscribe(u=>{for(let c of u)c[0]===M&&(s(),i())});return()=>{a(),d(),s()}},ce(n))}function ml(t,e){return z((n,r)=>{"n"in r.store||(r.store.n=0);let o=setInterval(()=>{n.emit(r.store.n),r.store.n=r.store.n+1},t);return()=>clearInterval(o)},ce(e))}function gl(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return z(r=>{let o=e,s,i=()=>{s?.(),s=t.subscribe(a=>{let d=!1,u=[];for(let c of a)c[0]===P?d=!0:u.push(c);u.length>0&&r.down(u),d&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[P]]))})};return i(),()=>{s?.()}},ce(n))}function hl(t,e){return U([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[q]]);return}for(let s of o)r.emit(s)},ce(e))}function ro(t,e,n){return z(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===M)r.emit(i[1]);else if(i[0]===I)try{r.emit(e(i[1]))}catch(a){r.down([[I,a]])}else i[0]===P&&r.down([[P]])});return()=>{o()}},ce(n))}function yl(t,e,n){return U([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[q]]);return}let d=r[0];if(d!=null&&d.length>0){for(let u of d)o.emit(u);return}if(i!=null&&i.length>0&&s.prevData[0]!==void 0){o.emit(s.prevData[0]);return}o.down([[q]])},Bc(n))}var bl=Ka,vl=za,Tl=Ha,wl=ro;ae();Me();ne();Wn();var Wa=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new gn(e),this.arr=null)}get length(){return this.ring!=null?this.ring.size:this.arr.length}push(e){this.ring!=null?this.ring.push(e):this.arr.push(e)}shift(){return this.ring!=null?this.ring.shift():this.arr.shift()}drain(){if(this.ring!=null){let n=this.ring.toArray();return this.ring.clear(),n}let e=this.arr;return this.arr=[],e}};function oo(t){return t instanceof Error?t:new Error(String(t))}function Xg(t){return t===void 0?null:typeof t=="string"?qt(t):t}function Ue(t,e){let{name:n,onTransportError:r,retry:o,backpressure:s,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:d,stopOn:u,onUpstreamMessage:c,onDispose:l,send:p,sendBatch:f,ctx:m}=e;if(!p&&!f)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let h=m,g=Math.max(1,o?.maxAttempts??1),y=Xg(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=f!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=W=>n?`${n}::${W}`:void 0,w=A(void 0,{equals:()=>!1,name:T("sent")}),x=A(null,{name:T("failed")}),k=A(0,{name:T("inFlight")}),S=A(null,{name:T("errors")}),R=v?A(0,{name:T("buffered")}):void 0,E=s?A(!1,{name:T("paused")}):void 0,_=0,O=W=>{_+=W,k.down([[M,_]])},N=W=>{try{r?.(W)}catch{}try{S.down([[M,W]])}catch{}},L=new Set,j=W=>{L.add(W);let fe=()=>L.delete(W);W.then(fe,fe)},$=(W,fe,Ne)=>{let Ee=y?y(fe-1,Ne,null):0,me=Ee==null?0:typeof Ee=="number"&&Ee>0?Ee:0,De=Math.max(1,Math.ceil(me/1e6));return new Promise(ye=>{setTimeout(()=>ye(W()),De)})},D=W=>W!=null&&typeof W=="object"&&typeof W.then=="function",K=W=>{let fe;try{fe=d?d(W):W}catch(ye){let be=oo(ye);return N({stage:"serialize",error:be,value:W}),x.down([[M,{value:W,error:be,attempts:0}]]),Promise.resolve()}let Ne=0,Ee=ye=>{O(-1);let be=oo(ye);if(N({stage:"send",error:be,value:W,attempt:Ne}),!(Ne<g&&b(be,Ne))){x.down([[M,{value:W,error:be,attempts:Ne}]]);return}return $(De,Ne,be)},me=()=>{O(-1),w.down([[M,W]])};function De(){Ne+=1,O(1);let ye;try{ye=p(fe,h)}catch(be){return Ee(be)??Promise.resolve()}return D(ye)?ye.then(me,be=>Ee(be)):(me(),Promise.resolve())}return De()},F=s?.maxBuffer??Number.POSITIVE_INFINITY,H=new Wa(F),G,B=!1,re=()=>{R?.down([[M,H.length]])},pe=W=>{E&&E.down([[M,W]])},ee=s?.strategy??"drop-oldest",ue=(W,fe)=>{let Ne={value:W,payload:fe};if(H.length<F)return H.push(Ne),re(),!0;if(ee==="drop-oldest"){let me=H.shift();return H.push(Ne),re(),pe(!0),x.down([[M,{value:me.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(ee==="drop-newest")return pe(!0),x.down([[M,{value:W,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Ee=new Error("backpressure: buffer overflow");return N({stage:"send",error:Ee,value:W}),x.down([[M,{value:W,error:Ee,attempts:0}]]),pe(!0),!1},Ce=W=>{let fe=0,Ne=W.map(ye=>ye.payload),Ee=ye=>{O(-1);let be=oo(ye);if(N({stage:"send",error:be,value:W.map(Mn=>Mn.value),attempt:fe}),!(fe<g&&b(be,fe))){for(let{value:Mn}of W)x.down([[M,{value:Mn,error:be,attempts:fe}]]);return}return $(De,fe,be)},me=()=>{O(-1);for(let{value:ye}of W)w.down([[M,ye]])};function De(){fe+=1,O(1);let ye;try{ye=f(Ne,h)}catch(be){return Ee(be)??Promise.resolve()}return D(ye)?ye.then(me,be=>Ee(be)):(me(),Promise.resolve())}return De()},Ye=async W=>{for(let fe of W)await Be(fe.value,fe.payload)},Be=(W,fe)=>{let Ne=0,Ee=ye=>{O(-1);let be=oo(ye);if(N({stage:"send",error:be,value:W,attempt:Ne}),!(Ne<g&&b(be,Ne))){x.down([[M,{value:W,error:be,attempts:Ne}]]);return}return $(De,Ne,be)},me=()=>{O(-1),w.down([[M,W]])};function De(){Ne+=1,O(1);let ye;try{ye=p(fe,h)}catch(be){return Ee(be)??Promise.resolve()}return D(ye)?ye.then(me,be=>Ee(be)):(me(),Promise.resolve())}return De()},J=()=>{if(B||H.length===0)return Promise.resolve();let W=H.drain();if(re(),pe(!1),f!==void 0){let Ne=Ce(W);return j(Ne),Ne}let fe=Ye(W);return j(fe),fe},de=()=>{G!==void 0||B||a<=0||(G=setTimeout(()=>{G=void 0,J()},a))},Le=t.subscribe(W=>{for(let fe of W){let Ne=fe[0];if(Ne!==M)try{c?.(fe)}catch{}if(Ne===M){let Ee=fe[1];if(v){let me;if(d)try{me=d(Ee)}catch(ye){let be=oo(ye);N({stage:"serialize",error:be,value:Ee}),x.down([[M,{value:Ee,error:be,attempts:0}]]);continue}else me=Ee;if(!ue(Ee,me))continue;H.length>=i?J():de()}else{let me=K(Ee);j(me)}}else Fe.messageTier(Ne)>=3&&v&&(G!==void 0&&(clearTimeout(G),G=void 0),J())}}),Te;if(u){let W=!1;Te=u.subscribe(fe=>{if(!W){W=!0;return}fe.length>0&&!X&&ie()})}let X=!1,ie=()=>{if(X)return;X=!0,G!==void 0&&(clearTimeout(G),G=void 0),v&&J(),B=!0,Te?.(),Le();let W=fe=>{try{fe.down([[le]])}catch{}};W(S),W(x),W(w),W(k),R&&W(R),E&&W(E);try{l?.()}catch{}},xe={dispose:ie,sent:w,failed:x,inFlight:k,errors:S};return v&&(xe.buffered=R,xe.flush=async()=>{B||(await J(),await Promise.all(L))}),E&&(xe.paused=E),xe}It();ve();function Tt(t){return{describeKind:"producer",...t}}function Ja(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return z(s=>{let i=!0,a,d=()=>{let y=a;a=void 0,y?.()},u=y=>{i&&(i=!1,s.down([y]),d())},c=(y,b=y)=>{if(i)try{let v=y!==null&&typeof y=="object"&&"data"in y?y.data:y,T=n?n(v,b):v;s.emit(T)}catch(v){u([I,v])}},l=y=>{u([I,y])},p=()=>{u([P])};if(typeof t=="function"){try{if(a=t(c,l,p),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){u([I,y])}return()=>{i=!1,d()}}let f=t,m=y=>c(y,y),h=y=>l(y),g=()=>p();return f.addEventListener("message",m),f.addEventListener("error",h),f.addEventListener("close",g),a=()=>{f.removeEventListener("message",m),f.removeEventListener("error",h),f.removeEventListener("close",g),r&&f.close()},()=>{i=!1,d()}},Tt(o))}function kl(t,e){return bn(t,e)}function Ya(t,e){let{method:n="GET",headers:r,body:o,transform:s=v=>v.json(),timeoutNs:i=30*1e9,signal:a,completeAfterFetch:d=!1,refetchOnSubscribe:u=!1,...c}=e??{},l=A(0,{name:`${c.name??"http"}/fetchCount`}),p=A(0,{name:`${c.name??"http"}/lastUpdated`}),f=A(!1,{name:`${c.name??"http"}/fetched`}),m=0,h=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0,g=v=>{let T=new AbortController,w=!0;if(a?.aborted)return w=!1,v.down([[I,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let x=setTimeout(()=>T.abort(new Error("Request timeout")),Math.ceil(i/1e6));return fetch(t,{method:n,headers:r,body:h,signal:T.signal}).then(async k=>{if(clearTimeout(x),!w)return;if(!k.ok)throw new Error(`HTTP ${k.status}: ${k.statusText}`);let S=await s(k);w&&(Z(()=>{m+=1,l.down([[M,m]]),p.down([[M,se()]]),f.down([[M,!0]]),v.emit(S)}),d&&v.down([[P]]))}).catch(k=>{clearTimeout(x),w&&(k&&k.name==="AbortError"||v.down([[I,k]]))}),()=>{w=!1,T.abort()}},y=z(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{...Tt(c),resubscribable:u});return{...Ht(y),fetchCount:l,lastUpdated:p,fetched:f}}function xl(t,e,n){let{method:r="POST",headers:o={"Content-Type":"application/json"},serialize:s=m=>JSON.stringify(m),timeoutNs:i,batchFormat:a="json-array",batchSize:d,flushIntervalMs:u,retry:c,onTransportError:l}=n??{},p=async m=>{let h=i!==void 0?new AbortController:void 0,g;h&&i!==void 0&&(g=setTimeout(()=>h.abort(new Error("Request timeout")),Math.ceil(i/1e6)));try{let y=await fetch(e,{method:r,headers:o,body:m,signal:h?.signal}),b=async()=>{try{await y.arrayBuffer?.()}catch{}};if(!y.ok)throw await b(),new Error(`HTTP ${y.status}: ${y.statusText}`);await b()}finally{g!==void 0&&clearTimeout(g)}};return d!==void 0||u!==void 0?Ue(t,{onTransportError:l,retry:c,batchSize:d,flushIntervalMs:u,sendBatch:async m=>{let h;a==="ndjson"?h=m.map(g=>{let y=s(g);return typeof y=="string"?y:new TextDecoder().decode(y)}).join(`
|
|
16
|
-
`):h=JSON.stringify(m),await p(h)}}):
|
|
9
|
+
`,n}function pg(t){return JSON.parse(t)}function fg(t,e){try{t.send(JSON.stringify(e))}catch{}}function Pa(t,e){try{t(e)}catch{}}Gr();var vs="graphReflyActor";function Ga(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function Mc(t="x-graphrefly-actor"){return e=>{let r=e.switchToHttp().getRequest()?.headers?.[t.toLowerCase()];if(!(typeof r!="string"||r.length===0))try{return JSON.parse(r)}catch{return}}}function Oc(t){let e=t?.[vs];return e!=null?Lt(e):Nt}var Yr=class{constructor(e){this.extractor=e}canActivate(e){let n=Lt(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[vs]=n),!0}};function Ac(t){return new Yr(t??Ga())}var oo=require("@nestjs/common"),al=require("@nestjs/core");Gr();Ae();Se();zt();ae();et();Me();ne();Se();function Fa(t,e){if(Object.is(t,e))return!0;if(t==null||e==null||typeof t!="object"||typeof e!="object")return!1;if(Array.isArray(t)){if(!Array.isArray(e)||t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!Fa(t[s],e[s]))return!1;return!0}if(Array.isArray(e))return!1;let n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;let o=new Set(r);for(let s of n)if(!o.has(s)||!Fa(t[s],e[s]))return!1;return!0}function Cc(t,e){return`${t}\0${e}`}function cr(t,e){let n=[],r=new Set(t.subgraphs),o=new Set(e.subgraphs),s=[];for(let g of o)r.has(g)||s.push(g);s.sort();for(let g of s)n.push({type:"subgraph-mounted",path:g});let i=new Set(Object.keys(t.nodes)),a=new Set(Object.keys(e.nodes)),d=[];for(let g of a)i.has(g)||d.push(g);d.sort();for(let g of d)n.push({type:"node-added",path:g,node:{...e.nodes[g]}});let u=[];for(let g of a){if(!i.has(g))continue;let y=t.nodes[g]?.meta,b=e.nodes[g]?.meta;y==null&&b==null||Fa(y??{},b??{})||u.push(g)}u.sort();for(let g of u)n.push({type:"node-meta-changed",path:g,prevMeta:t.nodes[g]?.meta??{},nextMeta:e.nodes[g]?.meta??{}});let c=new Map;for(let g of t.edges)c.set(Cc(g.from,g.to),g);let l=new Map;for(let g of e.edges)l.set(Cc(g.from,g.to),g);let p=[];for(let[g,y]of l)c.has(g)||p.push(y);p.sort((g,y)=>g.from<y.from?-1:g.from>y.from?1:g.to<y.to?-1:g.to>y.to?1:0);for(let g of p)n.push({type:"edge-added",from:g.from,to:g.to});let f=[];for(let[g,y]of c)l.has(g)||f.push(y);f.sort((g,y)=>g.from<y.from?-1:g.from>y.from?1:g.to<y.to?-1:g.to>y.to?1:0);for(let g of f)n.push({type:"edge-removed",from:g.from,to:g.to});let m=[];for(let g of i)a.has(g)||m.push(g);m.sort();for(let g of m)n.push({type:"node-removed",path:g});let h=[];for(let g of r)o.has(g)||h.push(g);h.sort();for(let g of h)n.push({type:"subgraph-unmounted",path:g});return{events:n,flushedAt_ns:H()}}ue();Et();cs();Uo();function Qr(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return Ts(e,n,"no-such-from");if(!s)return Ts(e,n,"no-such-to");let i=r.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===n){if(r.findCycle===!0){let u=mg(t,e,r);if(u!=null)return u}let d=ws(e,t.nodes[e],0,r);return ks(e,n,[d])}if(i===0)return Ts(e,n,"no-path");let a=Lc(t,e,n,i);return a.found?ks(e,n,Ic(t,a.pathOrder,r)):Ts(e,n,a.truncated?"max-depth-exceeded":"no-path")}function Lc(t,e,n,r){let o=new Map,s=[{path:n,depth:0}],i=new Set([n]),a=0,d=!1;for(;a<s.length;){let l=s[a++];if(l.path===e)break;if(r!=null&&l.depth>=r){let h=t.nodes[l.path];h?.deps&&h.deps.length>0&&(d=!0);continue}let p=t.nodes[l.path];if(p==null)continue;let f=p.deps??[],m=new Map;for(let h=0;h<f.length;h++){let g=f[h];if(!g)continue;let y=m.get(g);y==null&&(y=[],m.set(g,y)),y.push(h)}for(let[h,g]of m)i.has(h)||(i.add(h),o.set(h,{from:l.path,depIndices:g}),s.push({path:h,depth:l.depth+1}))}if(!o.has(e))return{found:!1,pathOrder:[],truncated:d};let u=[{path:e}],c=e;for(;c!==n;){let l=o.get(c);if(l==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=l.depIndices,u.push({path:l.from}),c=l.from}return{found:!0,pathOrder:u,truncated:!1}}function mg(t,e,n){let r=t.nodes[e];if(r==null)return null;let o=r.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===e&&s.push(a);if(s.length>0){let a=ws(e,r,0,n);a.dep_index=s[0];let d=ws(e,r,1,n);return ks(e,e,[a,d])}let i=null;for(let a=0;a<o.length;a++){let d=o[a];if(!d||d===e)continue;let u=Lc(t,d,e,n.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:e,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:ks(e,e,Ic(t,i.pathOrder,n))}function Ic(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=ws(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 ws(t,e,n,r){let o={path:t,type:e.type,hop:n};e.status!==void 0&&(o.status=e.status),"value"in e&&(o.value=e.value),e.v!=null&&(o.v=e.v);let s=r.annotations?.get(t)??e.annotation;s!=null&&(o.annotation=s);let i=r.lastMutations?.get(t)??e.lastMutation;return i!=null&&(o.lastMutation=i),o}function ks(t,e,n){return Dc(t,e,!0,"ok",n)}function Ts(t,e,n){return Dc(t,e,!1,n,[])}function Dc(t,e,n,r,o){let s=gg(t,e,n,r,o);return{from:t,to:e,found:n,reason:r,steps:o,text:s,toJSON(){return{from:t,to:e,found:n,reason:r,steps:o}}}}function gg(t,e,n,r,o){if(!n)switch(r){case"no-such-from":return`explainPath: no node named "${t}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${t}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${t}" to "${e}"`}let s=[`Causal path: ${t} \u2192 ${e} (${o.length} step(s))`];for(let i of o){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(d),"value"in i&&s.push(` value: ${hg(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(`
|
|
10
|
+
`)}function hg(t){if(t===void 0)return"<sentinel>";if(t===null)return"null";if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(t)}}Me();var je={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},xs=Symbol.for("sizeof");function Xr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=yg(s,e,n,r)}return o}function yg(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return je.number;case"boolean":return je.boolean;case"string":return je.string+t.length*2;case"bigint":return je.bigint+bg(t);case"symbol":return je.symbol;case"function":return e.has(t)?0:(e.add(t),je.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[xs];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 je.date;if(s instanceof RegExp)return je.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,c=s.stack?s.stack.length*2:0;return je.error+u+c}if(typeof URL<"u"&&s instanceof URL)return je.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return je.promise;if(s instanceof WeakMap)return je.weakmap;if(s instanceof WeakSet)return je.weakset;if(s instanceof Map){let u=je.map;for(let[c,l]of s)u+=je.mapEntry,r.push(c),r.push(l);return u}if(s instanceof Set){let u=je.set;for(let c of s)u+=je.setEntry,r.push(c);return u}if(Array.isArray(s)){let u=je.array+s.length*8;for(let c of s)r.push(c);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=je.object,d=Object.keys(s);for(let u of d){a+=je.string+u.length*2;try{r.push(s[u])}catch{}}return a}function bg(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}function En(t,e){let n=e?.topN??10,r=t.describe({detail:"standard"}),o=[],s=t._collectObserveTargets;typeof s=="function"&&s.call(t,"",o);let i=new Map;for(let[p,f]of o)i.set(p,f);let a=[];for(let[p,f]of Object.entries(r.nodes)){let m=i.get(p),h=m instanceof Ce?m:null,g=h?Xr(h.cache):0,y=h?h._sinkCount:0,b=f.deps?.length??0,v=f.type==="effect"&&y===0,T=y===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:g,subscriberCount:y,depCount:b,isOrphanEffect:v,orphanKind:T})}let d=a.reduce((p,f)=>p+f.valueSizeBytes,0),u=(p,f)=>[...a].sort(f??((m,h)=>h[p]-m[p])).slice(0,n),c=a.filter(p=>p.orphanKind!=null),l=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:r.edges.length,subgraphCount:r.subgraphs.length,nodes:a,totalValueSizeBytes:d,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:c,orphanEffects:l}}var Fe="::",rt="__meta__",wt=1;function Pc(t,e){let n=Math.max(16,t.size*4),r=0;for(;t.size>0;){if(r++>=n){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${n}); ${t.size} disposer(s) discarded`),t.clear();return}let o=t.values().next();if(o.done)return;let s=o.value;t.delete(s);try{s()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Bc(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function vg(t){if(t!=null)return Bc(t)?t.cache:t}function _n(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function Xt(t){return _n(t)?t.cache??"":t}function Gc(t){return _n(t)?t.cache??0:t}function Fc(t){return _n(t)?t.cache??!1:t}function Tg(t){let e=[];for(let n of Object.keys(t).sort()){let r=t[n].v;r!=null&&e.push(`${n} ${r.id} ${r.version}`)}return e.join(`
|
|
11
|
+
`)}function $c(t){if(t.version!==wt)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${wt})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in t))throw new Error(`snapshot missing required key "${e}"`);if(typeof t.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof t.nodes!="object"||t.nodes===null||Array.isArray(t.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(t.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(t.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function wg(t,e){let n=new WeakMap,r=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let i=n.get(o);if(i==null&&(i=new WeakSet,n.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,d=s.constructor;if(a!==d)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,m]of o)if(!p.has(f)||!r(m,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 m=!1;for(let h of p)if(r(f,h)){m=!0;break}if(!m)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let m=0;m<p.length;m++)if(p[m]!==f[m])return!1;return!0}let u=Object.keys(o),c=Object.keys(s);if(u.length!==c.length)return!1;let l=new Set(c);for(let p of u)if(!l.has(p)||!r(o[p],s[p]))return!1;return!0};return r(t,e)}function kg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rs(t){let e="^";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="*"){e+=".*";continue}if(r==="?"){e+=".";continue}if(r==="["){let o=t.indexOf("]",n+1);if(o<=n+1){e+="\\[";continue}let s=t.slice(n+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),e+=`[${s}]`,n=o;continue}e+=kg(r)}return e+="$",new RegExp(e)}var xg={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"},Rg={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function $a(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function Sg(t){return t==="none"?Rg:t==="ansi"||t==null?xg:{data:t.data??"",dirty:t.dirty??"",resolved:t.resolved??"",invalidate:t.invalidate??"",pause:t.pause??"",resume:t.resume??"",complete:t.complete??"",error:t.error??"",teardown:t.teardown??"",derived:t.derived??"",path:t.path??"",reset:t.reset??""}}function jc(t){if(t==null)return{};let e=t.detail;return e==="full"?{...t,structured:t.structured??!0,timeline:t.timeline??!0,causal:t.causal??!0,derived:t.derived??!0}:e==="minimal"?{...t,structured:t.structured??!0}:t.format==="stage-log"?{...t,structured:t.structured??!0,timeline:t.timeline??!0}:t}function Ng(t,e,n){for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o<32||o===127)throw new Error(`Graph "${e}": ${n} "${t}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${r})`)}}function ja(t,e,n){if(t==="")throw new Error(`Graph "${e}": ${n} name must be non-empty`);if(t.includes(Fe))throw new Error(`Graph "${e}": ${n} "${t}" must not contain '${Fe}' (path separator)`);if(t===rt)throw new Error(`Graph "${e}": ${n} name "${rt}" is reserved for meta companion paths`);Ng(t,e,n)}function Eg(t,e){if(t==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let n=t.split(Fe);for(let r of n)if(r==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return n}function _g(t,e){let n=!1;for(let o of t)if(!e.isMetaPassthrough(o[0])){n=!0;break}return n?t.filter(o=>e.isMetaPassthrough(o[0])):t}function Vc(t){for(let e of t._mounts.values())Vc(e);for(let e of t._nodes.values())try{e.down([[ce]],{internal:!0})}catch{}}var Q=class t{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;_factory;_factoryArgs;constructor(e,n){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(Fe))throw new Error(`Graph name must not contain '${Fe}' (got "${e}")`);if(e===rt)throw new Error(`Graph name "${rt}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??$e,this._traceRing=new Pt(n?.traceCapacity??1e3),n?.versioning!=null&&this.setVersioning(n.versioning),typeof n?.factory=="string"&&(this._factory=n.factory,n.factoryArgs!==void 0&&(this._factoryArgs=n.factoryArgs))}tagFactory(e,n){return this._factory=e,this._factoryArgs=n,this}ancestors(e=!0){let n=[],r=e?this:this._parent;for(;r!=null;)n.push(r),r=r._parent;return n}get topology(){return this._topology==null&&(this._topology=z(e=>{let n=r=>{e.emit(r)};return this._topologyEmitters.add(n),()=>{this._topologyEmitters.delete(n)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let n of this._topologyEmitters)n(e)}nameOf(e){return this._nodeToName.get(e)}add(e,n){let r=e.name,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(ja(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let a=this._nodeToName.get(e);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,e),this._nodeToName.set(e,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:H()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Ce&&n._applyVersioning(e)}remove(e){ja(e,this.name,"remove");let n=this._mounts.get(e);if(n){let s={kind:"mount",nodes:[],mounts:[]},i=[];n._collectObserveTargets("",i);for(let[a,d]of i)a.includes(`${Fe}${rt}${Fe}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(e),s.mounts.push(...n._collectSubgraphs(`${e}${Fe}`)),this._mounts.delete(e),n._parent=void 0,Vc(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[ce]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=Rs(e);return i=>s.test(i)})(),r={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>n(s));for(let s of o){let i=this.remove(s);r.nodes.push(...i.nodes),r.mounts.push(...i.mounts)}return r.nodes.sort(),r.mounts.sort(),r}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),n=this._nodes,r=0;return{[Symbol.iterator](){return this},next(){if(r>=e.length)return{value:void 0,done:!0};let o=e[r++];return{value:[o,n.get(o)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(Fe))return this.resolve(e);let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return n}get(e){return this.node(e).cache}set(e,n,r){let o=r?.internal===!0;this.node(e).down([[_,n]],{actor:r?.actor,internal:o,delivery:"write"})}setAll(e,n){let r=Symbol.iterator in e?e:Object.entries(e);Z(()=>{for(let[o,s]of r)this.set(o,s,n)})}invalidate(e,n){let r=n?.internal===!0;this.node(e).down([[Ze]],{actor:n?.actor,internal:r,delivery:"write"})}error(e,n,r){let o=r?.internal===!0;this.node(e).down([[L,n]],{actor:r?.actor,internal:o,delivery:"write"})}complete(e,n){let r=n?.internal===!0;this.node(e).down([[I]],{actor:n?.actor,internal:r,delivery:"write"})}edges(e){let n=e?.recursive===!0,r=new Map;if(!n){for(let[d,u]of this._nodes)r.set(u,d);let a=[];for(let[d,u]of this._nodes)if(u instanceof Ce)for(let c of u._deps){let l=r.get(c.node);l!=null&&a.push([l,d])}return a.sort((d,u)=>d[0]<u[0]?-1:d[0]>u[0]?1:d[1]<u[1]?-1:d[1]>u[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,d]of o)s.set(d,a);let i=[];for(let[a,d]of o)if(d instanceof Ce)for(let u of d._deps){let c=s.get(u.node);c!=null&&i.push([c,a])}return i.sort((a,d)=>a[0]<d[0]?-1:a[0]>d[0]?1:a[1]<d[1]?-1:a[1]>d[1]?1:0),i}mount(e,n){if(n===void 0){let o=new t(e);return this.mount(e,o)}if(typeof n=="function"){let o=new t(e);return n(o),this.mount(e,o)}let r=n;if(ja(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let o=this;o!=null;o=o._parent)if(o===r)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,r),r._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),r}resolve(e){let n=Eg(e,this.name);return this._resolveFromSegments(n)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let n=e;if(n[0]===this.name&&(n=n.slice(1),n.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let r=n[0],o=n.slice(1);if(o.length===0){let a=this._nodes.get(r);if(a)return a;throw this._mounts.has(r)?new Error(`Graph "${this.name}": path ends at subgraph "${r}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${r}"`)}let s=this._nodes.get(r);if(s&&o.length>0&&o[0]===rt)return this._resolveMetaChainFromNode(s,o,n.join(Fe));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(Fe)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${r}"`);return i.resolve(o.join(Fe))}_resolveMetaChainFromNode(e,n,r){let o=e,s=0,i=[...n];for(;s<i.length;){if(i[s]!==rt)throw new Error(`Graph "${this.name}": expected ${rt} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${rt} in "${r}"`);let a=i[s+1],d=o.meta[a];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${r}"`);o=d,s+=2}return o}signal(e,n){if(n?.internal!==!0){for(let o of e)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let r=[];if(this._signalDeliver(e,n??{},new Set,r),r.length>0)throw r[0]}_signalDeliver(e,n,r,o){for(let d of this._mounts.values())d._signalDeliver(e,n,r,o);let i=n.internal===!0?{internal:!0}:{actor:n.actor,delivery:"signal"},a=_g(e,this.config);for(let d of[...this._nodes.keys()].sort()){let u=this._nodes.get(d);if(!r.has(u)){r.add(u);try{u.down(e,i)}catch(c){if(c instanceof ut)throw c;o.push(c)}a.length!==0&&this._signalMetaSubtree(u,a,r,i,o)}}}_signalMetaSubtree(e,n,r,o,s){for(let i of Object.keys(e.meta).sort()){let a=e.meta[i];if(!r.has(a)){r.add(a);try{a.down(n,o)}catch(d){if(d instanceof ut)throw d;s.push(d)}this._signalMetaSubtree(a,n,r,o,s)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let n=vg(e?.actor),r=e?.filter;if(e?.detail!=null&&e?.fields!=null)throw new TypeError("Graph.describe(): pass either `detail` or `fields`, not both. `detail: 'spec'` is the canonical spec projection; use `fields` only when you need a custom subset.");let o=Ut(e?.detail,e?.fields),s=e?.detail==="spec",i=o,a=[];this._collectObserveTargets("",a);let d=new Map;for(let[T,w]of a)d.set(w,T);let u=[];{let T=a.map(([,R])=>R),w=new Set(d.values()),k=0;for(;T.length>0;){let R=T.shift();if(R instanceof Ce)for(let S of R._deps){let x=S.node;if(d.has(x))continue;let N=x.name??"",E=N;if(!E||w.has(E))if(N){let D=2;for(;w.has(`${N}#${D}`);)D++;E=`${N}#${D}`}else for(E=`__internal__/${k++}`;w.has(E);)E=`__internal__/${k++}`;d.set(x,E),w.add(E),u.push([E,x]),T.push(x)}}}let c=[...a,...u],l={};for(let[T,w]of c){if(n!=null&&!w.allowsObserve(n))continue;let k=Ur(w,i,s),R=w instanceof Ce?w._deps.map(E=>d.get(E.node)??E.node.name??""):[],{name:S,...x}=k,N={...x,deps:R};if(!s){let E=this._annotations.get(T);E!=null&&(N.annotation=E)}if(r!=null)if(typeof r=="function"){let E=r;if(!(E.length>=2?E(T,N):E(N)))continue}else{let E=!0;for(let[D,M]of Object.entries(r)){let C=D==="deps_includes"?"depsIncludes":D==="meta_has"?"metaHas":D;if(C==="depsIncludes"){if(!N.deps.includes(String(M))){E=!1;break}continue}if(C==="metaHas"){if(!Object.hasOwn(N.meta??{},String(M))){E=!1;break}continue}if(N[C]!==M){E=!1;break}}if(!E)continue}l[T]=N}let p=new Set(Object.keys(l)),f=[];for(let[T,w]of c)if(w instanceof Ce)for(let k of w._deps){let R=d.get(k.node);R!=null&&f.push([R,T])}f.sort((T,w)=>T[0]<w[0]?-1:T[0]>w[0]?1:T[1]<w[1]?-1:T[1]>w[1]?1:0);let m=f.map(([T,w])=>({from:T,to:w}));(n!=null||r!=null)&&(m=m.filter(T=>p.has(T.from)&&p.has(T.to)));let h=this._collectSubgraphs(""),g=n!=null||r!=null?h.filter(T=>{let w=`${T}${Fe}`;return[...p].some(k=>k===T||k.startsWith(w))}):h,y=this,b=e;return{name:this.name,nodes:l,edges:m,subgraphs:g,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(T){let w={...b};return Array.isArray(T)?(w.fields=T,w.detail=void 0):(w.detail=T,w.fields=void 0),y.describe(w)}}}_collectSubgraphs(e){let n=[];for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${r}`;n.push(o),n.push(...this._mounts.get(r)._collectSubgraphs(`${o}${Fe}`))}return n}resourceProfile(e){return En(this,e)}reachable(e,n,r={}){return r.withDetail===!0?Mn(this.describe(),e,n,{...r,withDetail:!0}):Mn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(Xt(e),Xt(n),{...r?.maxDepth!==void 0?{maxDepth:Gc(r.maxDepth)}:{},...r?.findCycle!==void 0?{findCycle:Fc(r.findCycle)}:{}})}_explainStatic(e,n,r){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,d]of Object.entries(o.nodes))d.lastMutation!=null&&i.set(a,d.lastMutation);return Qr(o,e,n,{...r?.maxDepth!=null?{maxDepth:r.maxDepth}:{},...r?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(e){let n={...e,reactive:!1},r=e.reactiveName??"describe",o=0,s=O(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,Qn(()=>{a=!1,!d&&(o+=1,s.emit(o))}))},c=i.onEvent(b=>{let v=b.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||u()}),l=[],p=new WeakSet,f=b=>{if(p.has(b)||d)return;p.add(b);let v=b.topology.subscribe(T=>{for(let w of T){if(w[0]!==_)continue;let k=w[1];if(u(),k.kind==="added"&&k.nodeKind==="mount"){let R=b._mounts.get(k.name);R!=null&&f(R)}}});l.push(v);for(let T of b._mounts.keys()){let w=b._mounts.get(T);w!=null&&f(w)}};f(this);let m,h=e.actor;Bc(h)&&(m=h.subscribe(b=>{let v=!1,T=!1;for(let w of b){let k=w[0];k===_?v=!0:(k===I||k===L||k===ce)&&(T=!0)}v&&u(),T&&(m?.(),m=void 0,u())}));let g;try{g=A([s],()=>this.describe(n),{name:r,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(b,v)=>b===v})}catch(b){c(),m?.();for(let v of l)v();throw i.dispose(),b}let y=te(g);return{node:g,dispose(){d=!0,c(),m?.();for(let b of l)b();l.length=0,i.dispose(),y()}}}_describeReactiveDiff(e){let n={...e,reactive:!1},r=e.reactiveName??"describe-diff",o={name:this.name,nodes:{},edges:[],subgraphs:[]},s=this.describe(n),i=cr(o,s),a=O(i,{name:r,meta:{domain:"audit",kind:"describe-diff"},equals:(p,f)=>p===f}),d=this._describeReactive({...e,reactiveName:void 0}),u=!1,c=d.node.subscribe(p=>{if(!u)for(let f of p){if(f[0]!==_)continue;let m=f[1],h=cr(s,m);s=m,h.events.length!==0&&a.emit(h)}}),l=te(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[ce,"describe-diff disposed"]]),l()}}}_explainReactive(e,n,r){let o=0,s=O(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,Qn(()=>{a=!1,!d&&(o+=1,s.emit(o))}))},c=i.onEvent(b=>{let v=b.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||u()}),l=[];e!=null&&_n(e)&&l.push(e),n!=null&&_n(n)&&l.push(n),r?.maxDepth!=null&&_n(r.maxDepth)&&l.push(r.maxDepth),r?.findCycle!=null&&_n(r.findCycle)&&l.push(r.findCycle);let p=()=>{for(let b of l)if(b.cache===void 0)return!1;return!0},f=()=>{let b=Xt(e),v=Xt(n);return{from:b,to:v,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:b,to:v,found:!1,reason:"pending",steps:[]})}},m;try{m=A([s],()=>{if(!p())return f();let b=Xt(e),v=Xt(n),T={...r?.maxDepth!==void 0?{maxDepth:Gc(r.maxDepth)}:{},...r?.findCycle!==void 0?{findCycle:Fc(r.findCycle)}:{}};return this._explainStatic(b,v,T)},{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:Xt(e),to:Xt(n)},equals:(b,v)=>b.found===v.found&&b.reason===v.reason&&b.steps.length===v.steps.length&&Mg(b.steps,v.steps)})}catch(b){throw c(),i.dispose(),b}let h=te(m),g=[],y=b=>{let v;return v=b.subscribe(T=>{let w=!1,k=!1;for(let R of T){let S=R[0];S===_?w=!0:(S===I||S===L||S===ce)&&(k=!0)}(w||k)&&u(),k&&v&&(v(),v=void 0)}),()=>{v&&(v(),v=void 0)}};for(let b of l)g.push(y(b));return{node:m,dispose(){d=!0,c();for(let b of g)b?.();g.length=0,i.dispose(),h()}}}_pathsMatching(e){let n=Rs(e),r=[];return this._collectObserveTargets("",r),r.map(([o])=>o).filter(o=>n.test(o))}_collectObserveTargets(e,n){for(let r of[...this._mounts.keys()].sort()){let o=e===""?r:`${e}${Fe}${r}`;this._mounts.get(r)._collectObserveTargets(o,n)}for(let r of[...this._nodes.keys()].sort()){let o=this._nodes.get(r),s=e===""?r:`${e}${Fe}${r}`;n.push([s,o]),this._appendMetaObserveTargets(s,o,n)}}_appendMetaObserveTargets(e,n,r){for(let o of Object.keys(n.meta).sort()){let s=n.meta[o],i=`${e}${Fe}${rt}${Fe}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=jc(r?n:e);if(s.reactive===!0)return this._observeReactive(r?e:void 0,s);let 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 c=e,l=this.resolve(c);if(a!=null&&!l.allowsObserve(a))throw new ut({actor:a,action:"observe",nodeName:c});return i?this._buildStructuredObserver([[c,l]],s,"one"):{subscribe(p){return l.subscribe(p)},up(p){try{l.up?.(p)}catch(f){if(f instanceof ut)return;throw f}}}}let d=[];this._collectObserveTargets("",d),d.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let u=a==null?d:d.filter(([,c])=>c.allowsObserve(a));return i?this._buildStructuredObserver(u,s,"all"):{subscribe:c=>{let l=u.map(([p,f])=>f.subscribe(m=>{c(p,m)}));return()=>{for(let p of l)p()}},up:(c,l)=>{try{this.resolve(c).up?.(l)}catch(p){if(p instanceof ut)return;throw p}}}}_observeReactive(e,n){let r=n.tiers,o=r!=null?new Set(r):null,s=n.reactiveName??"observe";return z(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let h={events:a.slice(),flushedAt_ns:H()};a.length=0,i.emit(h)},l={...n,reactive:!1,structured:!0,timeline:!0},p=e!=null?this.observe(e,l):this.observe(l),f=h=>{u||(a.push(h),!d&&(d=!0,Qn(()=>{d=!1,c()})))};for(let h of p.events)f(h);let m=p.onEvent(f);return()=>{u=!0,m(),p.dispose()}},{name:s,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,n,r){let o=r==="one"?e[0]?.[0]:void 0,s=i=>{if(r==="one"&&o!=null){let c=this.resolve(o);return this._buildStructuredObserver([[o,c]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((c,l)=>c[0]<l[0]?-1:c[0]>l[0]?1:0);let d=i.actor,u=d==null?a:a.filter(([,c])=>c.allowsObserve(d));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(e,n,s)}_createObserveResult(e,n,r){let o=n.timeline===!0,s=n.causal===!0,i=n.derived===!0,a=n.detail==="minimal",d=this.config.inspectorEnabled,u=(s||i)&&d,c=n.maxEvents,l=c!=null&&c>0?new Pt(c):null,p=[],f=new Set,m=n.tiers!=null?new Set(n.tiers):null,h={},g=new Set,y=0,b=0,v=0,T=0,w=0,k=0,R=!1,S=!1,x=0,N=new Map,E=new Map,D=new Map,M=ee=>{if(!(m!=null&&!m.has(ee.type))){l?l.push(ee):p.push(ee);for(let le of f)le(ee)}},C=ee=>m==null||m.has(ee),$=()=>o?{timestamp_ns:H(),in_batch:mn(),batch_id:x}:{},B=(ee,le)=>{if(!(!u||!(ee instanceof Ce)))return ee._setInspectorHook(Le=>{if(Le.kind==="dep_message")N.set(ee,Le.depIndex);else if(Le.kind==="run"){let Xe=Le.batchData.map((J,de)=>J!=null&&J.length>0?J.at(-1):Le.prevData[de]);E.set(ee,Xe);let Be=Le.batchData.map(J=>J!=null?[...J]:void 0);D.set(ee,Be),i&&M({type:"derived",path:le,dep_values:Xe,dep_batches:Be,...$()})}})},G=ee=>{let le=N.get(ee),Le=E.get(ee);if(!s||Le==null)return{};let Be=(le!=null&&le>=0&&ee instanceof Ce?ee._deps[le]:void 0)?.node,J=Be?.v,de=D.get(ee);return{trigger_dep_index:le,trigger_dep_name:Be?.name,...J!=null?{trigger_version:{id:J.id,version:J.version}}:{},dep_values:[...Le],...de!=null?{dep_batches:de}:{}}},V=[],F=[];for(let[ee,le]of e){let Le=B(le,ee);Le&&V.push(Le),F.push(le.subscribe(Xe=>{x++;for(let Be of Xe){let J=Be[0],de=$();if(J===_){h[ee]=Be[1];let Ie=le instanceof Ce?le.lastMutation?.actor??Nt:Nt;M({type:"data",path:ee,data:Be[1],actor:Ie,...de,...G(le)})}else if(a)J===se?C("dirty")&&y++:J===q?C("resolved")&&b++:J===Ze?C("invalidate")&&v++:J===Ke?C("pause")&&T++:J===He?C("resume")&&w++:J===ce?C("teardown")&&k++:J===I&&!g.has(ee)?C("complete")&&(R=!0):J===L&&C("error")&&(S=!0,g.add(ee));else if(J===se)C("dirty")&&y++,M({type:"dirty",path:ee,...de});else if(J===q)C("resolved")&&b++,M({type:"resolved",path:ee,...de,...G(le)});else if(J===Ze)C("invalidate")&&v++,M({type:"invalidate",path:ee,...de});else if(J===Ke)C("pause")&&T++,M({type:"pause",path:ee,lockId:Be[1],...de});else if(J===He)C("resume")&&w++,M({type:"resume",path:ee,lockId:Be[1],...de});else if(J===I)C("complete")&&!g.has(ee)&&(R=!0),M({type:"complete",path:ee,...de});else if(J===L){C("error")&&(S=!0,g.add(ee));let Ie=le instanceof Ce?le.lastMutation?.actor??Nt:Nt;M({type:"error",path:ee,data:Be[1],actor:Ie,...de})}else J===ce&&(C("teardown")&&k++,M({type:"teardown",path:ee,...de}))}}))}let K=!1,P=()=>{if(!K){K=!0;for(let ee of F)ee();for(let ee of V)ee();for(let ee of re)ee({value:void 0,done:!0});re.length=0}},j=[],re=[];f.add(ee=>{let le=re.shift();le?le({value:ee,done:!1}):j.push(ee)});let fe={get values(){return h},get dirtyCount(){return y},get resolvedCount(){return b},get invalidateCount(){return v},get pauseCount(){return T},get resumeCount(){return w},get teardownCount(){return k},get events(){return l?l.toArray():[...p]},get anyCompletedCleanly(){return R},get anyErrored(){return S},get completedWithoutErrors(){return R&&!S},onEvent(ee){return f.add(ee),()=>f.delete(ee)},dispose:P,expand(ee){P();let le={...n};return typeof ee=="string"?le.detail=ee:Object.assign(le,ee),r(jc(le))},[Symbol.asyncIterator](){return{next(){return j.length>0?Promise.resolve({value:j.shift(),done:!1}):K?Promise.resolve({value:void 0,done:!0}):new Promise(ee=>re.push(ee))},return(){return P(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(fe,n),fe}_attachFormatLogger(e,n){let r=n.format;if(r==null)return;let o=n.logger??(m=>console.log(m)),s=n.includeTypes?new Set(n.includeTypes):null,i=n.excludeTypes?new Set(n.excludeTypes):null,a=s==null&&i==null?()=>!0:m=>(s==null||s.has(m))&&(i==null||!i.has(m)),d=Sg(n.theme),u=r==="stage-log"?H():0,c=m=>m==null?"":n.stageLabels?.[m]??m,l=(m,h)=>m.length>h?`${m.slice(0,h-1)}\u2026`:m,p=m=>m.type==="data"||m.type==="error"?l($a(m.data),120):"",f=m=>{if(r==="stage-log"){let R=(H()-u)/1e9,S=c(m.path).padEnd(9);if(m.type==="data"){let x=p(m);return`[${R.toFixed(3)}s] ${S} \u2190${x?` ${x}`:""}`}if(m.type==="error"){let x=p(m);return`[${R.toFixed(3)}s] ${S} \u2717${x?` ${x}`:""}`}return m.type==="complete"?`[${R.toFixed(3)}s] ${S} \u25A0 complete`:`[${R.toFixed(3)}s] ${S} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let h=d[m.type]??"",g=m.path?`${d.path}${m.path}${d.reset} `:"",y=m.type==="data"||m.type==="error",b=m.type==="pause"||m.type==="resume",v=y?` ${$a(m.data)}`:b?` ${$a(m.lockId)}`:"",T=m.type==="data"||m.type==="resolved"||m.type==="derived"?m:void 0,w=T?.trigger_dep_name!=null?` <- ${T.trigger_dep_name}`:T?.trigger_dep_index!=null?` <- #${T.trigger_dep_index}`:"",k=m.in_batch?" [batch]":"";return`${g}${h}${m.type.toUpperCase()}${d.reset}${v}${w}${k}`};e.onEvent(m=>{a(m.type)&&o(f(m),m)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){Pc(this._disposers,this.name),this.signal([[ce]],{internal:!0}),Pc(this._storageDisposers,this.name);for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let e of[...this._mounts.values()])e._parent=void 0,e._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(e){let{expand:n,...r}=this.describe({detail:"full"}),o={};for(let a of Object.keys(r.nodes).sort()){let{lastMutation:d,guard:u,...c}=r.nodes[a];o[a]=c}let s=[...r.subgraphs].sort(),i={...r,version:1,nodes:o,subgraphs:s};if(e?.format==null)return i;if(e.format==="json-string")return JSON.stringify(i);if(e.format==="bytes"){if(e.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(e.codec);if(a==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return Ir(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??$e,{codec:o,codecVersion:s,payload:i}=Dr(e,r);return o.decode(i,s)}restore(e,n){if($c(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let r=n?.only==null?null:(Array.isArray(n.only)?n.only:[n.only]).map(s=>Rs(s)),o=n?.includeProducers===!0;for(let s of Object.keys(e.nodes).sort()){if(r!==null&&!r.some(a=>a.test(s)))continue;let i=e.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&n?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let d=this.tryResolve(s)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){n?.onError?.(s,a)}}}}}static fromSnapshot(e,n){$c(e);let r=typeof n=="function"?n:n?.build,o=typeof n=="function"?void 0:n?.factories,s=new t(e.name);if(r)return r(s),s.restore(e),s;for(let f of[...e.subgraphs].sort((m,h)=>{let g=m.split(Fe).length,y=h.split(Fe).length;return g!==y?g-y:m<h?-1:m>h?1:0})){let m=f.split(Fe),h=s;for(let g of m)h._mounts.has(g)||h.mount(g,new t(g)),h=h._mounts.get(g)}let i=o?Object.entries(o).map(([f,m])=>({re:Rs(f),factory:m})):[],a=f=>{for(let m of i)if(m.re.test(f))return m.factory},d=f=>{let m=f.split(Fe),h=m.pop();if(h==null||h.length===0)throw new Error(`invalid snapshot path "${f}"`);let g=s;for(let y of m){let b=g._mounts.get(y);if(!b)throw new Error(`unknown mount "${y}" in path "${f}"`);g=b}return[g,h]},u=Object.entries(e.nodes).filter(([f])=>!f.includes(`${Fe}${rt}${Fe}`)).sort((f,m)=>f[0]<m[0]?-1:f[0]>m[0]?1:0),c=new Map(u),l=new Map,p=!0;for(;c.size>0&&p;){p=!1;for(let[f,m]of[...c.entries()]){let h=m?.deps??[];if(!h.every(w=>l.has(w)))continue;let[g,y]=d(f),b={...m?.meta??{}},v=a(f),T;if(m?.type==="state")T=O(m.value,{meta:b});else{if(v==null)continue;T=v(y,{path:f,type:m.type,value:m.value,meta:b,deps:h,resolvedDeps:h.map(w=>l.get(w))})}g.add(T,{name:y}),l.set(f,T),c.delete(f),p=!0}}if(c.size>0){let f=[...c.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(e),s}toJSON(){return this.snapshot()}attachSnapshotStorage(e,n={}){let r=e.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));n.autoRestore===!0&&this._cascadeRestore(e,n.onError);let o=(u,c)=>{if(u.disposed)return;let l=Tg(c.nodes);if(u.lastSnapshot!=null&&l!==""&&l===u.lastFingerprint)return;let p=u.seq+1,f=oe(),g=u.lastSnapshot==null||p%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:f,format_version:wt}:{name:this.name,mode:"diff",diff:Ss(u.lastSnapshot,c),seq:p,timestamp_ns:f,format_version:wt};if(u.tier.filter&&!u.tier.filter(g))return;let y;try{y=u.tier.save(g)}catch(b){n.onError?.(b,u.tier);return}if(y&&typeof y.then=="function"){let T=(u.savePending??Promise.resolve()).then(()=>y,()=>y).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l)},w=>{n.onError?.(w,u.tier)});u.savePending=T.finally(()=>{u.savePending===T&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=c,u.lastFingerprint=l},s=(u,c)=>{try{o(u,c)}catch(l){n.onError?.(l,u.tier)}},i=(u,c)=>{if(!c.some(m=>{let h=this.config.messageTier(m[0]);return h>=3&&h<5}))return;if(n.filter){let m=this.tryResolve(u);if(m==null)return;let h=Ur(m,Ut("standard"));if(!n.filter(u,h))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let m of r)m.disposed||(m.debounceMs===0?s(m,f()):(m.timer==null&&(m.timer=new De),m.timer.start(m.debounceMs,()=>{m.disposed||s(m,this.snapshot())})))},a;if(n.paths!=null){let c=(typeof n.paths=="string"?this._pathsMatching(n.paths):n.paths).map(l=>{let p=this.tryResolve(l);return p==null?()=>{}:p.subscribe(f=>i(l,f))});a=()=>{for(let l of c)l()}}else a=this.observe().subscribe((u,c)=>i(u,c));let d=()=>{a();for(let u of r)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,n){for(let r of e){let o;try{o=await r.load?.()}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===wt&&s.nodes!=null)return this.restore(s),!0}catch(i){n?.(i,r)}}return!1}static async fromStorage(e,n,r){for(let o of n){let s;try{s=await o.load?.()}catch(d){r?.onError?.(d,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===wt&&i.nodes!=null?i:void 0;if(a!=null)try{return t.fromSnapshot(a,r)}catch(d){r?.onError?.(d,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${n.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,n,r){if(e!=null&&n!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,n),this.config.inspectorEnabled){let o={path:e,annotation:n,timestamp_ns:H(),...r?.actor!=null?{actor:r.actor}:{}};this._traceRing.push(o)}return}return e!=null?this.config.inspectorEnabled?this._annotations.get(e):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(e){return this._annotations.get(e)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(e){let n=this._traceRing.toArray().filter(o=>!e(o)),r=this._traceRing.size-n.length;this._traceRing.clear();for(let o of n)this._traceRing.push(o);return r}static diff(e,n){let r=new Set(Object.keys(e.nodes)),o=new Set(Object.keys(n.nodes)),s=[...o].filter(b=>!r.has(b)).sort(),i=[...r].filter(b=>!o.has(b)).sort(),a=[],d=[];for(let b of r){if(!o.has(b))continue;let v=e.nodes[b],T=n.nodes[b],w=v.v,k=T.v;w!=null&&k!=null&&w.id===k.id&&w.version!==k.version&&d.push({path:b,id:w.id,from:w.version,to:k.version});let R=w!=null&&k!=null&&w.id===k.id&&w.version===k.version;for(let S of["type","status","sentinel"]){let x=v[S],N=T[S];x!==N&&a.push({path:b,field:S,from:x,to:N})}if(!R)for(let S of["value","meta"]){let x=v[S],N=T[S];wg(x,N)||a.push({path:b,field:S,from:x,to:N})}}let u=b=>`${b.from} ${b.to}`,c=new Set(e.edges.map(u)),l=new Set(n.edges.map(u)),p=n.edges.filter(b=>!c.has(u(b))),f=e.edges.filter(b=>!l.has(u(b))),m=new Set(e.subgraphs),h=new Set(n.subgraphs),g=[...h].filter(b=>!m.has(b)).sort(),y=[...m].filter(b=>!h.has(b)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:d,edgesAdded:p,edgesRemoved:f,subgraphsAdded:g,subgraphsRemoved:y}}};function Ss(t,e){let n=Q.diff(t,e),r={};for(let o of n.nodesAdded){let s=e.nodes[o];s!=null&&(r[o]=s)}return{...n,nodesAddedFull:r}}function Mn(t,e,n,r={}){let o={paths:[],depths:new Map,truncated:!1};if(!e)return r.withDetail?o:[];if(!r.both&&n!=="upstream"&&n!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=r.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return r.withDetail?o:[];let i=new Map,a=new Map,d=new Map,u=new Map,c=new Set;for(let[v,T]of Object.entries(t.nodes)){if(!v)continue;c.add(v);let w=T.deps??[];i.set(v,w);for(let k of w)k&&(c.add(k),a.has(k)||a.set(k,new Set),a.get(k).add(v))}for(let v of t.edges){if(v==null||typeof v!="object")continue;let T=typeof v.from=="string"?v.from:"",w=typeof v.to=="string"?v.to:"";!T||!w||(c.add(T),c.add(w),u.has(T)||u.set(T,new Set),u.get(T).add(w),d.has(w)||d.set(w,new Set),d.get(w).add(T))}if(!c.has(e))return r.withDetail?o:[];let l=r.both===!0,p=v=>{if(l){let R=i.get(v)??[],S=d.get(v),x=a.get(v),N=u.get(v),E=[...R];return S&&E.push(...S),x&&E.push(...x),N&&E.push(...N),E}if(n==="upstream"){let R=i.get(v)??[],S=d.get(v);return S?[...R,...S]:R}let T=a.get(v),w=u.get(v),k=T?[...T]:[];return w&&k.push(...w),k},f=new Set([e]),m=new Map,h=[{path:e,depth:0}],g=0,y=!1;for(;g<h.length;){let v=h[g++];if(s!=null&&v.depth>=s){p(v.path).length>0&&(y=!0);continue}for(let T of p(v.path))!T||f.has(T)||(f.add(T),m.set(T,v.depth+1),h.push({path:T,depth:v.depth+1}))}let b=[...m.keys()].sort((v,T)=>v<T?-1:v>T?1:0);return r.withDetail?{paths:b,depths:m,truncated:y}:b}function Mg(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.path!==o.path||r.type!==o.type||r.status!==o.status||r.hop!==o.hop||r.dep_index!==o.dep_index||r.annotation!==o.annotation||r.value!==o.value||r.lastMutation!==o.lastMutation)return!1;let s=r.v,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}var Gs={};Ne(Gs,{CqrsGraph:()=>Ps,cqrs:()=>ed,cqrsEventKeyOf:()=>rh,dispatchKeyOf:()=>oh,sagaInvocationKeyOf:()=>sh});Ae();Se();zt();var Ba={};Ne(Ba,{COMPLETE:()=>I,COMPLETE_MSG:()=>zo,COMPLETE_ONLY_BATCH:()=>Lr,DATA:()=>_,DEFAULT_ACTOR:()=>Nt,DIRTY:()=>se,DIRTY_MSG:()=>Ct,DIRTY_ONLY_BATCH:()=>Hn,ERROR:()=>L,GraphReFlyConfig:()=>gn,GuardDenied:()=>ut,INVALIDATE:()=>Ze,INVALIDATE_MSG:()=>qo,INVALIDATE_ONLY_BATCH:()=>Cr,NodeImpl:()=>Ce,PAUSE:()=>Ke,RESOLVED:()=>q,RESOLVED_MSG:()=>qn,RESOLVED_ONLY_BATCH:()=>Ar,RESUME:()=>He,START:()=>mt,START_MSG:()=>zn,TEARDOWN:()=>ce,TEARDOWN_MSG:()=>Ho,TEARDOWN_ONLY_BATCH:()=>Wn,accessHintForGuard:()=>Vr,advanceVersion:()=>Kr,autoTrackNode:()=>hn,batch:()=>Z,configure:()=>xa,createVersioning:()=>Xn,defaultConfig:()=>$e,defaultHash:()=>Ht,derived:()=>A,downWithBatch:()=>It,dynamicNode:()=>qr,effect:()=>ye,factoryTag:()=>be,isBatching:()=>mn,isV1:()=>Ta,monotonicNs:()=>H,node:()=>U,normalizeActor:()=>Lt,pipe:()=>Ra,placeholderArgs:()=>We,policy:()=>Dt,policyFromRules:()=>Br,producer:()=>z,registerBuiltins:()=>jr,resolveDescribeFields:()=>Ut,state:()=>O,wallClockNs:()=>oe});Gr();Ae();Se();ba();zt();ae();et();Me();ne();Jo();Ae();Se();zt();ae();ne();Ae();ae();Me();ne();ue();var eo=class{_version=0;_maxSize;_buf;_head=0;_size=0;constructor(e,n){if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(this._maxSize=n,n!==void 0){if(this._buf=new Array(n),e&&e.length>0){let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}}else this._buf=e?[...e]:[],this._size=this._buf.length}get version(){return this._version}get size(){return this._size}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._size+e;if(!(n<0||n>=this._size))return this._maxSize!==void 0?this._buf[(this._head+n)%this._maxSize]:this._buf[n]}append(e){this._rawAppend(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._maxSize!==void 0&&e.length>this._maxSize?e.length-this._maxSize:0;for(let r=n;r<e.length;r++)this._rawAppend(e[r]);this._version+=1}clear(){if(this._size===0)return 0;let e=this._size;if(this._maxSize===void 0)this._buf.length=0;else for(let n=0;n<e;n++)this._buf[(this._head+n)%this._maxSize]=void 0;return this._head=0,this._size=0,this._version+=1,e}trimHead(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`trimHead: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return 0;let n=Math.min(e,this._size);if(this._maxSize===void 0)this._buf.splice(0,n);else{for(let r=0;r<n;r++)this._buf[(this._head+r)%this._maxSize]=void 0;this._head=(this._head+n)%this._maxSize}return this._size-=n,this._version+=1,n}slice(e,n){if(!Number.isInteger(e)||e<0)throw new RangeError(`slice: start must be a non-negative integer (got ${e})`);if(n!==void 0&&(!Number.isInteger(n)||n<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${n})`);let r=n===void 0?this._size:Math.min(Math.max(n,0),this._size),o=Math.min(e,this._size);if(o>=r)return[];let s=r-o;if(this._maxSize===void 0)return this._buf.slice(o,r);let i=new Array(s);for(let a=0;a<s;a++)i[a]=this._buf[(this._head+o+a)%this._maxSize];return i}tail(e){if(!Number.isInteger(e)||e<0)throw new RangeError(`tail: n must be a non-negative integer (got ${e})`);if(e===0||this._size===0)return[];let n=Math.min(e,this._size);return this.slice(this._size-n,this._size)}toArray(){if(this._maxSize===void 0)return[...this._buf];let e=new Array(this._size);for(let n=0;n<this._size;n++)e[n]=this._buf[(this._head+n)%this._maxSize];return e}snapshot(){return this.toArray()}restore(e){if(this._maxSize===void 0){this._buf.length=0;for(let n=0;n<e.length;n++)this._buf.push(e[n]);this._size=this._buf.length}else{let n=this._maxSize;for(let s=0;s<n;s++)this._buf[s]=void 0;this._head=0;let r=Math.min(e.length,n),o=e.length-r;for(let s=0;s<r;s++)this._buf[s]=e[o+s];this._size=r}this._version+=1}_rawAppend(e){if(this._maxSize===void 0){this._buf.push(e),this._size=this._buf.length;return}this._size<this._maxSize?(this._buf[(this._head+this._size)%this._maxSize]=e,this._size+=1):(this._buf[this._head]=e,this._head=(this._head+1)%this._maxSize)}};function Zr(t){return t.subscribe(()=>{})}var Og=64;function qe(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:i}=e,a=i??new eo(t,r),d=O(a.toArray(),{name:n,describeKind:"state",equals:(R,S)=>R===S,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function u(){let R=a.toArray();Z(()=>{d.down([[se]],{internal:!0}),d.down([[_,R]],{internal:!0})})}let c=new Map,l=new Map,p=new Map;function f(R,S){return`${R}:${S===void 0?"END":S}`}function m(R){if(R.size<Og)return;let S=R.keys().next();if(S.done)return;let x=R.get(S.value);x!==void 0&&x.dispose(),R.delete(S.value)}function h(R){let S=a.version;try{return R()}finally{a.version!==S&&u()}}function g(R){if(!Number.isInteger(R)||R<0)throw new RangeError(`tail: n must be a non-negative integer (got ${R})`);let S=c.get(R);if(S!==void 0)return c.delete(R),c.set(R,S),S.node;m(c);let x=A([d],([E])=>{let D=E;return R===0||D.length===0?[]:D.slice(Math.max(0,D.length-R))},{initial:a.tail(R),describeKind:"derived"}),N=Zr(x);return c.set(R,{node:x,dispose:N}),x}function y(R,S){if(!Number.isInteger(R)||R<0)throw new RangeError(`slice: start must be a non-negative integer (got ${R})`);if(S!==void 0&&(!Number.isInteger(S)||S<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${S})`);let x=f(R,S),N=l.get(x);if(N!==void 0)return l.delete(x),l.set(x,N),N.node;m(l);let E=A([d],([M])=>{let C=M;return S===void 0?C.slice(R):C.slice(R,S)},{initial:a.slice(R,S),describeKind:"derived"}),D=Zr(E);return l.set(x,{node:E,dispose:D}),E}function b(R){let S=p.get(R);if(S!==void 0)return S.node;let x=A([d,R],([E,D])=>{let M=E,C=Math.max(0,Math.trunc(D??0));return M.slice(C)},{initial:[],describeKind:"derived"}),N=Zr(x);return p.set(R,{node:x,dispose:N}),x}let v,T;function w(){v===void 0&&(v=U([d],(R,S,x)=>{let N=R[0],D=N!=null&&N.length>0?N.at(-1):x.prevData[0];if(D==null||D.length===0){S.down([[q]]);return}S.emit(D[D.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),T=A([d],([R])=>R.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),Zr(v),Zr(T))}let k={entries:d,get size(){return a.size},at(R){return a.at(R)},append(R){h(()=>a.append(R))},appendMany(R){R.length!==0&&h(()=>a.appendMany(R))},clear(){h(()=>a.clear())},trimHead(R){h(()=>a.trimHead(R))},withLatest(){return w(),d},get lastValue(){return w(),v},get hasLatest(){return w(),T},view(R){switch(R.kind){case"tail":return g(R.n);case"slice":return y(R.start,R.stop);case"fromCursor":return b(R.cursor)}},attach(R){let S=R.subscribe(x=>{for(let N of x)N[0]===_&&k.append(N[1])});return()=>S()},attachStorage(R){if(R.length===0)return()=>{};let S=new Map;for(let N of R)S.set(N,a.size);(async()=>{for(let N of R)if(typeof N.loadEntries=="function")try{let E=await Promise.resolve(N.loadEntries());E.entries.length>0&&a.size===0&&(a.restore(E.entries),S.set(N,E.entries.length),u());break}catch{}})();let x=d.subscribe(N=>{for(let E of N){if(E[0]!==_)continue;let D=E[1];for(let M of R){let C=S.get(M)??0;if(D.length<C){try{let B=M.appendEntries(D);B instanceof Promise&&B.catch(()=>{})}catch{}S.set(M,D.length);continue}if(D.length===C)continue;let $=D.slice(C);S.set(M,D.length);try{let B=M.appendEntries($);B instanceof Promise&&B.catch(()=>{})}catch{}}}});return()=>x()},disposeAllViews(){for(let R of c.values())R.dispose();c.clear();for(let R of l.values())R.dispose();l.clear();for(let R of p.values())R.dispose();p.clear()},dispose(){for(let R of c.values())R.dispose();c.clear();for(let R of l.values())R.dispose();l.clear();for(let R of p.values())R.dispose();p.clear()}};return k}var Va=new WeakMap;function Kc(t){let e=Va.get(t);if(e)return e;let n=t.map(c=>c.cache??[]),r=n.flat(),o=O(r,{name:"mergeReactiveLogs",describeKind:"state",equals:(c,l)=>c===l}),s=t.map((c,l)=>[...n[l]??[]]),i=[];for(let c=0;c<t.length;c++){let l=c,p=t[l].subscribe(f=>{for(let m of f)if(m[0]===_)s[l]=[...m[1]],o.emit(s.flat());else if(m[0]===I){s[l]=[];let h=i[l];h!==void 0&&(i[l]=void 0,h())}else m[0]===L&&o.down([[L,m[1]]])});i.push(p)}let a=te(o),d=!1,u={node:o,dispose(){if(!d){d=!0;for(let c of i)c?.();i.length=0,a(),Va.delete(t)}}};return Va.set(t,u),u}function On(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[se],[_,n+1]]),!0)}var Ka=Dt((t,e)=>{t("observe"),t("signal"),e("write")});function ot(t){let e=qe([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??Ka,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function qa(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))qa(t[e]);return Object.freeze(t)}function An(t){let e=t.cache,r=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return t.down([[se],[_,r]]),r}function lr(t,e,n,r,o,s){let i=e(n,r,o);if(i===void 0)return;let a=s!=null?{...i,handlerVersion:s}:i;t.append(a)}function dt(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(qa):o,i=oe(),a=e.seq?An(e.seq):void 0;try{let d=t(...s);return e.onSuccess&&lr(e.audit,e.onSuccess,s,d,{t_ns:i,seq:a},e.handlerVersion),d}catch(d){if(e.onFailure){let u=d instanceof Error?d.name:typeof d;lr(e.audit,e.onFailure,s,d,{t_ns:i,seq:a,errorType:u},e.handlerVersion)}throw d}}}function Zt(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(qa):o,i=oe(),a,d,u=!1,c;try{Z(()=>{e.seq&&(c=An(e.seq));try{a=t(...s),e.onSuccess&&lr(e.audit,e.onSuccess,s,a,{t_ns:i,seq:c},e.handlerVersion)}catch(l){throw d=l,u=!0,l}})}catch(l){if(u&&e.onFailure){let p=d instanceof Error?d.name:typeof d;lr(e.audit,e.onFailure,s,d,{t_ns:i,seq:c,errorType:p},e.handlerVersion)}throw u?d:l}return a}}function _t(t,e,n=0){let r=O(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function Ns(t,e,n,r=0){let o={},s=new Q(e);for(let i of n){let a=O(r,{name:i,describeKind:"state"});s.add(a,{name:i}),o[i]=a}return t.mount(e,s),o}var Xa={};Ne(Xa,{ENVELOPE_VERSION:()=>Un,GRAPH_META_SEGMENT:()=>rt,Graph:()=>Q,JsonCodec:()=>Wo,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>xs,SNAPSHOT_VERSION:()=>wt,createDagCborCodec:()=>ga,createDagCborZstdCodec:()=>ha,decodeEnvelope:()=>Dr,diffForWAL:()=>Ss,encodeEnvelope:()=>Ir,explainPath:()=>Qr,graphProfile:()=>En,reachable:()=>Mn,registerBuiltinCodecs:()=>Pr,replayWAL:()=>ya,sizeof:()=>Xr,validateGraphObservability:()=>Qa,watchTopologyTree:()=>Cn});Uo();ae();function Cn(t,e){let n=new Map,r=(o,s)=>{if(n.has(o))return;let i={off:()=>{},prefix:s};n.set(o,i);let a=o.topology.subscribe(d=>{for(let u of d){if(u[0]!==_)continue;let c=u[1];if(e(c,o,s),c.kind==="added"&&c.nodeKind==="mount"){let l=o._mounts.get(c.name);if(l instanceof Q){let p=`${s}${c.name}::`;r(l,p)}}else if(c.kind==="removed"&&c.nodeKind==="mount"){let l=`${s}${c.name}::`;for(let[p,f]of Array.from(n.entries()))p!==t&&f.prefix.startsWith(l)&&(f.off(),n.delete(p))}}});i.off=a;for(let[d,u]of o._mounts)if(u instanceof Q){let c=`${s}${d}::`;r(u,c)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}function za(t){return t>=768&&t<=879||t>=1155&&t<=1161||t>=1425&&t<=1469||t>=1552&&t<=1562||t>=1611&&t<=1631||t>=1648&&t===1648||t>=1750&&t<=1756||t>=1759&&t<=1764||t>=1767&&t<=1768||t>=1770&&t<=1773||t>=1840&&t<=1866||t>=1958&&t<=1968||t>=2304&&t<=2307||t>=2362&&t<=2383||t>=2385&&t<=2391||t>=2402&&t<=2403||t>=2433&&t<=2435||t>=2492&&t<=2509||t>=2561&&t<=2563||t>=2620&&t<=2641||t>=2672&&t<=2673||t>=2677&&t===2677||t>=3633&&t===3633||t>=3636&&t<=3642||t>=3655&&t<=3662||t>=3761&&t===3761||t>=3764&&t<=3772||t>=3784&&t<=3790||t>=7616&&t<=7679||t>=8400&&t<=8447||t>=65024&&t<=65039||t>=65056&&t<=65071||t===8205?0:t>=4352&&t<=4447||t>=8986&&t<=8987||t>=9001&&t<=9002||t>=9193&&t<=9203||t>=9208&&t<=9210||t>=9725&&t<=9726||t>=9748&&t<=9749||t>=9800&&t<=9811||t===9855||t===9875||t===9889||t>=9898&&t<=9899||t>=9917&&t<=9918||t>=9924&&t<=9925||t===9934||t===9940||t===9962||t>=9970&&t<=9971||t===9973||t===9978||t===9981||t===9986||t===9989||t>=9992&&t<=9997||t===9999||t>=10067&&t<=10069||t===10071||t>=10133&&t<=10135||t===10160||t===10175||t>=10548&&t<=10549||t>=11013&&t<=11015||t>=11035&&t<=11036||t===11088||t===11093||t>=11904&&t<=12350||t>=12352&&t<=12447||t>=12448&&t<=12543||t>=12549&&t<=12591||t>=12593&&t<=12686||t>=12688&&t<=12771||t>=12784&&t<=12830||t>=12832&&t<=12871||t>=12880&&t<=19903||t>=19968&&t<=40959||t>=43360&&t<=43388||t>=44032&&t<=55203||t>=63744&&t<=64255||t>=65040&&t<=65049||t>=65072&&t<=65131||t>=65281&&t<=65376||t>=65504&&t<=65510||t>=126980&&t===126980||t===127183||t>=127344&&t<=127345||t===127358||t===127359||t===127374||t>=127377&&t<=127386||t>=127456&&t<=127487||t>=127488&&t<=127490||t===127514||t===127535||t>=127538&&t<=127546||t>=127568&&t<=127569||t>=127744&&t<=129535||t>=129536&&t<=129791||t>=129792&&t<=130047||t>=131072&&t<=196605||t>=196608&&t<=262141?2:1}function pr(t){let e=0;for(let n of t)e+=za(n.codePointAt(0));return e}function qc(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=za(o.codePointAt(0));if(n+s>e){if(e<=1)return"\u2026";for(;n+1>e&&r.length>0;){let i=[...r].pop();r=r.slice(0,-i.length),n-=za(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var Ag={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"},Cg={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function Uc(t,e){let n=e.charset==="ascii"?Cg:Ag,r=t.width,o=t.height,s=Array.from({length:o},()=>Array.from({length:r},()=>" ")),i=Array.from({length:o},()=>Array.from({length:r},()=>"empty"));for(let a of t.edges)Ig(s,i,n,a);for(let a of t.boxes)Lg(s,i,n,a,e.labelOf(a.id));return s.map(a=>Fg(a.join(""))).join(`
|
|
12
|
+
`)}function Lg(t,e,n,r,o){let{x:s,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&zc(t,e,s,i,a,o);return}en(t,e,s,i,n.boxTL);for(let c=s+1;c<s+a-1;c+=1)en(t,e,c,i,n.boxH);en(t,e,s+a-1,i,n.boxTR);for(let c=i+1;c<i+d-1;c+=1){en(t,e,s,c,n.boxV);for(let l=s+1;l<s+a-1;l+=1)Jc(t,e,l,c," ","empty");en(t,e,s+a-1,c,n.boxV)}en(t,e,s,i+d-1,n.boxBL);for(let c=s+1;c<s+a-1;c+=1)en(t,e,c,i+d-1,n.boxH);en(t,e,s+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);zc(t,e,s+1,u,a-2,o)}function en(t,e,n,r,o){Jc(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function Jc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];n<0||n>=i.length||(i[n]=o,e[r][n]=s)}function zc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=n,a=o;for(let d of s){let u=pr(d);if(u!==0){if(a<u)break;i>=0&&i<t[r].length&&(t[r][i]=d,e[r][i]="label",u===2&&i+1<t[r].length&&(t[r][i+1]="",e[r][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<t[r].length&&(t[r][i]=" ",e[r][i]="empty"),i+=1,a-=1}function Ig(t,e,n,r){let o=r.points;if(o.length<2)return;for(let d=0;d+1<o.length;d+=1)Dg(t,e,n,o[d],o[d+1]);for(let d=1;d+1<o.length;d+=1){let u=o[d-1],c=o[d],l=o[d+1],p=Pg(u,c,l,n);p&&Wc(t,e,c.x,c.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=Gg(i,s,n);a&&Wc(t,e,s.x,s.y,a,"arrow")}function Dg(t,e,n,r,o){if(!(r.x===o.x&&r.y===o.y)){if(r.y===o.y){let s=r.y,i=Math.min(r.x,o.x),a=Math.max(r.x,o.x);for(let d=i;d<=a;d+=1)Hc(t,e,d,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 d=i;d<=a;d+=1)Hc(t,e,s,d,n,"v")}}}function Hc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[n]=s==="h"?o.horizontal:o.vertical,e[r][n]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[n]=o.cross,e[r][n]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[n]=o.cross,e[r][n]="edgeCorner";return}}}function Wc(t,e,n,r,o,s){if(r<0||r>=t.length)return;let i=t[r];if(n<0||n>=i.length)return;let a=e[r][n];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[n]=o,e[r][n]=s)}function Pg(t,e,n,r){let o=t.y===e.y,s=e.y===n.y;if(o===s)return;if(o){let d=t.x<e.x,u=n.y>e.y;return d&&u?r.cornerTR:d&&!u?r.cornerBR:!d&&u?r.cornerTL:r.cornerBL}let i=t.y<e.y,a=n.x>e.x;return i&&a?r.cornerBL:i&&!a?r.cornerBR:!i&&a?r.cornerTL:r.cornerTR}function Gg(t,e,n){if(e.x>t.x)return n.arrowRight;if(e.x<t.x)return n.arrowLeft;if(e.y>t.y)return n.arrowDown;if(e.y<t.y)return n.arrowUp}function Fg(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}function Xc(t){let e=$g(t);jg(e),Bg(e),Vg(e),Kg(e,t);let n=Hg(e,t),{width:r,height:o}=Ug(e),s=[];for(let i of e.layers)for(let a of i)a.isVirtual||s.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:s,edges:n,width:r,height:o}}function $g(t){let e=new Map;for(let o of t.nodes)e.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:t.widthCells(o),h:t.heightCells(o),in:[],out:[]});let n=[],r=0;for(let o of t.edges){if(o.from===o.to)continue;let s=e.get(o.from),i=e.get(o.to);if(!s||!i)continue;let a={chainId:r++,chainFrom:o.from,chainTo:o.to,fromId:o.from,toId:o.to,hopIndex:0,chainLen:1};s.out.push(a),i.in.push(a),n.push(a)}return{nodes:e,layers:[],hops:n}}function jg(t){let e=new Map;for(let s of t.nodes.values())e.set(s.id,s.in.length);let n=[];for(let s of t.nodes.values())(e.get(s.id)??0)===0&&(s.layer=0,n.push(s));let r=new Set,o=0;for(;o<n.length;){let s=n[o++];if(!r.has(s.id)){r.add(s.id);for(let i of s.out){let a=t.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let d=(e.get(a.id)??0)-1;e.set(a.id,d),d<=0&&n.push(a)}}}for(let s of t.nodes.values())s.layer<0&&(s.layer=0)}function Bg(t){let e=Math.max(0,...Array.from(t.nodes.values(),s=>s.layer)),n=Array.from({length:e+1},()=>[]);for(let s of t.nodes.values())n[s.layer].push(s);let r=[],o=0;for(let s of t.hops){let i=t.nodes.get(s.fromId),a=t.nodes.get(s.toId),d=a.layer-i.layer;if(d<=0){i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);continue}if(d===1){s.hopIndex=0,s.chainLen=1,r.push(s);continue}i.out=i.out.filter(l=>l!==s),a.in=a.in.filter(l=>l!==s);let u=i;for(let l=1;l<d;l+=1){let p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+l,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};t.nodes.set(p,f),n[f.layer].push(f);let m={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:p,hopIndex:l-1,chainLen:d};u.out.push(m),f.in.push(m),r.push(m),u=f}let c={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:a.id,hopIndex:d-1,chainLen:d};u.out.push(c),a.in.push(c),r.push(c)}for(let s of n)for(let i=0;i<s.length;i+=1)s[i].order=i;t.layers=n,t.hops=r}function Vg(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Yc(t,t.layers[r],"in"),Es(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Yc(t,t.layers[r],"out"),Es(t.layers[r])}for(let n=0;n<2;n+=1){let r=!1;for(let o=1;o<t.layers.length;o+=1){let s=t.layers[o];for(let i=0;i+1<s.length;i+=1){let a=Qc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],Es(s),Qc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],Es(s))}}if(!r)break}}function Yc(t,e,n){let r=new Map;for(let o of e){let s=n==="in"?o.in:o.out;if(s.length===0){r.set(o.id,o.order);continue}let i=0,a=0;for(let d of s){let u=t.nodes.get(n==="in"?d.fromId:d.toId);u&&(i+=u.order,a+=1)}r.set(o.id,a===0?o.order:i/a)}e.sort((o,s)=>{let i=r.get(o.id),a=r.get(s.id);return i!==a?i-a:o.order-s.order})}function Es(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Qc(t,e,n,r){let o=r==="in"?e.in:e.out,s=r==="in"?n.in:n.out,i=0;for(let a of o)for(let d of s){let u=t.nodes.get(r==="in"?a.fromId:a.toId)?.order??0,c=t.nodes.get(r==="in"?d.fromId:d.toId)?.order??0;(e.order<n.order&&u>c||e.order>n.order&&u<c)&&(i+=1)}return i}function Kg(t,e){e.direction==="LR"?qg(t,e):zg(t,e)}function qg(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.w);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.x=n[o];for(let o of t.layers){let s=0;for(let i of o)i.y=s,s+=i.h+e.nodeGap}Zc(t,e,"y")}function zg(t,e){let n=[],r=0;for(let o=0;o<t.layers.length;o+=1){n.push(r);let s=0;for(let i of t.layers[o])s=Math.max(s,i.h);r+=s+e.layerGap}for(let o=0;o<t.layers.length;o+=1)for(let s of t.layers[o])s.y=n[o];for(let o of t.layers){let s=0;for(let i of o)i.x=s,s+=i.w+e.nodeGap}Zc(t,e,"x")}function Zc(t,e,n){let r=s=>n==="y"?s.h:s.w,o=e.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?t.layers.slice(1):t.layers.slice(0,-1).reverse();for(let a of i){let d=new Map;for(let c of a){let l=s===0?c.in:c.out;if(l.length===0)continue;let p=[];for(let m of l){let h=t.nodes.get(s===0?m.fromId:m.toId);if(!h)continue;let g=n==="y"?h.y:h.x;p.push(g+Math.floor(r(h)/2))}if(p.length===0)continue;p.sort((m,h)=>m-h);let f=p[Math.floor(p.length/2)];d.set(c.id,f-Math.floor(r(c)/2))}let u=0;for(let c of a){let l=d.get(c.id),p=n==="y"?c.y:c.x,m=Math.max(l??p,u);n==="y"?c.y=m:c.x=m,u=m+r(c)+o}}}}function Hg(t,e){let n=new Map;for(let u of t.hops){let c=n.get(u.chainId);c?c.push(u):n.set(u.chainId,[u])}for(let u of n.values())u.sort((c,l)=>c.hopIndex-l.hopIndex);let r=e.direction==="LR",o=u=>r?u.x:u.y,s=u=>r?u.w:u.h,i=u=>r?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<t.layers.length;u+=1){let c=t.layers[u],l=t.layers[u+1],p=0;for(let S of c)p=Math.max(p,o(S)+s(S));let f=Number.POSITIVE_INFINITY;for(let S of l)f=Math.min(f,o(S));let m=Number.isFinite(f)?f-1:p,h=Math.max(1,m-p+1),g=[];for(let S of c)for(let x of S.out)g.push(x);g.sort((S,x)=>{let N=i(t.nodes.get(S.fromId)),E=i(t.nodes.get(x.fromId));if(N!==E)return N-E;let D=i(t.nodes.get(S.toId)),M=i(t.nodes.get(x.toId));return D-M});let y=[],b=new Map;for(let S of g){let x=i(t.nodes.get(S.fromId)),N=i(t.nodes.get(S.toId)),E=Math.min(x,N),D=Math.max(x,N),M=-1;for(let C=0;C<y.length;C+=1){let $=y[C],B=!0;for(let G of $)if(G.lo<=D&&E<=G.hi){B=!1;break}if(B){$.push({lo:E,hi:D}),M=C;break}}M<0&&(y.push([{lo:E,hi:D}]),M=y.length-1),b.set(S,M)}let v=y.length,T=h>=Math.max(3,v+2),w=T?p+1:p,k=T?m-1:m,R=Math.max(1,k-w+1);for(let S of g){let x=b.get(S),N;if(v<=1)N=w+Math.floor(R/2);else{let E=(R-1)/(v-1);N=w+Math.floor(x*E)}a.set(S,Math.max(p,Math.min(m,N)))}}let d=[];for(let[,u]of n){let c=[];for(let p=0;p<u.length;p+=1){let f=u[p],m=t.nodes.get(f.fromId),h=t.nodes.get(f.toId),g=a.get(f),y=m.isVirtual?o(m):o(m)+s(m),b=h.isVirtual?o(h):o(h)-1,v=i(m),T=i(h);p===0&&_s(c,r,y,v),v!==T&&(_s(c,r,g,v),_s(c,r,g,T)),_s(c,r,b,T)}let l=u[0];d.push({from:l.chainFrom,to:l.chainTo,points:Wg(c)})}return d}function _s(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function Wg(t){let e=[];for(let n of t){let r=e[e.length-1];(!r||r.x!==n.x||r.y!==n.y)&&e.push(n)}return e}function Ug(t){let e=0,n=0;for(let r of t.layers)for(let o of r)e=Math.max(e,o.x+o.w),n=Math.max(n,o.y+o.h);return{width:e,height:n}}var Jg=24,Yg=4,Qg=1,Xg=3;function Ha(t,e){let n=Zg(e?.direction),r=Math.max(3,e?.maxLabelWidth??Jg),o=e?.asciiCharset??"unicode",s=Object.keys(t.nodes).sort(),i=new Set(s),a=t.edges.filter(p=>i.has(p.from)&&i.has(p.to)),d=new Map,u=new Map;for(let p of s){let f=qc(p,r);d.set(p,f),u.set(p,pr(f)+4)}let c=Xc({nodes:s,edges:a,widthCells:p=>u.get(p)??3,heightCells:()=>Xg,layerGap:Yg,nodeGap:Qg,direction:n}),l=Uc(c,{charset:o,labelOf:p=>d.get(p)??p});return e?.logger?.(l),l}function Zg(t){if(t===void 0||t==="LR")return"LR";if(t==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(t)}`)}function Ms(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Ms);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Ms(e[o]);return r}function el(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function tl(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function nl(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Os(t){let e=new Set,n=[];function r(o,s){let i=`${o}\0${s}`;e.has(i)||(e.add(i),n.push([o,s]))}for(let[o,s]of Object.entries(t.nodes)){let i=s.deps;if(i)for(let a of i)r(a,o)}for(let o of t.edges)r(o.from,o.to);return n}function As(t){if(t===void 0)return"LR";if(t==="TD"||t==="LR"||t==="BT"||t==="RL")return t;throw new Error(`invalid diagram direction ${String(t)}; expected one of: TD, LR, BT, RL`)}function rl(t){if(typeof t=="string")return JSON.stringify(t);if(typeof t=="number"||typeof t=="boolean"||t==null)return String(t);try{return JSON.stringify(t)}catch{return"[unserializable]"}}function Wa(t,e){let n=As(e?.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`direction: ${nl(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${tl(i)}"`)}for(let[i,a]of Os(t)){let d=o.get(i),u=o.get(a);!d||!u||s.push(`${d} -> ${u}`)}return s.join(`
|
|
13
|
+
`)}function Ua(t,e){let n=e?.includeEdges??!0,r=e?.includeSubgraphs??!0,{expand:o,...s}=t,i={...s,edges:n?t.edges:[],subgraphs:r?t.subgraphs:[]},a=JSON.stringify(Ms(i),null,e?.indent??2);return e?.logger?.(a),a}function tn(t,e){let n=As(e?.direction),r=Object.keys(t.nodes).sort(),o=new Map;for(let i=0;i<r.length;i+=1)o.set(r[i],`n${i}`);let s=[`flowchart ${n}`];for(let i of r){let a=o.get(i);s.push(` ${a}["${el(i)}"]`)}for(let[i,a]of Os(t)){let d=o.get(i),u=o.get(a);!d||!u||s.push(` ${d} --> ${u}`)}return s.join(`
|
|
14
|
+
`)}function ol(t,e){let n=e?.theme??"default",r=e?.autoSync??!0,s=JSON.stringify({code:t,mermaid:{theme:n},autoSync:r}),i=new TextEncoder().encode(s),a="";for(let u=0;u<i.length;u++)a+=String.fromCharCode(i[u]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function Ja(t,e){let n=tn(t,e);return ol(n,e)}function Ya(t,e){let n=e?.includeEdges??!0,r=e?.includeSubgraphs??!0,o=[];o.push(`Graph ${t.name}`),o.push("Nodes:");for(let i of Object.keys(t.nodes).sort()){let a=t.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${rl(a.value)}`)}if(n){o.push("Edges:");for(let i of t.edges)o.push(`- ${i.from} -> ${i.to}`)}if(r){o.push("Subgraphs:");for(let i of t.subgraphs)o.push(`- ${i}`)}let s=o.join(`
|
|
15
|
+
`);return e?.logger?.(s),s}var eh={json:t=>Ua(t),pretty:t=>Ya(t),mermaid:t=>tn(t),"mermaid-url":t=>Ja(t),d2:t=>Wa(t),ascii:t=>Ha(t)};function Qa(t,e={}){let n=[],r=e.requireFound??!0;if(e.skipDescribe!==!0)try{let u=t.describe(),c=new Set(Object.keys(u.nodes)),l=[];for(let[p,f]of Object.entries(u.nodes))for(let m of f.deps)m!==""&&!c.has(m)&&l.push(`${p} \u2192 ${m}`);for(let p of u.edges)c.has(p.from)||l.push(`edge.from: ${p.from}`),c.has(p.to)||l.push(`edge.to: ${p.to}`);l.length>0?n.push({kind:"describe",ok:!1,reason:`describe() has ${l.length} dangling pointer(s); nodes \u2289 deps`,danglingDeps:l}):n.push({kind:"describe",ok:!0,nodeCount:c.size,edgeCount:u.edges.length})}catch(u){n.push({kind:"describe",ok:!1,reason:`describe() threw: ${u instanceof Error?u.message:String(u)}`})}if((e.formats?.length??0)>0){let u=t.describe();for(let c of e.formats)try{let l=eh[c](u);typeof l!="string"||l.length===0?n.push({kind:"describe-format",ok:!1,format:c,reason:`${c} renderer returned empty or non-string output`}):n.push({kind:"describe-format",ok:!0,format:c,length:l.length})}catch(l){n.push({kind:"describe-format",ok:!1,format:c,reason:l instanceof Error?l.message:String(l)})}}for(let u of e.paths??[])try{t.resolve(u),n.push({kind:"observe",ok:!0,path:u})}catch(c){n.push({kind:"observe",ok:!1,path:u,reason:c instanceof Error?c.message:String(c)})}for(let[u,c]of e.pairs??[])try{let l=t.explain(u,c);r&&l.found===!1?n.push({kind:"explain",ok:!1,from:u,to:c,reason:`explain(${u} \u2192 ${c}) found no path${l.reason?`: ${l.reason}`:""}`}):n.push({kind:"explain",ok:!0,from:u,to:c,found:l.found,steps:l.steps.length})}catch(l){n.push({kind:"explain",ok:!1,from:u,to:c,reason:l instanceof Error?l.message:String(l)})}let o=n.filter(u=>!u.ok),s=o.length===0,i=e.paths?.length??0,a=e.pairs?.length??0,d=e.formats?.length??0;return{ok:s,checks:n,failures:o,summary(){let u=[e.skipDescribe===!0?null:"describe",d>0?`${d} format${d===1?"":"s"}`:null,i>0?`${i} observe path${i===1?"":"s"}`:null,a>0?`${a} explain pair${a===1?"":"s"}`:null].filter(l=>l!=null),c=u.length>0?u.join(", "):"describe-only";return s?`validateGraphObservability: OK (${c})`:`validateGraphObservability: ${o.length} failure(s) across ${c}`}}}var nn=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},Cs=class extends nn{constructor(n,r){super(`Duplicate ${n} registration: "${r}"`);this.kind=n;this.registrationName=r}},Ls=class extends nn{constructor(n,r,o){super(`Command "${n}" emitted undeclared event "${r}". Declared emits: [${o.join(", ")}]`);this.commandName=n;this.eventName=r;this.declaredEmits=o}},Is=class extends nn{constructor(n,r,o){super(`Optimistic concurrency conflict on aggregate "${n}": expected version ${r}, got ${o}`);this.aggregateId=n;this.expected=r;this.actual=o}},Ds=class extends nn{constructor(n){super(`Unknown command: "${n}". Register with command() first.`);this.commandName=n}},to=class extends nn{constructor(n,r){super(`Command handler "${n}" threw: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.commandName=n}};var no=class extends nn{constructor(n,r){super(`Projection "${n}" rebuild failed: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.projectionName=n}};at();ue();var th=Dt((t,e)=>{t("write"),t("signal"),e("observe")}),nh=Dt((t,e)=>{t("observe"),t("signal"),e("write")}),sl=Dt((t,e)=>{t("observe"),t("signal"),e("write")});function ro(t,e){return xe("cqrs",t,e)}function Za(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))Za(t[e]);return Object.freeze(t)}var rh=t=>`${t.type}::${t.aggregateId??"__default__"}`,oh=t=>t.commandName,sh=t=>t.eventType,Ps=class extends Q{_eventLogs=new Map;_eventLogsByAggregate=new Map;_aggregateVersions=new Map;_aggregateLru=new Map;_commandRegs=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_seq=0;_retainedLimit;_freezeCommandPayload;_freezeEventPayload;_maxAggregates;_dispatchSeqCursor;dispatches;audit;aggregateEvictions;constructor(e,n={}){super(e,n.graph),this._retainedLimit=n.retainedLimit??1024,this._freezeCommandPayload=n.freezeCommandPayload??!0,this._freezeEventPayload=n.freezeEventPayload??!0,this._maxAggregates=n.maxAggregates??1e4,this.dispatches=ot({name:"dispatches",retainedLimit:this._retainedLimit,graph:this}),this.audit=this.dispatches,this.aggregateEvictions=ot({name:"aggregateEvictions",retainedLimit:this._retainedLimit,graph:this}),this._dispatchSeqCursor=_t(this,"dispatch_seq",0)}aggregateVersion(e,n){return this._aggregateVersions.get(`${e}::${n}`)??0}_touchAggregate(e){this._aggregateLru.delete(e),this._aggregateLru.set(e,!0)}_enforceAggregateLru(){for(;this._aggregateLru.size>this._maxAggregates;){let e=this._aggregateLru.keys().next();if(e.done)break;let n=e.value;this._aggregateLru.delete(n);let r=n.indexOf("::");if(r<0)continue;let o=n.slice(0,r),s=n.slice(r+2),i=this._aggregateVersions.get(n)??0;this._aggregateVersions.delete(n);let a=this._eventLogsByAggregate.get(o);a&&(a.delete(s),a.size===0&&this._eventLogsByAggregate.delete(o)),this.aggregateEvictions.append({aggregateId:s,type:o,lastVersion:i,t_ns:oe()})}}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}_attachedEventTiers=[];_attachedTierDisposers=new Map;attachEventStorage(e){this._attachedEventTiers.push(e);for(let[n,r]of this._eventLogs){let o=r.log.attachStorage(e),s=this._attachedTierDisposers.get(n);s||(s=[],this._attachedTierDisposers.set(n,s)),s.push(o)}for(let[n,r]of this._eventLogsByAggregate)for(let[o,s]of r){let i=`${n}::${o}`,a=s.log.attachStorage(e),d=this._attachedTierDisposers.get(i);d||(d=[],this._attachedTierDisposers.set(i,d)),d.push(a)}return()=>{let n=this._attachedEventTiers.indexOf(e);n>=0&&this._attachedEventTiers.splice(n,1)}}_autoWireStreamStorage(e,n){if(this._attachedEventTiers.length===0)return;let r=this._attachedTierDisposers.get(e);r||(r=[],this._attachedTierDisposers.set(e,r));for(let o of this._attachedEventTiers)r.push(n.attachStorage(o))}_bumpDispatchSeq(){let n=(this._dispatchSeqCursor.cache??0)+1;return this._dispatchSeqCursor.emit(n),n}event(e,n){if(n!==void 0)return this._ensureAggregateStream(e,n).node;let r=this._eventLogs.get(e);if(r)return r.node;let o=qe([],{name:e,versioning:0,maxSize:this._retainedLimit});o.withLatest();let s=o.entries,i=A([s],([a])=>a,{name:e,describeKind:"state",meta:ro("event",{event_name:e}),guard:sl,initial:s.cache});return this.add(i,{name:e}),this._keepaliveDisposers.push(te(i)),this._eventLogs.set(e,{log:o,node:i}),this._autoWireStreamStorage(e,o),i}_ensureAggregateStream(e,n){this._eventLogs.has(e)||this.event(e);let r=this._eventLogsByAggregate.get(e);r||(r=new Map,this._eventLogsByAggregate.set(e,r));let o=`${e}::${n}`;this._touchAggregate(o);let s=r.get(n);if(s)return s;let i=`${e}_${n.replace(/[^a-zA-Z0-9_-]/g,"_")}`,a=qe([],{name:i,versioning:0,maxSize:this._retainedLimit});a.withLatest();let d=a.entries,u=A([d],([f])=>f,{name:i,describeKind:"state",meta:ro("event_aggregate",{event_name:e,aggregate_id:n}),guard:sl,initial:d.cache}),c=i,l=0;for(;this.nameOf(this.resolveOptional(c)??u)===c&&(l+=1,c=`${i}_${l}`,this.resolveOptional(c)!==void 0););try{this.add(u,{name:c})}catch{}this._keepaliveDisposers.push(te(u));let p={log:a,node:u};return r.set(n,p),this._autoWireStreamStorage(`${e}::${n}`,a),this._enforceAggregateLru(),p}resolveOptional(e){try{return this.resolve(e)}catch{return}}_appendEvent(e,n,r){let o=this._eventLogs.get(e);if(o||(this.event(e),o=this._eventLogs.get(e)),o.node.status==="completed"||o.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${o.node.status}).`);let s,i;if(r?.aggregateId!==void 0){let c=`${e}::${r.aggregateId}`;s=(this._aggregateVersions.get(c)??0)+1,this._aggregateVersions.set(c,s),i=this._ensureAggregateStream(e,r.aggregateId)}let a=o.log.entries.v,d=this._freezeEventPayload?Za(n):n,u={type:e,payload:d,timestampNs:oe(),seq:++this._seq,...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...s!==void 0?{aggregateVersion:s}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...r?.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{},...a!=null?{v0:{id:a.id,version:a.version}}:{}};return o.log.append(u),i&&i.log.append(u),u}command(e,n){if(this._commandRegs.has(e))throw new Cs("command",e);let r=typeof n=="function"?{handler:n}:n,o=O(void 0,{name:e,describeKind:"state",meta:{...ro("command",{command_name:e}),error:null},guard:th});if(this.add(o,{name:e}),this._commandRegs.set(e,{handler:r.handler,...r.emits!==void 0?{emits:r.emits}:{},...r.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{}}),r.emits)for(let s of r.emits)this._eventLogs.has(s)||this.event(s);return o}dispatch(e,n,r){let o=this._commandRegs.get(e);if(!o)throw new Ds(e);if(r?.aggregateId!==void 0&&r.expectedAggregateVersion!==void 0&&o.emits!==void 0){let p=0;for(let f of o.emits){let m=this._aggregateVersions.get(`${f}::${r.aggregateId}`);m!==void 0&&m>p&&(p=m)}if(p!==r.expectedAggregateVersion)throw new Is(r.aggregateId,r.expectedAggregateVersion,p)}let s=this.resolve(e),i=this._freezeCommandPayload?Za(n):n,a=[],d=oe(),u=0,c,l=!1;try{Z(()=>{u=this._bumpDispatchSeq(),s.emit(i,{internal:!0});try{o.handler(i,{emit:(p,f)=>{if(o.emits!==void 0&&!o.emits.includes(p))throw new Ls(e,p,o.emits);a.push(p),this._appendEvent(p,f,{...r?.aggregateId!==void 0?{aggregateId:r.aggregateId}:{},...r?.correlationId!==void 0?{correlationId:r.correlationId}:{},...r?.causationId!==void 0?{causationId:r.causationId}:{},...r?.metadata!==void 0?{metadata:Object.freeze({...r.metadata})}:{},...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}}),s.meta.error.emit(null,{internal:!0}),this.dispatches.append({commandName:e,payload:i,outcome:"success",emittedEvents:[...a],t_ns:d,seq:u,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}catch(p){throw c=p,l=!0,p}})}catch(p){if(l){s.meta.error.emit(c,{internal:!0});let f=c instanceof Error?c.name:typeof c,m=c instanceof to?c:new to(e,c);this.dispatches.append({commandName:e,payload:i,outcome:"failure",error:m,errorType:f,emittedEvents:[...a],t_ns:d,seq:u,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}})}throw l?c:p}}projection(e){let{name:n,events:r,reducer:o,initial:s}=e,i=e.mode??"scan",a=e.freezeInputs??!0,d=e.snapshot,u=r.map(N=>(this._eventLogs.has(N)||this.event(N),this._eventLogs.get(N).node));function c(N){N.sort((E,D)=>E.timestampNs-D.timestampNs||E.seq-D.seq||(E.aggregateId??"").localeCompare(D.aggregateId??""))}function l(N){let E=[];for(let D of N)E.push(...D);return c(E),E}let p=u.map(N=>N.cache??[]),f=l(p),m=a?Object.freeze(f):f,h=0,g=s;i==="scan"&&f.length>0&&(g=o(s,m),h=f.length);let y=i==="replay"?o(s,m):g,b=d?.saveDebounceMs??1e3,v=d?.saveEvery??1e3,T,w=0;function k(N){if(d?.save){if(w+=1,w>=v){w=0,T!==void 0&&(clearTimeout(T),T=void 0);let E=d.save(N);E instanceof Promise&&E.catch(()=>{});return}T!==void 0&&clearTimeout(T),T=setTimeout(()=>{T=void 0,w=0;let E=d.save(N);E instanceof Promise&&E.catch(()=>{})},b)}}let R=A(u,N=>{let E=l(N),D;if(i==="replay"){let M=a?Object.freeze(E):E;D=o(s,M)}else{let M=E.slice(h);h=E.length;let C=a?Object.freeze(M):M;D=o(g,C),g=D}return k(D),D},{name:n,describeKind:"derived",meta:ro("projection",{projection_name:n,source_events:r}),guard:nh,initial:y});return this.add(R,{name:n}),this._keepaliveDisposers.push(te(R)),this._keepaliveDisposers.push(()=>{T!==void 0&&(clearTimeout(T),T=void 0)}),this._projections.add(n),{node:R,rebuild:async N=>{try{let E=N?.pageSize??1e3,D=N?.fromTier??this._attachedEventTiers[0]?.[0],M=l(u.map($=>$.cache??[])).length,C=s;if(d?.load){let $=await d.load();$!==void 0&&(C=$)}if(!D||!D.loadEntries){let $=l(u.map(G=>G.cache??[])),B=a?Object.freeze($):$;C=o(C,B)}else{let $=new Set(r),B,G=!1;for(;!G;){let V=await D.loadEntries({cursor:B,pageSize:E}),F=[...V.entries].filter(P=>$.has(P.type));c(F);let K=a?Object.freeze(F):F;C=o(C,K),B=V.cursor,G=!B||V.entries.length===0}}if(i==="scan"){let $=l(u.map(G=>G.cache??[])),B=$.slice(M);if(B.length>0){let G=a?Object.freeze(B):B;C=o(C,G)}g=C,h=$.length}return R.emit(C,{internal:!0}),C}catch(E){throw new no(n,E)}},reset:async()=>{try{let N=s;if(d?.load){let C=await d.load();C!==void 0&&(N=C)}let E=l(u.map(C=>C.cache??[])),D=a?Object.freeze(E):E,M=o(N,D);return i==="scan"&&(g=M,h=E.length),R.emit(M,{internal:!0}),M}catch(N){throw new no(n,N)}}}}saga(e,n,r,o={}){let s=n.map(f=>(this._eventLogs.has(f)||this.event(f),this._eventLogs.get(f).node)),i=Ns(this,`${e}_cursor`,n,0),a=ot({name:`${e}_invocations`,retainedLimit:this._retainedLimit,graph:this}),d=o.aggregateId,u=o.errorPolicy??"advance",c=new Map;for(let f of n){let m=i[f];c.set(f,m.cache??0);let h=m.subscribe(g=>{for(let y of g)y[0]===_&&c.set(f,y[1])});this._keepaliveDisposers.push(h)}let l={},p=U(s,(f,m)=>{let h=l.n.meta.error;for(let g=0;g<f.length;g++){let y=f[g];if(y==null||y.length===0)continue;let b=y.at(-1);if(!b)continue;let v=n[g],T=i[v],w=c.get(v)??0;if(b.length>w){let k=b.slice(w),R=w;for(let S of k){let x=S;if(d!==void 0&&x.aggregateId!==d){R+=1;continue}try{r(x),h.emit(null,{internal:!0}),a.append({eventType:v,outcome:"success",aggregateId:x.aggregateId,event:x,t_ns:oe(),...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),R+=1}catch(N){if(h.emit(N,{internal:!0}),a.append({eventType:v,outcome:"failure",error:N,errorType:N instanceof Error?N.name:typeof N,aggregateId:x.aggregateId,event:x,t_ns:oe(),...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),u==="hold")break;R+=1}}T.emit(R)}}},{name:e,describeKind:"effect",meta:{...ro("saga",{saga_name:e,source_events:n}),error:null}});return l.n=p,this.add(p,{name:e}),this._keepaliveDisposers.push(te(p)),this._sagas.add(e),{node:p,invocations:a,audit:a,cursors:i}}};function ed(t,e){let n=new Ps(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("cqrs",We(s)),n}var nd=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},rd=class{graph=new Q("request");onModuleDestroy(){this.graph.destroy()}},il,td;il=[(0,oo.Module)({})];var rn=class rn{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:gt,useFactory:()=>{let s=new Q(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new nd(s),inject:[gt]},{provide:Nn,useFactory:(s,i)=>new Nn(s,i),inject:[gt,al.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:yt(s),useFactory:i=>i.resolve(s),inject:[gt]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new rd,scope:oo.Scope.REQUEST},{provide:yn,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:oo.Scope.REQUEST}),{module:rn,global:!0,providers:o,exports:[gt,...(n.nodes??[]).map(yt),...n.requestScope?[yn]:[]]}}static forFeature(e){let n=[{provide:ct(e.name),useFactory:r=>{let o=new Q(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),r.mount(e.name,o),o},inject:[gt]}];if(e.nodes)for(let r of e.nodes)n.push({provide:yt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[ct(e.name)]});return{module:rn,providers:n,exports:[ct(e.name),...(e.nodes??[]).map(r=>yt(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:ct(e.name),useFactory:r=>{let o=ed(e.name,e.cqrs);return e.eventStorage&&o.attachEventStorage(e.eventStorage),e.build&&e.build(o),r.mount(e.name,o),o},inject:[gt]}];if(e.nodes)for(let r of e.nodes)n.push({provide:yt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[ct(e.name)]});return{module:rn,providers:n,exports:[ct(e.name),...(e.nodes??[]).map(r=>yt(`${e.name}::${r}`))]}}};td=Au(null),rn=Iu(td,0,"GraphReflyModule",il,rn),Lu(td,1,rn);var Fs=rn;var js={};Ne(js,{useStore:()=>ih,useSubscribe:()=>dl,useSubscribeRecord:()=>ah});var Ft=require("react");ae();function dl(t){return(0,Ft.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function ih(t){let e=dl(t),n=(0,Ft.useCallback)(r=>{t.down([[se],[_,r]])},[t]);return[e,n]}function ah(t,e){let n=(0,Ft.useRef)(e);n.current=e;let r=(0,Ft.useMemo)(()=>{let o=()=>{let i={},a=t.cache??[];for(let d of a){let u=n.current(d),c={};for(let l of Object.keys(u))c[l]=u[l].cache;i[d]=c}return i},s=o();return{subscribe:i=>{let a=!1,d=[],u=()=>{for(let p of d)p();d=[]},c=p=>{u();for(let f of p){let m=n.current(f);for(let h of Object.keys(m)){let g=m[h].subscribe(()=>{s=o(),a||i()});d.push(g)}}s=o(),a||i()},l=t.subscribe(p=>{let f=p.some(m=>m[0]===_||m[0]===q);!a&&f&&c(t.cache??[])});return c(t.cache??[]),()=>{a=!0,l(),u()}},getSnapshot:()=>s}},[t]);return(0,Ft.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var Vs={};Ne(Vs,{Signal:()=>dh});Ae();ae();ne();var fr=[];function Bs(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===_&&(e=s)})(),e}var od=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=O(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=fr[fr.length-1];return e?(this._node.status==="sentinel"&&Bs(this._node),e(this._node)):this._node.status==="sentinel"?Bs(this._node):this._node.cache}set(e){this._equals(this.get(),e)||Z(()=>{this._node.down([[se],[_,e]])})}},sd=class{_node;constructor(e,n){this._node=hn(r=>{fr.push(r);try{return e()}finally{fr.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=fr[fr.length-1];return e?(this._node.status==="sentinel"&&Bs(this._node),e(this._node)):this._node.status==="sentinel"?Bs(this._node):this._node.cache}},dh={State:od,Computed:sd,sub:(t,e)=>{let n=typeof e=="function"?{data:e,error:void 0,complete:void 0}:e,r=!0;return t._node.subscribe(o=>{for(let[s,i]of o){if(s===_){if(r){r=!1;continue}n.data?.(i)}s===L&&n.error?.(i),s===I&&n.complete?.()}})}};var Ks={};Ne(Ks,{useStore:()=>uh,useSubscribe:()=>ul,useSubscribeRecord:()=>ch});var $t=require("solid-js");ae();function ul(t){let[e,n]=(0,$t.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,$t.getOwner)()?(0,$t.onCleanup)(()=>r()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),e}function uh(t){return[ul(t),r=>{t.down([[se],[_,r]])}]}function ch(t,e){let[n,r]=(0,$t.createSignal)({},{equals:!1}),o=[],s=()=>{for(let u of o)u();o=[]},i=()=>{let u={};for(let c of t.cache??[]){let l=e(c),p={};for(let f of Object.keys(l))p[f]=l[f].cache;u[c]=p}return u},a=u=>{s();for(let c of u){let l=e(c);for(let p of Object.keys(l)){let f=l[p].subscribe(()=>{r(()=>i())});o.push(f)}}r(()=>i())},d=t.subscribe(u=>{u.some(c=>c[0]===_||c[0]===q)&&a(t.cache??[])});return a(t.cache??[]),(0,$t.getOwner)()?(0,$t.onCleanup)(()=>{d(),s()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Solid reactive owner \u2014 subscription will not be auto-disposed."),n}var qs={};Ne(qs,{useStore:()=>ph,useSubscribe:()=>lh,useSubscribeRecord:()=>fh});ae();function lh(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function ph(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[se],[_,e]])},update(e){let n=e(t.cache);t.down([[se],[_,n]])}}}function fh(t,e){return{subscribe(n){let r=[],o=()=>{for(let d of r)d();r=[]},s=()=>{let d={};for(let u of t.cache??[]){let c=e(u),l={};for(let p of Object.keys(c))l[p]=c[p].cache;d[u]=l}return d},i=d=>{o();for(let u of d){let c=e(u);for(let l of Object.keys(c)){let p=c[l].subscribe(()=>{n(s())});r.push(p)}}n(s())},a=t.subscribe(d=>{d.some(u=>u[0]===_||u[0]===q)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var zs={};Ne(zs,{useStore:()=>gh,useSubscribe:()=>mh,useSubscribeRecord:()=>hh});var ze=require("vue");ae();function mh(t){let e=(0,ze.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,ze.getCurrentScope)()?(0,ze.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,ze.readonly)(e)}function gh(t){let e=(0,ze.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,ze.getCurrentScope)()?(0,ze.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,ze.computed)({get:()=>e.value,set:r=>{t.down([[se],[_,r]])}})}function hh(t,e){let n=(0,ze.shallowRef)({}),r=new Map;function o(){let a={};for(let[d,u]of r)a[d]={...u.values};n.value=a}function s(a){for(let u of r.values())for(let c of u.subs)c();r.clear();for(let u of a){let c=e(u),l=Object.keys(c),p={},f=[];for(let m of l){let h=c[m];p[m]=h.cache;let g=h.subscribe(()=>{p[m]=h.cache,o()});f.push(g)}r.set(u,{subs:f,values:p})}let d={};for(let[u,c]of r)d[u]={...c.values};n.value=d}return(0,ze.watch)(()=>[...(typeof t=="function"?t():(0,ze.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,ze.getCurrentScope)()?(0,ze.onScopeDispose)(()=>{for(let a of r.values())for(let d of a.subs)d();r.clear()}):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribeRecord called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,ze.readonly)(n)}var Hs={};Ne(Hs,{create:()=>bh});ae();ne();var yh=()=>!1;function bh(t){let e=new Q("zustand"),n=O(void 0,{name:"state",equals:yh});e.add(n,{name:"state"});let r=()=>n.cache,o=(a,d)=>{let u=n.cache,c=typeof a=="function"?a(u):a;n.emit(d?c:{...u,...c})},s={getState:r,setState:o,getInitialState:()=>i,subscribe:a=>{let d=!0,u=n.cache;return n.subscribe(c=>{for(let[l,p]of c)if(l===_){if(d){d=!1;continue}a(p,u),u=p}})},destroy:e.destroy.bind(e)},i=t(o,r,s);return n.emit(i),Object.assign(e,s)}var kd={};Ne(kd,{CircuitOpenError:()=>bt,ContentAddressedMissError:()=>fo,DEFAULT_AUDIT_GUARD:()=>Ka,NS_PER_MS:()=>Ue,NS_PER_SEC:()=>pt,NativeIndexBackend:()=>ho,NativeListBackend:()=>yo,NativeLogBackend:()=>eo,NativeMapBackend:()=>lo,NativePubSubBackend:()=>go,RateLimiterOverflowError:()=>Tn,ResettableTimer:()=>De,TimeoutError:()=>wn,appendAudit:()=>lr,appendLogStorage:()=>vd,audit:()=>Al,awaitSettled:()=>hs,budgetGate:()=>Wt,buffer:()=>Cl,bufferCount:()=>Ll,bufferTime:()=>Dl,bumpCursor:()=>An,cached:()=>kc,canonicalJson:()=>mo,cascadingCache:()=>Kp,catchError:()=>zl,checkpointToRedis:()=>Dp,checkpointToS3:()=>Ip,circuitBreaker:()=>Tt,combine:()=>dd,combineLatest:()=>Vl,concat:()=>Rl,concatMap:()=>El,constant:()=>ss,contentAddressedStorage:()=>Xs,createAuditLog:()=>ot,createTransport:()=>sn,createWatermarkController:()=>ur,csvRows:()=>hp,debounce:()=>cd,debounceTime:()=>Kl,decay:()=>Ot,decorrelatedJitter:()=>us,defer:()=>vc,delay:()=>Ml,deserializeError:()=>Pn,dictKv:()=>nf,dictSnapshot:()=>rf,distill:()=>Ys,distinctUntilChanged:()=>wl,domainMeta:()=>xe,elementAt:()=>bl,empty:()=>hc,escapeRegexChar:()=>La,exhaustMap:()=>Nl,exponential:()=>as,externalBundle:()=>Ws,externalProducer:()=>Ln,fallback:()=>ar,fibonacci:()=>ds,filter:()=>st,find:()=>yl,first:()=>Us,firstValueFrom:()=>nt,firstWhere:()=>ps,flatMap:()=>_l,forEach:()=>Qt,fromAny:()=>Y,fromAsyncIter:()=>Jr,fromCSV:()=>gp,fromClickHouseWatch:()=>Tp,fromCron:()=>fs,fromDrizzle:()=>jp,fromEvent:()=>gc,fromHTTP:()=>gd,fromHTTPPoll:()=>tp,fromHTTPStream:()=>ep,fromIter:()=>ms,fromKafka:()=>lp,fromKysely:()=>Bp,fromMCP:()=>op,fromNATS:()=>xp,fromNDJSON:()=>vp,fromOTel:()=>sp,fromPrisma:()=>$p,fromPrometheus:()=>cp,fromPromise:()=>dr,fromPulsar:()=>wp,fromRabbitMQ:()=>Sp,fromRaf:()=>mc,fromRedisStream:()=>fp,fromSSE:()=>Zl,fromSqlite:()=>Pp,fromSqliteCursor:()=>Gp,fromStatsD:()=>dp,fromSyslog:()=>ip,fromTimer:()=>tt,fromWebSocket:()=>md,fromWebSocketReconnect:()=>rp,fromWebhook:()=>Hl,globToRegExp:()=>pc,interval:()=>Fl,jsonCodec:()=>yr,jsonCodecFor:()=>Zp,keepalive:()=>te,kvStorage:()=>ri,last:()=>hl,lightMutation:()=>dt,linear:()=>is,lru:()=>bd,makeHttpError:()=>xt,map:()=>so,matchesAnyPattern:()=>fc,matchesCron:()=>os,memoryAppendLog:()=>tf,memoryBackend:()=>vo,memoryKv:()=>To,memorySnapshot:()=>ef,merge:()=>Mt,mergeMap:()=>ud,mergeReactiveLogs:()=>Kc,nameToSignal:()=>In,ndjsonRows:()=>yp,never:()=>yc,nodeSignal:()=>ys,of:()=>Ia,onFirstData:()=>ao,pairwise:()=>kl,parseCron:()=>rs,parsePrometheusText:()=>hd,parseSSEStream:()=>Bt,parseStatsD:()=>up,parseSyslog:()=>ap,pausable:()=>jl,pubsub:()=>Up,race:()=>Sl,rateLimiter:()=>Rn,reactiveCounter:()=>Rc,reactiveIndex:()=>Qp,reactiveList:()=>Zs,reactiveLog:()=>qe,reactiveMap:()=>Ye,reactiveSink:()=>Je,reduce:()=>fl,registerCursor:()=>_t,registerCursorMap:()=>Ns,repeat:()=>$l,replay:()=>gs,rescue:()=>uo,resolveBackoffPreset:()=>vn,retry:()=>vt,sample:()=>Ol,scan:()=>pl,serializeError:()=>Dn,share:()=>wc,shareReplay:()=>xc,signalToName:()=>on,singleFromAny:()=>ei,singleNodeFromAny:()=>Xp,skip:()=>ad,snapshotStorage:()=>ni,sortJsonValue:()=>bo,stableJsonString:()=>ti,stratify:()=>wo,switchMap:()=>me,take:()=>io,takeUntil:()=>gl,takeWhile:()=>ml,tap:()=>vl,tapFirst:()=>Tl,throttle:()=>ld,throttleTime:()=>ql,throwError:()=>bc,timeout:()=>Sn,toArray:()=>Tc,toCSV:()=>Ep,toClickHouse:()=>_p,toFile:()=>yd,toHTTP:()=>Wl,toKafka:()=>pp,toLoki:()=>Cp,toMongo:()=>Ap,toNATS:()=>Rp,toObservable:()=>ns,toPostgres:()=>Op,toPulsar:()=>kp,toRabbitMQ:()=>Np,toReadableStream:()=>Xl,toRedisStream:()=>mp,toS3:()=>Mp,toSSE:()=>Yl,toSSEBytes:()=>Ql,toSqlite:()=>Fp,toTempo:()=>Lp,toWebSocket:()=>np,tokenBucket:()=>Jt,topologyDiff:()=>cr,tryIncrementBounded:()=>On,valve:()=>Bl,verifiable:()=>Hp,window:()=>Gl,windowCount:()=>Il,windowTime:()=>Pl,withBreaker:()=>xn,withLatestFrom:()=>jt,withMaxAttempts:()=>Oa,withStatus:()=>Yt,workerBridge:()=>Td,workerSelf:()=>wd,wrapMutation:()=>Zt,zip:()=>xl});Ae();Se();ae();Me();ne();Ae();ae();ne();function cl(t){return{describeKind:"producer",...t}}function Ln(t,e){return z(n=>{let r=!0,o={emit(i){r&&n.emit(i)},error(i){r&&(r=!1,n.down([[L,i]]))},complete(){r&&(r=!1,n.down([[I]]))}},s;try{let i=t(o);s=typeof i=="function"?i:void 0}catch(i){return o.error(i),()=>{r=!1}}return()=>{r=!1;try{s?.()}catch{}}},cl(e))}function Ws(t,e,n){let r=!0,o,s=0,i=0,a={},d=[],u=()=>{let f=o;o=void 0;try{f?.()}catch{}};for(let f of e){let m=n?.name?`${n.name}::${f}`:f,h=n?.channelOpts?.[f],g=z(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&u()}),cl({...h,name:m}));a[f]=g,d.push(g)}let c={};for(let f of e)c[f]=m=>{r&&a[f].down([[_,m]])};c.error=f=>{r&&(r=!1,Z(()=>{for(let m of d)m.down([[L,f]])}),u())},c.complete=()=>{r&&(r=!1,Z(()=>{for(let f of d)f.down([[I]])}),u())};let l=t(c);return o=typeof l=="function"?l:void 0,Object.assign(a,{dispose:()=>{r&&(r=!1,Z(()=>{for(let f of d)try{f.down([[I]])}catch{}}),u())}})}Se();ae();et();Me();ne();ue();function pe(t){return{describeKind:"derived",...t}}function ll(t){return{describeKind:"derived",partial:!0,...t}}function so(t,e,n){return U([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[q]]);return}for(let i of s)o.emit(e(i))},{...pe(n),meta:{...be("map"),...n?.meta??{}}})}function st(t,e,n){return U([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[q]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[q]])},{...pe(n),meta:{...be("filter"),...n?.meta??{}}})}function pl(t,e,n,r){return U([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[q]]);return}for(let d of a)i.store.acc=e(i.store.acc,d),s.emit(i.store.acc)},{...pe(r),initial:n,resetOnTeardown:!0,meta:{...be("scan",{initial:n}),...r?.meta??{}}})}function fl(t,e,n,r){return U([t],(o,s,i)=>{if("acc"in i.store||(i.store.acc=n),i.terminalDeps[0]===!0){s.emit(i.store.acc),s.down([[I]]);return}let a=o[0];if(a==null||a.length===0){s.down([[q]]);return}for(let d of a)i.store.acc=e(i.store.acc,d)},{...pe(r),completeWhenDepsComplete:!1,meta:{...be("reduce",{initial:n}),...r?.meta??{}}})}function io(t,e,n){return e<=0?U([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[I]]))},{...pe(n),completeWhenDepsComplete:!1,meta:{...be("take",{count:e}),...n?.meta??{}}}):U([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[q]]);return}if(s.terminalDeps[0]===!0){s.store.done=!0,o.down([[I]]);return}let i=r[0];if(i==null||i.length===0){o.down([[q]]);return}for(let a of i)if(s.store.taken++,o.emit(a),s.store.taken>=e){s.store.done=!0,o.down([[I]]);return}},{...pe(n),completeWhenDepsComplete:!1,meta:{...be("take",{count:e}),...n?.meta??{}}})}function ad(t,e,n){return U([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[q]]);return}let a=!1;for(let d of i)s.store.skipped++,s.store.skipped<=e||(o.emit(d),a=!0);a||o.down([[q]])},pe(n))}function ml(t,e,n){return U([t],(r,o,s)=>{if(s.store.done){o.down([[q]]);return}let i=r[0];if(i==null||i.length===0){o.down([[q]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[I]]);return}o.emit(a)}},{...pe(n),completeWhenDepsComplete:!1})}function gl(t,e,n){let r=n?.predicate??(i=>i[0]===_),{predicate:o,...s}=n??{};return z(i=>{let a=!1,d=t.subscribe(c=>{if(!a)for(let l of c){if(a)return;l[0]===_?i.emit(l[1]):(l[0]===I||l[0]===L)&&(a=!0,i.down([l]))}}),u=e.subscribe(c=>{if(!a)for(let l of c){if(a)return;if(r(l)){a=!0,i.down([[I]]);return}}});return()=>{d(),u()}},pe(s))}function Us(t,e){return io(t,1,e)}function hl(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return U([t],(s,i,a)=>{if(a.terminalDeps[0]===!0){a.store.has?i.emit(a.store.latest):o&&i.emit(n),i.down([[I]]);return}let d=s[0];if(d==null||d.length===0){i.down([[q]]);return}a.store.latest=d.at(-1),a.store.has=!0},{...pe(r),completeWhenDepsComplete:!1})}function yl(t,e,n){return io(st(t,e,n),1,n)}function bl(t,e,n){return io(ad(t,e,n),1,n)}function vl(t,e,n){if(typeof e=="function")return U([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[q]]);return}for(let a of i)e(a),s.emit(a)},{...pe(n),meta:{...be("tap"),...n?.meta??{}}});let r=e;return U([t],(o,s,i)=>{if(i.terminalDeps[0]!==void 0){i.terminalDeps[0]===!0?(r.complete?.(),s.down([[I]])):(r.error?.(i.terminalDeps[0]),s.down([[L,i.terminalDeps[0]]]));return}let a=o[0];if(a==null||a.length===0){s.down([[q]]);return}for(let d of a)r.data?.(d),s.emit(d)},{...pe(n),completeWhenDepsComplete:!1,meta:{...be("tap"),...n?.meta??{}}})}function ao(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return U([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[q]]);return}for(let d of a)!o&&r(d)&&(o=!0,e(d)),i.emit(d)},pe(n))}var Tl=ao;function wl(t,e=Object.is,n){return U([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[q]]);return}let a=!1;for(let d of i)s.store.hasPrev&&e(s.store.prev,d)||(s.store.prev=d,s.store.hasPrev=!0,o.emit(d),a=!0);a||o.down([[q]])},{...pe(n),meta:{...be("distinctUntilChanged"),...n?.meta??{}}})}function kl(t,e){return U([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[q]]);return}let i=!1;for(let a of s)if(!o.store.hasPrev)o.store.prev=a,o.store.hasPrev=!0;else{let d=[o.store.prev,a];o.store.prev=a,r.emit(d),i=!0}i||r.down([[q]])},pe(e))}function dd(...t){let e=[...t];return A(e,n=>n,{...pe(),equals:(n,r)=>{if(n.length!==r.length)return!1;for(let o=0;o<n.length;o++)if(!Object.is(n[o],r[o]))return!1;return!0}})}function jt(t,e,n){return U([t,e],(r,o,s)=>{let i=r[0],a=r[1],d=a!=null&&a.length>0?a.at(-1):s.prevData[1];if(i!=null&&i.length>0){if(!(a!=null&&a.length>0)&&s.prevData[1]===void 0){o.down([[q]]);return}for(let u of i)o.emit([u,d])}else o.down([[q]])},{...ll(n),meta:{...be("withLatestFrom"),...n?.meta??{}}})}function Mt(...t){return t.length===0?z(e=>{e.down([[I]])},{...pe(),meta:{...be("merge")}}):z(e=>{let n=t.length,r=0,o=[];for(let s of t){let i=s.subscribe(a=>{for(let d of a)d[0]===_?e.emit(d[1]):d[0]===I?(r+=1,r>=n&&e.down([[I]])):d[0]===L&&e.down([d])});o.push(i)}return()=>{for(let s of o)s()}},{...pe(),meta:{...be("merge")}})}function xl(...t){let e=t.length;return e===0?z(n=>{n.emit([]),n.down([[I]])},pe()):z(n=>{let r=Array.from({length:e},()=>[]),o=e;function s(){for(;r.every(a=>a.length>0);){let a=r.map(d=>d.shift());n.emit(a)}}let i=[];for(let a=0;a<e;a++){let d=a,u=t[a].subscribe(c=>{for(let l of c)l[0]===_?(r[d].push(l[1]),s()):l[0]===I?(o-=1,(o===0||r[d].length===0)&&n.down([[I]])):l[0]===L&&n.down([l])});i.push(u)}return()=>{for(let a of i)a()}},pe())}function Rl(t,e,n){return z(r=>{let o=0,s=[],i,a;return a=e.subscribe(d=>{for(let u of d)o===0?u[0]===_?s.push(u[1]):u[0]===L&&r.down([u]):u[0]===_?r.emit(u[1]):(u[0]===I||u[0]===L)&&r.down([u])}),i=t.subscribe(d=>{for(let u of d)if(o===0)if(u[0]===_)r.emit(u[1]);else if(u[0]===I){o=1;for(let c of s)r.emit(c);s.length=0}else u[0]===L&&r.down([u])}),()=>{i?.(),a?.()}},pe(n))}function Sl(...t){return t.length===0?z(e=>{e.down([[I]])},pe()):t.length===1?U([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[q]]);return}for(let o of r)n.emit(o)},pe()):z(e=>{let n=null,r=[];for(let o=0;o<t.length;o++){let s=o,i=t[o].subscribe(a=>{for(let d of a){if(n!==null&&s!==n)return;d[0]===_?(n===null&&(n=s),e.emit(d[1])):(d[0]===I||d[0]===L)&&(n===null||s===n)&&e.down([d])}});r.push(i)}return()=>{for(let o of r)o()}},pe())}function Js(t,e,n){let r,o=!1,s=()=>{o||(o=!0,n())};return r=t.subscribe(i=>{let a=!1,d=!1;for(let u of i)u[0]!==mt&&(u[0]===_?e.emit(u[1]):u[0]===I?a=!0:u[0]===L?(d=!0,e.down([u])):(u[0]===se||u[0]===q)&&e.down([u]));d?(r?.(),r=void 0,s()):a&&s()}),()=>{r?.(),r=void 0}}function me(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return U([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){s();return}if(d.terminalDeps[0]===!0){o=!0,r||a.down([[I]]);return}let u=i[0];if(!(u==null||u.length===0))return s(),r=Js(Y(e(u[u.length-1])),a,()=>{s(),o&&a.down([[I]])}),{deactivate:()=>{s(),o=!1}}},{...pe(n),completeWhenDepsComplete:!1,meta:{...be("switchMap"),...n?.meta??{}}})}function Nl(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return U([t],(i,a,d)=>{if(d.terminalDeps[0]!=null&&d.terminalDeps[0]!==!0){s();return}if(d.terminalDeps[0]===!0){o=!0,r||a.down([[I]]);return}let u=i[0];if(!(u==null||u.length===0))return r===void 0?r=Js(Y(e(u[0])),a,()=>{s(),o&&a.down([[I]])}):a.down([[q]]),{deactivate:()=>{s(),o=!1}}},{...pe(n),completeWhenDepsComplete:!1})}function El(t,e,n){let{maxBuffer:r,...o}=n??{},s=[],i,a=!1,d;function u(){i?.(),i=void 0}function c(){if(!d||i!==void 0)return;if(s.length===0){a&&d.down([[I]]);return}let p=s.shift();i=Js(Y(e(p)),d,()=>{u(),c()})}function l(p){r&&r>0&&s.length>=r&&s.shift(),s.push(p),c()}return U([t],(p,f,m)=>{if(d=f,m.terminalDeps[0]!=null&&m.terminalDeps[0]!==!0){u(),s.length=0;return}if(m.terminalDeps[0]===!0){a=!0,c();return}let h=p[0];if(!(h==null||h.length===0)){for(let g of h)l(g);return{deactivate:()=>{u(),s.length=0,a=!1}}}},{...pe(o),completeWhenDepsComplete:!1})}function ud(t,e,n){let{concurrent:r,...o}=n??{},s=r!=null&&r>0?r:Number.POSITIVE_INFINITY,i=0,a=!1,d=new Set,u=[],c;function l(){a&&i===0&&u.length===0&&c&&c.down([[I]])}function p(g){if(!c)return;i++;let y;y=Js(Y(e(g)),c,()=>{y&&d.delete(y),i--,f(),l()}),d.add(y)}function f(){for(;u.length>0&&i<s;)p(u.shift())}function m(g){i<s?p(g):u.push(g)}function h(){for(let g of d)g();d.clear(),i=0,u.length=0}return U([t],(g,y,b)=>{if(c=y,b.terminalDeps[0]!=null&&b.terminalDeps[0]!==!0){h();return}if(b.terminalDeps[0]===!0){a=!0,l();return}let v=g[0];if(!(v==null||v.length===0)){for(let T of v)m(T);return{deactivate:()=>{h(),a=!1}}}},{...pe(o),completeWhenDepsComplete:!1})}var _l=ud;function Ml(t,e,n){return z(r=>{let o=new Set;function s(){for(let a of o)clearTimeout(a);o.clear()}let i=t.subscribe(a=>{for(let d of a)if(d[0]===_){let u=setTimeout(()=>{o.delete(u),r.emit(d[1])},e);o.add(u)}else if(d[0]===I){let u=setTimeout(()=>{o.delete(u),r.down([[I]])},e);o.add(u)}else d[0]===L&&(s(),r.down([d]))});return()=>{i(),s()}},pe(n))}function cd(t,e,n){return z(r=>{let o,s;function i(){o!==void 0&&(clearTimeout(o),o=void 0)}let a=t.subscribe(d=>{for(let u of d)u[0]===_?(i(),s=u[1],o=setTimeout(()=>{o=void 0,r.emit(s)},e)):u[0]===I?(o!==void 0&&(i(),r.emit(s)),r.down([[I]])):u[0]===L&&(i(),r.down([u]))});return()=>{a(),i()}},{...pe(n),meta:{...be("debounce",{ms:e}),...n?.meta??{}}})}function ld(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,d=e*1e6;return z(u=>{let c,l=-1/0,p,f=!1;function m(){c!==void 0&&(clearTimeout(c),c=void 0)}let h=t.subscribe(g=>{for(let y of g)if(y[0]===_){let b=y[1],v=H();if(i&&v-l>=d)l=v,u.emit(b),m(),a&&(c=setTimeout(()=>{c=void 0,f&&(l=H(),u.emit(p),f=!1)},e));else if(a&&(p=b,f=!0,c===void 0)){let T=(v-l)/1e6;c=setTimeout(()=>{c=void 0,f&&(l=H(),u.emit(p),f=!1)},Math.max(0,e-T))}}else(y[0]===I||y[0]===L)&&(m(),u.down([y]))});return()=>{h(),m()}},{...pe(s),meta:{...be("throttle",{ms:e,leading:i,trailing:a}),...s.meta??{}}})}function Ol(t,e,n){return z(r=>{let o,s=!1,i=!1,a=t.subscribe(u=>{if(!s)for(let c of u){if(s)return;c[0]===_?o={v:c[1]}:c[0]===L?(s=!0,r.down([c])):c[0]===I&&(i=!0,o=void 0)}}),d=e.subscribe(u=>{if(!s)for(let c of u){if(s)return;c[0]===_?o!==void 0&&!i&&r.emit(o.v):c[0]===L?(s=!0,r.down([c])):c[0]===I&&(s=!0,r.down([[I]]))}});return()=>{a(),d()}},pe(n))}function Al(t,e,n){return z(r=>{let o,s,i=!1;function a(){o!==void 0&&(clearTimeout(o),o=void 0)}let d=t.subscribe(u=>{for(let c of u)c[0]===_?(s=c[1],i=!0,a(),o=setTimeout(()=>{o=void 0,i&&(i=!1,r.emit(s))},e)):(c[0]===I||c[0]===L)&&(a(),r.down([c]))});return()=>{d(),a()}},pe(n))}function Cl(t,e,n){return z(r=>{let o=[],s=t.subscribe(a=>{for(let d of a)d[0]===_?o.push(d[1]):d[0]===I?(o.length>0&&r.emit([...o]),o.length=0,r.down([[I]])):d[0]===L&&r.down([d])}),i=e.subscribe(a=>{for(let d of a)d[0]===_?o.length>0&&(r.emit([...o]),o.length=0):d[0]===I?r.down([[I]]):d[0]===L&&r.down([d])});return()=>{s(),i(),o.length=0}},pe(n))}function Ll(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return z(r=>{let o=[],s=t.subscribe(i=>{for(let a of i)a[0]===_?(o.push(a[1]),o.length>=e&&r.emit(o.splice(0,o.length))):a[0]===I?(o.length>0&&r.emit([...o]),o.length=0,r.down([[I]])):a[0]===L&&r.down([a])});return()=>{s(),o.length=0}},pe(n))}function Il(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return z(r=>{let o,s=0;function i(){let d=z(u=>(o=u.down.bind(u),()=>{o=void 0}),pe());s=0,r.emit(d)}let a=t.subscribe(d=>{for(let u of d)u[0]===_?(o||i(),o?.([[_,u[1]]]),s+=1,s>=e&&(o?.([[I]]),o=void 0)):u[0]===I?(o?.([[I]]),o=void 0,r.down([[I]])):u[0]===L&&(o?.([u]),o=void 0,r.down([u]))});return()=>{a(),o?.([[I]]),o=void 0}},pe(n))}function Dl(t,e,n){return z(r=>{let o=[],s=setInterval(()=>{o.length>0&&(r.emit([...o]),o.length=0)},e),i=t.subscribe(a=>{for(let d of a)d[0]===_?o.push(d[1]):d[0]===I?(clearInterval(s),o.length>0&&r.emit([...o]),o.length=0,r.down([[I]])):d[0]===L&&(clearInterval(s),r.down([d]))});return()=>{i(),clearInterval(s),o.length=0}},{...pe(n),meta:{...be("bufferTime",{ms:e}),...n?.meta??{}}})}function Pl(t,e,n){return z(r=>{let o;function s(){o?.([[I]]),o=void 0}function i(){let u=z(c=>(o=c.down.bind(c),()=>{o=void 0}),pe());r.emit(u)}i();let a=setInterval(()=>{s(),i()},e),d=t.subscribe(u=>{for(let c of u)c[0]===_?o?.([[_,c[1]]]):c[0]===I?(clearInterval(a),s(),r.down([[I]])):c[0]===L&&(clearInterval(a),o?.([c]),s(),r.down([c]))});return()=>{d(),clearInterval(a),s()}},pe(n))}function Gl(t,e,n){return z(r=>{let o;function s(){o?.([[I]]),o=void 0}function i(){let u=z(c=>(o=c.down.bind(c),()=>{o=void 0}),pe());r.emit(u)}let a=t.subscribe(u=>{for(let c of u)c[0]===_?(o||i(),o?.([[_,c[1]]])):c[0]===I?(s(),r.down([[I]])):c[0]===L&&(o?.([c]),o=void 0,r.down([c]))}),d=e.subscribe(u=>{for(let c of u)c[0]===_&&(s(),i())});return()=>{a(),d(),s()}},pe(n))}function Fl(t,e){return z((n,r)=>{"n"in r.store||(r.store.n=0);let o=setInterval(()=>{n.emit(r.store.n),r.store.n=r.store.n+1},t);return()=>clearInterval(o)},pe(e))}function $l(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return z(r=>{let o=e,s,i=()=>{s?.(),s=t.subscribe(a=>{let d=!1,u=[];for(let c of a)c[0]===I?d=!0:u.push(c);u.length>0&&r.down(u),d&&(s?.(),s=void 0,o-=1,o>0?i():r.down([[I]]))})};return i(),()=>{s?.()}},pe(n))}function jl(t,e){return U([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[q]]);return}for(let s of o)r.emit(s)},pe(e))}function uo(t,e,n){return z(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===_)r.emit(i[1]);else if(i[0]===L)try{r.emit(e(i[1]))}catch(a){r.down([[L,a]])}else i[0]===I&&r.down([[I]])});return()=>{o()}},pe(n))}function Bl(t,e,n){return U([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[q]]);return}let d=r[0];if(d!=null&&d.length>0){for(let u of d)o.emit(u);return}if(i!=null&&i.length>0&&s.prevData[0]!==void 0){o.emit(s.prevData[0]);return}o.down([[q]])},ll(n))}var Vl=dd,Kl=cd,ql=ld,zl=uo;ae();Me();ne();ir();cs();var pd=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new Pt(e),this.arr=null)}get length(){return this.ring!=null?this.ring.size:this.arr.length}push(e){this.ring!=null?this.ring.push(e):this.arr.push(e)}shift(){return this.ring!=null?this.ring.shift():this.arr.shift()}drain(){if(this.ring!=null){let n=this.ring.toArray();return this.ring.clear(),n}let e=this.arr;return this.arr=[],e}};function co(t){return t instanceof Error?t:new Error(String(t))}function vh(t){return t===void 0?null:typeof t=="string"?vn(t):t}function Je(t,e){let{name:n,onTransportError:r,retry:o,backpressure:s,batchSize:i=Number.POSITIVE_INFINITY,flushIntervalMs:a=0,serialize:d,stopOn:u,onUpstreamMessage:c,onDispose:l,send:p,sendBatch:f,ctx:m}=e;if(!p&&!f)throw new Error("reactiveSink: `send` or `sendBatch` must be provided");let h=m,g=Math.max(1,o?.maxAttempts??1),y=vh(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=f!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=W=>n?`${n}::${W}`:void 0,w=O(void 0,{equals:()=>!1,name:T("sent")}),k=O(null,{name:T("failed")}),R=O(0,{name:T("inFlight")}),S=O(null,{name:T("errors")}),x=v?O(0,{name:T("buffered")}):void 0,N=s?O(!1,{name:T("paused")}):void 0,E=0,D=W=>{E+=W,R.down([[_,E]])},M=W=>{try{r?.(W)}catch{}try{S.down([[_,W]])}catch{}},C=new Set,$=W=>{C.add(W);let ge=()=>C.delete(W);W.then(ge,ge)},B=(W,ge,Ee)=>{let _e=y?y(ge-1,Ee,null):0,he=_e==null?0:typeof _e=="number"&&_e>0?_e:0,Ge=Math.max(1,Math.ceil(he/1e6));return new Promise(Te=>{setTimeout(()=>Te(W()),Ge)})},G=W=>W!=null&&typeof W=="object"&&typeof W.then=="function",V=W=>{let ge;try{ge=d?d(W):W}catch(Te){let we=co(Te);return M({stage:"serialize",error:we,value:W}),k.down([[_,{value:W,error:we,attempts:0}]]),Promise.resolve()}let Ee=0,_e=Te=>{D(-1);let we=co(Te);if(M({stage:"send",error:we,value:W,attempt:Ee}),!(Ee<g&&b(we,Ee))){k.down([[_,{value:W,error:we,attempts:Ee}]]);return}return B(Ge,Ee,we)},he=()=>{D(-1),w.down([[_,W]])};function Ge(){Ee+=1,D(1);let Te;try{Te=p(ge,h)}catch(we){return _e(we)??Promise.resolve()}return G(Te)?Te.then(he,we=>_e(we)):(he(),Promise.resolve())}return Ge()},F=s?.maxBuffer??Number.POSITIVE_INFINITY,K=new pd(F),P,j=!1,re=()=>{x?.down([[_,K.length]])},fe=W=>{N&&N.down([[_,W]])},ee=s?.strategy??"drop-oldest",le=(W,ge)=>{let Ee={value:W,payload:ge};if(K.length<F)return K.push(Ee),re(),!0;if(ee==="drop-oldest"){let he=K.shift();return K.push(Ee),re(),fe(!0),k.down([[_,{value:he.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(ee==="drop-newest")return fe(!0),k.down([[_,{value:W,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let _e=new Error("backpressure: buffer overflow");return M({stage:"send",error:_e,value:W}),k.down([[_,{value:W,error:_e,attempts:0}]]),fe(!0),!1},Le=W=>{let ge=0,Ee=W.map(Te=>Te.payload),_e=Te=>{D(-1);let we=co(Te);if(M({stage:"send",error:we,value:W.map(Vn=>Vn.value),attempt:ge}),!(ge<g&&b(we,ge))){for(let{value:Vn}of W)k.down([[_,{value:Vn,error:we,attempts:ge}]]);return}return B(Ge,ge,we)},he=()=>{D(-1);for(let{value:Te}of W)w.down([[_,Te]])};function Ge(){ge+=1,D(1);let Te;try{Te=f(Ee,h)}catch(we){return _e(we)??Promise.resolve()}return G(Te)?Te.then(he,we=>_e(we)):(he(),Promise.resolve())}return Ge()},Xe=async W=>{for(let ge of W)await Be(ge.value,ge.payload)},Be=(W,ge)=>{let Ee=0,_e=Te=>{D(-1);let we=co(Te);if(M({stage:"send",error:we,value:W,attempt:Ee}),!(Ee<g&&b(we,Ee))){k.down([[_,{value:W,error:we,attempts:Ee}]]);return}return B(Ge,Ee,we)},he=()=>{D(-1),w.down([[_,W]])};function Ge(){Ee+=1,D(1);let Te;try{Te=p(ge,h)}catch(we){return _e(we)??Promise.resolve()}return G(Te)?Te.then(he,we=>_e(we)):(he(),Promise.resolve())}return Ge()},J=()=>{if(j||K.length===0)return Promise.resolve();let W=K.drain();if(re(),fe(!1),f!==void 0){let Ee=Le(W);return $(Ee),Ee}let ge=Xe(W);return $(ge),ge},de=()=>{P!==void 0||j||a<=0||(P=setTimeout(()=>{P=void 0,J()},a))},Ie=t.subscribe(W=>{for(let ge of W){let Ee=ge[0];if(Ee!==_)try{c?.(ge)}catch{}if(Ee===_){let _e=ge[1];if(v){let he;if(d)try{he=d(_e)}catch(Te){let we=co(Te);M({stage:"serialize",error:we,value:_e}),k.down([[_,{value:_e,error:we,attempts:0}]]);continue}else he=_e;if(!le(_e,he))continue;K.length>=i?J():de()}else{let he=V(_e);$(he)}}else $e.messageTier(Ee)>=3&&v&&(P!==void 0&&(clearTimeout(P),P=void 0),J())}}),ke;if(u){let W=!1;ke=u.subscribe(ge=>{if(!W){W=!0;return}ge.length>0&&!X&&ie()})}let X=!1,ie=()=>{if(X)return;X=!0,P!==void 0&&(clearTimeout(P),P=void 0),v&&J(),j=!0,ke?.(),Ie();let W=ge=>{try{ge.down([[ce]])}catch{}};W(S),W(k),W(w),W(R),x&&W(x),N&&W(N);try{l?.()}catch{}},Re={dispose:ie,sent:w,failed:k,inFlight:R,errors:S};return v&&(Re.buffered=x,Re.flush=async()=>{j||(await J(),await Promise.all(C))}),N&&(Re.paused=N),Re}Gt();ue();function kt(t){return{describeKind:"producer",...t}}function md(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return z(s=>{let i=!0,a,d=()=>{let y=a;a=void 0,y?.()},u=y=>{i&&(i=!1,s.down([y]),d())},c=(y,b=y)=>{if(i)try{let v=y!==null&&typeof y=="object"&&"data"in y?y.data:y,T=n?n(v,b):v;s.emit(T)}catch(v){u([L,v])}},l=y=>{u([L,y])},p=()=>{u([I])};if(typeof t=="function"){try{if(a=t(c,l,p),typeof a!="function")throw new Error("fromWebSocket register contract violation: register must return cleanup callable")}catch(y){u([L,y])}return()=>{i=!1,d()}}let f=t,m=y=>c(y,y),h=y=>l(y),g=()=>p();return f.addEventListener("message",m),f.addEventListener("error",h),f.addEventListener("close",g),a=()=>{f.removeEventListener("message",m),f.removeEventListener("error",h),f.removeEventListener("close",g),r&&f.close()},()=>{i=!1,d()}},kt(o))}function Hl(t,e){return Ln(t,e)}function gd(t,e){let{method:n="GET",headers:r,body:o,transform:s=v=>v.json(),timeoutNs:i=30*1e9,signal:a,completeAfterFetch:d=!1,refetchOnSubscribe:u=!1,...c}=e??{},l=O(0,{name:`${c.name??"http"}/fetchCount`}),p=O(0,{name:`${c.name??"http"}/lastUpdated`}),f=O(!1,{name:`${c.name??"http"}/fetched`}),m=0,h=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0,g=v=>{let T=new AbortController,w=!0;if(a?.aborted)return w=!1,v.down([[L,a.reason??new Error("Aborted")]]),()=>{};a?.addEventListener("abort",()=>T.abort(a.reason),{once:!0});let k=setTimeout(()=>T.abort(new Error("Request timeout")),Math.ceil(i/1e6));return fetch(t,{method:n,headers:r,body:h,signal:T.signal}).then(async R=>{if(clearTimeout(k),!w)return;if(!R.ok)throw new Error(`HTTP ${R.status}: ${R.statusText}`);let S=await s(R);w&&(Z(()=>{m+=1,l.down([[_,m]]),p.down([[_,oe()]]),f.down([[_,!0]]),v.emit(S)}),d&&v.down([[I]]))}).catch(R=>{clearTimeout(k),w&&(R&&R.name==="AbortError"||v.down([[L,R]]))}),()=>{w=!1,T.abort()}},y=z(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{...kt(c),resubscribable:u});return{...Yt(y),fetchCount:l,lastUpdated:p,fetched:f}}function Wl(t,e,n){let{method:r="POST",headers:o={"Content-Type":"application/json"},serialize:s=m=>JSON.stringify(m),timeoutNs:i,batchFormat:a="json-array",batchSize:d,flushIntervalMs:u,retry:c,onTransportError:l}=n??{},p=async m=>{let h=i!==void 0?new AbortController:void 0,g;h&&i!==void 0&&(g=setTimeout(()=>h.abort(new Error("Request timeout")),Math.ceil(i/1e6)));try{let y=await fetch(e,{method:r,headers:o,body:m,signal:h?.signal}),b=async()=>{try{await y.arrayBuffer?.()}catch{}};if(!y.ok)throw await b(),new Error(`HTTP ${y.status}: ${y.statusText}`);await b()}finally{g!==void 0&&clearTimeout(g)}};return d!==void 0||u!==void 0?Je(t,{onTransportError:l,retry:c,batchSize:d,flushIntervalMs:u,sendBatch:async m=>{let h;a==="ndjson"?h=m.map(g=>{let y=s(g);return typeof y=="string"?y:new TextDecoder().decode(y)}).join(`
|
|
16
|
+
`):h=JSON.stringify(m),await p(h)}}):Je(t,{onTransportError:l,retry:c,serialize:s,send:async m=>{await p(m)}})}function Ul(t){return Symbol.keyFor(t)??t.description??"message"}function mr(t,e){return typeof t=="string"?t:e(t)}function Jl(t,e){let n=`event: ${t}
|
|
17
17
|
`;if(e!==void 0){let r=e.split(/\r?\n/);for(let o of r)n+=`data: ${o}
|
|
18
18
|
`}return`${n}
|
|
19
|
-
`}function
|
|
19
|
+
`}function Yl(t,e){let{serialize:n=f=>{if(f instanceof Error)return f.message;try{return JSON.stringify(f)}catch{return String(f)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:d,signal:u,eventNameResolver:c=Ul}=e??{},l=new TextEncoder,p;return new ReadableStream({start(f){let m=!1,h,g=()=>{},y=()=>{m||(m=!0,h!==void 0&&clearInterval(h),u?.removeEventListener("abort",v),g(),f.close())};p=y;let b=(T,w)=>{m||f.enqueue(l.encode(Jl(T,w)))},v=()=>{m||y()};g=t.subscribe(T=>{for(let w of T){let k=w[0];if(!($e.isLocalOnly(k)&&!(k===se&&a))){if(k===_){b(r,mr(w[1],n));continue}if(k===L){b(o,mr(w[1],n)),y();return}if(k===I){b(s),y();return}!i&&k===q||b(c(k),w.length>1?mr(w[1],n):void 0)}}}),d!==void 0&&d>0&&(h=setInterval(()=>{m||f.enqueue(l.encode(`: keepalive
|
|
20
20
|
|
|
21
|
-
`))},d)),u?.aborted?v():u?.addEventListener("abort",v,{once:!0})},cancel(){p?.()}})}function
|
|
21
|
+
`))},d)),u?.aborted?v():u?.addEventListener("abort",v,{once:!0})},cancel(){p?.()}})}function Ql(t,e){let{serialize:n=p=>{if(p instanceof Error)return p.message;try{return JSON.stringify(p)}catch{return String(p)}},dataEvent:r="data",errorEvent:o="error",completeEvent:s="complete",includeResolved:i=!1,includeDirty:a=!1,keepAliveMs:d,signal:u,eventNameResolver:c=Ul}=e??{},l=new TextEncoder;return z(p=>{let f=!0,m,h=(b,v)=>{f&&p.emit(l.encode(Jl(b,v)))},g=()=>{f&&(f=!1,p.down([[I]]))},y=t.subscribe(b=>{if(f)for(let v of b){let T=v[0];if(!($e.isLocalOnly(T)&&!(T===se&&a))){if(T===_){h(r,mr(v[1],n));continue}if(T===L){h(o,mr(v[1],n)),f=!1,p.down([[I]]);return}if(T===I){h(s),f=!1,p.down([[I]]);return}!i&&T===q||h(c(T),v.length>1?mr(v[1],n):void 0)}}});return d!==void 0&&d>0&&(m=setInterval(()=>{f&&p.emit(l.encode(`: keepalive
|
|
22
22
|
|
|
23
|
-
`))},d)),u?.aborted?g():u?.addEventListener("abort",g,{once:!0}),()=>{f=!1,m!==void 0&&clearInterval(m),u?.removeEventListener("abort",g),y()}})}function
|
|
24
|
-
`);c.push({event:i,data:n(w),id:d,retry:u}),i="message",a=[],d=void 0,u=void 0},p=w=>{if(w===""){l();return}if(w.startsWith(":"))return;let
|
|
25
|
-
`)){let s=o.trim();if(!s)continue;if(s.startsWith("# TYPE ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&n.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("# HELP ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&r.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("#"))continue;let i,a={},d,u,c=s.indexOf("{");if(c>=0){i=s.slice(0,c);let p=s.indexOf("}",c);if(p<0)continue;let f=s.slice(c+1,p);a=
|
|
26
|
-
`,flushIntervalMs:o=0,batchSize:s=Number.POSITIVE_INFINITY,onTransportError:i,mode:a}=n??{},u=o>0||s<Number.POSITIVE_INFINITY?
|
|
27
|
-
`)?`"${t.replace(/"/g,'""')}"`:t}function
|
|
23
|
+
`))},d)),u?.aborted?g():u?.addEventListener("abort",g,{once:!0}),()=>{f=!1,m!==void 0&&clearInterval(m),u?.removeEventListener("abort",g),y()}})}function Xl(t){let e,n=!1;return new ReadableStream({start(r){e=t.subscribe(o=>{for(let s of o){let i=s[0];if(n)return;if(i===_)try{r.enqueue(s[1])}catch{n=!0,e?.()}else if(i===L){n=!0;try{r.error(s[1])}catch{}return}else if(i===I){n=!0;try{r.close()}catch{}return}}})},cancel(){n=!0,e?.()}})}async function*Bt(t,e){let n=e?.parse??(w=>w),r=e?.signal,o=new TextDecoder,s="",i="message",a=[],d,u,c=[],l=()=>{if(a.length===0&&i==="message"&&d===void 0){a=[];return}let w=a.join(`
|
|
24
|
+
`);c.push({event:i,data:n(w),id:d,retry:u}),i="message",a=[],d=void 0,u=void 0},p=w=>{if(w===""){l();return}if(w.startsWith(":"))return;let k=w.indexOf(":"),R=k<0?w:w.slice(0,k),S=k<0?"":w.slice(k+1);switch(S.startsWith(" ")&&(S=S.slice(1)),R){case"event":i=S;break;case"data":a.push(S);break;case"id":S.includes("\0")||(d=S);break;case"retry":{let x=Number(S);Number.isFinite(x)&&(u=x);break}}},f=(w,k)=>{s+=o.decode(w,{stream:!k});let R=s.split(/\r?\n/);s=R.pop()??"";for(let S of R)p(S)},m=t,h=t instanceof ReadableStream?t:m&&typeof m=="object"&&m.body instanceof ReadableStream?m.body:null,g,y,b=!1,v=()=>{b||(b=!0,g&&g.cancel().catch(()=>{}),y&&typeof y.return=="function"&&Promise.resolve(y.return()).catch(()=>{}))},T=()=>{v()};if(r){if(r.aborted)return;r.addEventListener("abort",T,{once:!0})}try{if(h){for(g=h.getReader();!r?.aborted;){let{value:w,done:k}=await g.read();if(k)break;for(f(w,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}else{for(y=t[Symbol.asyncIterator]();!r?.aborted;){let k=await y.next();if(k.done)break;for(f(k.value,!1);c.length>0;)yield c.shift()}f(new Uint8Array,!0)}if(s.trim()){for(let w of s.split(/\r?\n/))p(w);l()}for(;c.length>0;)yield c.shift()}finally{r&&r.removeEventListener("abort",T),v()}}function Zl(t,e){let{parse:n,...r}=e??{};return z(o=>{let s=!0,i=new AbortController;return(async()=>{try{for await(let d of Bt(t,{parse:n,signal:i.signal})){if(!s)return;o.emit(d)}s&&o.down([[I]])}catch(d){s&&o.down([[L,d]])}})(),()=>{s=!1,i.abort()}},kt(r))}function ep(t,e){let{method:n="GET",headers:r,body:o,signal:s,...i}=e??{};return z(a=>{let d=!0,u=new AbortController;if(s?.aborted)return a.down([[L,s.reason??new Error("Aborted")]]),()=>{};s?.addEventListener("abort",()=>u.abort(s.reason),{once:!0});let c=o!==void 0?typeof o=="string"?o:JSON.stringify(o):void 0;return(async()=>{try{let p=await fetch(t,{method:n,headers:r,body:c,signal:u.signal});if(!d)return;if(!p.ok)throw new Error(`HTTP ${p.status}: ${p.statusText}`);if(!p.body)throw new Error("HTTP response has no body");let f=p.body.getReader();for(;d;){let{value:m,done:h}=await f.read();if(h)break;m&&a.emit(m)}d&&a.down([[I]])}catch(p){if(!d||p&&p.name==="AbortError")return;a.down([[L,p]])}})(),()=>{d=!1,u.abort()}},kt(i))}function tp(t,e){let{intervalMs:n=5e3,...r}=e??{};return me(tt(n,{period:n}),()=>gd(t,{...r,completeAfterFetch:!0}).node)}function np(t,e,n){let{serialize:r=y=>{if(typeof y=="string"||y instanceof Blob||y instanceof ArrayBuffer||ArrayBuffer.isView(y))return y;try{return JSON.stringify(y)}catch{return String(y)}},closeOnComplete:o=!0,closeOnError:s=!0,closeCode:i,closeReason:a,onTransportError:d,retry:u,backpressure:c,stopOn:l}=n??{},p=!1,f=y=>{if(!p){p=!0;try{e.close(i,a)}catch(b){let v=b instanceof Error?b:new Error(String(b));try{d?.({stage:"close",error:v,value:void 0,message:y})}catch{}}}},m=null,g=Je(t,{onTransportError:d,serialize:y=>{let b=r(y);if(b===void 0)throw new Error("serialize returned undefined");return b},retry:u,backpressure:c,stopOn:l,onDispose:()=>{if(m){try{e.removeEventListener("close",m)}catch{}m=null}},send:y=>{e.send(y)},onUpstreamMessage:y=>{(y[0]===I&&o||y[0]===L&&s)&&f(y)}});return m=()=>{p=!0,g.dispose()},e.addEventListener("close",m),g}function rp(t,e){let{parse:n,maxRetries:r,backoff:o="exponential",closeOnTeardown:s=!0,...i}=e??{};return vt(()=>md(t(),{parse:n,closeOnTeardown:s,...i}),{count:r,backoff:o})}function op(t,e){let{method:n="notifications/message",onDisconnect:r,...o}=e??{};return Ln(({emit:s,error:i})=>(t.setNotificationHandler(n,a=>s(a)),r?.(a=>i(a??new Error("MCP client disconnected"))),()=>t.setNotificationHandler(n,()=>{})),o)}function sp(t,e){return Ws(({traces:r,metrics:o,logs:s,error:i})=>t({onTraces:a=>{Z(()=>{for(let d of a)r(d)})},onMetrics:a=>{Z(()=>{for(let d of a)o(d)})},onLogs:a=>{Z(()=>{for(let d of a)s(d)})},onError:i})??void 0,["traces","metrics","logs"],e?.name?{name:e.name}:void 0)}function ip(t,e){return Ln(t,e)}function ap(t){let e=t.match(/^<(\d{1,3})>\d?\s*(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*)/s);if(!e){let r=oe();return{facility:1,severity:6,timestamp:new Date(Math.floor(r/1e6)).toISOString(),hostname:"-",appName:"-",procId:"-",msgId:"-",message:t.trim(),timestampNs:r}}let n=Number(e[1]);return{facility:n>>3,severity:n&7,timestamp:e[2],hostname:e[3],appName:e[4],procId:e[5],msgId:e[6],message:(e[7]??"").trim(),timestampNs:oe()}}function dp(t,e){return Ln(t,e)}var Th={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function up(t){let e=t.split("|"),[n,r]=(e[0]??"").split(":");if(!n||r===void 0)throw new Error(`Invalid StatsD line: ${t}`);let o=e[1]?.trim()??"c",s=Th[o]??"counter",i=s==="set"?0:Number(r),a,d={};for(let u=2;u<e.length;u++){let c=e[u].trim();if(c.startsWith("@"))a=Number(c.slice(1));else if(c.startsWith("#"))for(let l of c.slice(1).split(",")){let[p,f]=l.split(":");p&&(d[p]=f??"")}}return{name:n.trim(),value:i,type:s,sampleRate:a,tags:d,timestampNs:oe()}}function cp(t,e){let{intervalNs:n=15*1e9,headers:r,timeoutNs:o=10*1e9,signal:s,maxConsecutiveErrors:i=1}=e??{},a=Math.ceil(n/1e6),d=0;return me(tt(0,{period:a,signal:s}),()=>z(u=>{let c=!0,l=new AbortController,p=setTimeout(()=>l.abort(new Error("Scrape timeout")),Math.ceil(o/1e6));return(async()=>{try{let m=await fetch(t,{headers:{Accept:"text/plain",...r},signal:l.signal});if(clearTimeout(p),!c)return;if(!m.ok)throw new Error(`Prometheus scrape ${m.status}: ${m.statusText}`);let h=await m.text();if(!c)return;let g=hd(h);for(let y of g)u.emit(y);d=0,u.down([[I]])}catch(m){if(clearTimeout(p),!c||m instanceof Error&&m.name==="AbortError")return;d+=1,d>=i&&u.down([[L,m]])}})(),()=>{c=!1,clearTimeout(p),l.abort()}}))}function hd(t){let e=[],n=new Map,r=new Map;for(let o of t.split(`
|
|
25
|
+
`)){let s=o.trim();if(!s)continue;if(s.startsWith("# TYPE ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&n.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("# HELP ")){let p=s.slice(7),f=p.indexOf(" ");f>0&&r.set(p.slice(0,f),p.slice(f+1).trim());continue}if(s.startsWith("#"))continue;let i,a={},d,u,c=s.indexOf("{");if(c>=0){i=s.slice(0,c);let p=s.indexOf("}",c);if(p<0)continue;let f=s.slice(c+1,p);a=wh(f);let m=s.slice(p+1).trim().split(/\s+/);d=m[0]??"",u=m[1]}else{let p=s.split(/\s+/);i=p[0]??"",d=p[1]??"",u=p[2]}if(!i||!d)continue;let l=i.replace(/(_total|_count|_sum|_bucket|_created|_info)$/,"");e.push({name:i,labels:a,value:Number(d),timestampMs:u?Number(u):void 0,type:n.get(l)??n.get(i),help:r.get(l)??r.get(i),timestampNs:oe()})}return e}function wh(t){let e={},n=/(\w+)="((?:[^"\\]|\\.)*)"/g,r=n.exec(t);for(;r!==null;)e[r[1]]=r[2].replace(/\\(.)/g,"$1"),r=n.exec(t);return e}function lp(t,e,n){let{fromBeginning:r=!1,deserialize:o=i=>{if(i===null)return null;try{return JSON.parse(i.toString())}catch{return i.toString()}},...s}=n??{};return z(i=>{let a=!0;return(async()=>{try{await t.subscribe({topic:e,fromBeginning:r}),await t.run({eachMessage:async({topic:u,partition:c,message:l})=>{if(!a)return;let p={};if(l.headers)for(let[f,m]of Object.entries(l.headers))m!==void 0&&(p[f]=typeof m=="string"?m:m.toString());i.emit({topic:u,partition:c,key:l.key?.toString()??null,value:o(l.value),headers:p,offset:l.offset,timestamp:l.timestamp,timestampNs:oe()})}})}catch(u){a&&i.down([[L,u]])}})(),()=>{a=!1}},kt(s))}function pp(t,e,n,r){let{serialize:o=a=>JSON.stringify(a),keyExtractor:s,onTransportError:i}=r??{};return Je(t,{onTransportError:i,send:async a=>{let d=s?.(a)??null,u=o(a);await e.send({topic:n,messages:[{key:d,value:Buffer.from(u)}]})}})}function fp(t,e,n){let{blockMs:r=5e3,startId:o="$",parse:s=a=>{for(let u=0;u<a.length;u+=2)if(a[u]==="data")try{return JSON.parse(a[u+1])}catch{return a[u+1]}let d={};for(let u=0;u<a.length;u+=2)d[a[u]]=a[u+1];return d},...i}=n??{};return z(a=>{let d=!0,u=o;return(async()=>{for(;d;)try{let l=await t.xread("BLOCK",r,"STREAMS",e,u);if(!d)return;if(l)for(let[p,f]of l)for(let[m,h]of f)u=m,a.emit({id:m,key:e,data:s(h),timestampNs:oe()})}catch(l){if(!d)return;a.down([[L,l]]);return}})(),()=>{d=!1}},kt(i))}function mp(t,e,n,r){let{serialize:o=a=>["data",JSON.stringify(a)],maxLen:s,onTransportError:i}=r??{};return Je(t,{onTransportError:i,send:async a=>{let d=o(a);await(s!==void 0?e.xadd(n,"MAXLEN","~",String(s),"*",...d):e.xadd(n,"*",...d))}})}function gp(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(d=>bp(d,n));return z(d=>{let u=!1;return(async()=>{try{let l=o,p="";for await(let f of t){if(u)return;p+=f;let m=p.split(/\r?\n/);p=m.pop()??"";for(let h of m){if(u)return;if(!h.trim())continue;let g=a(h);if(!l&&r){l=g;continue}l||(l=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<l.length;b++)y[l[b]]=g[b]??"";d.emit(y)}}if(!u&&p.trim()){let f=a(p);if(l){let m={};for(let h=0;h<l.length;h++)m[l[h]]=f[h]??"";d.emit(m)}}u||d.down([[I]])}catch(l){u||d.down([[L,l]])}})(),()=>{u=!0}},kt(i))}function hp(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(d=>bp(d,n));return U([t],(d,u,c)=>{let l=d[0];if(l==null||l.length===0)return;let p=c.store;typeof p.buffer!="string"&&(p.buffer=""),p.headers===void 0&&o&&(p.headers=o.slice());for(let f of l){p.buffer=p.buffer+f;let m=p.buffer.split(/\r?\n/);p.buffer=m.pop()??"";for(let h of m){if(!h.trim())continue;let g=a(h);if(!p.headers&&r){p.headers=g;continue}p.headers||(p.headers=g.map((b,v)=>`col${v}`));let y={};for(let b=0;b<p.headers.length;b++)y[p.headers[b]]=g[b]??"";u.emit(y)}}},{describeKind:"derived",...i})}function yp(t,e){return U([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0)return;let i=o.store;typeof i.buffer!="string"&&(i.buffer="");for(let a of s){i.buffer=i.buffer+a;let d=i.buffer.split(/\r?\n/);i.buffer=d.pop()??"";for(let u of d)if(u.trim())try{r.emit(JSON.parse(u))}catch(c){r.down([[L,c]]);return}}},{describeKind:"derived",...e??{}})}function bp(t,e){let n=[],r="",o=!1;for(let s=0;s<t.length;s++){let i=t[s];o?i==='"'?t[s+1]==='"'?(r+='"',s++):o=!1:r+=i:i==='"'?o=!0:i===e?(n.push(r),r=""):r+=i}return n.push(r),n}function vp(t,e){return z(n=>{let r=!1;return(async()=>{try{let s="";for await(let i of t){if(r)return;s+=i;let a=s.split(/\r?\n/);s=a.pop()??"";for(let d of a){if(r)return;let u=d.trim();u&&n.emit(JSON.parse(u))}}!r&&s.trim()&&n.emit(JSON.parse(s.trim())),r||n.down([[I]])}catch(s){r||n.down([[L,s]])}})(),()=>{r=!0}},kt(e))}function Tp(t,e,n){let{intervalNs:r=5*1e9,format:o="JSONEachRow",signal:s,maxConsecutiveErrors:i=1}=n??{},a=Math.ceil(r/1e6),d=0;return me(tt(0,{period:a,signal:s}),()=>z(u=>{let c=!0;return(async()=>{try{let p=await t.query({query:e,format:o});if(!c)return;let f=await p.json();if(!c)return;for(let m of f)u.emit(m);d=0,u.down([[I]])}catch(p){if(!c)return;d+=1,d>=i&&u.down([[L,p]])}})(),()=>{c=!1}}))}function wp(t,e){let{autoAck:n=!0,deserialize:r=a=>{try{return JSON.parse(a.toString())}catch{return a.toString()}},onAckError:o,...s}=e??{},i=a=>{if(o)try{o(a instanceof Error?a:new Error(String(a)))}catch{}};return z(a=>{let d=!0;return(async()=>{for(;d;)try{let c=await t.receive();if(!d)return;let l={topic:c.getTopicName(),messageId:c.getMessageId().toString(),key:c.getPartitionKey(),value:r(c.getData()),properties:c.getProperties(),publishTime:c.getPublishTimestamp(),eventTime:c.getEventTimestamp(),timestampNs:oe()};if(n)a.emit(l),t.acknowledge(c).catch(i);else{let p=!1,f={value:l,ack(){p||(p=!0,t.acknowledge(c).catch(i))},nack(m){if(p)return;p=!0;let h=t;try{let g=h.negativeAcknowledge?.(c);g&&typeof g.then=="function"&&g.catch(i)}catch(g){i(g)}}};a.emit(f)}}catch(c){d&&a.down([[L,c]]);return}})(),()=>{d=!1}},kt(s))}function kp(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:o,propertiesExtractor:s,onTransportError:i}=n??{};return Je(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:o?.(a),properties:s?.(a)})}})}function xp(t,e,n){let r=new TextDecoder,{queue:o,deserialize:s=a=>{let d=r.decode(a);try{return JSON.parse(d)}catch{return d}},...i}=n??{};return z(a=>{let d=!0,u=t.subscribe(e,o?{queue:o}:void 0);return(async()=>{try{for await(let l of u){if(!d)return;let p={};if(l.headers)for(let f of l.headers.keys())p[f]=l.headers.get(f);a.emit({subject:l.subject,data:s(l.data),headers:p,reply:l.reply,sid:l.sid,timestampNs:oe()})}d&&a.down([[I]])}catch(l){d&&a.down([[L,l]])}})(),()=>{d=!1}},kt(i))}function Rp(t,e,n,r){let o=new TextEncoder,{serialize:s=a=>o.encode(JSON.stringify(a)),onTransportError:i}=r??{};return Je(t,{onTransportError:i,send:a=>{e.publish(n,s(a))}})}function Sp(t,e,n){let{autoAck:r=!0,deserialize:o=d=>{try{return JSON.parse(d.toString())}catch{return d.toString()}},onAckError:s,...i}=n??{},a=d=>{if(s)try{s(d instanceof Error?d:new Error(String(d)))}catch{}};return z(d=>{let u=!0,c;return(async()=>{try{c=(await t.consume(e,f=>{if(!u)return;if(f===null){u&&d.down([[L,new Error("Consumer cancelled by broker")]]);return}let m={queue:e,routingKey:f.fields.routingKey,exchange:f.fields.exchange,content:o(f.content),properties:f.properties,deliveryTag:f.fields.deliveryTag,redelivered:f.fields.redelivered,timestampNs:oe()};if(r){d.emit(m);try{t.ack(f)}catch(h){a(h)}}else{let h=!1,g=t,y={value:m,ack(){if(!h){h=!0;try{t.ack(f)}catch(b){a(b)}}},nack(b){if(h)return;h=!0;let v=b?.requeue;if(!g.nack){a(new Error("RabbitMQ channel does not expose `nack`; cannot negative-ack"));return}try{g.nack(f,!1,v)}catch(T){a(T)}}};d.emit(y)}},{noAck:!1})).consumerTag}catch(p){u&&d.down([[L,p]])}})(),()=>{u=!1,c!==void 0&&t.cancel(c)}},kt(i))}function Np(t,e,n,r){let{serialize:o=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:s=()=>"",onTransportError:i}=r??{};return Je(t,{onTransportError:i,send:a=>{let d=s(a),u=o(a);e.publish(n,d,u)}})}function yd(t,e,n){let{serialize:r=l=>`${JSON.stringify(l)}
|
|
26
|
+
`,flushIntervalMs:o=0,batchSize:s=Number.POSITIVE_INFINITY,onTransportError:i,mode:a}=n??{},u=o>0||s<Number.POSITIVE_INFINITY?Je(t,{onTransportError:i,batchSize:s,flushIntervalMs:o,serialize:r,sendBatch:l=>{e.write(l.join(""))}}):Je(t,{onTransportError:i,serialize:r,send:l=>{e.write(l)}}),c=u.dispose;return u.dispose=()=>{c();try{e.end()}catch{}},u}function fd(t,e){return t.includes(e)||t.includes('"')||t.includes(`
|
|
27
|
+
`)?`"${t.replace(/"/g,'""')}"`:t}function Ep(t,e,n){let{columns:r,delimiter:o=",",writeHeader:s=!0,cellExtractor:i=(f,m)=>String(f[m]??""),flushIntervalMs:a=0,batchSize:d=Number.POSITIVE_INFINITY,onTransportError:u,...c}=n,l=!1;return yd(t,e,{serialize:f=>{if(!l&&s){l=!0;let m=r.map(g=>fd(g,o)).join(o),h=r.map(g=>fd(i(f,g),o)).join(o);return`${m}
|
|
28
28
|
${h}
|
|
29
|
-
`}return`${r.map(m=>
|
|
30
|
-
`},flushIntervalMs:a,batchSize:d,onTransportError:u,...c})}function
|
|
29
|
+
`}return`${r.map(m=>fd(i(f,m),o)).join(o)}
|
|
30
|
+
`},flushIntervalMs:a,batchSize:d,onTransportError:u,...c})}function _p(t,e,n,r){let{batchSize:o=1e3,flushIntervalMs:s=5e3,format:i="JSONEachRow",transform:a=u=>u,onTransportError:d}=r??{};return Je(t,{onTransportError:d,batchSize:o,flushIntervalMs:s,serialize:a,sendBatch:async u=>{await e.insert({table:n,values:u,format:i})}})}function Mp(t,e,n,r){let{format:o="ndjson",keyGenerator:s=(p,f)=>{let m=Math.floor(f/1e6);return`data/${new Date(m).toISOString().replace(/[:.]/g,"-")}-${p}.${o==="ndjson"?"ndjson":"json"}`},batchSize:i=1e3,flushIntervalMs:a=1e4,transform:d=p=>p,onTransportError:u}=r??{},c=o==="ndjson"?"application/x-ndjson":"application/json",l=0;return Je(t,{onTransportError:u,batchSize:i,flushIntervalMs:a,serialize:d,sendBatch:async p=>{l+=1;let f=o==="ndjson"?`${p.map(h=>JSON.stringify(h)).join(`
|
|
31
31
|
`)}
|
|
32
|
-
`:JSON.stringify(p),m=s(l,se());await e.putObject({Bucket:n,Key:m,Body:f,ContentType:c})}})}function ip(t,e,n,r){let{toSQL:o=(i,a)=>({sql:`INSERT INTO "${a.replace(/"/g,'""')}" (data) VALUES ($1)`,params:[JSON.stringify(i)]}),onTransportError:s}=r??{};return Ue(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function ap(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return Ue(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function dp(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return Ue(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:d,labels:u}=a,c=`${se()}`;await e.push({streams:[{stream:u,values:[[c,d]]}]})}})}function up(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return Ue(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function cp(t,e,n,r){let{prefix:o="checkpoints/",debounceMs:s=500,compactEvery:i=10,onError:a}=r??{},d={name:`s3:${n}`,debounceMs:s,compactEvery:i,save(u){let c=Math.floor(se()/1e6),l=`${o}${t.name}/checkpoint-${c}.json`,p;try{p=JSON.stringify(u)}catch(f){a?.(f);return}e.putObject({Bucket:n,Key:l,Body:p,ContentType:"application/json"}).catch(f=>a?.(f))}};return t.attachSnapshotStorage([d],{onError:u=>a?.(u)})}function lp(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:o=500,compactEvery:s=10,onError:i}=n??{},a=`${r}${t.name}`,d={name:`redis:${a}`,debounceMs:o,compactEvery:s,save(u){let c;try{c=JSON.stringify(u)}catch(l){i?.(l);return}e.set(a,c).catch(l=>i?.(l))},async load(){let u=await e.get(a);if(u!=null)try{return JSON.parse(u)}catch{return}}};return t.attachSnapshotStorage([d],{onError:u=>i?.(u)})}function pp(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return z(i=>{try{let d=t.query(e,o).map(r);i.emit(d),i.down([[P]])}catch(a){i.down([[I,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function fp(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return z(i=>{try{let a=t.iterate(e,o);Z(()=>{for(let d of a)i.emit(r(d));i.down([[P]])})}catch(a){i.down([[I,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function mp(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(N,L)=>({sql:`INSERT INTO "${L.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(N)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:d=0}=r??{},u=N=>o(N,n);if(!i)return Ue(t,{onTransportError:s,serialize:u,send:N=>{let L=N;e.query(L.sql,L.params)}});let c=A(null),l=A(void 0,{equals:()=>!1}),p=A(null),f=A(0),m=A(0),h=N=>{try{s?.(N)}catch{}try{c.down([[M,N]])}catch{}},g=[],y=!1,b,v=!1,T=()=>m.down([[M,g.length]]),w=N=>{v||l.down([[M,N]])},x=N=>{v||p.down([[M,N]])},k=N=>{v||f.down([[M,N]])},S=N=>{v||h(N)},R=()=>{if(g.length===0||y)return;y=!0,k(1);try{e.query("BEGIN",[])}catch($){y=!1,k(0),S({stage:"send",error:$ instanceof Error?$:new Error(String($)),value:void 0});return}let N=g;g=[],T();let L,j=0;for(let $ of N)try{e.query($.query.sql,$.query.params),j+=1}catch(D){L=D instanceof Error?D:new Error(String(D));break}if(L){try{e.query("ROLLBACK",[])}catch{}S({stage:"send",error:L,value:void 0});for(let $ of N)x({value:$.value,error:L,attempts:1})}else try{e.query("COMMIT",[]);for(let $ of N)w($.value)}catch($){let D=$ instanceof Error?$:new Error(String($));S({stage:"send",error:D,value:void 0});for(let K=0;K<j;K++)x({value:N[K].value,error:D,attempts:1})}y=!1,k(0)},E=()=>{d>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,R()},d))},_=t.subscribe(N=>{for(let L of N){let j=L[0];if(j===M){let $=L[1],D;try{D=u($)}catch(K){let F=K instanceof Error?K:new Error(String(K));h({stage:"serialize",error:F,value:$}),p.down([[M,{value:$,error:F,attempts:0}]]);continue}g.push({value:$,query:D}),T(),g.length>=a?R():E()}else Fe.messageTier(j)>=3&&R()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),R(),v=!0,_();for(let N of[c,l,p,f,m])try{N.down([[le]])}catch{}}},sent:l,failed:p,inFlight:f,errors:c,buffered:m,flush:async()=>{v||R()}}}function gp(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return z(s=>{let i=!0;return t.findMany(n).then(a=>{i&&(s.emit(a.map(r)),s.down([[P]]))}).catch(a=>{if(i)try{s.down([[I,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...o,describeKind:"producer",completeWhenDepsComplete:!1})}function hp(t,e){let{mapRow:n=o=>o,...r}=e??{};return z(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[P]]))}).catch(i=>{if(s)try{o.down([[I,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function yp(t,e){let{mapRow:n=o=>o,...r}=e??{};return z(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[P]]))}).catch(i=>{if(s)try{o.down([[I,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}Wn();ae();ne();function Za(){let t=new Map,e=null,n=null;function r(s){s.prev?s.prev.next=s.next:e=s.next,s.next?s.next.prev=s.prev:n=s.prev,s.prev=null,s.next=null}function o(s){s.next=e,s.prev=null,e&&(e.prev=s),e=s,n===null&&(n=s)}return{insert(s){if(t.has(s)){this.touch(s);return}let i={key:s,prev:null,next:null};t.set(s,i),o(i)},touch(s){let i=t.get(s);i&&(r(i),o(i))},delete(s){let i=t.get(s);i&&(r(i),t.delete(s))},evict(s){let i=[];for(let a=0;a<s&&n!==null;a++){let d=n;i.push(d.key),r(d),t.delete(d.key)}return i},size(){return t.size}}}function bp(t){return t!=null&&typeof t.then=="function"}function sr(t){bp(t)&&t.catch(()=>{})}function vp(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Za():null,s=e?.writeThrough??!1;function i(u,c,l){for(let p=0;p<l;p++)try{sr(t[p].save(u,c))}catch{}}function a(u,c,l=0){for(let p=l;p<t.length;p++){let f;try{f=t[p].load(u)}catch{continue}if(bp(f)){let m=p;f.then(h=>{h!==void 0?(c.down([[M,h]]),i(u,h,m)):a(u,c,m+1)},()=>{a(u,c,m+1)});return}if(f!==void 0){c.down([[M,f]]),i(u,f,p);return}}}function d(){if(!(!o||r<=0))for(;o.size()>=r;){let u=o.evict(1);if(u.length===0)break;for(let c of u){let l=n.get(c);if(l){let p=l.cache;if(l.status!=="sentinel"&&t.length>0){let f=t.length-1;try{sr(t[f].save(c,p))}catch{}for(let m=0;m<f;m++)try{let h=t[m].delete;h&&sr(h.call(t[m],c))}catch{}}l.down([[le]])}n.delete(c)}}}return{load(u){let c=n.get(u);if(c)return o?.touch(u),c;o&&r>0&&o.size()>=r&&d();let l=A(void 0);return n.set(u,l),o?.insert(u),a(u,l),l},save(u,c){if(s)for(let p of t)try{sr(p.save(u,c))}catch{}else if(t[0])try{sr(t[0].save(u,c))}catch{}let l=n.get(u);if(l)l.down([[M,c]]),o?.touch(u);else{o&&r>0&&o.size()>=r&&d();let p=A(c);n.set(u,p),o?.insert(u)}},invalidate(u){let c=n.get(u);c&&a(u,c)},delete(u){o?.delete(u);let c=n.get(u);c&&c.down([[le]]),n.delete(u);for(let l of t)try{let p=l.delete;p&&sr(p.call(l,u))}catch{}},has(u){return n.has(u)},get size(){return n.size}}}Ae();ae();it();ne();Ae();Re();ae();ne();var so=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let o=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:o}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),o=0;try{for(let[s,i]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:i,expiresAt:r}),o+=1}finally{o>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=V(),n=0;for(let[r,o]of this._store)this._isExpired(o,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=V(),n=new Map;for(let[r,o]of this._store)this._isExpired(o,e)||n.set(r,o.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return V()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??V())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function je(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s,retention:i}=t;if(i&&n!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=s??new so({maxSize:n,defaultTtl:r}),d=A(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function u(){let p=a.toMap();Z(()=>{d.down([[oe]]),d.down([[M,p]])})}function c(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,h=[];for(let[y,b]of p)h.push({key:y,value:b,score:i.score(y,b)});h.sort((y,b)=>y.score-b.score);let g=new Set;if(f!==void 0)for(let y of h)if(y.score<f)g.add(y.key);else break;if(m!==void 0&&h.length-g.size>m)for(let y of h){if(h.length-g.size<=m)break;g.has(y.key)||g.add(y.key)}if(g.size!==0)for(let y of h)g.has(y.key)&&(i.onArchive?.(y.key,y.value,y.score),a.delete(y.key))}function l(p,f="mutation"){let m=a.version;try{return p()}finally{a.version!==m&&(f==="mutation"&&c(),u())}}return{entries:d,has(p){return l(()=>a.has(p),"read")},get(p){return l(()=>a.get(p),"read")},set(p,f,m){l(()=>a.set(p,f,m?.ttl))},setMany(p,f){l(()=>a.setMany(p,f?.ttl))},delete(p){l(()=>a.delete(p))},deleteMany(p){l(()=>a.deleteMany(p))},clear(){l(()=>a.clear())},pruneExpired(){l(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}ve();function th(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function kp(t,e,n){let r=Y(t),o=r.v!=null,s=A(n?.initialVerified??null,{meta:{...we("verifiable"),...o?{sourceVersion:null}:{}}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=Et(Y(n.trigger),r):i?a=Y(n.trigger):n?.autoVerify&&(a=r),a!==null){let d;if(a===r)d=ke(r,u=>e(u));else{let u=r.cache;r.subscribe(c=>{for(let l of c)l[0]===M&&(u=l[1])}),d=ke(a,()=>e(u))}Wt(d,u=>{Z(()=>{if(s.down([[M,u]]),o){let c=r.v;c!=null&&s.meta.sourceVersion.down([[M,{id:c.id,version:c.version}]])}})})}return{node:r,verified:s,trigger:a}}function Tp(t){t.subscribe(()=>{})}function io(t){return t instanceof Map?t:new Map}function wp(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");Z(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function js(t,e,n){let r=Y(t),o=je(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?Y(n.context):A(null),d=io(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===M&&(d=io(m[1]))});let u=Y(e(r,o.entries));if(Wt(u,f=>{wp(o,f)}),n.evict){let f=new Map,m=C([o.entries],([h])=>{let g=[],y=io(h);for(let b of f.keys())y.has(b)||(f.get(b)(),f.delete(b));for(let[b,v]of y){let T=n.evict(b,v);if(th(T)){if(!f.has(b)){let w=Wt(T,x=>{x===!0&&o.has(b)&&o.delete(b)});f.set(b,w)}continue}if(typeof T=="boolean"){T&&g.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});Wt(m,h=>{for(let g of h)o.delete(g)})}let c=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&c){let f=Y(n.consolidateTrigger),m=ke(f,()=>n.consolidate(d));Wt(m,h=>{wp(o,h)})}let l=C([o.entries,a],([f,m])=>{let h=[...io(f).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));h.sort((b,v)=>v.score-b.score);let g=[],y=s;for(let b of h)b.cost<=y&&(g.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return g},{meta:{...we("distill",{budget:s})}}),p=C([o.entries],([f])=>io(f).size);return Tp(l),Tp(p),{store:o,compact:l,size:p}}async function Bs(t){let e=typeof t=="string"?new TextEncoder().encode(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(n),o="";for(let s=0;s<r.length;s++)o+=xp[r[s]];return o}var xp=new Array(256);for(let t=0;t<256;t++)xp[t]=t.toString(16).padStart(2,"0");var ao=class extends Error{constructor(n,r){super(`content-addressed lookup miss in read-strict mode: ${n}`);this.key=n;this.context=r;this.name="ContentAddressedMissError"}};function uo(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let o=r;if(e.has(o))return{__cycle:!0};e.add(o);try{if(Array.isArray(r))return r.map(n);let s={};for(let i of Object.keys(r).sort())s[i]=n(r[i]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}function Vs(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let d=uo(s(a)),u=await Bs(d);return r?`${r}:${u}`:u}return{keyFor:i,async lookup(a){if(o==="write")return;let d=await i(a),u=await e.load(d);if(u===void 0){if(o==="read-strict")throw new ao(d,a);return}return u},async store(a,d){if(o==="read")return;let u=await i(a);await e.save(u,d)},async forget(a){if(o==="read"||o==="write"||!e.delete)return;let d=await i(a);await e.delete(d)}}}ga();async function wt(t,e){let n;try{n=await t.text()}catch{n=""}let r=e??"HTTP",o=new Error(`${r} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return o.status=t.status,o.headers=t.headers,o}Ae();ae();Me();var co=class{_version=0;_topics=new Set;get version(){return this._version}get topicCount(){return this._topics.size}hasTopic(e){return this._topics.has(e)}topicNames(){return this._topics.values()}createTopic(e){return this._topics.has(e)?!1:(this._topics.add(e),this._version+=1,!0)}removeTopic(e){let n=this._topics.delete(e);return n&&(this._version+=1),n}};function Rp(t={}){let{backend:e}=t,n=e??new co,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=U({describeKind:"state"}),r.set(s,i),n.createTopic(s)),i}return{topic(s){return o(s)},publish(s,i){o(s).emit(i)},publishMany(s){Z(()=>{for(let[i,a]of s)o(i).emit(a)})},removeTopic(s){let i=r.get(s);return i===void 0?!1:(r.delete(s),n.removeTopic(s),i.down([[le]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Ae();ae();ne();function Sp(t,e){if(t===e)return 0;let n=typeof t;if(n===typeof e&&(n==="number"||n==="string"||n==="boolean"||n==="bigint")){let o=t,s=e;return o<s?-1:o>s?1:0}return String(t).localeCompare(String(e))}function nh(t,e){let n=Sp(t[0],e[0]);return n!==0?n:Sp(t[1],e[1])}function Np(t){return[t.secondary,t.primary]}function ir(t,e){let n=Np(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;nh(n,Np(t[s]))>0?r=s+1:o=s}return r}var lo=class{_version=0;_buf=[];_byPrimary=new Map;get version(){return this._version}get size(){return this._buf.length}has(e){return this._byPrimary.has(e)}get(e){return this._byPrimary.get(e)?.value}upsert(e,n,r,o){let s=this._byPrimary.get(e),i={primary:e,secondary:n,value:r};if(s!==void 0&&o?.equals?.(s,i))return!1;if(s!==void 0){let d=ir(this._buf,s);this._buf.splice(d,1)}let a=ir(this._buf,i);return this._buf.splice(a,0,i),this._byPrimary.set(e,i),this._version+=1,s===void 0}upsertMany(e,n){let r=0;try{for(let o of e){let s=this._byPrimary.get(o.primary),i={primary:o.primary,secondary:o.secondary,value:o.value};if(s!==void 0&&n?.equals?.(s,i))continue;if(s!==void 0){let d=ir(this._buf,s);this._buf.splice(d,1)}let a=ir(this._buf,i);this._buf.splice(a,0,i),this._byPrimary.set(o.primary,i),r+=1}}finally{r>0&&(this._version+=1)}return r}delete(e){let n=this._byPrimary.get(e);if(n===void 0)return!1;let r=ir(this._buf,n);return this._buf.splice(r,1),this._byPrimary.delete(e),this._version+=1,!0}deleteMany(e){let n=0;try{for(let r of e){let o=this._byPrimary.get(r);if(o===void 0)continue;let s=ir(this._buf,o);this._buf.splice(s,1),this._byPrimary.delete(r),n+=1}}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._byPrimary.clear(),this._version+=1,e)}toArray(){return[...this._buf]}toPrimaryMap(){let e=new Map;for(let n of this._buf)e.set(n.primary,n.value);return e}};function rh(t){return t.subscribe(()=>{})}function Ep(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new lo;function i(f){return f?.equals!==void 0||r===void 0?f:{...f,equals:r}}let a=A([],{name:e,describeKind:"state",equals:(f,m)=>f===m,...n!=null?{versioning:n}:{}}),d=C([a],([f])=>{let m=f,h=new Map;for(let g of m)h.set(g.primary,g.value);return h},{initial:s.toPrimaryMap(),describeKind:"derived"}),u=rh(d),c=!1;function l(){let f=s.toArray();Z(()=>{a.down([[oe]]),a.down([[M,f]])})}function p(f){let m=s.version;try{return f()}finally{s.version!==m&&l()}}return{ordered:a,byPrimary:d,has(f){return s.has(f)},get(f){return s.get(f)},get size(){return s.size},upsert(f,m,h,g){return p(()=>s.upsert(f,m,h,i(g)))},upsertMany(f,m){let h=[...f];h.length!==0&&p(()=>s.upsertMany(h,i(m)))},delete(f){p(()=>s.delete(f))},deleteMany(f){let m=[...f];m.length!==0&&p(()=>s.deleteMany(m))},clear(){p(()=>s.clear())},dispose(){c||(c=!0,u())}}}Ae();ae();ne();var po=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Ks(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new po(t),i=A(s.toArray(),{name:n,describeKind:"state",equals:(u,c)=>u===c,...r!=null?{versioning:r}:{}});function a(){let u=s.toArray();Z(()=>{i.down([[oe]]),i.down([[M,u]])})}function d(u){let c=s.version;try{return u()}finally{s.version!==c&&a()}}return{items:i,get size(){return s.size},at(u){return s.at(u)},append(u){d(()=>s.append(u))},appendMany(u){d(()=>s.appendMany(u))},insert(u,c){d(()=>s.insert(u,c))},insertMany(u,c){d(()=>s.insertMany(u,c))},pop(u=-1){return d(()=>s.pop(u))},clear(){d(()=>s.clear())},dispose(){}}}It();ae();ve();function qs(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=t(o),d;a!=null&&typeof a.then=="function"?d=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?d=et(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?d=(async()=>{let l=a[Symbol.asyncIterator]();try{let{value:p,done:f}=await l.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return p}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?d=(async()=>{let l=a[Symbol.iterator]();try{let{value:p,done:f}=l.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return p}finally{l.return?.()}})():d=Promise.resolve(a);let u,c=()=>{r.get(s)===u&&r.delete(s)};return u=d.then(l=>(c(),l),l=>{throw c(),l}),r.set(s,u),u}}function _p(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=Y(t(o));r.set(s,a);let d=a.subscribe(u=>{for(let c of u)if(c[0]===I||c[0]===P){r.get(s)===a&&r.delete(s),d();return}});return a}}ve();function fo(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(fo);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=fo(e[o]);return r}function zs(t){return JSON.stringify(fo(t),void 0,0)}var oh=new TextEncoder,sh=new TextDecoder("utf-8",{fatal:!0}),ar={name:"json",version:1,encode(t){return oh.encode(zs(t))},decode(t){return JSON.parse(sh.decode(t))}};function Mp(){return ar}function mo(){let t=new Map;return{name:"memory",read(e){let n=t.get(e);return n===void 0?void 0:new Uint8Array(n)},write(e,n){t.set(e,new Uint8Array(n))},delete(e){t.delete(e)},list(e){let n=[...t.keys()];return e?n.filter(r=>r.startsWith(e)).sort():n.sort()}}}function Hs(t,e={}){let n=e.codec??ar,r=e.name??t.name??"snapshot",o=e.keyOf??(l=>l.name??e.name??t.name??"snapshot"),s,i=0,a=e.compactEvery,d,u={name:r,debounceMs:e.debounceMs,compactEvery:a,filter:e.filter,keyOf:o,save(l){if(!(e.filter&&!e.filter(l))&&(s={snapshot:l},i+=1,a!==void 0&&i%a===0||!e.debounceMs))return c()},load(){let l=d??r,p=t.read(l);if(p!==void 0)return p instanceof Uint8Array?p.length===0?void 0:n.decode(p):Promise.resolve(p).then(f=>f===void 0||f.length===0?void 0:n.decode(f))},async flush(){await c()},async rollback(){s=void 0}};function c(){let l=s;if(!l)return;s=void 0;let p=o(l.snapshot),f=n.encode(l.snapshot),m=t.write(p,f);if(m instanceof Promise)return m.then(()=>{d=p});d=p}return u}function ed(t,e={}){let n=e.codec??ar,r=e.name??t.name??"append-log",o=e.keyOf??(p=>r),s=e.compactEvery,i=new Map,a=0,d,u={name:r,debounceMs:e.debounceMs,compactEvery:s,keyOf:o,appendEntries(p){if(p.length!==0){for(let f of p){let m=o(f),h=i.get(m);h||(h=[],i.set(m,h)),h.push(f)}if(a+=p.length,s!==void 0&&a%s===0||!e.debounceMs)return c()}},async loadEntries(p){let f=p?.keyFilter,m=t.list===void 0?f!==void 0?[f]:[r]:await Promise.resolve(t.list(f)),h=[];for(let g of m){let y=await Promise.resolve(t.read(g));if(y===void 0||y.length===0)continue;let b=n.decode(y);Array.isArray(b)&&h.push(...b)}return{entries:h,cursor:void 0}},async flush(){await c()},async rollback(){i=new Map}};function c(){if(i.size===0)return;let p=i;i=new Map;let f=(d??Promise.resolve()).then(()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()},()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()});return d=f.finally(()=>{d===f&&(d=void 0)}),d}function l(p){let f=[];for(let[m,h]of p){let g=t.read(m),y=b=>{let T=[...b===void 0||b.length===0?[]:n.decode(b)??[],...h],w=n.encode(T);return t.write(m,w)};if(g instanceof Promise)f.push(g.then(async b=>{let v=y(b);v instanceof Promise&&await v}));else{let b=y(g);b instanceof Promise&&f.push(b)}}if(f.length>0)return Promise.all(f).then(()=>{})}return u}function Ws(t,e={}){let n=e.codec??ar,r=e.name??t.name??"kv",o=e.compactEvery,s=new Map,i=0,a={name:r,debounceMs:e.debounceMs,compactEvery:o,filter:e.filter,save(u,c){if(!(e.filter&&!e.filter(u,c))&&(s.set(u,c),i+=1,o!==void 0&&i%o===0||!e.debounceMs))return d()},load(u){let c=t.read(u);if(c!==void 0)return c instanceof Uint8Array?c.length===0?void 0:n.decode(c):Promise.resolve(c).then(l=>l===void 0||l.length===0?void 0:n.decode(l))},delete(u){if(s.delete(u),!!t.delete)return t.delete(u)},list(u){return t.list?t.list(u):[]},async flush(){await d()},async rollback(){s=new Map}};function d(){if(s.size===0)return;let u=s;s=new Map;let c=[];for(let[l,p]of u){let f=n.encode(p),m=t.write(l,f);m instanceof Promise&&c.push(m)}if(c.length>0)return Promise.all(c).then(()=>{})}return a}function Op(t){return Hs(mo(),t)}function Ap(t){return ed(mo(),t)}function go(t){return Ws(mo(),t)}function Cp(t,e){let n={name:e?.name??"dict-kv",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}};return Ws(n,e)}function Lp(t,e){return Hs({name:"dict",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}},e)}ae();Me();ne();function ho(t,e,n,r){let o=new Q(t,r);o.add(e,{name:"source"});let s=A(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)ih(o,e,s,i);return o}function ih(t,e,n,r){let o=`branch/${r.name}`,s=Symbol("noValue"),i=!1,a=!1,d=!1,u=s,c=!1,l=n.cache??[];function p(h){if(d){d=!1;let g=u;if(u=s,g!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(g)??!1}catch{b=!1}b?(c=!1,h.emit(g)):c&&(c=!1,h.down([[oe],[q]]))}else c?(c=!1,h.down([[oe],[q]])):h.down([[q]])}}let f=U([],(h,g)=>{let y=e.subscribe(v=>{for(let T of v)m(T,0,g)}),b=n.subscribe(v=>{for(let T of v)m(T,1,g)});return()=>{y(),b()}},{describeKind:"derived",meta:{kind:"stratify_branch",branch:r.name},completeWhenDepsComplete:!1});function m(h,g,y){let b=h[0];return b===oe?(g===0?(i=!0,c=!0):a=!0,!0):b===M||b===q?(g===0?(i=!1,d=!0,u=b===M?h[1]:s):(b===M&&(l=h[1]),a=!1),i||a||p(y),!0):b===P||b===I||b===le?(i=!1,a=!1,d=!1,u=s,c=!1,g===0&&y.down([h]),!0):g===1}if(t.add(f,{name:o}),r.ops){let h=r.ops(f),g=`branch/${r.name}/out`;t.add(h,{name:g})}}Rt();Ae();ae();Me();ne();ve();ae();var ah=new Map([[Qe,"INVALIDATE"],[Ve,"PAUSE"],[ze,"RESUME"],[le,"TEARDOWN"],[P,"COMPLETE"],[I,"ERROR"]]),dh=new Map([["INVALIDATE",Qe],["PAUSE",Ve],["RESUME",ze],["TEARDOWN",le],["COMPLETE",P],["ERROR",I]]);function Xt(t){let e=ah.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function vn(t){let e=dh.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function Tn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function wn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function Zt(t){if(typeof MessagePort<"u"&&t instanceof MessagePort)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),t.start(),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof SharedWorker<"u"&&t instanceof SharedWorker)return Zt(t.port);if(typeof Worker<"u"&&t instanceof Worker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.terminate()}};if(typeof BroadcastChannel<"u"&&t instanceof BroadcastChannel)return{post(e,n){n&&n.length>0&&console.warn("[graphrefly] WorkerTransport: BroadcastChannel does not support Transferable objects. The transfer argument is ignored and objects will be cloned instead."),t.postMessage(e)},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof ServiceWorker<"u"&&t instanceof ServiceWorker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>{r.source===t&&e(r.data)};return navigator.serviceWorker.addEventListener("message",n),()=>navigator.serviceWorker.removeEventListener("message",n)}};throw new Error("createTransport: unsupported target type. Expected Worker, SharedWorker, ServiceWorker, BroadcastChannel, or MessagePort.")}function uh(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function td(t,e){let n=uh(t)?t:Zt(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=A("connecting",{name:`${r}::meta::status`}),d=A(null,{name:`${r}::meta::error`}),u=new Map,c=new Map;for(let b of s){let v=A(void 0,{name:`${r}::${b}`});u.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=U(b,(w,x)=>{let k={};for(let S=0;S<o.length;S++){let[R]=o[S],E=w[S];E!=null&&E.length>0&&(k[R]=E.at(-1))}Object.keys(k).length!==0&&x.emit(k)},{name:`${r}::aggregated`,partial:!0});l=ge([v],w=>{let x=w[0];if(x==null||Object.keys(x).length===0)return;let k=[];for(let E of Object.keys(x)){let _=i[E];_&&k.push(..._(x[E]))}let S;for(let[E,_]of o)E in x&&_.v!=null&&(S==null&&(S={}),S[E]=_.v.version);let R={t:"b",u:x,...S?{v:S}:{}};try{n.post(R,k.length>0?k:void 0)}catch(E){d.down([[M,E instanceof Error?E:new Error(String(E))]])}}).subscribe(()=>{})}let p=!1,f=n.listen(b=>{if(p)return;let v=b;switch(v.t){case"r":{Z(()=>{for(let[w,x]of Object.entries(v.stores)){let k=u.get(w);k&&k.down([[M,x]])}}),a.down([[M,"connected"]]);let T={};for(let[w,x]of o)T[w]=x.cache;n.post({t:"i",stores:T});break}case"v":{let T=u.get(v.s);T&&T.down([[M,v.d]]);break}case"b":{Z(()=>{for(let[T,w]of Object.entries(v.u)){let x=v.v?.[T];if(x!=null){let S=c.get(T);if(S!=null&&x<=S)continue;c.set(T,x)}let k=u.get(T);k&&k.down([[M,w]])}});break}case"e":{let T=u.get(v.s);T&&T.down([[I,wn(v.err)]]);break}case"s":{let T=vn(v.sig);if(!T)break;let w=v.s==="*"?[...u.values()]:u.has(v.s)?[u.get(v.s)]:[];for(let x of w)x.down(v.d===void 0?[[T]]:[[T,v.d]]);break}}}),m=[];for(let[b,v]of o){let T=v.subscribe((w=>{if(!p)for(let x of w){let k=x[0];k!==M&&(Fe.isLocalOnly(k)||(k===I?n.post({t:"e",s:b,err:Tn(x[1])}):n.post({t:"s",s:b,sig:Xt(k),d:x.length>1?x[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=Ze(e.timeoutMs),v=rt(a,w=>w==="connected");h=Fs(Et(eo(b,()=>"timeout"),eo(v,()=>"ready"))).subscribe(w=>{for(let x of w)x[0]===M&&x[1]==="timeout"&&(d.down([[M,new Error("Worker bridge handshake timeout")]]),g())})}function g(){if(!p){p=!0,h?.(),n.post({t:"s",s:"*",sig:Xt(le)}),l&&l();for(let b of m)b();m.length=0,f(),a.down([[M,"closed"]]),c.clear(),u.clear()}}let y={meta:{status:a,error:d},destroy:g};for(let[b,v]of u)y[b]=v;return y}Ae();ae();Me();ne();function ch(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function nd(t,e){let n=ch(t)?t:Zt(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let g of r){let y=A(void 0,{name:`worker::${g}`});s.set(g,y),a[g]=y}let d=e.expose(a),u=Object.entries(d),c,l=!1;if(u.length>0){let g=u.map(([,v])=>v),y=U(g,(v,T)=>{let w={};for(let x=0;x<u.length;x++){let[k]=u[x],S=v[x];S!=null&&S.length>0&&(w[k]=S.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});c=ge([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let S of Object.keys(T)){let R=o[S];R&&w.push(...R(T[S]))}let x;for(let[S,R]of u)S in T&&R.v!=null&&(x==null&&(x={}),x[S]=R.v.version);let k={t:"b",u:T,...x?{v:x}:{}};try{n.post(k,w.length>0?w:void 0)}catch{}}).subscribe(()=>{})}let p=[];for(let[g,y]of u){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==M&&(Fe.isLocalOnly(w)||(w===I?n.post({t:"e",s:g,err:Tn(T[1])}):n.post({t:"s",s:g,sig:Xt(w),d:T.length>1?T[1]:void 0})))}}));p.push(b)}let f=n.listen(g=>{if(l)return;let y=g;switch(y.t){case"i":{Z(()=>{for(let[b,v]of Object.entries(y.stores)){let T=s.get(b);T&&T.down([[M,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[M,y.d]]);break}case"b":{Z(()=>{for(let[b,v]of Object.entries(y.u)){let T=y.v?.[b];if(T!=null){let x=i.get(b);if(x!=null&&T<=x)continue;i.set(b,T)}let w=s.get(b);w&&w.down([[M,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[I,wn(y.err)]]);break}case"s":{let b=vn(y.sig);if(!b)break;if(b===le&&y.s==="*"){h();return}let v=y.s==="*"?[...s.values()]:s.has(y.s)?[s.get(y.s)]:[];for(let T of v)T.down(y.d===void 0?[[b]]:[[b,y.d]]);break}}}),m={};for(let[g,y]of u)m[g]=y.cache;n.post({t:"r",stores:m});function h(){if(!l){l=!0,c&&c();for(let g of p)g();p.length=0,f(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:h}}var du={};Se(du,{SNAPSHOT_WIRE_VERSION:()=>Io,SurfaceError:()=>_e,accountability:()=>Si,ai:()=>ki,asSurfaceError:()=>Hi,cqrs:()=>Es,createGraph:()=>vr,deleteSnapshot:()=>Zi,demoShell:()=>Ei,diffSnapshots:()=>Qi,domainTemplates:()=>_i,graphspec:()=>wi,guarded:()=>Oi,harness:()=>ji,jobQueue:()=>Fi,layout:()=>qi,lens:()=>Vi,listSnapshots:()=>Xi,memory:()=>bi,messaging:()=>li,orchestration:()=>pi,process:()=>Ki,reduction:()=>Ti,refine:()=>Li,resilientPipeline:()=>zi,restoreSnapshot:()=>Yi,runReduction:()=>Wi,saveSnapshot:()=>Ji,surface:()=>ea});var ki={};Se(ki,{AgentLoopGraph:()=>gi,AllTiersExhaustedError:()=>vo,BudgetExhaustedError:()=>ni,ChatStreamGraph:()=>fi,CircuitOpenError:()=>yt,DEFAULT_DECAY_RATE:()=>Ad,FallbackMissError:()=>bh,LLMTimeoutError:()=>ur,ReplayCacheMissError:()=>Rn,ToolRegistryGraph:()=>mi,admissionFilter3D:()=>xy,admissionScored:()=>of,agentLoop:()=>Ty,agentMemory:()=>My,anthropicAdapter:()=>od,canonicalJson:()=>id,cascadingLlmAdapter:()=>vd,chatStream:()=>xd,composePricing:()=>Gh,computePrice:()=>pd,contentGate:()=>hy,costMeterExtractor:()=>cy,createAdapter:()=>Ch,createCapabilitiesRegistry:()=>lh,createPricingRegistry:()=>Ph,dryRunAdapter:()=>kn,fallbackAdapter:()=>ad,fromLLM:()=>Qh,frozenContext:()=>ty,gatedStream:()=>ay,gaugesAsContext:()=>Oy,googleAdapter:()=>dd,graphFromSpec:()=>wf,graphFromSpecReactive:()=>Vy,handoff:()=>wy,keywordFlagExtractor:()=>py,knobsAsTools:()=>qy,llmConsolidator:()=>Ed,llmExtractor:()=>Nd,memoryRetrieval:()=>Pd,memoryWithKG:()=>Ld,memoryWithTiers:()=>Id,memoryWithVectors:()=>Cd,observableAdapter:()=>Lh,openAICompatAdapter:()=>cd,parseRateLimitFromError:()=>hd,pricingFor:()=>Fh,promptNode:()=>Sn,redactor:()=>yy,registryPricing:()=>Dh,resilientAdapter:()=>Yh,streamExtractor:()=>fy,streamingPromptNode:()=>iy,suggestStrategy:()=>kf,suggestStrategyReactive:()=>Hy,systemPromptBuilder:()=>dy,tier:()=>Uh,toolCallExtractor:()=>gy,toolExecution:()=>Rd,toolRegistry:()=>Sd,toolSelector:()=>ky,validateGraphDef:()=>Wy,withBreaker:()=>fd,withBudgetGate:()=>gd,withDryRun:()=>jh,withRateLimiter:()=>bd,withReplayCache:()=>bo,withRetry:()=>Td,withTimeout:()=>wd,zeroPrice:()=>ti});ne();function yo(t,e){return`${t}::${e}`}function lh(t){let e=je({name:"capabilitiesRegistry"}),n=u=>{e.set(yo(u.provider,u.id),u)};if(t)for(let u of t)n(u);let r=(u,c)=>{let l=e.get(yo(u,c));if(l)return l;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==u)continue;let h=m.id;c.startsWith(h)&&(!f||h.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(u,c,l,p)=>{for(u.has(c)&&u.delete(c),u.set(c,l);u.size>p;){let f=u.keys().next().value;if(f===void 0)break;u.delete(f)}},d=C([e.entries],([u])=>Array.from(u.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(u,c){let l=e.has(yo(u,c));return l&&e.delete(yo(u,c)),l},entries(){let u=e.entries.cache;return(function*(){if(u)for(let c of u.values())yield c})()},lookupNode(u,c){let l=yo(u,c),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=C([e.entries],()=>r(u,c),{name:`capabilitiesRegistry/lookup/${u}::${c}`,initial:void 0});return a(s,l,f,o),f},entriesNode:d,byProvider(u){let c=i.get(u);if(c)return i.delete(u),i.set(u,c),c;let l=C([d],([p])=>p.filter(f=>f.provider===u),{name:`capabilitiesRegistry/byProvider/${u}`,initial:[]});return a(i,u,l,o),l}}}Re();function od(t={}){return t.sdk?hh(t):gh(t)}function Us(t,e,n,r){let o=e?.model??n;if(!o)throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");let{system:s,chat:i}=ph(t,e?.systemPrompt),a={model:o,messages:i.map(fh),max_tokens:e?.maxTokens??4096};return s&&(a.system=s),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(mh)),e?.maxReasoningTokens!=null&&(a.thinking={type:"enabled",budget_tokens:e.maxReasoningTokens}),e?.cacheHint,r&&(a.stream=!0),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function ph(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
|
|
32
|
+
`:JSON.stringify(p),m=s(l,oe());await e.putObject({Bucket:n,Key:m,Body:f,ContentType:c})}})}function Op(t,e,n,r){let{toSQL:o=(i,a)=>({sql:`INSERT INTO "${a.replace(/"/g,'""')}" (data) VALUES ($1)`,params:[JSON.stringify(i)]}),onTransportError:s}=r??{};return Je(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function Ap(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return Je(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function Cp(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return Je(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:d,labels:u}=a,c=`${oe()}`;await e.push({streams:[{stream:u,values:[[c,d]]}]})}})}function Lp(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return Je(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function Ip(t,e,n,r){let{prefix:o="checkpoints/",debounceMs:s=500,compactEvery:i=10,onError:a}=r??{},d={name:`s3:${n}`,debounceMs:s,compactEvery:i,save(u){let c=Math.floor(oe()/1e6),l=`${o}${t.name}/checkpoint-${c}.json`,p;try{p=JSON.stringify(u)}catch(f){a?.(f);return}e.putObject({Bucket:n,Key:l,Body:p,ContentType:"application/json"}).catch(f=>a?.(f))}};return t.attachSnapshotStorage([d],{onError:u=>a?.(u)})}function Dp(t,e,n){let{prefix:r="graphrefly:checkpoint:",debounceMs:o=500,compactEvery:s=10,onError:i}=n??{},a=`${r}${t.name}`,d={name:`redis:${a}`,debounceMs:o,compactEvery:s,save(u){let c;try{c=JSON.stringify(u)}catch(l){i?.(l);return}e.set(a,c).catch(l=>i?.(l))},async load(){let u=await e.get(a);if(u!=null)try{return JSON.parse(u)}catch{return}}};return t.attachSnapshotStorage([d],{onError:u=>i?.(u)})}function Pp(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return z(i=>{try{let d=t.query(e,o).map(r);i.emit(d),i.down([[I]])}catch(a){i.down([[L,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function Gp(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return z(i=>{try{let a=t.iterate(e,o);Z(()=>{for(let d of a)i.emit(r(d));i.down([[I]])})}catch(a){i.down([[L,a instanceof Error?a:new Error(String(a))]])}},{describeKind:"producer",completeWhenDepsComplete:!1,...s})}function Fp(t,e,n,r){if(n.includes("\0")||n.length===0)throw new Error(`toSqlite: invalid table name: ${JSON.stringify(n)}`);let{toSQL:o=(M,C)=>({sql:`INSERT INTO "${C.replace(/"/g,'""')}" (data) VALUES (?)`,params:[JSON.stringify(M)]}),onTransportError:s,batchInsert:i=!1,maxBatchSize:a=1e3,flushIntervalMs:d=0}=r??{},u=M=>o(M,n);if(!i)return Je(t,{onTransportError:s,serialize:u,send:M=>{let C=M;e.query(C.sql,C.params)}});let c=O(null),l=O(void 0,{equals:()=>!1}),p=O(null),f=O(0),m=O(0),h=M=>{try{s?.(M)}catch{}try{c.down([[_,M]])}catch{}},g=[],y=!1,b,v=!1,T=()=>m.down([[_,g.length]]),w=M=>{v||l.down([[_,M]])},k=M=>{v||p.down([[_,M]])},R=M=>{v||f.down([[_,M]])},S=M=>{v||h(M)},x=()=>{if(g.length===0||y)return;y=!0,R(1);try{e.query("BEGIN",[])}catch(B){y=!1,R(0),S({stage:"send",error:B instanceof Error?B:new Error(String(B)),value:void 0});return}let M=g;g=[],T();let C,$=0;for(let B of M)try{e.query(B.query.sql,B.query.params),$+=1}catch(G){C=G instanceof Error?G:new Error(String(G));break}if(C){try{e.query("ROLLBACK",[])}catch{}S({stage:"send",error:C,value:void 0});for(let B of M)k({value:B.value,error:C,attempts:1})}else try{e.query("COMMIT",[]);for(let B of M)w(B.value)}catch(B){let G=B instanceof Error?B:new Error(String(B));S({stage:"send",error:G,value:void 0});for(let V=0;V<$;V++)k({value:M[V].value,error:G,attempts:1})}y=!1,R(0)},N=()=>{d>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,x()},d))},E=t.subscribe(M=>{for(let C of M){let $=C[0];if($===_){let B=C[1],G;try{G=u(B)}catch(V){let F=V instanceof Error?V:new Error(String(V));h({stage:"serialize",error:F,value:B}),p.down([[_,{value:B,error:F,attempts:0}]]);continue}g.push({value:B,query:G}),T(),g.length>=a?x():N()}else $e.messageTier($)>=3&&x()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),x(),v=!0,E();for(let M of[c,l,p,f,m])try{M.down([[ce]])}catch{}}},sent:l,failed:p,inFlight:f,errors:c,buffered:m,flush:async()=>{v||x()}}}function $p(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return z(s=>{let i=!0;return t.findMany(n).then(a=>{i&&(s.emit(a.map(r)),s.down([[I]]))}).catch(a=>{if(i)try{s.down([[L,a instanceof Error?a:new Error(String(a))]])}catch{}}),()=>{i=!1}},{...o,describeKind:"producer",completeWhenDepsComplete:!1})}function jp(t,e){let{mapRow:n=o=>o,...r}=e??{};return z(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[I]]))}).catch(i=>{if(s)try{o.down([[L,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}function Bp(t,e){let{mapRow:n=o=>o,...r}=e??{};return z(o=>{let s=!0;return t.execute().then(i=>{s&&(o.emit(i.map(n)),o.down([[I]]))}).catch(i=>{if(s)try{o.down([[L,i instanceof Error?i:new Error(String(i))]])}catch{}}),()=>{s=!1}},{...r,describeKind:"producer",completeWhenDepsComplete:!1})}ir();ae();ne();function bd(){let t=new Map,e=null,n=null;function r(s){s.prev?s.prev.next=s.next:e=s.next,s.next?s.next.prev=s.prev:n=s.prev,s.prev=null,s.next=null}function o(s){s.next=e,s.prev=null,e&&(e.prev=s),e=s,n===null&&(n=s)}return{insert(s){if(t.has(s)){this.touch(s);return}let i={key:s,prev:null,next:null};t.set(s,i),o(i)},touch(s){let i=t.get(s);i&&(r(i),o(i))},delete(s){let i=t.get(s);i&&(r(i),t.delete(s))},evict(s){let i=[];for(let a=0;a<s&&n!==null;a++){let d=n;i.push(d.key),r(d),t.delete(d.key)}return i},size(){return t.size}}}function Vp(t){return t!=null&&typeof t.then=="function"}function gr(t){Vp(t)&&t.catch(()=>{})}function Kp(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??bd():null,s=e?.writeThrough??!1;function i(u,c,l){for(let p=0;p<l;p++)try{gr(t[p].save(u,c))}catch{}}function a(u,c,l=0){for(let p=l;p<t.length;p++){let f;try{f=t[p].load(u)}catch{continue}if(Vp(f)){let m=p;f.then(h=>{h!==void 0?(c.down([[_,h]]),i(u,h,m)):a(u,c,m+1)},()=>{a(u,c,m+1)});return}if(f!==void 0){c.down([[_,f]]),i(u,f,p);return}}}function d(){if(!(!o||r<=0))for(;o.size()>=r;){let u=o.evict(1);if(u.length===0)break;for(let c of u){let l=n.get(c);if(l){let p=l.cache;if(l.status!=="sentinel"&&t.length>0){let f=t.length-1;try{gr(t[f].save(c,p))}catch{}for(let m=0;m<f;m++)try{let h=t[m].delete;h&&gr(h.call(t[m],c))}catch{}}l.down([[ce]])}n.delete(c)}}}return{load(u){let c=n.get(u);if(c)return o?.touch(u),c;o&&r>0&&o.size()>=r&&d();let l=O(void 0);return n.set(u,l),o?.insert(u),a(u,l),l},save(u,c){if(s)for(let p of t)try{gr(p.save(u,c))}catch{}else if(t[0])try{gr(t[0].save(u,c))}catch{}let l=n.get(u);if(l)l.down([[_,c]]),o?.touch(u);else{o&&r>0&&o.size()>=r&&d();let p=O(c);n.set(u,p),o?.insert(u)}},invalidate(u){let c=n.get(u);c&&a(u,c)},delete(u){o?.delete(u);let c=n.get(u);c&&c.down([[ce]]),n.delete(u);for(let l of t)try{let p=l.delete;p&&gr(p.call(l,u))}catch{}},has(u){return n.has(u)},get size(){return n.size}}}Ae();ae();et();ne();Ae();Se();ae();ne();var lo=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(e={}){let{maxSize:n,defaultTtl:r}=e;if(n!==void 0&&n<1)throw new RangeError("maxSize must be >= 1");if(r!==void 0&&r<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=n,this._defaultTtl=r}get version(){return this._version}get size(){return this._store.size}has(e){let n=this._store.get(e);return n===void 0?!1:this._isExpired(n)?(this._store.delete(e),this._version+=1,!1):(this._touchLru(e,n),!0)}get(e){let n=this._store.get(e);if(n!==void 0){if(this._isExpired(n)){this._store.delete(e),this._version+=1;return}return this._touchLru(e,n),n.value}}set(e,n,r){let o=this._resolveExpiresAt(r);this._store.has(e)&&this._store.delete(e),this._store.set(e,{value:n,expiresAt:o}),this._evictLruWhileOver(),this._version+=1}setMany(e,n){let r=this._resolveExpiresAt(n),o=0;try{for(let[s,i]of e)this._store.has(s)&&this._store.delete(s),this._store.set(s,{value:i,expiresAt:r}),o+=1}finally{o>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(e){let n=this._store.delete(e);return n&&(this._version+=1),n}deleteMany(e){let n=0;try{for(let r of e)this._store.delete(r)&&(n+=1)}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._store.size;return e===0?0:(this._store.clear(),this._version+=1,e)}pruneExpired(){let e=H(),n=0;for(let[r,o]of this._store)this._isExpired(o,e)&&(this._store.delete(r),n+=1);return n>0&&(this._version+=1),n}toMap(){let e=H(),n=new Map;for(let[r,o]of this._store)this._isExpired(o,e)||n.set(r,o.value);return n}_resolveExpiresAt(e){let n=e??this._defaultTtl;if(n!==void 0){if(!Number.isFinite(n)||n<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${n})`);return H()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??H())>=e.expiresAt}_touchLru(e,n){this._store.delete(e),this._store.set(e,n)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let e=this._store.keys().next().value;if(e===void 0)break;this._store.delete(e)}}};function Ye(t={}){let{name:e,maxSize:n,defaultTtl:r,versioning:o,backend:s,retention:i}=t;if(i&&n!==void 0)throw new RangeError("reactiveMap: `maxSize` (LRU) and `retention` (score-based) are mutually exclusive. Pick one eviction policy.");if(i&&i.archiveThreshold===void 0&&i.maxSize===void 0)throw new RangeError("reactiveMap: `retention` requires at least one of `archiveThreshold` or `maxSize` to trigger archival.");let a=s??new lo({maxSize:n,defaultTtl:r}),d=O(a.toMap(),{name:e,describeKind:"state",equals:(p,f)=>p===f,...o!=null?{versioning:o}:{}});function u(){let p=a.toMap();Z(()=>{d.down([[se]]),d.down([[_,p]])})}function c(){if(!i)return;let p=a.toMap(),f=i.archiveThreshold,m=i.maxSize,h=[];for(let[y,b]of p)h.push({key:y,value:b,score:i.score(y,b)});h.sort((y,b)=>y.score-b.score);let g=new Set;if(f!==void 0)for(let y of h)if(y.score<f)g.add(y.key);else break;if(m!==void 0&&h.length-g.size>m)for(let y of h){if(h.length-g.size<=m)break;g.has(y.key)||g.add(y.key)}if(g.size!==0)for(let y of h)g.has(y.key)&&(i.onArchive?.(y.key,y.value,y.score),a.delete(y.key))}function l(p,f="mutation"){let m=a.version;try{return p()}finally{a.version!==m&&(f==="mutation"&&c(),u())}}return{entries:d,has(p){return l(()=>a.has(p),"read")},get(p){return l(()=>a.get(p),"read")},set(p,f,m){l(()=>a.set(p,f,m?.ttl))},setMany(p,f){l(()=>a.setMany(p,f?.ttl))},delete(p){l(()=>a.delete(p))},deleteMany(p){l(()=>a.deleteMany(p))},clear(){l(()=>a.clear())},pruneExpired(){l(()=>a.pruneExpired())},get size(){return a.size},dispose(){}}}ue();function kh(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function Hp(t,e,n){let r=Y(t),o=r.v!=null,s=O(n?.initialVerified??null,{meta:{...be("verifiable"),...o?{sourceVersion:null}:{}}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=Mt(Y(n.trigger),r):i?a=Y(n.trigger):n?.autoVerify&&(a=r),a!==null){let d;if(a===r)d=me(r,u=>e(u));else{let u=r.cache;r.subscribe(c=>{for(let l of c)l[0]===_&&(u=l[1])}),d=me(a,()=>e(u))}Qt(d,u=>{Z(()=>{if(s.down([[_,u]]),o){let c=r.v;c!=null&&s.meta.sourceVersion.down([[_,{id:c.id,version:c.version}]])}})})}return{node:r,verified:s,trigger:a}}function qp(t){t.subscribe(()=>{})}function po(t){return t instanceof Map?t:new Map}function zp(t,e){if(!Array.isArray(e.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");Z(()=>{for(let{key:n,value:r}of e.upsert)t.set(n,r);for(let n of e.remove??[])t.delete(n)})}function Ys(t,e,n){let r=Y(t),o=Ye(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?Y(n.context):O(null),d=po(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===_&&(d=po(m[1]))});let u=Y(e(r,o.entries));if(Qt(u,f=>{zp(o,f)}),n.evict){let f=new Map,m=A([o.entries],([h])=>{let g=[],y=po(h);for(let b of f.keys())y.has(b)||(f.get(b)(),f.delete(b));for(let[b,v]of y){let T=n.evict(b,v);if(kh(T)){if(!f.has(b)){let w=Qt(T,k=>{k===!0&&o.has(b)&&o.delete(b)});f.set(b,w)}continue}if(typeof T=="boolean"){T&&g.push(b);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return g});Qt(m,h=>{for(let g of h)o.delete(g)})}let c=n.consolidateTrigger!==void 0&&n.consolidateTrigger!==null;if(n.consolidate&&c){let f=Y(n.consolidateTrigger),m=me(f,()=>n.consolidate(d));Qt(m,h=>{zp(o,h)})}let l=A([o.entries,a],([f,m])=>{let h=[...po(f).entries()].map(([b,v])=>({key:b,value:v,score:n.score(v,m),cost:n.cost(v)}));h.sort((b,v)=>v.score-b.score);let g=[],y=s;for(let b of h)b.cost<=y&&(g.push({key:b.key,value:b.value,score:b.score}),y-=b.cost);return g},{meta:{...be("distill",{budget:s})}}),p=A([o.entries],([f])=>po(f).size);return qp(l),qp(p),{store:o,compact:l,size:p}}async function Qs(t){let e=typeof t=="string"?new TextEncoder().encode(t):t,n=await globalThis.crypto.subtle.digest("SHA-256",e),r=new Uint8Array(n),o="";for(let s=0;s<r.length;s++)o+=Wp[r[s]];return o}var Wp=new Array(256);for(let t=0;t<256;t++)Wp[t]=t.toString(16).padStart(2,"0");var fo=class extends Error{constructor(n,r){super(`content-addressed lookup miss in read-strict mode: ${n}`);this.key=n;this.context=r;this.name="ContentAddressedMissError"}};function mo(t){let e=new Set,n=r=>{if(r===null||typeof r!="object")return r;let o=r;if(e.has(o))return{__cycle:!0};e.add(o);try{if(Array.isArray(r))return r.map(n);let s={};for(let i of Object.keys(r).sort())s[i]=n(r[i]);return s}finally{e.delete(o)}};return JSON.stringify(n(t))}function Xs(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let d=mo(s(a)),u=await Qs(d);return r?`${r}:${u}`:u}return{keyFor:i,async lookup(a){if(o==="write")return;let d=await i(a),u=await e.load(d);if(u===void 0){if(o==="read-strict")throw new fo(d,a);return}return u},async store(a,d){if(o==="read")return;let u=await i(a);await e.save(u,d)},async forget(a){if(o==="read"||o==="write"||!e.delete)return;let d=await i(a);await e.delete(d)}}}Ea();async function xt(t,e){let n;try{n=await t.text()}catch{n=""}let r=e??"HTTP",o=new Error(`${r} API ${t.status}: ${t.statusText}${n?` \u2014 ${n}`:""}`);return o.status=t.status,o.headers=t.headers,o}at();Ae();ae();Me();var go=class{_version=0;_topics=new Set;get version(){return this._version}get topicCount(){return this._topics.size}hasTopic(e){return this._topics.has(e)}topicNames(){return this._topics.values()}createTopic(e){return this._topics.has(e)?!1:(this._topics.add(e),this._version+=1,!0)}removeTopic(e){let n=this._topics.delete(e);return n&&(this._version+=1),n}};function Up(t={}){let{backend:e}=t,n=e??new go,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=U({describeKind:"state"}),r.set(s,i),n.createTopic(s)),i}return{topic(s){return o(s)},publish(s,i){o(s).emit(i)},publishMany(s){Z(()=>{for(let[i,a]of s)o(i).emit(a)})},removeTopic(s){let i=r.get(s);return i===void 0?!1:(r.delete(s),n.removeTopic(s),i.down([[ce]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Ae();ae();ne();function Jp(t,e){if(t===e)return 0;let n=typeof t;if(n===typeof e&&(n==="number"||n==="string"||n==="boolean"||n==="bigint")){let o=t,s=e;return o<s?-1:o>s?1:0}return String(t).localeCompare(String(e))}function xh(t,e){let n=Jp(t[0],e[0]);return n!==0?n:Jp(t[1],e[1])}function Yp(t){return[t.secondary,t.primary]}function hr(t,e){let n=Yp(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;xh(n,Yp(t[s]))>0?r=s+1:o=s}return r}var ho=class{_version=0;_buf=[];_byPrimary=new Map;get version(){return this._version}get size(){return this._buf.length}has(e){return this._byPrimary.has(e)}get(e){return this._byPrimary.get(e)?.value}upsert(e,n,r,o){let s=this._byPrimary.get(e),i={primary:e,secondary:n,value:r};if(s!==void 0&&o?.equals?.(s,i))return!1;if(s!==void 0){let d=hr(this._buf,s);this._buf.splice(d,1)}let a=hr(this._buf,i);return this._buf.splice(a,0,i),this._byPrimary.set(e,i),this._version+=1,s===void 0}upsertMany(e,n){let r=0;try{for(let o of e){let s=this._byPrimary.get(o.primary),i={primary:o.primary,secondary:o.secondary,value:o.value};if(s!==void 0&&n?.equals?.(s,i))continue;if(s!==void 0){let d=hr(this._buf,s);this._buf.splice(d,1)}let a=hr(this._buf,i);this._buf.splice(a,0,i),this._byPrimary.set(o.primary,i),r+=1}}finally{r>0&&(this._version+=1)}return r}delete(e){let n=this._byPrimary.get(e);if(n===void 0)return!1;let r=hr(this._buf,n);return this._buf.splice(r,1),this._byPrimary.delete(e),this._version+=1,!0}deleteMany(e){let n=0;try{for(let r of e){let o=this._byPrimary.get(r);if(o===void 0)continue;let s=hr(this._buf,o);this._buf.splice(s,1),this._byPrimary.delete(r),n+=1}}finally{n>0&&(this._version+=1)}return n}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._byPrimary.clear(),this._version+=1,e)}toArray(){return[...this._buf]}toPrimaryMap(){let e=new Map;for(let n of this._buf)e.set(n.primary,n.value);return e}};function Rh(t){return t.subscribe(()=>{})}function Qp(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new ho;function i(f){return f?.equals!==void 0||r===void 0?f:{...f,equals:r}}let a=O([],{name:e,describeKind:"state",equals:(f,m)=>f===m,...n!=null?{versioning:n}:{}}),d=A([a],([f])=>{let m=f,h=new Map;for(let g of m)h.set(g.primary,g.value);return h},{initial:s.toPrimaryMap(),describeKind:"derived"}),u=Rh(d),c=!1;function l(){let f=s.toArray();Z(()=>{a.down([[se]]),a.down([[_,f]])})}function p(f){let m=s.version;try{return f()}finally{s.version!==m&&l()}}return{ordered:a,byPrimary:d,has(f){return s.has(f)},get(f){return s.get(f)},get size(){return s.size},upsert(f,m,h,g){return p(()=>s.upsert(f,m,h,i(g)))},upsertMany(f,m){let h=[...f];h.length!==0&&p(()=>s.upsertMany(h,i(m)))},delete(f){p(()=>s.delete(f))},deleteMany(f){let m=[...f];m.length!==0&&p(()=>s.deleteMany(m))},clear(){p(()=>s.clear())},dispose(){c||(c=!0,u())}}}Ae();ae();ne();var yo=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let r=0;r<e.length;r++)this._buf[n+r]=e[r];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[r]=this._buf.splice(n,1);return this._version+=1,r}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function Zs(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new yo(t),i=O(s.toArray(),{name:n,describeKind:"state",equals:(u,c)=>u===c,...r!=null?{versioning:r}:{}});function a(){let u=s.toArray();Z(()=>{i.down([[se]]),i.down([[_,u]])})}function d(u){let c=s.version;try{return u()}finally{s.version!==c&&a()}}return{items:i,get size(){return s.size},at(u){return s.at(u)},append(u){d(()=>s.append(u))},appendMany(u){d(()=>s.appendMany(u))},insert(u,c){d(()=>s.insert(u,c))},insertMany(u,c){d(()=>s.insertMany(u,c))},pop(u=-1){return d(()=>s.pop(u))},clear(){d(()=>s.clear())},dispose(){}}}Gt();ae();ue();function ei(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=t(o),d;a!=null&&typeof a.then=="function"?d=Promise.resolve(a):a!=null&&typeof a=="object"&&"subscribe"in a&&"cache"in a?d=nt(a):a!=null&&typeof a=="object"&&Symbol.asyncIterator in a?d=(async()=>{let l=a[Symbol.asyncIterator]();try{let{value:p,done:f}=await l.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return p}finally{await l.return?.()}})():a!=null&&typeof a=="object"&&Symbol.iterator in a?d=(async()=>{let l=a[Symbol.iterator]();try{let{value:p,done:f}=l.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return p}finally{l.return?.()}})():d=Promise.resolve(a);let u,c=()=>{r.get(s)===u&&r.delete(s)};return u=d.then(l=>(c(),l),l=>{throw c(),l}),r.set(s,u),u}}function Xp(t,e={}){let n=e.keyFn??(o=>String(o)),r=new Map;return o=>{let s=n(o),i=r.get(s);if(i)return i;let a=Y(t(o));r.set(s,a);let d=a.subscribe(u=>{for(let c of u)if(c[0]===L||c[0]===I){r.get(s)===a&&r.delete(s),d();return}});return a}}ue();function bo(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(bo);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=bo(e[o]);return r}function ti(t){return JSON.stringify(bo(t),void 0,0)}var Sh=new TextEncoder,Nh=new TextDecoder("utf-8",{fatal:!0}),yr={name:"json",version:1,encode(t){return Sh.encode(ti(t))},decode(t){return JSON.parse(Nh.decode(t))}};function Zp(){return yr}function vo(){let t=new Map;return{name:"memory",read(e){let n=t.get(e);return n===void 0?void 0:new Uint8Array(n)},write(e,n){t.set(e,new Uint8Array(n))},delete(e){t.delete(e)},list(e){let n=[...t.keys()];return e?n.filter(r=>r.startsWith(e)).sort():n.sort()}}}function ni(t,e={}){let n=e.codec??yr,r=e.name??t.name??"snapshot",o=e.keyOf??(l=>l.name??e.name??t.name??"snapshot"),s,i=0,a=e.compactEvery,d,u={name:r,debounceMs:e.debounceMs,compactEvery:a,filter:e.filter,keyOf:o,save(l){if(!(e.filter&&!e.filter(l))&&(s={snapshot:l},i+=1,a!==void 0&&i%a===0||!e.debounceMs))return c()},load(){let l=d??r,p=t.read(l);if(p!==void 0)return p instanceof Uint8Array?p.length===0?void 0:n.decode(p):Promise.resolve(p).then(f=>f===void 0||f.length===0?void 0:n.decode(f))},async flush(){await c()},async rollback(){s=void 0}};function c(){let l=s;if(!l)return;s=void 0;let p=o(l.snapshot),f=n.encode(l.snapshot),m=t.write(p,f);if(m instanceof Promise)return m.then(()=>{d=p});d=p}return u}function vd(t,e={}){let n=e.codec??yr,r=e.name??t.name??"append-log",o=e.keyOf??(p=>r),s=e.compactEvery,i=new Map,a=0,d,u={name:r,debounceMs:e.debounceMs,compactEvery:s,keyOf:o,appendEntries(p){if(p.length!==0){for(let f of p){let m=o(f),h=i.get(m);h||(h=[],i.set(m,h)),h.push(f)}if(a+=p.length,s!==void 0&&a%s===0||!e.debounceMs)return c()}},async loadEntries(p){let f=p?.keyFilter,m=t.list===void 0?f!==void 0?[f]:[r]:await Promise.resolve(t.list(f)),h=[];for(let g of m){let y=await Promise.resolve(t.read(g));if(y===void 0||y.length===0)continue;let b=n.decode(y);Array.isArray(b)&&h.push(...b)}return{entries:h,cursor:void 0}},async flush(){await c()},async rollback(){i=new Map}};function c(){if(i.size===0)return;let p=i;i=new Map;let f=(d??Promise.resolve()).then(()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()},()=>{let m=l(p);return m instanceof Promise?m:Promise.resolve()});return d=f.finally(()=>{d===f&&(d=void 0)}),d}function l(p){let f=[];for(let[m,h]of p){let g=t.read(m),y=b=>{let T=[...b===void 0||b.length===0?[]:n.decode(b)??[],...h],w=n.encode(T);return t.write(m,w)};if(g instanceof Promise)f.push(g.then(async b=>{let v=y(b);v instanceof Promise&&await v}));else{let b=y(g);b instanceof Promise&&f.push(b)}}if(f.length>0)return Promise.all(f).then(()=>{})}return u}function ri(t,e={}){let n=e.codec??yr,r=e.name??t.name??"kv",o=e.compactEvery,s=new Map,i=0,a={name:r,debounceMs:e.debounceMs,compactEvery:o,filter:e.filter,save(u,c){if(!(e.filter&&!e.filter(u,c))&&(s.set(u,c),i+=1,o!==void 0&&i%o===0||!e.debounceMs))return d()},load(u){let c=t.read(u);if(c!==void 0)return c instanceof Uint8Array?c.length===0?void 0:n.decode(c):Promise.resolve(c).then(l=>l===void 0||l.length===0?void 0:n.decode(l))},delete(u){if(s.delete(u),!!t.delete)return t.delete(u)},list(u){return t.list?t.list(u):[]},async flush(){await d()},async rollback(){s=new Map}};function d(){if(s.size===0)return;let u=s;s=new Map;let c=[];for(let[l,p]of u){let f=n.encode(p),m=t.write(l,f);m instanceof Promise&&c.push(m)}if(c.length>0)return Promise.all(c).then(()=>{})}return a}function ef(t){return ni(vo(),t)}function tf(t){return vd(vo(),t)}function To(t){return ri(vo(),t)}function nf(t,e){let n={name:e?.name??"dict-kv",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}};return ri(n,e)}function rf(t,e){return ni({name:"dict",read(r){return t[r]},write(r,o){t[r]=new Uint8Array(o)},delete(r){delete t[r]},list(r){let o=Object.keys(t).sort();return r?o.filter(s=>s.startsWith(r)):o}},e)}ae();Me();ne();function wo(t,e,n,r){let o=new Q(t,r);o.add(e,{name:"source"});let s=O(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)Eh(o,e,s,i);return o}function Eh(t,e,n,r){let o=`branch/${r.name}`,s=Symbol("noValue"),i=!1,a=!1,d=!1,u=s,c=!1,l=n.cache??[];function p(h){if(d){d=!1;let g=u;if(u=s,g!==s){let y=l.find(v=>v.name===r.name),b=!1;try{b=y?.classify(g)??!1}catch{b=!1}b?(c=!1,h.emit(g)):c&&(c=!1,h.down([[se],[q]]))}else c?(c=!1,h.down([[se],[q]])):h.down([[q]])}}let f=U([],(h,g)=>{let y=e.subscribe(v=>{for(let T of v)m(T,0,g)}),b=n.subscribe(v=>{for(let T of v)m(T,1,g)});return()=>{y(),b()}},{describeKind:"derived",meta:{kind:"stratify_branch",branch:r.name},completeWhenDepsComplete:!1});function m(h,g,y){let b=h[0];return b===se?(g===0?(i=!0,c=!0):a=!0,!0):b===_||b===q?(g===0?(i=!1,d=!0,u=b===_?h[1]:s):(b===_&&(l=h[1]),a=!1),i||a||p(y),!0):b===I||b===L||b===ce?(i=!1,a=!1,d=!1,u=s,c=!1,g===0&&y.down([h]),!0):g===1}if(t.add(f,{name:o}),r.ops){let h=r.ops(f),g=`branch/${r.name}/out`;t.add(h,{name:g})}}Et();var oi=Math.LN2/604800;function Ot(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let o=t*Math.exp(-n*e);return Math.max(r,o)}Ae();ae();Me();ne();ue();ae();var _h=new Map([[Ze,"INVALIDATE"],[Ke,"PAUSE"],[He,"RESUME"],[ce,"TEARDOWN"],[I,"COMPLETE"],[L,"ERROR"]]),Mh=new Map([["INVALIDATE",Ze],["PAUSE",Ke],["RESUME",He],["TEARDOWN",ce],["COMPLETE",I],["ERROR",L]]);function on(t){let e=_h.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function In(t){let e=Mh.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function Dn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function Pn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function sn(t){if(typeof MessagePort<"u"&&t instanceof MessagePort)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),t.start(),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof SharedWorker<"u"&&t instanceof SharedWorker)return sn(t.port);if(typeof Worker<"u"&&t instanceof Worker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.terminate()}};if(typeof BroadcastChannel<"u"&&t instanceof BroadcastChannel)return{post(e,n){n&&n.length>0&&console.warn("[graphrefly] WorkerTransport: BroadcastChannel does not support Transferable objects. The transfer argument is ignored and objects will be cloned instead."),t.postMessage(e)},listen(e){let n=r=>e(r.data);return t.addEventListener("message",n),()=>t.removeEventListener("message",n)},terminate(){t.close()}};if(typeof ServiceWorker<"u"&&t instanceof ServiceWorker)return{post(e,n){t.postMessage(e,n??[])},listen(e){let n=r=>{r.source===t&&e(r.data)};return navigator.serviceWorker.addEventListener("message",n),()=>navigator.serviceWorker.removeEventListener("message",n)}};throw new Error("createTransport: unsupported target type. Expected Worker, SharedWorker, ServiceWorker, BroadcastChannel, or MessagePort.")}function Oh(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Td(t,e){let n=Oh(t)?t:sn(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=O("connecting",{name:`${r}::meta::status`}),d=O(null,{name:`${r}::meta::error`}),u=new Map,c=new Map;for(let b of s){let v=O(void 0,{name:`${r}::${b}`});u.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=U(b,(w,k)=>{let R={};for(let S=0;S<o.length;S++){let[x]=o[S],N=w[S];N!=null&&N.length>0&&(R[x]=N.at(-1))}Object.keys(R).length!==0&&k.emit(R)},{name:`${r}::aggregated`,partial:!0});l=ye([v],w=>{let k=w[0];if(k==null||Object.keys(k).length===0)return;let R=[];for(let N of Object.keys(k)){let E=i[N];E&&R.push(...E(k[N]))}let S;for(let[N,E]of o)N in k&&E.v!=null&&(S==null&&(S={}),S[N]=E.v.version);let x={t:"b",u:k,...S?{v:S}:{}};try{n.post(x,R.length>0?R:void 0)}catch(N){d.down([[_,N instanceof Error?N:new Error(String(N))]])}}).subscribe(()=>{})}let p=!1,f=n.listen(b=>{if(p)return;let v=b;switch(v.t){case"r":{Z(()=>{for(let[w,k]of Object.entries(v.stores)){let R=u.get(w);R&&R.down([[_,k]])}}),a.down([[_,"connected"]]);let T={};for(let[w,k]of o)T[w]=k.cache;n.post({t:"i",stores:T});break}case"v":{let T=u.get(v.s);T&&T.down([[_,v.d]]);break}case"b":{Z(()=>{for(let[T,w]of Object.entries(v.u)){let k=v.v?.[T];if(k!=null){let S=c.get(T);if(S!=null&&k<=S)continue;c.set(T,k)}let R=u.get(T);R&&R.down([[_,w]])}});break}case"e":{let T=u.get(v.s);T&&T.down([[L,Pn(v.err)]]);break}case"s":{let T=In(v.sig);if(!T)break;let w=v.s==="*"?[...u.values()]:u.has(v.s)?[u.get(v.s)]:[];for(let k of w)k.down(v.d===void 0?[[T]]:[[T,v.d]]);break}}}),m=[];for(let[b,v]of o){let T=v.subscribe((w=>{if(!p)for(let k of w){let R=k[0];R!==_&&($e.isLocalOnly(R)||(R===L?n.post({t:"e",s:b,err:Dn(k[1])}):n.post({t:"s",s:b,sig:on(R),d:k.length>1?k[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=tt(e.timeoutMs),v=st(a,w=>w==="connected");h=Us(Mt(so(b,()=>"timeout"),so(v,()=>"ready"))).subscribe(w=>{for(let k of w)k[0]===_&&k[1]==="timeout"&&(d.down([[_,new Error("Worker bridge handshake timeout")]]),g())})}function g(){if(!p){p=!0,h?.(),n.post({t:"s",s:"*",sig:on(ce)}),l&&l();for(let b of m)b();m.length=0,f(),a.down([[_,"closed"]]),c.clear(),u.clear()}}let y={meta:{status:a,error:d},destroy:g};for(let[b,v]of u)y[b]=v;return y}Ae();ae();Me();ne();function Ah(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function wd(t,e){let n=Ah(t)?t:sn(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let g of r){let y=O(void 0,{name:`worker::${g}`});s.set(g,y),a[g]=y}let d=e.expose(a),u=Object.entries(d),c,l=!1;if(u.length>0){let g=u.map(([,v])=>v),y=U(g,(v,T)=>{let w={};for(let k=0;k<u.length;k++){let[R]=u[k],S=v[k];S!=null&&S.length>0&&(w[R]=S.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});c=ye([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let S of Object.keys(T)){let x=o[S];x&&w.push(...x(T[S]))}let k;for(let[S,x]of u)S in T&&x.v!=null&&(k==null&&(k={}),k[S]=x.v.version);let R={t:"b",u:T,...k?{v:k}:{}};try{n.post(R,w.length>0?w:void 0)}catch{}}).subscribe(()=>{})}let p=[];for(let[g,y]of u){let b=y.subscribe((v=>{if(!l)for(let T of v){let w=T[0];w!==_&&($e.isLocalOnly(w)||(w===L?n.post({t:"e",s:g,err:Dn(T[1])}):n.post({t:"s",s:g,sig:on(w),d:T.length>1?T[1]:void 0})))}}));p.push(b)}let f=n.listen(g=>{if(l)return;let y=g;switch(y.t){case"i":{Z(()=>{for(let[b,v]of Object.entries(y.stores)){let T=s.get(b);T&&T.down([[_,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[_,y.d]]);break}case"b":{Z(()=>{for(let[b,v]of Object.entries(y.u)){let T=y.v?.[b];if(T!=null){let k=i.get(b);if(k!=null&&T<=k)continue;i.set(b,T)}let w=s.get(b);w&&w.down([[_,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[L,Pn(y.err)]]);break}case"s":{let b=In(y.sig);if(!b)break;if(b===ce&&y.s==="*"){h();return}let v=y.s==="*"?[...s.values()]:s.has(y.s)?[s.get(y.s)]:[];for(let T of v)T.down(y.d===void 0?[[b]]:[[b,y.d]]);break}}}),m={};for(let[g,y]of u)m[g]=y.cache;n.post({t:"r",stores:m});function h(){if(!l){l=!0,c&&c();for(let g of p)g();p.length=0,f(),n.terminate?.(),i.clear(),s.clear()}}return{destroy:h}}var Su={};Ne(Su,{SNAPSHOT_WIRE_VERSION:()=>Vo,SurfaceError:()=>Oe,accountability:()=>Gi,ai:()=>Ii,asSurfaceError:()=>oa,cqrs:()=>Gs,createGraph:()=>Er,deleteSnapshot:()=>la,demoShell:()=>$i,diffSnapshots:()=>ua,domainTemplates:()=>ji,graphspec:()=>Li,guarded:()=>Vi,harness:()=>Xi,jobQueue:()=>Yi,layout:()=>ta,lens:()=>Zi,listSnapshots:()=>ca,memory:()=>Mi,messaging:()=>ki,orchestration:()=>xi,process:()=>ea,reduction:()=>Oi,refine:()=>zi,resilientPipeline:()=>ra,restoreSnapshot:()=>da,runReduction:()=>sa,saveSnapshot:()=>aa,surface:()=>pa});var Ii={};Ne(Ii,{AgentLoopGraph:()=>Ni,AllTiersExhaustedError:()=>Ro,BudgetExhaustedError:()=>fi,ChatStreamGraph:()=>Ri,CircuitOpenError:()=>bt,DEFAULT_DECAY_RATE:()=>oi,FallbackMissError:()=>$h,LLMTimeoutError:()=>vr,ReplayCacheMissError:()=>$n,ToolRegistryGraph:()=>Si,admissionFilter3D:()=>Ky,admissionScored:()=>Mf,agentLoop:()=>jy,agentMemory:()=>Uy,anthropicAdapter:()=>xd,canonicalJson:()=>Sd,cascadingLlmAdapter:()=>Fd,chatStream:()=>zd,composePricing:()=>oy,computePrice:()=>Ad,contentGate:()=>Py,costMeterExtractor:()=>Oy,createAdapter:()=>Zh,createCapabilitiesRegistry:()=>Ch,createPricingRegistry:()=>ny,dryRunAdapter:()=>Gn,fallbackAdapter:()=>Nd,frozenContext:()=>wy,gatedStream:()=>Ey,gaugesAsContext:()=>Jy,googleAdapter:()=>Ed,graphFromSpec:()=>Kf,graphFromSpecReactive:()=>sb,handoff:()=>By,keywordFlagExtractor:()=>Cy,knobsAsTools:()=>ab,llmConsolidator:()=>qd,llmExtractor:()=>Kd,memoryRetrieval:()=>eu,memoryWithKG:()=>Xd,memoryWithTiers:()=>Zd,memoryWithVectors:()=>Qd,observableAdapter:()=>ey,openAICompatAdapter:()=>Md,parseRateLimitFromError:()=>Dd,pricingFor:()=>sy,promptCall:()=>Vd,promptNode:()=>jn,redactor:()=>Gy,registryPricing:()=>ry,resilientAdapter:()=>yy,streamExtractor:()=>Ly,streamingPromptNode:()=>Ny,suggestStrategy:()=>qf,suggestStrategyReactive:()=>ub,systemPromptBuilder:()=>_y,tier:()=>gy,toolCallExtractor:()=>Dy,toolExecution:()=>Hd,toolRegistry:()=>Wd,toolSelector:()=>Vy,validateGraphDef:()=>cb,withBreaker:()=>Cd,withBudgetGate:()=>Id,withDryRun:()=>ay,withRateLimiter:()=>Gd,withReplayCache:()=>xo,withRetry:()=>$d,withTimeout:()=>jd,zeroPrice:()=>pi});ne();function ko(t,e){return`${t}::${e}`}function Ch(t){let e=Ye({name:"capabilitiesRegistry"}),n=u=>{e.set(ko(u.provider,u.id),u)};if(t)for(let u of t)n(u);let r=(u,c)=>{let l=e.get(ko(u,c));if(l)return l;let p=e.entries.cache;if(!p)return;let f;for(let[,m]of p){if(m.provider!==u)continue;let h=m.id;c.startsWith(h)&&(!f||h.length>f.id.length)&&(f=m)}return f},o=128,s=new Map,i=new Map,a=(u,c,l,p)=>{for(u.has(c)&&u.delete(c),u.set(c,l);u.size>p;){let f=u.keys().next().value;if(f===void 0)break;u.delete(f)}},d=A([e.entries],([u])=>Array.from(u.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(u,c){let l=e.has(ko(u,c));return l&&e.delete(ko(u,c)),l},entries(){let u=e.entries.cache;return(function*(){if(u)for(let c of u.values())yield c})()},lookupNode(u,c){let l=ko(u,c),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=A([e.entries],()=>r(u,c),{name:`capabilitiesRegistry/lookup/${u}::${c}`,initial:void 0});return a(s,l,f,o),f},entriesNode:d,byProvider(u){let c=i.get(u);if(c)return i.delete(u),i.set(u,c),c;let l=A([d],([p])=>p.filter(f=>f.provider===u),{name:`capabilitiesRegistry/byProvider/${u}`,initial:[]});return a(i,u,l,o),l}}}Se();function xd(t={}){return t.sdk?Gh(t):Ph(t)}function si(t,e,n,r){let o=e?.model??n;if(!o)throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");let{system:s,chat:i}=Lh(t,e?.systemPrompt),a={model:o,messages:i.map(Ih),max_tokens:e?.maxTokens??4096};return s&&(a.system=s),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(Dh)),e?.maxReasoningTokens!=null&&(a.thinking={type:"enabled",budget_tokens:e.maxReasoningTokens}),e?.cacheHint,r&&(a.stream=!0),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function Lh(t,e){let n=[];e&&n.push(e);let r=[];for(let o of t)o.role==="system"?n.push(o.content):r.push(o);return{system:n.length>0?n.join(`
|
|
33
33
|
|
|
34
|
-
`):void 0,chat:r}}function fh(t){if(t.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:t.toolCallId,content:t.content}]};if(t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:"text",text:t.content});for(let n of t.toolCalls)e.push({type:"tool_use",id:n.id,name:n.name,input:n.arguments});return{role:"assistant",content:e}}return{role:t.role,content:t.content}}function mh(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function Js(t,e){if(!t)return{...e};let n={...t};return e.input_tokens!=null&&(n.input_tokens=e.input_tokens),e.output_tokens!=null&&(n.output_tokens=e.output_tokens),e.cache_read_input_tokens!=null&&(n.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(n.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(n.cache_creation={...t.cache_creation??{},...e.cache_creation}),e.server_tool_use&&(n.server_tool_use={...t.server_tool_use??{},...e.server_tool_use}),n}function sd(t){let e={input:{regular:t?.input_tokens??0},output:{regular:t?.output_tokens??0},raw:t};return t?.cache_read_input_tokens&&(e.input.cacheRead=t.cache_read_input_tokens),t?.cache_creation?(t.cache_creation.ephemeral_5m_input_tokens&&(e.input.cacheWrite5m=t.cache_creation.ephemeral_5m_input_tokens),t.cache_creation.ephemeral_1h_input_tokens&&(e.input.cacheWrite1h=t.cache_creation.ephemeral_1h_input_tokens)):t?.cache_creation_input_tokens&&(e.input.cacheWrite5m=t.cache_creation_input_tokens),t?.server_tool_use?.web_search_requests&&(e.auxiliary={webSearchRequests:t.server_tool_use.web_search_requests}),e}function Ip(t,e){let n=[],r=[];for(let o of t.content)if(o.type==="text"&&typeof o.text=="string")n.push(o.text);else if(o.type==="tool_use"){let s=o;r.push({id:s.id,name:s.name,arguments:s.input??{}})}return{content:n.join(""),toolCalls:r.length>0?r:void 0,usage:sd(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function gh(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",o=t.fetchImpl??fetch,s=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(i,a){let d=Us(i,a,t.model,!1),u=V(),c=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(d),signal:a?.signal});if(!c.ok)throw await wt(c,"Anthropic");let l=await c.json(),p=Math.max(0,(V()-u)/1e6);return Ip(l,p)},async*stream(i,a){let d=Us(i,a,t.model,!0),u=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(d),signal:a?.signal});if(!u.ok)throw await wt(u,"Anthropic");if(!u.body)throw new Error("anthropicAdapter: streaming response has no body");let c,l,p=new Map;for await(let f of $t(u.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{c=Js(c,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(p.set(g.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let g=h,y=g.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let b=p.get(g.index);b&&(b.argBuf+=y.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:y.partial_json}}}else y.type==="thinking_delta"&&typeof y.thinking=="string"&&(yield{type:"thinking",delta:y.thinking});break}case"message_delta":{let g=h;g.delta.stop_reason&&(l=g.delta.stop_reason),g.delta.usage&&(c=Js(c,g.delta.usage));break}case"message_stop":break}}c&&(yield{type:"usage",usage:sd(c)}),yield{type:"finish",reason:l??"stop"}}}}function hh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:t.model,async invoke(n,r){let o=Us(n,r,t.model,!1),s=V(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(V()-s)/1e6);return Ip(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=Us(n,r,t.model,!0),s,i;for await(let a of e.messages.stream(o,{signal:r?.signal}))switch(a.type){case"message_start":s=Js(s,a.message.usage);break;case"content_block_delta":{let d=a.delta;d?.type==="text_delta"&&typeof d.text=="string"?yield{type:"token",delta:d.text}:d?.type==="input_json_delta"&&typeof d.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:d.partial_json}}:d?.type==="thinking_delta"&&typeof d.thinking=="string"&&(yield{type:"thinking",delta:d.thinking});break}case"message_delta":{let d=a;d.delta.stop_reason&&(i=d.delta.stop_reason),d.delta.usage&&(s=Js(s,d.delta.usage));break}}s&&(yield{type:"usage",usage:sd(s)}),yield{type:"finish",reason:i??"stop"}}}}Rt();function Ys(){let t=new Error("aborted");return t.name="AbortError",t}function Pp(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ys()):new Promise((n,r)=>{let o=new Ie,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Ys())},e.addEventListener("abort",s,{once:!0}))})}function kn(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(a=>{let d=[...a].reverse().find(u=>u.role==="user");return d?`echo: ${d.content}`:"dry-run: no user message"}),i=t.usage??((a,d)=>{let u=a.reduce((c,l)=>c+l.content.length,0);return{input:{regular:Math.ceil(u/4)},output:{regular:Math.ceil(d.length/4)}}});return{provider:e,model:n,async invoke(a,d){if(await Pp(r,d?.signal),d?.signal?.aborted)throw Ys();let u=s(a,d),c=i(a,u);return{content:u,usage:c,finishReason:"stop",model:d?.model??n,provider:e,tier:d?.tier,metadata:{dryRun:!0}}},async*stream(a,d){let u=s(a,d),c=i(a,u),l=Math.ceil(u.length/o)||1,p=r>0?r/l:0;for(let f=0;f<u.length;f+=o){if(d?.signal?.aborted)throw Ys();await Pp(p,d?.signal),yield{type:"token",delta:u.slice(f,f+o)}}yield{type:"usage",usage:c},yield{type:"finish",reason:"stop"}}}}Re();Re();ve();Rt();function Dp(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=Vs({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:d,opts:u})=>{let{signal:c,keyContext:l,...p}=u??{};return{messages:d,opts:p}}});async function a(d,u){if(r){if(r.length<=1){let l={messages:d,opts:u,context:u?.keyContext},p=await r(l);return`${o}:${p}`}let c=await r(d,u);return`${o}:${c}`}return i.keyFor({messages:d,opts:u})}return{keyFor:a,async lookup(d,u){if(n!=="write"){if(r){let c=await a(d,u),l=await e.load(c);return l===void 0?void 0:l}return i.lookup({messages:d,opts:u})}},async store(d,u,c){if(n!=="read"){if(r){let l=await a(d,u);await e.save(l,c);return}await i.store({messages:d,opts:u},c)}},async forget(d,u){if(!(n==="read"||n==="write")&&e.delete){if(r){let c=await a(d,u);await e.delete(c);return}await i.forget({messages:d,opts:u})}}}}Re();ae();ne();ve();function ot(t,e,n){return{provider:n?.provider??t.provider,model:n?.model??t.model,capabilities:n?.capabilities??t.capabilities?.bind(t),invoke:e.invoke,stream:e.stream}}function Qs(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let u=t;return r?u.then(n).catch(c=>{throw r(c),c}):u.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=Y(t);if(r){let u=!1;s.subscribe(c=>{for(let l of c){if(u)return;l[0]===I&&(u=!0,r(l[1]))}})}let i,a=!1,d=no(s,u=>{i=n(u),a=!0});return C([d],([u])=>u==null?null:a?i:n(u),{name:o??"adapt/invokeTap"})}function xn(t){let e=t.endNs??V();return{timestamp:e,wallClock:t.startWallClockNs??se(),provider:t.provider,model:t.model,tier:t.tier,usage:t.usage,latencyMs:Math.max(0,(e-t.startNs)/1e6),method:t.method,...t.error?{error:t.error}:{}}}function _t(){return{input:{regular:0},output:{regular:0}}}var Gp=Symbol.for("graphrefly.adapter.middlewareLayers");function Je(t,e,n){let o=[...n?yh(n):[],e];return Object.defineProperty(t,Gp,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function yh(t){let e=t[Gp];return Array.isArray(e)?e:[]}var Rn=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function bo(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=n==="read"||n==="read-strict",d=Dp({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),u=p=>p<=0?Promise.resolve():new Promise(f=>{new Ie().start(p,()=>f())}),c=qs(async({messages:p,invokeOpts:f})=>await et(Y(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=ot(t,{async invoke(p,f){let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h?.response){let y=h.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new Rn(m,"invoke");let g=await c({messages:p,invokeOpts:f,_precomputedKey:m});return a||await d.store(p,f,{response:g,storedAtNs:se()}),g},async*stream(p,f){if(!r){for await(let x of t.stream(p,f))yield x;return}let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h){let x=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let k=0;k<h.streamChunks.length;k++){let S=h.streamCadenceMs[k]??0,R=s>0?S/s:0;R>0&&await u(R),yield{type:"token",delta:h.streamChunks[k]?.delta??""}}else x.content&&(yield{type:"token",delta:x.content});x.usage&&(yield{type:"usage",usage:x.usage}),yield{type:"finish",reason:x.finishReason??"stop"};return}if(n==="read-strict")throw new Rn(m,"stream");let g="",y,b,v=[],T=[],w;for await(let x of t.stream(p,f)){if(x.type==="token"&&(g+=x.delta,o)){let k=V(),S=w===void 0?0:(k-w)/1e6;T.push(S),w=k,v.push({delta:x.delta})}x.type==="usage"&&(y=x.usage),x.type==="finish"&&(b=x.reason),yield x}if((g||y)&&!a){let k={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:se(),...o?{streamChunks:v,streamCadenceMs:T}:{}};await d.store(p,f,k)}}});return Je(l,"withReplayCache",t),l}var id=uo;var bh=Rn;function Fp(t,e){return{content:"[fallback: no cached response available for this request]",usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:e,provider:t,metadata:{degraded:!0,reason:"no-fixture"}}}function $p(t,e,n){return typeof t=="string"?{content:t,usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:n,provider:e,metadata:{degraded:!0,reason:"respond"}}:t}async function vh(t,e){if("key"in t)return t.key;let n=id({messages:t.messages,opts:t.invokeOpts??{}}),r=await Bs(n);return`${e}:${r}`}function Th(t){let e={response:t.response,storedAtNs:se()};if("key"in t&&t.stream){let n=t.stream.chunks.filter(r=>r.type==="token");return{...e,streamChunks:n.map(r=>({delta:r.delta})),streamCadenceMs:t.stream.delaysMs??n.map(()=>0)}}return e}function wh(t,e){let n=[];if(t.fixtures!=null&&n.push("fixtures"),t.fixturesStorage!=null&&n.push("fixturesStorage"),n.length>1)throw new TypeError(`fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${n.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`);if(t.fixtures){let r=go(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await vh(i,e);await r.save(a,Th(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function ad(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",o=t.keyPrefix??"fallback",s=t.record?t.record.adapter:r==="throw"?kn({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(c,l){let p=t.respond?t.respond(c,l):Fp(e,n);return $p(p,e,n)},async*stream(c,l){let p=t.respond?t.respond(c,l):Fp(e,n),f=$p(p,e,n);yield{type:"token",delta:f.content},f.usage&&(yield{type:"usage",usage:f.usage}),yield{type:"finish",reason:f.finishReason??"stop"}}},i,a=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");i=t.record.storage}else{let c=wh(t,o);i=c.tier??go(),a=c.seedReady}let d=t.record?"read-write":r==="throw"?"read-strict":"read",u=bo(s,{storage:i,mode:d,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:u.capabilities?.bind(u),async invoke(c,l){return await a,u.invoke(c,l)},async*stream(c,l){await a;for await(let p of u.stream(c,l))yield p}}}Re();function dd(t={}){return t.sdk?Sh(t):Rh(t)}function Xs(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let d of i.toolCalls)a.push({functionCall:{name:d.name,args:d.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
|
|
34
|
+
`):void 0,chat:r}}function Ih(t){if(t.role==="tool")return{role:"user",content:[{type:"tool_result",tool_use_id:t.toolCallId,content:t.content}]};if(t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0){let e=[];t.content&&e.push({type:"text",text:t.content});for(let n of t.toolCalls)e.push({type:"tool_use",id:n.id,name:n.name,input:n.arguments});return{role:"assistant",content:e}}return{role:t.role,content:t.content}}function Dh(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function ii(t,e){if(!t)return{...e};let n={...t};return e.input_tokens!=null&&(n.input_tokens=e.input_tokens),e.output_tokens!=null&&(n.output_tokens=e.output_tokens),e.cache_read_input_tokens!=null&&(n.cache_read_input_tokens=e.cache_read_input_tokens),e.cache_creation_input_tokens!=null&&(n.cache_creation_input_tokens=e.cache_creation_input_tokens),e.cache_creation&&(n.cache_creation={...t.cache_creation??{},...e.cache_creation}),e.server_tool_use&&(n.server_tool_use={...t.server_tool_use??{},...e.server_tool_use}),n}function Rd(t){let e={input:{regular:t?.input_tokens??0},output:{regular:t?.output_tokens??0},raw:t};return t?.cache_read_input_tokens&&(e.input.cacheRead=t.cache_read_input_tokens),t?.cache_creation?(t.cache_creation.ephemeral_5m_input_tokens&&(e.input.cacheWrite5m=t.cache_creation.ephemeral_5m_input_tokens),t.cache_creation.ephemeral_1h_input_tokens&&(e.input.cacheWrite1h=t.cache_creation.ephemeral_1h_input_tokens)):t?.cache_creation_input_tokens&&(e.input.cacheWrite5m=t.cache_creation_input_tokens),t?.server_tool_use?.web_search_requests&&(e.auxiliary={webSearchRequests:t.server_tool_use.web_search_requests}),e}function of(t,e){let n=[],r=[];for(let o of t.content)if(o.type==="text"&&typeof o.text=="string")n.push(o.text);else if(o.type==="tool_use"){let s=o;r.push({id:s.id,name:s.name,arguments:s.input??{}})}return{content:n.join(""),toolCalls:r.length>0?r:void 0,usage:Rd(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function Ph(t){let e=t.apiKey??globalThis.process?.env?.ANTHROPIC_API_KEY,n=t.baseURL??"https://api.anthropic.com",r=t.anthropicVersion??"2023-06-01",o=t.fetchImpl??fetch,s=()=>{if(!e)throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");return{"x-api-key":e,"anthropic-version":r,"content-type":"application/json",...t.headers??{}}};return{provider:"anthropic",model:t.model,async invoke(i,a){let d=si(i,a,t.model,!1),u=H(),c=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(d),signal:a?.signal});if(!c.ok)throw await xt(c,"Anthropic");let l=await c.json(),p=Math.max(0,(H()-u)/1e6);return of(l,p)},async*stream(i,a){let d=si(i,a,t.model,!0),u=await o(`${n}/v1/messages`,{method:"POST",headers:{...s(),accept:"text/event-stream"},body:JSON.stringify(d),signal:a?.signal});if(!u.ok)throw await xt(u,"Anthropic");if(!u.body)throw new Error("anthropicAdapter: streaming response has no body");let c,l,p=new Map;for await(let f of Bt(u.body,{signal:a?.signal})){let m=f.data;if(!m)continue;let h;try{h=JSON.parse(m)}catch{continue}switch(h.type){case"message_start":{c=ii(c,h.message.usage);break}case"content_block_start":{let g=h,y=g.content_block;y.type==="tool_use"&&(p.set(g.index,{id:String(y.id??""),name:String(y.name??""),argBuf:""}),yield{type:"tool-call-delta",delta:{id:String(y.id??""),name:String(y.name??"")}});break}case"content_block_delta":{let g=h,y=g.delta;if(y.type==="text_delta"&&typeof y.text=="string")yield{type:"token",delta:y.text};else if(y.type==="input_json_delta"&&typeof y.partial_json=="string"){let b=p.get(g.index);b&&(b.argBuf+=y.partial_json),yield{type:"tool-call-delta",delta:{argumentsDelta:y.partial_json}}}else y.type==="thinking_delta"&&typeof y.thinking=="string"&&(yield{type:"thinking",delta:y.thinking});break}case"message_delta":{let g=h;g.delta.stop_reason&&(l=g.delta.stop_reason),g.delta.usage&&(c=ii(c,g.delta.usage));break}case"message_stop":break}}c&&(yield{type:"usage",usage:Rd(c)}),yield{type:"finish",reason:l??"stop"}}}}function Gh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedAnthropic: sdk instance required");return{provider:"anthropic",model:t.model,async invoke(n,r){let o=si(n,r,t.model,!1),s=H(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(H()-s)/1e6);return of(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=si(n,r,t.model,!0),s,i;for await(let a of e.messages.stream(o,{signal:r?.signal}))switch(a.type){case"message_start":s=ii(s,a.message.usage);break;case"content_block_delta":{let d=a.delta;d?.type==="text_delta"&&typeof d.text=="string"?yield{type:"token",delta:d.text}:d?.type==="input_json_delta"&&typeof d.partial_json=="string"?yield{type:"tool-call-delta",delta:{argumentsDelta:d.partial_json}}:d?.type==="thinking_delta"&&typeof d.thinking=="string"&&(yield{type:"thinking",delta:d.thinking});break}case"message_delta":{let d=a;d.delta.stop_reason&&(i=d.delta.stop_reason),d.delta.usage&&(s=ii(s,d.delta.usage));break}}s&&(yield{type:"usage",usage:Rd(s)}),yield{type:"finish",reason:i??"stop"}}}}Et();function ai(){let t=new Error("aborted");return t.name="AbortError",t}function sf(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(ai()):new Promise((n,r)=>{let o=new De,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(ai())},e.addEventListener("abort",s,{once:!0}))})}function Gn(t={}){let e=t.provider??"dry-run",n=t.model??"dry-run-v1",r=t.latencyMs??0,o=Math.max(1,t.streamChunkSize??16),s=t.respond??(a=>{let d=[...a].reverse().find(u=>u.role==="user");return d?`echo: ${d.content}`:"dry-run: no user message"}),i=t.usage??((a,d)=>{let u=a.reduce((c,l)=>c+l.content.length,0);return{input:{regular:Math.ceil(u/4)},output:{regular:Math.ceil(d.length/4)}}});return{provider:e,model:n,async invoke(a,d){if(await sf(r,d?.signal),d?.signal?.aborted)throw ai();let u=s(a,d),c=i(a,u);return{content:u,usage:c,finishReason:"stop",model:d?.model??n,provider:e,tier:d?.tier,metadata:{dryRun:!0}}},async*stream(a,d){let u=s(a,d),c=i(a,u),l=Math.ceil(u.length/o)||1,p=r>0?r/l:0;for(let f=0;f<u.length;f+=o){if(d?.signal?.aborted)throw ai();await sf(p,d?.signal),yield{type:"token",delta:u.slice(f,f+o)}}yield{type:"usage",usage:c},yield{type:"finish",reason:"stop"}}}}Se();Se();ue();Et();function af(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=Xs({storage:e,keyPrefix:o,mode:n==="read-strict"?"read":n,keyContext:({messages:d,opts:u})=>{let{signal:c,keyContext:l,...p}=u??{};return{messages:d,opts:p}}});async function a(d,u){if(r){if(r.length<=1){let l={messages:d,opts:u,context:u?.keyContext},p=await r(l);return`${o}:${p}`}let c=await r(d,u);return`${o}:${c}`}return i.keyFor({messages:d,opts:u})}return{keyFor:a,async lookup(d,u){if(n!=="write"){if(r){let c=await a(d,u),l=await e.load(c);return l===void 0?void 0:l}return i.lookup({messages:d,opts:u})}},async store(d,u,c){if(n!=="read"){if(r){let l=await a(d,u);await e.save(l,c);return}await i.store({messages:d,opts:u},c)}},async forget(d,u){if(!(n==="read"||n==="write")&&e.delete){if(r){let c=await a(d,u);await e.delete(c);return}await i.forget({messages:d,opts:u})}}}}Se();ae();ne();ue();function it(t,e,n){return{provider:n?.provider??t.provider,model:n?.model??t.model,capabilities:n?.capabilities??t.capabilities?.bind(t),invoke:e.invoke,stream:e.stream}}function di(t,e){let{onResp:n,onError:r,name:o}=e;if(t!=null&&typeof t.then=="function"){let u=t;return r?u.then(n).catch(c=>{throw r(c),c}):u.then(n)}if(t!=null&&typeof t=="object"&&"content"in t)return n(t);let s=Y(t);if(r){let u=!1;s.subscribe(c=>{for(let l of c){if(u)return;l[0]===L&&(u=!0,r(l[1]))}})}let i,a=!1,d=ao(s,u=>{i=n(u),a=!0});return A([d],([u])=>u==null?null:a?i:n(u),{name:o??"adapt/invokeTap"})}function Fn(t){let e=t.endNs??H();return{timestamp:e,wallClock:t.startWallClockNs??oe(),provider:t.provider,model:t.model,tier:t.tier,usage:t.usage,latencyMs:Math.max(0,(e-t.startNs)/1e6),method:t.method,...t.error?{error:t.error}:{}}}function At(){return{input:{regular:0},output:{regular:0}}}var df=Symbol.for("graphrefly.adapter.middlewareLayers");function Qe(t,e,n){let o=[...n?Fh(n):[],e];return Object.defineProperty(t,df,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function Fh(t){let e=t[df];return Array.isArray(e)?e:[]}var $n=class extends Error{constructor(n,r){super(`withReplayCache: no cached response for ${r} (key=${n}, mode=read-strict)`);this.key=n;this.method=r}name="ReplayCacheMissError"};function xo(t,e){let n=e.mode??"read-write",r=e.cacheStreaming??!1,o=e.captureStreamCadence??!1,s=e.replaySpeed??1,i=e.keyPrefix??"llm-replay",a=n==="read"||n==="read-strict",d=af({storage:e.storage,mode:n==="write-only"?"write":n,keyFn:e.keyFn,keyPrefix:i}),u=p=>p<=0?Promise.resolve():new Promise(f=>{new De().start(p,()=>f())}),c=ei(async({messages:p,invokeOpts:f})=>await nt(Y(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=it(t,{async invoke(p,f){let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h?.response){let y=h.response;return{...y,metadata:{...y.metadata??{},replayCache:"hit"}}}if(n==="read-strict")throw new $n(m,"invoke");let g=await c({messages:p,invokeOpts:f,_precomputedKey:m});return a||await d.store(p,f,{response:g,storedAtNs:oe()}),g},async*stream(p,f){if(!r){for await(let k of t.stream(p,f))yield k;return}let m=await d.keyFor(p,f),h=await d.lookup(p,f);if(h){let k=h.response;if(h.streamChunks&&h.streamCadenceMs)for(let R=0;R<h.streamChunks.length;R++){let S=h.streamCadenceMs[R]??0,x=s>0?S/s:0;x>0&&await u(x),yield{type:"token",delta:h.streamChunks[R]?.delta??""}}else k.content&&(yield{type:"token",delta:k.content});k.usage&&(yield{type:"usage",usage:k.usage}),yield{type:"finish",reason:k.finishReason??"stop"};return}if(n==="read-strict")throw new $n(m,"stream");let g="",y,b,v=[],T=[],w;for await(let k of t.stream(p,f)){if(k.type==="token"&&(g+=k.delta,o)){let R=H(),S=w===void 0?0:(R-w)/1e6;T.push(S),w=R,v.push({delta:k.delta})}k.type==="usage"&&(y=k.usage),k.type==="finish"&&(b=k.reason),yield k}if((g||y)&&!a){let R={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:oe(),...o?{streamChunks:v,streamCadenceMs:T}:{}};await d.store(p,f,R)}}});return Qe(l,"withReplayCache",t),l}var Sd=mo;var $h=$n;function uf(t,e){return{content:"[fallback: no cached response available for this request]",usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:e,provider:t,metadata:{degraded:!0,reason:"no-fixture"}}}function cf(t,e,n){return typeof t=="string"?{content:t,usage:{input:{regular:0},output:{regular:0}},finishReason:"stop",model:n,provider:e,metadata:{degraded:!0,reason:"respond"}}:t}async function jh(t,e){if("key"in t)return t.key;let n=Sd({messages:t.messages,opts:t.invokeOpts??{}}),r=await Qs(n);return`${e}:${r}`}function Bh(t){let e={response:t.response,storedAtNs:oe()};if("key"in t&&t.stream){let n=t.stream.chunks.filter(r=>r.type==="token");return{...e,streamChunks:n.map(r=>({delta:r.delta})),streamCadenceMs:t.stream.delaysMs??n.map(()=>0)}}return e}function Vh(t,e){let n=[];if(t.fixtures!=null&&n.push("fixtures"),t.fixturesStorage!=null&&n.push("fixturesStorage"),n.length>1)throw new TypeError(`fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${n.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`);if(t.fixtures){let r=To(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await jh(i,e);await r.save(a,Bh(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Nd(t={}){let e=t.provider??"fallback",n=t.model??"fallback",r=t.onMiss??"respond",o=t.keyPrefix??"fallback",s=t.record?t.record.adapter:r==="throw"?Gn({provider:e,model:n,respond:()=>"[unreachable: read-strict mode throws on miss]"}):{provider:e,model:n,async invoke(c,l){let p=t.respond?t.respond(c,l):uf(e,n);return cf(p,e,n)},async*stream(c,l){let p=t.respond?t.respond(c,l):uf(e,n),f=cf(p,e,n);yield{type:"token",delta:f.content},f.usage&&(yield{type:"usage",usage:f.usage}),yield{type:"finish",reason:f.finishReason??"stop"}}},i,a=Promise.resolve();if(t.record){if(!t.record.storage)throw new TypeError("fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`.");i=t.record.storage}else{let c=Vh(t,o);i=c.tier??To(),a=c.seedReady}let d=t.record?"read-write":r==="throw"?"read-strict":"read",u=xo(s,{storage:i,mode:d,keyPrefix:o,cacheStreaming:!0,captureStreamCadence:!0,replaySpeed:t.replaySpeed,...t.keyFn?{keyFn:t.keyFn}:{}});return{provider:e,model:n,capabilities:u.capabilities?.bind(u),async invoke(c,l){return await a,u.invoke(c,l)},async*stream(c,l){await a;for await(let p of u.stream(c,l))yield p}}}Se();function Ed(t={}){return t.sdk?Hh(t):zh(t)}function ui(t,e){let n=[],r=[];e?.systemPrompt&&n.push(e.systemPrompt);for(let i of t){if(i.role==="system"){n.push(i.content);continue}if(i.role==="tool"){r.push({role:"user",parts:[{functionResponse:{name:i.name??i.toolCallId??"tool",response:{result:i.content}}}]});continue}if(i.role==="assistant"&&i.toolCalls&&i.toolCalls.length>0){let a=[];i.content&&a.push({text:i.content});for(let d of i.toolCalls)a.push({functionCall:{name:d.name,args:d.arguments}});r.push({role:"model",parts:a});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o={contents:r};n.length>0&&(o.systemInstruction={role:"system",parts:[{text:n.join(`
|
|
35
35
|
|
|
36
|
-
`)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(kh)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function kh(t){return{name:t.name,description:t.description,parameters:t.parameters}}function jp(t,e,n){let r={},o=t.generationConfig;o&&(typeof o.maxOutputTokens=="number"&&(r.maxOutputTokens=o.maxOutputTokens),typeof o.temperature=="number"&&(r.temperature=o.temperature),o.thinkingConfig&&(r.thinkingConfig=o.thinkingConfig)),t.systemInstruction&&(r.systemInstruction=t.systemInstruction),t.tools&&(r.tools=t.tools);for(let[s,i]of Object.entries(t))s==="contents"||s==="generationConfig"||s==="systemInstruction"||s==="tools"||s==="abortSignal"||s==="model"||(r[s]=i);return n&&(r.abortSignal=n),{model:e,contents:t.contents,config:Object.keys(r).length>0?r:void 0}}function ud(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.promptTokenCount??0,r=t.cachedContentTokenCount??0;if(e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.toolUsePromptTokenCount&&(e.input.toolUse=t.toolUsePromptTokenCount),t.promptTokensDetails)for(let o of t.promptTokensDetails){let s=o.modality?.toLowerCase();s==="image"?e.input.image=(e.input.image??0)+o.tokenCount:s==="audio"?e.input.audio=(e.input.audio??0)+o.tokenCount:s==="video"&&(e.input.video=(e.input.video??0)+o.tokenCount)}return e.output.regular=t.candidatesTokenCount??0,t.thoughtsTokenCount&&(e.output.reasoning=t.thoughtsTokenCount),e}function Bp(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],i=0;for(let a of r)typeof a.text=="string"&&o.push(a.text),a.functionCall&&s.push({id:`${a.functionCall.name}-${i++}`,name:a.functionCall.name,arguments:a.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:ud(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function xh(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function Rh(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let i=s?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},o=()=>{let s=xh(t);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:t.model,async invoke(s,i){let a=r(i),d=Xs(s,i),u=V(),c=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(c,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(d),signal:i?.signal});if(!l.ok)throw await wt(l,"Google");let p=await l.json(),f=Math.max(0,(V()-u)/1e6);return Bp(p,f)},async*stream(s,i){let a=r(i),d=Xs(s,i),u=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,c=await n(u,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(d),signal:i?.signal});if(!c.ok)throw await wt(c,"Google");if(!c.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of $t(c.body,{signal:i?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(p=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:ud(l)}),yield{type:"finish",reason:p??"stop"}}}}function Sh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let o=Xs(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=jp(o,s,r?.signal),a=V(),d=await e.models.generateContent(i),u=Math.max(0,(V()-a)/1e6);return Bp(d,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=Xs(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=jp(o,s,r?.signal),a,d,u=await e.models.generateContentStream(i);for await(let c of u){let l=c.candidates?.[0];for(let p of l?.content?.parts??[])typeof p.text=="string"&&(p.thought?yield{type:"thinking",delta:p.text}:yield{type:"token",delta:p.text}),p.functionCall&&(yield{type:"tool-call-delta",delta:{name:p.functionCall.name,argumentsDelta:JSON.stringify(p.functionCall.args??{})}});l?.finishReason&&(d=l.finishReason),c.usageMetadata&&(a=c.usageMetadata)}a&&(yield{type:"usage",usage:ud(a)}),yield{type:"finish",reason:d??"stop"}}}}Re();var Nh={openai:{baseURL:"https://api.openai.com/v1",apiKeyEnv:"OPENAI_API_KEY",provider:"openai"},openrouter:{baseURL:"https://openrouter.ai/api/v1",apiKeyEnv:"OPENROUTER_API_KEY",provider:"openrouter"},groq:{baseURL:"https://api.groq.com/openai/v1",apiKeyEnv:"GROQ_API_KEY",provider:"groq"},ollama:{baseURL:"http://localhost:11434/v1",provider:"ollama"},deepseek:{baseURL:"https://api.deepseek.com/v1",apiKeyEnv:"DEEPSEEK_API_KEY",provider:"deepseek"},xai:{baseURL:"https://api.x.ai/v1",apiKeyEnv:"XAI_API_KEY",provider:"xai"}};function cd(t={}){return t.sdk?Ah(t):Oh(t)}function Zs(t,e,n,r,o){let s=e?.model??n;if(!s)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let i=t.map(Eh);e?.systemPrompt&&!t.some(d=>d.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:s,messages:i};return e?.maxTokens!=null&&(a.max_tokens=e.maxTokens),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(_h)),e?.maxReasoningTokens!=null&&(a.reasoning={max_tokens:e.maxReasoningTokens}),r&&(a.stream=!0,a.stream_options={include_usage:!0}),o&&Object.assign(a,o),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function Eh(t){return t.role==="tool"?{role:"tool",tool_call_id:t.toolCallId,content:t.content}:t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0?{role:"assistant",content:t.content||null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))}:{role:t.role,content:t.content}}function _h(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function ld(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.prompt_tokens??0,r=t.prompt_tokens_details?.cached_tokens??0;t.prompt_cache_hit_tokens!=null?(r=t.prompt_cache_hit_tokens,e.input.regular=t.prompt_cache_miss_tokens??Math.max(0,n-r)):e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.prompt_tokens_details?.audio_tokens&&(e.input.audio=t.prompt_tokens_details.audio_tokens);let o=t.completion_tokens??0,s=t.completion_tokens_details?.reasoning_tokens??0;return e.output.regular=Math.max(0,o-s),s>0&&(e.output.reasoning=s),t.completion_tokens_details?.audio_tokens&&(e.output.audio=t.completion_tokens_details.audio_tokens),t.completion_tokens_details?.accepted_prediction_tokens&&(e.output.predictionAccepted=t.completion_tokens_details.accepted_prediction_tokens),t.completion_tokens_details?.rejected_prediction_tokens&&(e.output.predictionRejected=t.completion_tokens_details.rejected_prediction_tokens),e}function Vp(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",i=(o?.tool_calls??[]).map(a=>({id:a.id,name:a.function.name,arguments:Mh(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:ld(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Mh(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function Kp(t){let e=t.preset??"openai",n=Nh[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,i=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:i}}function Oh(t){let{provider:e,baseURL:n,apiKey:r}=Kp(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,d){let u=Zs(a,d,t.model,!1,t.bodyExtras),c=V(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(u),signal:d?.signal});if(!l.ok)throw await wt(l,e);let p=await l.json(),f=Math.max(0,(V()-c)/1e6);return Vp(p,f,e)},async*stream(a,d){let u=Zs(a,d,t.model,!0,t.bodyExtras),c=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(u),signal:d?.signal});if(!c.ok)throw await wt(c,e);if(!c.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of $t(c.body,{signal:d?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let y of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:ld(l)})}yield{type:"finish",reason:p??"stop"}}}}function Ah(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=Kp(t);return{provider:n,model:t.model,async invoke(r,o){let s=Zs(r,o,t.model,!1,t.bodyExtras),i=V(),a=await e.chat.completions.create(s,{signal:o?.signal}),d=Math.max(0,(V()-i)/1e6);return Vp(a,d,n)},async*stream(r,o){let s=Zs(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,d;for await(let u of i){let c=u.choices;if(c){let p=c[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(d=p.finish_reason)}let l=u.usage;l&&(a=l,yield{type:"usage",usage:ld(l)})}yield{type:"finish",reason:d??"stop"}}}}function Ch(t){switch(t.provider){case"anthropic":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return od(e)}case"google":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return dd(e)}case"dry-run":{let e={model:t.model,...t.extras};return kn(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return ad(e)}case"openai":case"openrouter":case"groq":case"ollama":case"deepseek":case"xai":{let e={preset:t.provider,apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,bodyExtras:t.bodyExtras,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return cd(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}Re();ne();ve();function kt(t){let e=t.input,n=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function jt(t){let e=t.output,n=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function qp(){return{input:{regular:0},output:{regular:0}}}function Lh(t,e){let n=e?.logMax??1e3,r=Ke(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=A(null,{name:"adapterStats/lastCall"}),s=C([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),i=C([r.entries],([h])=>h.reduce((g,y)=>g+kt(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=C([r.entries],([h])=>h.reduce((g,y)=>g+jt(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),d=[te(s),te(i),te(a)],u=h=>{r.append(h),o.emit(h)},c=()=>{r.clear(),o.emit(null)},l=ot(t,{invoke(h,g){let y=V(),b=se(),v=t.model??g?.model??"",T=x=>(u(xn({provider:t.provider,model:t.model??g?.model??x.model??"",tier:g?.tier??x.tier,usage:x.usage??_t(),startNs:y,startWallClockNs:b,method:"invoke"})),x),w=x=>{let k=x;u(xn({provider:t.provider,model:v,tier:g?.tier,usage:_t(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:k?.name??"Error",message:k?.message??String(x)}}))};return Qs(t.invoke(h,g),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=V(),b=se(),v=t.model??g?.model??"",T;try{for await(let w of t.stream(h,g))w.type==="usage"&&(T=w.usage),yield w;u(xn({provider:t.provider,model:v,tier:g?.tier,usage:T??_t(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let x=w;throw u(xn({provider:t.provider,model:v,tier:g?.tier,usage:T??_t(),startNs:y,startWallClockNs:b,method:"stream",error:{type:x?.name??"Error",message:x?.message??String(w)}})),w}}});Je(l,"observableAdapter",t);let p=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:c,dispose:()=>{if(!p){p=!0;for(let h of d)h();d.length=0}}}}}function Ih(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function ti(t="USD"){return{total:0,currency:t}}function pd(t,e,n){let r=kt(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,d=(g,y,b)=>{if(!y||b==null)return;let v=Ih(b,r),T=y*v/1e6;a+=T,s&&(i[g]=(i[g]??0)+T)},u=t.input,c=e.input;if(c&&(d("input.regular",u.regular,c.regular),d("input.cacheRead",u.cacheRead??0,c.cacheRead),d("input.cacheWrite5m",u.cacheWrite5m??0,c.cacheWrite5m),d("input.cacheWrite1h",u.cacheWrite1h??0,c.cacheWrite1h),d("input.cacheWriteOther",u.cacheWriteOther??0,c.cacheWriteOther),d("input.audio",u.audio??0,c.audio),d("input.image",u.image??0,c.image),d("input.video",u.video??0,c.video),d("input.toolUse",u.toolUse??0,c.toolUse),u.extensions&&c.extensions))for(let[g,y]of Object.entries(u.extensions))d(`input.ext.${g}`,y,c.extensions[g]);let l=t.output,p=e.output;if(p&&(d("output.regular",l.regular,p.regular),d("output.reasoning",l.reasoning??0,p.reasoning),d("output.audio",l.audio??0,p.audio),d("output.predictionAccepted",l.predictionAccepted??0,p.predictionAccepted),d("output.predictionRejected",l.predictionRejected??0,p.predictionRejected),l.extensions&&p.extensions))for(let[g,y]of Object.entries(l.extensions))d(`output.ext.${g}`,y,p.extensions[g]);let f=n?.tier;if(f&&e.tierMultipliers){let g=e.tierMultipliers[f];if(g!=null&&(a*=g,s))for(let y of Object.keys(i))i[y]*=g}let m=t.auxiliary,h=e.auxiliary;if(m&&h)for(let[g,y]of Object.entries(m)){let b=h[g];if(b==null||!y)continue;let v=y*b;a+=v,s&&(i[`auxiliary.${g}`]=v)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function ei(t,e){return`${t}::${e}`}function Ph(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(ei(o,s),{provider:o,model:s,pricing:i});let a=n.get(o);a||(a=new Set,n.set(o,a)),a.add(s)};if(t)for(let[o,s,i]of t)r(o,s,i);return{register:r,lookup(o,s){let i=e.get(ei(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let d;for(let u of a)if(s.startsWith(u)&&(!d||u.length>d.key.length)){let c=e.get(ei(o,u));c&&(d={key:u,pricing:c.pricing})}return d?.pricing},remove(o,s){let i=e.delete(ei(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){let o=e.values();return(function*(){for(let{provider:s,model:i,pricing:a}of o)yield[s,i,a]})()}}}function Dh(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?pd(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):ti(e)}}function Gh(...t){return(e,n)=>{for(let r of t){let o=r(e,n);if(o.total!==0)return o}return t.length>0?t[0](e,n):ti()}}function Fh(t,e,n){return t?.pricing?pd(e,t.pricing,n):ti()}It();ve();function fd(t,e={}){let n=e.breaker??Nt(e),r=ot(t,{async invoke(o,s){if(!n.canExecute())throw new yt;try{let i=await et(Y(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new yt;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return Je(r,"withBreaker",t),{adapter:r,breaker:n}}Re();ae();ne();ve();var ni=class extends Error{constructor(n,r,o){super(`Budget exhausted: ${n} (limit=${r}, observed=${o})`);this.which=n;this.limit=r;this.observed=o}name="BudgetExhaustedError"},md=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),zp=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function gd(t,e){let n=Ke(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=A(zp(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=C([r],([u])=>{let c=u;return!(e.caps.calls!=null&&c.calls>=e.caps.calls||e.caps.inputTokens!=null&&c.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&c.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&c.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(te(o),e.onExhausted!=null){let u=e.onExhausted,c=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===M){let m=f[1];if(c&&l&&m===!1){let h=Hp(r.cache??md,e.caps);h&&u(h)}l=m,c=!0}})}let s=()=>{if(o.cache===!1){let u=r.cache??md,c=Hp(u,e.caps);return new ni(c??"budget",e.caps[c??"calls"]??0,$h(u,c??"calls"))}},i=(u,c)=>{let l=t.provider,p=xn({provider:l,model:c.model,tier:c.tier,usage:u,startNs:c.startNs,method:c.method,...c.error?{error:c.error}:{}});n.append(p);let f=r.cache??md,m=e.pricingFn?f.usd+e.pricingFn(u,{model:c.model,provider:l,tier:c.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+kt(u),outputTokens:f.outputTokens+jt(u),usd:m})},a=()=>{n.clear(),r.emit(zp())},d=ot(t,{invoke(u,c){let l=s();if(l)return Promise.reject(l);let p=V(),f=t.model??c?.model??"",m=g=>(i(g.usage??_t(),{model:t.model??c?.model??g.model??"",tier:c?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;i(_t(),{model:f,tier:c?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return Qs(t.invoke(u,c),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(u,c){let l=s();if(l)throw l;let p=V(),f;try{for await(let m of t.stream(u,c))m.type==="usage"&&(f=m.usage),yield m;i(f??_t(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw i(f??_t(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return Je(d,"withBudgetGate",t),{adapter:d,budget:{totals:r,isOpen:o,log:n,reset:a}}}function Hp(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 $h(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}ve();function jh(t,e){let n=e.mock??kn({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?Y(e.enabled):void 0,s;o&&(s=te(o));let i=()=>r!==void 0?r:!!o?.cache,a=ot(t,{invoke(u,c){return i()?n.invoke(u,c):t.invoke(u,c)},stream(u,c){return i()?n.stream(u,c):t.stream(u,c)}});return Je(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function hd(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Bh(e.headers);if(n!==429&&n!==503&&!Wh(e.message))return;let o={},s=r("retry-after"),i=Kh(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=Wp(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=r("anthropic-ratelimit-tokens-reset");if(d){let f=Wp(d);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=ri(r,"x-ratelimit-limit-requests");u!=null&&(o.rpmCap=u);let c=ri(r,"x-ratelimit-limit-tokens");c!=null&&(o.tpmCap=c);let l=ri(r,"x-ratelimit-remaining-requests"),p=ri(r,"x-ratelimit-remaining-tokens");if(l!=null&&u!=null&&u>0&&(o.usageHint??={},o.usageHint.rpm=1-l/u),p!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.tpm=1-p/c),o.retryAfterMs==null&&e.message){let f=zh(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:Vh(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function Bh(t){if(!t)return()=>{};if(typeof t.get=="function"){let r=t;return o=>r.get(o)??r.get(o.toLowerCase())??void 0}let e=t,n={};for(let[r,o]of Object.entries(e)){let s=Array.isArray(o)?o.join(", "):o;s!=null&&(n[r.toLowerCase()]=s)}return r=>n[r.toLowerCase()]}function Vh(t){let e={};if(typeof t.forEach=="function")return t.forEach((n,r)=>{e[r]=n}),e;for(let[n,r]of Object.entries(t))r!=null&&(e[n]=Array.isArray(r)?r.join(", "):r);return e}function ri(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Kh(t){if(!t)return;let e=t.trim(),n=Number(e);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);if(Number.isFinite(r)){let o=r-Date.now();if(o>0)return o}}function Wp(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var qh=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function zh(t){let e=qh.exec(t);if(!e)return;let n=Number(e[1]);if(!Number.isFinite(n))return;let r=(e[2]??"s").toLowerCase();if(r==="ms")return n;if(r.startsWith("s"))return n*1e3;if(r.startsWith("m"))return n*6e4}var Hh=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Wh(t){return!!t&&Hh.test(t)}Re();ae();ne();It();ve();Rt();function yd(t){let e=new Error(t);return e.name="AbortError",e}function Jp(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?Y(t.rpm):A(Number.POSITIVE_INFINITY),o=t.tpm!=null?Y(t.tpm):A(Number.POSITIVE_INFINITY),s=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=A({},{name:"adaptiveRateLimiter/lastSignal"}),d=C([r,s],([N,L])=>Math.min(Number(N??1/0),Number(L??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),u=C([o,i],([N,L])=>Math.min(Number(N??1/0),Number(L??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),c=dr(Number(r.cache??Number.POSITIVE_INFINITY),e),l=dr(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=d.subscribe(N=>{for(let L of N)if(L[0]===M){let j=Number(L[1]);Number.isFinite(j)&&j>0?(c=dr(j,e),p=!1):j===1/0?(c=dr(1/0,e),p=!1):j<=0&&(p=!0)}}),h=u.subscribe(N=>{for(let L of N)if(L[0]===M){let j=Number(L[1]);Number.isFinite(j)&&j>0?(l=dr(j,e),f=!1):j===1/0?(l=dr(1/0,e),f=!1):j<=0&&(f=!0)}}),g=0,y=new Ie,b=new Ie,v;t.adaptation!=null&&(v=Y(t.adaptation).subscribe(L=>{for(let j of L)j[0]===M&&T(j[1])}));function T(N){if(a.emit(N),N.rpmCap!=null&&Number.isFinite(N.rpmCap)&&N.rpmCap>=0&&(s.emit(N.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),N.tpmCap!=null&&Number.isFinite(N.tpmCap)&&N.tpmCap>=0&&(i.emit(N.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),N.retryAfterMs!=null&&N.retryAfterMs>0){let L=V()+N.retryAfterMs*1e6;L>g&&(g=L)}}let w=A(0,{name:"adaptiveRateLimiter/pending"}),x=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),k=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),S=N=>{w.emit((w.cache??0)+N)},R=()=>{x.emit(c.available()),k.emit(l.available())};async function E(N={}){let L=N.requestCost??1,j=N.tokenCost??0,$=N.signal;S(1);try{for(;;){if($?.aborted)throw yd("AdaptiveRateLimiter.acquire aborted");let D=V();if(g>D){let B=Math.ceil((g-D)/1e6);await oi(B,$);continue}if(L>0&&p||j>0&&f){await oi(250,$);continue}let K=c,F=l;if(!K.tryConsume(L)){await oi(Up(K,L),$);continue}if(!(j>0?F.tryConsume(j):!0)){K.putBack(L),await oi(Up(F,j),$);continue}R();return}}finally{S(-1)}}function _(N){N>0?l.tryConsume(N):N<0&&l.putBack(-N),R()}function O(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:d,effectiveTpm:u,lastSignal:a,pending:w,rpmAvailable:x,tpmAvailable:k,acquire:E,recordUsage:_,recordSignal:T,dispose:O}}function dr(t,e){if(!Number.isFinite(t)||t===1/0)return zt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return zt(n,r)}function Up(t,e){let n=t.available(),r=Math.max(0,e-n);return r<=0?25:Math.min(5e3,Math.max(50,r*100))}function oi(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(yd("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new Ie,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(yd("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}ve();function bd(t,e={}){let n=e.limiter??Jp({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(i,a)=>e.costFn?e.costFn(i,a):0,o=i=>{let a=hd(i);a&&n.recordSignal(a)},s=ot(t,{async invoke(i,a){let d=r(i,a);await n.acquire({requestCost:1,tokenCost:d,signal:a?.signal});try{let u=await et(Y(t.invoke(i,a))),c=u.usage??qp(),p=kt(c)+jt(c)-d;return p>0&&n.recordUsage(p),u}catch(u){throw o(u),u}},async*stream(i,a){let d=r(i,a);await n.acquire({requestCost:1,tokenCost:d,signal:a?.signal});try{let u=0;for await(let l of t.stream(i,a))l.type==="usage"&&(u=kt(l.usage)+jt(l.usage)),yield l;let c=u-d;c>0&&n.recordUsage(c)}catch(u){throw o(u),u}}});return Je(s,"withRateLimiter",t),{adapter:s,limiter:n}}It();ve();var vo=class extends Error{name="AllTiersExhaustedError";skipped;failed;constructor(e){let n=[];e.failed.size>0&&n.push(`failed=[${[...e.failed.keys()].join(",")}]`),e.skipped.length>0&&n.push(`skipped=[${e.skipped.map(r=>`${r.name}(${r.reason})`).join(",")}]`),super(`All LLM adapter tiers exhausted: ${n.join(" ")}`),this.skipped=e.skipped,this.failed=e.failed}};function vd(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(s=>({name:s.name,adapter:s.adapter,filter:s.filter,breaker:s.breaker?"canExecute"in s.breaker?s.breaker:Nt(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],d=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}try{let p=await et(Y(l.adapter.invoke(s,i)));return l.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:l.name}}}catch(p){d.set(l.name,p),l.breaker?.recordFailure(p);let f=n[c+1];f&&e.onFallback?.(l.name,f.name,p)}}let u={skipped:a,failed:d};throw e.onExhausted?.(u),new vo(u)},async*stream(s,i){let a=[],d=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}let p=!1;try{for await(let f of l.adapter.stream(s,i))p=!0,yield f;l.breaker?.recordSuccess();return}catch(f){if(d.set(l.name,f),l.breaker?.recordFailure(f),p||!r)throw f;let m=n[c+1];m&&e.onFallback?.(l.name,m.name,f)}}let u={skipped:a,failed:d};throw e.onExhausted?.(u),new vo(u)}};return Je(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function Uh(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}ve();Rt();function si(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Yp(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(si()):new Promise((n,r)=>{let o=new Ie,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(si())},e.addEventListener("abort",s,{once:!0}))})}function Td(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",i=e.jitter??!0,a=e.shouldRetry??Jh,d=e.retryStreaming??!0,u=(l,p)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,p*3));return r+Math.random()*(g-r)}let f=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,f);if(!i)return m;let h=m*(.5+Math.random());return Math.min(o,h)},c=ot(t,{async invoke(l,p){if(p?.signal?.aborted)throw si();let f,m=r;for(let h=1;h<=n;h++)try{return await et(Y(t.invoke(l,p)))}catch(g){if(f=g,h>=n||!a(g,h))throw g;let y=u(h,m);m=y,await Yp(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw si();if(!d){for await(let h of t.stream(l,p))yield h;return}let f,m=r;for(let h=1;h<=n;h++){let g=!1;try{for await(let y of t.stream(l,p))g=!0,yield y;return}catch(y){if(f=y,g||h>=n||!a(y,h))throw y;let b=u(h,m);m=b,await Yp(b,p?.signal)}}throw f}});return Je(c,"withRetry",t),c}function Jh(t,e){if(t==null)return!1;let n=t;return n.name==="LLMTimeoutError"?!0:n.name==="AbortError"||n.message==="aborted"||n.name==="DOMException"&&n.code!=null&&Number(n.code)===20||n.name==="BudgetExhaustedError"||n.name==="CircuitOpenError"?!1:n.status!=null?n.status===429||n.status>=500&&n.status<600:n.code&&typeof n.code=="string"&&/^E[A-Z]+$/.test(n.code)?!0:n.message?/network|timeout|socket|fetch|econn|eai_/i.test(n.message):!1}ve();Rt();var ur=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function wd(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,d,u=new Ie;return s&&(s.aborted?i.abort(s.reason):(d=()=>{u.cancel(),i.abort(s.reason)},s.addEventListener("abort",d,{once:!0}))),u.start(e,()=>{a=!0,i.abort(new ur(e))}),{signal:i.signal,cancel:()=>{u.cancel(),s&&d&&s.removeEventListener("abort",d)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof ur)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let u=new ur(e);throw u.cause=s,u}throw s},o=ot(t,{async invoke(s,i){let{signal:a,cancel:d,timedOut:u}=n(i?.signal);try{return await et(Y(t.invoke(s,{...i,signal:a})))}catch(c){return r(c,u())}finally{d()}},async*stream(s,i){let{signal:a,cancel:d,timedOut:u}=n(i?.signal);try{for await(let c of t.stream(s,{...i,signal:a}))yield c}catch(c){r(c,u())}finally{d()}}});return Je(o,"withTimeout",t),o}function Yh(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=bd(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=gd(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=fd(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=wd(r,e.timeoutMs)),e.retry&&(r=Td(r,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),r=vd([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=bo(r,e.cache)),n.adapter=r,n}ne();ve();function Qh(t,e,n){let r=Y(e);return ke(r,s=>{if(!s||s.length===0)return A(null);let i=n?.tools;return t.invoke(s,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,tools:i,systemPrompt:n?.systemPrompt})})}it();Me();ve();ae();ve();Rt();function he(t,e){return We("ai",t,e)}function Xh(t){return t!=null&&typeof t.then=="function"}function kd(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Zh(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var ey=3e4;function Qp(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??ey;return new Promise((r,o)=>{let s=new Ie,i=t.subscribe(a=>{for(let d of a){if(d[0]===M){s.cancel(),i(),r(d[1]);return}if(d[0]===I){s.cancel(),i(),o(d[1]);return}if(d[0]===P){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function To(t){return Xh(t)?To(await t):kd(t)?Qp(t):Zh(t)?Qp(Y(t)):t}function cr(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function ty(t,e){let n=Y(t),r=e?.refreshTrigger!=null?Y(e.refreshTrigger):null,o=e?.name!==void 0?{name:e.name}:void 0,s=we("frozenContext",o);return r==null?U([n],(i,a,d)=>{if(d.store.emitted===!0)return;let c=i[0],l=c!=null&&c.length>0?c.at(-1):d.prevData[0];if(l!==void 0)return d.store.emitted=!0,a.emit(l),{invalidate:()=>{d.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:he("frozen_context",{...s})}):U([n,r],(i,a,d)=>{let u=i[1];if(!(u!=null&&u.length>0))return;let l=i[0],p=l!=null&&l.length>0?l.at(-1):d.prevData[0];a.emit(p)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:he("frozen_context",{...s})})}ae();ne();ve();function Xp(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function ny(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Sn(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node",i=C(e,d=>{if(d.some(c=>c==null))return[];let u=typeof n=="string"?n:n(...d);return u?[{role:"user",content:u}]:[]},{name:`${s}::messages`,meta:he("prompt_node")});return ke(i,d=>!d||d.length===0?A(null):z(u=>{let c=!1,l=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt};if(r?.abort){let y=ds(r.abort);f.signal=y.signal,p=y.dispose}let m;try{m=t.invoke(d,f)}catch(y){return c=!0,u.down([[I,y]]),()=>{p?.()}}let g=Y(m).subscribe(y=>{if(!(l||c))for(let b of y){if(c)return;if(b[0]===M){let v=b[1];try{let T=Xp(v),w=o==="json"?JSON.parse(cr(T)):T;u.emit(w)}catch(T){let w=Xp(v),x=new Error(`promptNode: failed to parse LLM response as JSON: ${T.message}
|
|
37
|
-
Raw content (first 200 chars): ${ny(w)}`);c=!0,u.down([[I,x]]);return}}else if(b[0]===I){c=!0,u.down([[I,b[1]]]);return}else if(b[0]===P){c=!0,u.down([[P]]);return}else u.down([b])}});return()=>{l=!0,g(),p?.()}},{name:`${s}::call`,meta:he("prompt_node::call")}),{name:`${s}::output`,meta:r?.meta?{...he("prompt_node::output"),...r.meta}:he("prompt_node::output")})}Ae();Re();it();ne();ve();var li={};Se(li,{MessagingHubGraph:()=>di,SubscriptionGraph:()=>wo,TopicBridgeGraph:()=>ii,TopicGraph:()=>Nn,TopicRegistry:()=>ai,messagingHub:()=>ko,subscription:()=>Zp,topic:()=>ui,topicBridge:()=>ci});Me();var ry=256;function lr(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function en(t,e){return We("messaging",t,e)}var oy=1024,Nn=class extends Q{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ke([],{name:"events",maxSize:n.retainedLimit??oy}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=C([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:en("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(te(this.latest)),this.hasLatest=C([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:en("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(te(this.hasLatest)),this.addDisposer(()=>{this.events.down([[P]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._log.append(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},wo=class extends Q{cursor;available;topic;_disposed=!1;constructor(e,n,r={}){super(e,r.graph),this.topic=n;let o;if(r.from!==void 0?r.from==="retained"?o=0:r.from==="now"?o=n.events.cache.length:o=lr(r.from,"subscription from"):o=lr(r.cursor??0,"subscription cursor"),this.cursor=A(o,{name:"cursor",describeKind:"state",meta:en("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=n._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(te(this.available)),r.advanceOn!==void 0){let s=r.advanceOn,i=!1,a=U([s],()=>{if(!i){i=!0;return}if(this._disposed)return;let d=this.available.cache;if(d.length===0)return;let u=this.cursor.cache+d.length;this.cursor.emit(u)},{name:"advancePump",describeKind:"effect",meta:en("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(te(a))}}ack(e){if(this._disposed)return this.cursor.cache;let n=this.available.cache,r=e===void 0?n.length:lr(e,"subscription ack count"),o=Math.min(r,n.length);if(o<=0)return this.cursor.cache;let s=this.cursor.cache+o;return this.cursor.emit(s),s}pull(e){if(this._disposed)return[];let n=this.available.cache,r=e===void 0?n.length:lr(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let n=this.available.cache,r=e===void 0?n.length:lr(e,"subscription pullAndAck limit"),o=n.slice(0,r);if(o.length===0)return{items:o,cursor:this.cursor.cache};let s=this.cursor.cache+o.length;return this.cursor.emit(s),{items:o,cursor:s}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[P]]),this.destroy())}},ii=class extends Q{_sourceSub;bridgedCount;output;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=Zp(`${e}-subscription`,n,{cursor:o.cursor}),this.mount("subscription",this._sourceSub);let s=Math.max(1,lr(o.maxPerPump??ry,"topic bridge maxPerPump")),i=o.map??(p=>p);this.output=C([this._sourceSub.available],([p])=>{let f=p,m=[],h=Math.min(f.length,s);for(let g=0;g<h;g++){let y=i(f[g]);y!==void 0&&m.push(y)}return m},{name:"output",describeKind:"derived",meta:en("topic_bridge_output",{targetRef:r.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(te(this.output)),this.bridgedCount=A(0,{name:"bridgedCount",describeKind:"state",meta:en("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(te(this.bridgedCount));let a=this.output,d=this._sourceSub,u=this.bridgedCount,c=U([a],()=>{let p=a.cache;if(p.length===0)return;let f=d.available.cache.length,m=Math.min(f,s);if(m>0){d.ack(m);let h=u.cache??0;u.emit(h+p.length)}},{name:"ackPump",describeKind:"effect",meta:en("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(te(c));let l=sy(this.output,r);this.addDisposer(l)}};function sy(t,e){return t.subscribe(n=>{for(let r of n){if(r[0]!==M)continue;let o=r[1];o.length!==0&&Z(()=>{for(let s of o)e.publish(s)})}})}var ai=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,n){this._map.set(e,n)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},di=class extends Q{_registry;version;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph);let r=A(0,{name:"version",describeKind:"state",meta:en("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new ai(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,n){let r=this._registry.get(e);if(r===void 0){let o={...this._defaultTopicOptions,...n??{}};r=new Nn(e,o),this._registry.set(e,r),this.mount(e,r);let s=this.version.cache??0;this.version.emit(s+1)}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){Z(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new wo(e,o,r)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let n=this.version.cache??0;this.version.emit(n+1)}return!0}};function ui(t,e){return new Nn(t,e)}function ko(t,e){return new di(t,e)}function Zp(t,e,n){return new wo(t,e,n)}function ci(t,e,n,r){return new ii(t,e,n,r)}var pi={};Se(pi,{PipelineGraph:()=>Ro,decisionKeyOf:()=>ef,pipelineGraph:()=>pr});Ae();Re();ae();it();Me();ne();function xo(t,e){return We("orchestration",t,e)}var ef=t=>t.action,Ro=class extends Q{constructor(e,n){super(e,n)}task(e,n,r={}){let o=(r.deps??[]).map(i=>this._resolveStep(i)),s=C(o,n,{name:e,describeKind:"derived",meta:xo("task",r.meta)});return this.add(s,{name:e}),s}classify(e,n,r,o={}){let s=this._resolveStep(n),i=C([s],([a])=>{try{return{tag:r(a),value:a}}catch(d){return{tag:"error",value:a,error:d}}},{name:e,describeKind:"derived",meta:xo("classify",o.meta)});return this.add(i,{name:e}),i}combine(e,n,r={}){let o=Object.keys(n),s=o.map(a=>this._resolveStep(n[a])),i=C(s,a=>{let d={};for(let u=0;u<o.length;u++)d[o[u]]=a[u];return d},{name:e,describeKind:"derived",meta:xo("combine",r.meta)});return this.add(i,{name:e}),i}gate(e,n,r={}){let o=r.maxPending??1e3;if(o<1&&o!==Number.POSITIVE_INFINITY)throw new RangeError("gate: maxPending must be >= 1");let s=r.startOpen??!1;typeof n!="string"&&this.nameOf(n)===void 0&&this.add(n,{name:`${e}/source`});let i=this._resolveStep(n),a=new Q(`${e}_state`),d=A([],{name:"pending",equals:()=>!1}),u=A(s,{name:"isOpen"}),c=C([d],([F])=>F.length,{name:"count"}),l=A(0,{name:"droppedCount"}),p=at({name:"decisions",retainedLimit:1024,graph:a});a.add(d,{name:"pending"}),a.add(u,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(l,{name:"droppedCount"}),this.mount(`${e}_state`,a);let f=[],m=!1,h=!1,g=s,y=u.subscribe(F=>{for(let H of F)H[0]===M&&(g=H[1])});this.addDisposer(y);function b(){d.emit([...f])}function v(F,H,G){p.append({action:F,t_ns:se(),...H!==void 0?{items:H,count:H.length}:{},...G!==void 0?{unflushed:G}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function T(F){if(f.push(F),f.length>o){let H=f.shift();l.emit(l.cache+1),v("drop",[H])}b()}function w(F){let H=f.splice(0,F);return b(),H}let x=U([i],(F,H,G)=>{let B=G.terminalDeps[0];if(B!==void 0){m=!0;let pe=f.length;f=[],b(),v("teardown",void 0,pe),H.down(B===!0?[[P]]:[[I,B]]);return}let re=F[0];if(re==null||re.length===0){H.down([[q]]);return}for(let pe of re)g?H.emit(pe):(T(pe),H.down([[q]]))},{name:e,describeKind:"derived",meta:xo("gate",r.meta)});if(this.add(x,{name:e}),r.approver!=null){r.approver.cache&&(u.emit(!0),g=!0,r.onceOnly&&(h=!0));let H=r.approver.subscribe(G=>{for(let B of G){if(B[0]!==M)continue;let re=!!B[1];if(re&&!g){if(r.onceOnly){if(h)continue;h=!0}Z(()=>{u.emit(!0);let pe=w(f.length);v("open",pe);for(let ee of pe){if(m)break;x.emit(ee)}})}else if(!re&&g){if(r.onceOnly&&h)continue;Z(()=>{u.emit(!1),v("close")})}}});this.addDisposer(H)}let k=F=>{if(m)throw new Error(`gate: ${F}() called after gate was torn down`)},S=(F=1)=>{k("approve");let H=w(F);for(let G of H){if(m)break;x.emit(G)}},R=(F=1)=>{k("reject"),w(F)},E=(F,H=1)=>{k("modify");let G=[...f],B=w(H);for(let re=0;re<B.length&&!m;re++)x.emit(F(B[re],re,G))},_=()=>{k("open"),u.emit(!0);let F=w(f.length);for(let H of F){if(m)break;x.emit(H)}},O=()=>{k("close"),!(r.onceOnly&&h)&&u.emit(!1)},N=nr(S,{audit:p,freeze:!1,onSuccess:(F,H,G)=>({action:"approve",count:F[0]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,H,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),L=nr(R,{audit:p,freeze:!1,onSuccess:(F,H,G)=>({action:"reject",count:F[0]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,H,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),j=nr(E,{audit:p,freeze:!1,onSuccess:(F,H,G)=>({action:"modify",count:F[1]??1,t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,H,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),$=nr(_,{audit:p,freeze:!1,onSuccess:(F,H,G)=>({action:"open",t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,H,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),D=nr(O,{audit:p,freeze:!1,onSuccess:(F,H,G)=>({action:"close",t_ns:G.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,H,G)=>({action:"drop",t_ns:G.t_ns,errorType:G.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:x,pending:d,count:c,isOpen:u,droppedCount:l,decisions:p,audit:p,approve:N,reject:L,modify:j,open:$,close:D}}approval(e,n,r,o={}){return this.gate(e,n,{...o,approver:r,maxPending:1})}catch(e,n,r,o={}){let s=this._resolveStep(n),i=o.on??"error",a=U([s],(d,u,c)=>{let l=c.terminalDeps[0];if(l!==void 0){let f=l===!0?{kind:"complete"}:{kind:"error",error:l};if(i==="terminal"||i===f.kind){u.emit(r(f,u));return}u.down(f.kind==="complete"?[[P]]:[[I,f.error]]);return}let p=d[0];if(p==null||p.length===0){u.down([[q]]);return}for(let f of p)u.emit(f)},{name:e,describeKind:"derived",completeWhenDepsComplete:o.completeWhenDepsComplete??!(i==="complete"||i==="terminal"),errorWhenDepsError:!(i==="error"||i==="terminal"),meta:xo("catch",o.meta)});return this.add(a,{name:e}),a}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function pr(t,e){let n=new Ro(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("pipelineGraph",st(s)),n}async function tf(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:se()}),i.type==="token"&&(o+=i.delta);return o}function nf(t,e){if(e==="json")try{return JSON.parse(cr(t))}catch(n){let r=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${n.message}; content preview: ${r}`)}return t}function rf(t,e){return C([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:he("accumulated_text"),initial:""})}function iy(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=ui(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=C(e,l=>{if(l.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...l);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:he("prompt_node::messages"),initial:[]}),d=ke(a,l=>{let p=l;if(!p||p.length===0)return A(null);let f=new AbortController;async function*m(){try{let h=await tf(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield nf(h,s)}finally{f.abort()}}return Y(m())},{meta:we("streamingPromptNode")}),u=rf(i,`${o}::accumulatedText`),c=te(d);return{output:d,deltaTopic:i,accumulatedText:u,dispose:()=>{c(),i.destroy()}}}function ay(t,e,n,r,o,s){let i=A(0,{name:`${e}/cancel`}),a=0,d=[...r,i],u=s?.name??e,c=s?.format??"text",l=ui(`${u}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=C(d,k=>{let S=k.slice(0,-1);if(S.some(E=>E==null))return[];let R=typeof o=="string"?o:o(...S);return R?[{role:"user",content:R}]:[]},{name:`${u}::messages`,meta:he("prompt_node::messages"),initial:[]}),f=ke(p,k=>{let S=k;if(!S||S.length===0)return A(null);let R=new AbortController;async function*E(){try{let _=await tf(n,S,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:R.signal},l);yield nf(_,c)}finally{R.abort()}}return Y(E())},{meta:we("gatedStream")}),m=rf(l,`${u}::accumulatedText`),h=rt(f,k=>k!=null);t.add(h,{name:`${e}/raw`});let g=pr(`${e}/gate-graph`);t.mount(`${e}/gate-graph`,g),g.add(h,{name:`${e}/raw`});let y=g.gate(`${e}/gate`,`${e}/raw`,s?.gate),b=te(f),v=te(y.node),T=te(m);t.addDisposer(b),t.addDisposer(v),t.addDisposer(T);let w=y.reject.bind(y),x={...y,reject(k=1){Z(()=>{w(k),i.emit(++a)})}};return{output:y.node,deltaTopic:l,accumulatedText:m,gate:x,dispose:()=>{b(),v(),T(),l.destroy()}}}ne();ve();function dy(t,e){let n=e?.separator??`
|
|
36
|
+
`)}]});let s={};return e?.maxTokens!=null&&(s.maxOutputTokens=e.maxTokens),e?.temperature!=null&&(s.temperature=e.temperature),e?.maxReasoningTokens!=null&&(s.thinkingConfig={thinkingBudget:e.maxReasoningTokens}),Object.keys(s).length>0&&(o.generationConfig=s),e?.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(Kh)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function Kh(t){return{name:t.name,description:t.description,parameters:t.parameters}}function lf(t,e,n){let r={},o=t.generationConfig;o&&(typeof o.maxOutputTokens=="number"&&(r.maxOutputTokens=o.maxOutputTokens),typeof o.temperature=="number"&&(r.temperature=o.temperature),o.thinkingConfig&&(r.thinkingConfig=o.thinkingConfig)),t.systemInstruction&&(r.systemInstruction=t.systemInstruction),t.tools&&(r.tools=t.tools);for(let[s,i]of Object.entries(t))s==="contents"||s==="generationConfig"||s==="systemInstruction"||s==="tools"||s==="abortSignal"||s==="model"||(r[s]=i);return n&&(r.abortSignal=n),{model:e,contents:t.contents,config:Object.keys(r).length>0?r:void 0}}function _d(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.promptTokenCount??0,r=t.cachedContentTokenCount??0;if(e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.toolUsePromptTokenCount&&(e.input.toolUse=t.toolUsePromptTokenCount),t.promptTokensDetails)for(let o of t.promptTokensDetails){let s=o.modality?.toLowerCase();s==="image"?e.input.image=(e.input.image??0)+o.tokenCount:s==="audio"?e.input.audio=(e.input.audio??0)+o.tokenCount:s==="video"&&(e.input.video=(e.input.video??0)+o.tokenCount)}return e.output.regular=t.candidatesTokenCount??0,t.thoughtsTokenCount&&(e.output.reasoning=t.thoughtsTokenCount),e}function pf(t,e){let n=t.candidates?.[0],r=n?.content?.parts??[],o=[],s=[],i=0;for(let a of r)typeof a.text=="string"&&o.push(a.text),a.functionCall&&s.push({id:`${a.functionCall.name}-${i++}`,name:a.functionCall.name,arguments:a.functionCall.args??{}});return{content:o.join(""),toolCalls:s.length>0?s:void 0,usage:_d(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function qh(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function zh(t){let e=t.baseURL??"https://generativelanguage.googleapis.com/v1beta",n=t.fetchImpl??fetch,r=s=>{let i=s?.model??t.model;if(!i)throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");return i},o=()=>{let s=qh(t);if(!s)throw new Error("googleAdapter: apiKey required for invoke/stream");return`key=${encodeURIComponent(s)}`};return{provider:"google",model:t.model,async invoke(s,i){let a=r(i),d=ui(s,i),u=H(),c=`${e}/models/${encodeURIComponent(a)}:generateContent?${o()}`,l=await n(c,{method:"POST",headers:{"content-type":"application/json",...t.headers??{}},body:JSON.stringify(d),signal:i?.signal});if(!l.ok)throw await xt(l,"Google");let p=await l.json(),f=Math.max(0,(H()-u)/1e6);return pf(p,f)},async*stream(s,i){let a=r(i),d=ui(s,i),u=`${e}/models/${encodeURIComponent(a)}:streamGenerateContent?alt=sse&${o()}`,c=await n(u,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...t.headers??{}},body:JSON.stringify(d),signal:i?.signal});if(!c.ok)throw await xt(c,"Google");if(!c.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of Bt(c.body,{signal:i?.signal})){if(!f.data)continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.candidates?.[0];for(let g of h?.content?.parts??[])typeof g.text=="string"&&(g.thought?yield{type:"thinking",delta:g.text}:yield{type:"token",delta:g.text}),g.functionCall&&(yield{type:"tool-call-delta",delta:{name:g.functionCall.name,argumentsDelta:JSON.stringify(g.functionCall.args??{})}});h?.finishReason&&(p=h.finishReason),m.usageMetadata&&(l=m.usageMetadata)}l&&(yield{type:"usage",usage:_d(l)}),yield{type:"finish",reason:p??"stop"}}}}function Hh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedGoogle: sdk instance required");return{provider:"google",model:t.model,async invoke(n,r){let o=ui(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=lf(o,s,r?.signal),a=H(),d=await e.models.generateContent(i),u=Math.max(0,(H()-a)/1e6);return pf(d,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=ui(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=lf(o,s,r?.signal),a,d,u=await e.models.generateContentStream(i);for await(let c of u){let l=c.candidates?.[0];for(let p of l?.content?.parts??[])typeof p.text=="string"&&(p.thought?yield{type:"thinking",delta:p.text}:yield{type:"token",delta:p.text}),p.functionCall&&(yield{type:"tool-call-delta",delta:{name:p.functionCall.name,argumentsDelta:JSON.stringify(p.functionCall.args??{})}});l?.finishReason&&(d=l.finishReason),c.usageMetadata&&(a=c.usageMetadata)}a&&(yield{type:"usage",usage:_d(a)}),yield{type:"finish",reason:d??"stop"}}}}Se();var Wh={openai:{baseURL:"https://api.openai.com/v1",apiKeyEnv:"OPENAI_API_KEY",provider:"openai"},openrouter:{baseURL:"https://openrouter.ai/api/v1",apiKeyEnv:"OPENROUTER_API_KEY",provider:"openrouter"},groq:{baseURL:"https://api.groq.com/openai/v1",apiKeyEnv:"GROQ_API_KEY",provider:"groq"},ollama:{baseURL:"http://localhost:11434/v1",provider:"ollama"},deepseek:{baseURL:"https://api.deepseek.com/v1",apiKeyEnv:"DEEPSEEK_API_KEY",provider:"deepseek"},xai:{baseURL:"https://api.x.ai/v1",apiKeyEnv:"XAI_API_KEY",provider:"xai"}};function Md(t={}){return t.sdk?Xh(t):Qh(t)}function ci(t,e,n,r,o){let s=e?.model??n;if(!s)throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");let i=t.map(Uh);e?.systemPrompt&&!t.some(d=>d.role==="system")&&i.unshift({role:"system",content:e.systemPrompt});let a={model:s,messages:i};return e?.maxTokens!=null&&(a.max_tokens=e.maxTokens),e?.temperature!=null&&(a.temperature=e.temperature),e?.tools&&e.tools.length>0&&(a.tools=e.tools.map(Jh)),e?.maxReasoningTokens!=null&&(a.reasoning={max_tokens:e.maxReasoningTokens}),r&&(a.stream=!0,a.stream_options={include_usage:!0}),o&&Object.assign(a,o),e?.providerExtras&&Object.assign(a,e.providerExtras),a}function Uh(t){return t.role==="tool"?{role:"tool",tool_call_id:t.toolCallId,content:t.content}:t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0?{role:"assistant",content:t.content||null,tool_calls:t.toolCalls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))}:{role:t.role,content:t.content}}function Jh(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function Od(t){let e={input:{regular:0},output:{regular:0},raw:t};if(!t)return e;let n=t.prompt_tokens??0,r=t.prompt_tokens_details?.cached_tokens??0;t.prompt_cache_hit_tokens!=null?(r=t.prompt_cache_hit_tokens,e.input.regular=t.prompt_cache_miss_tokens??Math.max(0,n-r)):e.input.regular=Math.max(0,n-r),r>0&&(e.input.cacheRead=r),t.prompt_tokens_details?.audio_tokens&&(e.input.audio=t.prompt_tokens_details.audio_tokens);let o=t.completion_tokens??0,s=t.completion_tokens_details?.reasoning_tokens??0;return e.output.regular=Math.max(0,o-s),s>0&&(e.output.reasoning=s),t.completion_tokens_details?.audio_tokens&&(e.output.audio=t.completion_tokens_details.audio_tokens),t.completion_tokens_details?.accepted_prediction_tokens&&(e.output.predictionAccepted=t.completion_tokens_details.accepted_prediction_tokens),t.completion_tokens_details?.rejected_prediction_tokens&&(e.output.predictionRejected=t.completion_tokens_details.rejected_prediction_tokens),e}function ff(t,e,n){let r=t.choices[0],o=r?.message,s=o?.content??"",i=(o?.tool_calls??[]).map(a=>({id:a.id,name:a.function.name,arguments:Yh(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:Od(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Yh(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function mf(t){let e=t.preset??"openai",n=Wh[e],r=t.baseURL??n.baseURL,o=t.provider??n.provider,s=n.apiKeyEnv,i=t.apiKey??(s?globalThis.process?.env?.[s]:void 0);return{provider:o,baseURL:r,apiKey:i}}function Qh(t){let{provider:e,baseURL:n,apiKey:r}=mf(t),o=t.fetchImpl??fetch,s=e!=="ollama",i=()=>{let a={"content-type":"application/json",...t.headers??{}};if(s){if(!r)throw new Error(`openAICompatAdapter[${e}]: apiKey required for invoke/stream`);a.authorization=`Bearer ${r}`}return a};return{provider:e,model:t.model,async invoke(a,d){let u=ci(a,d,t.model,!1,t.bodyExtras),c=H(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(u),signal:d?.signal});if(!l.ok)throw await xt(l,e);let p=await l.json(),f=Math.max(0,(H()-c)/1e6);return ff(p,f,e)},async*stream(a,d){let u=ci(a,d,t.model,!0,t.bodyExtras),c=await o(`${n}/chat/completions`,{method:"POST",headers:{...i(),accept:"text/event-stream"},body:JSON.stringify(u),signal:d?.signal});if(!c.ok)throw await xt(c,e);if(!c.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of Bt(c.body,{signal:d?.signal})){if(!f.data||f.data==="[DONE]")continue;let m;try{m=JSON.parse(f.data)}catch{continue}let h=m.choices;if(h){let g=h[0];if(g?.delta?.content&&(yield{type:"token",delta:g.delta.content}),g?.delta?.reasoning_content&&(yield{type:"thinking",delta:g.delta.reasoning_content}),g?.delta?.tool_calls)for(let y of g.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:y.id,name:y.function?.name,argumentsDelta:y.function?.arguments}};g?.finish_reason&&(p=g.finish_reason)}m.usage&&(l=m.usage,yield{type:"usage",usage:Od(l)})}yield{type:"finish",reason:p??"stop"}}}}function Xh(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=mf(t);return{provider:n,model:t.model,async invoke(r,o){let s=ci(r,o,t.model,!1,t.bodyExtras),i=H(),a=await e.chat.completions.create(s,{signal:o?.signal}),d=Math.max(0,(H()-i)/1e6);return ff(a,d,n)},async*stream(r,o){let s=ci(r,o,t.model,!0,t.bodyExtras),i=await e.chat.completions.create(s,{signal:o?.signal}),a,d;for await(let u of i){let c=u.choices;if(c){let p=c[0];if(p?.delta?.content&&(yield{type:"token",delta:p.delta.content}),p?.delta?.reasoning_content&&(yield{type:"thinking",delta:p.delta.reasoning_content}),p?.delta?.tool_calls)for(let f of p.delta.tool_calls)yield{type:"tool-call-delta",delta:{id:f.id,name:f.function?.name,argumentsDelta:f.function?.arguments}};p?.finish_reason&&(d=p.finish_reason)}let l=u.usage;l&&(a=l,yield{type:"usage",usage:Od(l)})}yield{type:"finish",reason:d??"stop"}}}}function Zh(t){switch(t.provider){case"anthropic":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return xd(e)}case"google":{let e={apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Ed(e)}case"dry-run":{let e={model:t.model,...t.extras};return Gn(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Nd(e)}case"openai":case"openrouter":case"groq":case"ollama":case"deepseek":case"xai":{let e={preset:t.provider,apiKey:t.apiKey,model:t.model,baseURL:t.baseURL,headers:t.headers,bodyExtras:t.bodyExtras,sdk:t.sdk,fetchImpl:t.fetchImpl,...t.extras};return Md(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}Se();ne();ue();function Rt(t){let e=t.input,n=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function Vt(t){let e=t.output,n=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return n;let r=0;for(let o of Object.values(e.extensions))r+=o;return n+r}function gf(){return{input:{regular:0},output:{regular:0}}}function ey(t,e){let n=e?.logMax??1e3,r=qe(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=O(null,{name:"adapterStats/lastCall"}),s=A([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),i=A([r.entries],([h])=>h.reduce((g,y)=>g+Rt(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=A([r.entries],([h])=>h.reduce((g,y)=>g+Vt(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),d=[te(s),te(i),te(a)],u=h=>{r.append(h),o.emit(h)},c=()=>{r.clear(),o.emit(null)},l=it(t,{invoke(h,g){let y=H(),b=oe(),v=t.model??g?.model??"",T=k=>(u(Fn({provider:t.provider,model:t.model??g?.model??k.model??"",tier:g?.tier??k.tier,usage:k.usage??At(),startNs:y,startWallClockNs:b,method:"invoke"})),k),w=k=>{let R=k;u(Fn({provider:t.provider,model:v,tier:g?.tier,usage:At(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:R?.name??"Error",message:R?.message??String(k)}}))};return di(t.invoke(h,g),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=H(),b=oe(),v=t.model??g?.model??"",T;try{for await(let w of t.stream(h,g))w.type==="usage"&&(T=w.usage),yield w;u(Fn({provider:t.provider,model:v,tier:g?.tier,usage:T??At(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let k=w;throw u(Fn({provider:t.provider,model:v,tier:g?.tier,usage:T??At(),startNs:y,startWallClockNs:b,method:"stream",error:{type:k?.name??"Error",message:k?.message??String(w)}})),w}}});Qe(l,"observableAdapter",t);let p=!1;return{adapter:l,stats:{lastCall:o,allCalls:r,totalCalls:s,totalInputTokens:i,totalOutputTokens:a,reset:c,dispose:()=>{if(!p){p=!0;for(let h of d)h();d.length=0}}}}}function ty(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function pi(t="USD"){return{total:0,currency:t}}function Ad(t,e,n){let r=Rt(t),o=e.currency??"USD",s=n?.withBreakdown===!0,i=s?{}:null,a=0,d=(g,y,b)=>{if(!y||b==null)return;let v=ty(b,r),T=y*v/1e6;a+=T,s&&(i[g]=(i[g]??0)+T)},u=t.input,c=e.input;if(c&&(d("input.regular",u.regular,c.regular),d("input.cacheRead",u.cacheRead??0,c.cacheRead),d("input.cacheWrite5m",u.cacheWrite5m??0,c.cacheWrite5m),d("input.cacheWrite1h",u.cacheWrite1h??0,c.cacheWrite1h),d("input.cacheWriteOther",u.cacheWriteOther??0,c.cacheWriteOther),d("input.audio",u.audio??0,c.audio),d("input.image",u.image??0,c.image),d("input.video",u.video??0,c.video),d("input.toolUse",u.toolUse??0,c.toolUse),u.extensions&&c.extensions))for(let[g,y]of Object.entries(u.extensions))d(`input.ext.${g}`,y,c.extensions[g]);let l=t.output,p=e.output;if(p&&(d("output.regular",l.regular,p.regular),d("output.reasoning",l.reasoning??0,p.reasoning),d("output.audio",l.audio??0,p.audio),d("output.predictionAccepted",l.predictionAccepted??0,p.predictionAccepted),d("output.predictionRejected",l.predictionRejected??0,p.predictionRejected),l.extensions&&p.extensions))for(let[g,y]of Object.entries(l.extensions))d(`output.ext.${g}`,y,p.extensions[g]);let f=n?.tier;if(f&&e.tierMultipliers){let g=e.tierMultipliers[f];if(g!=null&&(a*=g,s))for(let y of Object.keys(i))i[y]*=g}let m=t.auxiliary,h=e.auxiliary;if(m&&h)for(let[g,y]of Object.entries(m)){let b=h[g];if(b==null||!y)continue;let v=y*b;a+=v,s&&(i[`auxiliary.${g}`]=v)}return s?{total:a,currency:o,breakdown:i}:{total:a,currency:o}}function li(t,e){return`${t}::${e}`}function ny(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(li(o,s),{provider:o,model:s,pricing:i});let a=n.get(o);a||(a=new Set,n.set(o,a)),a.add(s)};if(t)for(let[o,s,i]of t)r(o,s,i);return{register:r,lookup(o,s){let i=e.get(li(o,s));if(i)return i.pricing;let a=n.get(o);if(!a)return;let d;for(let u of a)if(s.startsWith(u)&&(!d||u.length>d.key.length)){let c=e.get(li(o,u));c&&(d={key:u,pricing:c.pricing})}return d?.pricing},remove(o,s){let i=e.delete(li(o,s));if(i){let a=n.get(o);a?.delete(s),a&&a.size===0&&n.delete(o)}return i},entries(){let o=e.values();return(function*(){for(let{provider:s,model:i,pricing:a}of o)yield[s,i,a]})()}}}function ry(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?Ad(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):pi(e)}}function oy(...t){return(e,n)=>{for(let r of t){let o=r(e,n);if(o.total!==0)return o}return t.length>0?t[0](e,n):pi()}}function sy(t,e,n){return t?.pricing?Ad(e,t.pricing,n):pi()}Gt();ue();function Cd(t,e={}){let n=e.breaker??Tt(e),r=it(t,{async invoke(o,s){if(!n.canExecute())throw new bt;try{let i=await nt(Y(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new bt;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return Qe(r,"withBreaker",t),{adapter:r,breaker:n}}Se();ae();ne();ue();var fi=class extends Error{constructor(n,r,o){super(`Budget exhausted: ${n} (limit=${r}, observed=${o})`);this.which=n;this.limit=r;this.observed=o}name="BudgetExhaustedError"},Ld=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),hf=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Id(t,e){let n=qe(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=O(hf(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=A([r],([u])=>{let c=u;return!(e.caps.calls!=null&&c.calls>=e.caps.calls||e.caps.inputTokens!=null&&c.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&c.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&c.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(te(o),e.onExhausted!=null){let u=e.onExhausted,c=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===_){let m=f[1];if(c&&l&&m===!1){let h=yf(r.cache??Ld,e.caps);h&&u(h)}l=m,c=!0}})}let s=()=>{if(o.cache===!1){let u=r.cache??Ld,c=yf(u,e.caps);return new fi(c??"budget",e.caps[c??"calls"]??0,iy(u,c??"calls"))}},i=(u,c)=>{let l=t.provider,p=Fn({provider:l,model:c.model,tier:c.tier,usage:u,startNs:c.startNs,method:c.method,...c.error?{error:c.error}:{}});n.append(p);let f=r.cache??Ld,m=e.pricingFn?f.usd+e.pricingFn(u,{model:c.model,provider:l,tier:c.tier}).total:f.usd;r.emit({calls:f.calls+1,inputTokens:f.inputTokens+Rt(u),outputTokens:f.outputTokens+Vt(u),usd:m})},a=()=>{n.clear(),r.emit(hf())},d=it(t,{invoke(u,c){let l=s();if(l)return Promise.reject(l);let p=H(),f=t.model??c?.model??"",m=g=>(i(g.usage??At(),{model:t.model??c?.model??g.model??"",tier:c?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;i(At(),{model:f,tier:c?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return di(t.invoke(u,c),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(u,c){let l=s();if(l)throw l;let p=H(),f;try{for await(let m of t.stream(u,c))m.type==="usage"&&(f=m.usage),yield m;i(f??At(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw i(f??At(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return Qe(d,"withBudgetGate",t),{adapter:d,budget:{totals:r,isOpen:o,log:n,reset:a}}}function yf(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 iy(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}ue();function ay(t,e){let n=e.mock??Gn({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?Y(e.enabled):void 0,s;o&&(s=te(o));let i=()=>r!==void 0?r:!!o?.cache,a=it(t,{invoke(u,c){return i()?n.invoke(u,c):t.invoke(u,c)},stream(u,c){return i()?n.stream(u,c):t.stream(u,c)}});return Qe(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function Dd(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=dy(e.headers);if(n!==429&&n!==503&&!my(e.message))return;let o={},s=r("retry-after"),i=cy(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=bf(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=r("anthropic-ratelimit-tokens-reset");if(d){let f=bf(d);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=mi(r,"x-ratelimit-limit-requests");u!=null&&(o.rpmCap=u);let c=mi(r,"x-ratelimit-limit-tokens");c!=null&&(o.tpmCap=c);let l=mi(r,"x-ratelimit-remaining-requests"),p=mi(r,"x-ratelimit-remaining-tokens");if(l!=null&&u!=null&&u>0&&(o.usageHint??={},o.usageHint.rpm=1-l/u),p!=null&&c!=null&&c>0&&(o.usageHint??={},o.usageHint.tpm=1-p/c),o.retryAfterMs==null&&e.message){let f=py(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:uy(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function dy(t){if(!t)return()=>{};if(typeof t.get=="function"){let r=t;return o=>r.get(o)??r.get(o.toLowerCase())??void 0}let e=t,n={};for(let[r,o]of Object.entries(e)){let s=Array.isArray(o)?o.join(", "):o;s!=null&&(n[r.toLowerCase()]=s)}return r=>n[r.toLowerCase()]}function uy(t){let e={};if(typeof t.forEach=="function")return t.forEach((n,r)=>{e[r]=n}),e;for(let[n,r]of Object.entries(t))r!=null&&(e[n]=Array.isArray(r)?r.join(", "):r);return e}function mi(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function cy(t){if(!t)return;let e=t.trim(),n=Number(e);if(Number.isFinite(n)&&n>=0)return n*1e3;let r=Date.parse(e);if(Number.isFinite(r)){let o=r-Date.now();if(o>0)return o}}function bf(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var ly=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function py(t){let e=ly.exec(t);if(!e)return;let n=Number(e[1]);if(!Number.isFinite(n))return;let r=(e[2]??"s").toLowerCase();if(r==="ms")return n;if(r.startsWith("s"))return n*1e3;if(r.startsWith("m"))return n*6e4}var fy=/rate\s*limit|too\s*many\s*requests|quota|429/i;function my(t){return!!t&&fy.test(t)}Se();ae();ne();Gt();ue();Et();function Pd(t){let e=new Error(t);return e.name="AbortError",e}function Tf(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?Y(t.rpm):O(Number.POSITIVE_INFINITY),o=t.tpm!=null?Y(t.tpm):O(Number.POSITIVE_INFINITY),s=O(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=O(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=O({},{name:"adaptiveRateLimiter/lastSignal"}),d=A([r,s],([M,C])=>Math.min(Number(M??1/0),Number(C??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),u=A([o,i],([M,C])=>Math.min(Number(M??1/0),Number(C??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),c=br(Number(r.cache??Number.POSITIVE_INFINITY),e),l=br(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=d.subscribe(M=>{for(let C of M)if(C[0]===_){let $=Number(C[1]);Number.isFinite($)&&$>0?(c=br($,e),p=!1):$===1/0?(c=br(1/0,e),p=!1):$<=0&&(p=!0)}}),h=u.subscribe(M=>{for(let C of M)if(C[0]===_){let $=Number(C[1]);Number.isFinite($)&&$>0?(l=br($,e),f=!1):$===1/0?(l=br(1/0,e),f=!1):$<=0&&(f=!0)}}),g=0,y=new De,b=new De,v;t.adaptation!=null&&(v=Y(t.adaptation).subscribe(C=>{for(let $ of C)$[0]===_&&T($[1])}));function T(M){if(a.emit(M),M.rpmCap!=null&&Number.isFinite(M.rpmCap)&&M.rpmCap>=0&&(s.emit(M.rpmCap),Number.isFinite(n)&&n>0&&y.start(n,()=>s.emit(Number.POSITIVE_INFINITY))),M.tpmCap!=null&&Number.isFinite(M.tpmCap)&&M.tpmCap>=0&&(i.emit(M.tpmCap),Number.isFinite(n)&&n>0&&b.start(n,()=>i.emit(Number.POSITIVE_INFINITY))),M.retryAfterMs!=null&&M.retryAfterMs>0){let C=H()+M.retryAfterMs*1e6;C>g&&(g=C)}}let w=O(0,{name:"adaptiveRateLimiter/pending"}),k=O(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),R=O(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),S=M=>{w.emit((w.cache??0)+M)},x=()=>{k.emit(c.available()),R.emit(l.available())};async function N(M={}){let C=M.requestCost??1,$=M.tokenCost??0,B=M.signal;S(1);try{for(;;){if(B?.aborted)throw Pd("AdaptiveRateLimiter.acquire aborted");let G=H();if(g>G){let j=Math.ceil((g-G)/1e6);await gi(j,B);continue}if(C>0&&p||$>0&&f){await gi(250,B);continue}let V=c,F=l;if(!V.tryConsume(C)){await gi(vf(V,C),B);continue}if(!($>0?F.tryConsume($):!0)){V.putBack(C),await gi(vf(F,$),B);continue}x();return}}finally{S(-1)}}function E(M){M>0?l.tryConsume(M):M<0&&l.putBack(-M),x()}function D(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:d,effectiveTpm:u,lastSignal:a,pending:w,rpmAvailable:k,tpmAvailable:R,acquire:N,recordUsage:E,recordSignal:T,dispose:D}}function br(t,e){if(!Number.isFinite(t)||t===1/0)return Jt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return Jt(n,r)}function vf(t,e){let n=t.available(),r=Math.max(0,e-n);return r<=0?25:Math.min(5e3,Math.max(50,r*100))}function gi(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Pd("AdaptiveRateLimiter.acquire aborted")):new Promise((n,r)=>{let o=new De,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(Pd("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}ue();function Gd(t,e={}){let n=e.limiter??Tf({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),r=(i,a)=>e.costFn?e.costFn(i,a):0,o=i=>{let a=Dd(i);a&&n.recordSignal(a)},s=it(t,{async invoke(i,a){let d=r(i,a);await n.acquire({requestCost:1,tokenCost:d,signal:a?.signal});try{let u=await nt(Y(t.invoke(i,a))),c=u.usage??gf(),p=Rt(c)+Vt(c)-d;return p>0&&n.recordUsage(p),u}catch(u){throw o(u),u}},async*stream(i,a){let d=r(i,a);await n.acquire({requestCost:1,tokenCost:d,signal:a?.signal});try{let u=0;for await(let l of t.stream(i,a))l.type==="usage"&&(u=Rt(l.usage)+Vt(l.usage)),yield l;let c=u-d;c>0&&n.recordUsage(c)}catch(u){throw o(u),u}}});return Qe(s,"withRateLimiter",t),{adapter:s,limiter:n}}Gt();ue();var Ro=class extends Error{name="AllTiersExhaustedError";skipped;failed;constructor(e){let n=[];e.failed.size>0&&n.push(`failed=[${[...e.failed.keys()].join(",")}]`),e.skipped.length>0&&n.push(`skipped=[${e.skipped.map(r=>`${r.name}(${r.reason})`).join(",")}]`),super(`All LLM adapter tiers exhausted: ${n.join(" ")}`),this.skipped=e.skipped,this.failed=e.failed}};function Fd(t,e={}){if(t.length===0)throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");let n=t.map(s=>({name:s.name,adapter:s.adapter,filter:s.filter,breaker:s.breaker?"canExecute"in s.breaker?s.breaker:Tt(s.breaker):void 0})),r=e.streamRetryBeforeFirstChunk??!0,o={provider:"cascading",model:void 0,async invoke(s,i){let a=[],d=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}try{let p=await nt(Y(l.adapter.invoke(s,i)));return l.breaker?.recordSuccess(),{...p,metadata:{...p.metadata??{},tier:l.name}}}catch(p){d.set(l.name,p),l.breaker?.recordFailure(p);let f=n[c+1];f&&e.onFallback?.(l.name,f.name,p)}}let u={skipped:a,failed:d};throw e.onExhausted?.(u),new Ro(u)},async*stream(s,i){let a=[],d=new Map;for(let c=0;c<n.length;c++){let l=n[c];if(l.filter&&!l.filter(s,i)){a.push({name:l.name,reason:"filter"});continue}if(l.breaker&&!l.breaker.canExecute()){a.push({name:l.name,reason:"breaker"});continue}let p=!1;try{for await(let f of l.adapter.stream(s,i))p=!0,yield f;l.breaker?.recordSuccess();return}catch(f){if(d.set(l.name,f),l.breaker?.recordFailure(f),p||!r)throw f;let m=n[c+1];m&&e.onFallback?.(l.name,m.name,f)}}let u={skipped:a,failed:d};throw e.onExhausted?.(u),new Ro(u)}};return Qe(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function gy(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}ue();Et();function hi(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function wf(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(hi()):new Promise((n,r)=>{let o=new De,s,i=()=>{o.cancel(),e&&s&&e.removeEventListener("abort",s)};o.start(t,()=>{i(),n()}),e&&(s=()=>{i(),r(hi())},e.addEventListener("abort",s,{once:!0}))})}function $d(t,e={}){let n=e.attempts??3,r=e.baseDelayMs??500,o=e.maxDelayMs??1e4,s=e.strategy??"decorrelated",i=e.jitter??!0,a=e.shouldRetry??hy,d=e.retryStreaming??!0,u=(l,p)=>{if(s==="decorrelated"){let g=Math.min(o,Math.max(r,p*3));return r+Math.random()*(g-r)}let f=s==="exp"?r*2**(l-1):r*l,m=Math.min(o,f);if(!i)return m;let h=m*(.5+Math.random());return Math.min(o,h)},c=it(t,{async invoke(l,p){if(p?.signal?.aborted)throw hi();let f,m=r;for(let h=1;h<=n;h++)try{return await nt(Y(t.invoke(l,p)))}catch(g){if(f=g,h>=n||!a(g,h))throw g;let y=u(h,m);m=y,await wf(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw hi();if(!d){for await(let h of t.stream(l,p))yield h;return}let f,m=r;for(let h=1;h<=n;h++){let g=!1;try{for await(let y of t.stream(l,p))g=!0,yield y;return}catch(y){if(f=y,g||h>=n||!a(y,h))throw y;let b=u(h,m);m=b,await wf(b,p?.signal)}}throw f}});return Qe(c,"withRetry",t),c}function hy(t,e){if(t==null)return!1;let n=t;return n.name==="LLMTimeoutError"?!0:n.name==="AbortError"||n.message==="aborted"||n.name==="DOMException"&&n.code!=null&&Number(n.code)===20||n.name==="BudgetExhaustedError"||n.name==="CircuitOpenError"?!1:n.status!=null?n.status===429||n.status>=500&&n.status<600:n.code&&typeof n.code=="string"&&/^E[A-Z]+$/.test(n.code)?!0:n.message?/network|timeout|socket|fetch|econn|eai_/i.test(n.message):!1}ue();Et();var vr=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function jd(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let n=s=>{let i=new AbortController,a=!1,d,u=new De;return s&&(s.aborted?i.abort(s.reason):(d=()=>{u.cancel(),i.abort(s.reason)},s.addEventListener("abort",d,{once:!0}))),u.start(e,()=>{a=!0,i.abort(new vr(e))}),{signal:i.signal,cancel:()=>{u.cancel(),s&&d&&s.removeEventListener("abort",d)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof vr)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let u=new vr(e);throw u.cause=s,u}throw s},o=it(t,{async invoke(s,i){let{signal:a,cancel:d,timedOut:u}=n(i?.signal);try{return await nt(Y(t.invoke(s,{...i,signal:a})))}catch(c){return r(c,u())}finally{d()}},async*stream(s,i){let{signal:a,cancel:d,timedOut:u}=n(i?.signal);try{for await(let c of t.stream(s,{...i,signal:a}))yield c}catch(c){r(c,u())}finally{d()}}});return Qe(o,"withTimeout",t),o}function yy(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=Gd(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=Id(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=Cd(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=jd(r,e.timeoutMs)),e.retry&&(r=$d(r,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),r=Fd([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=xo(r,e.cache)),n.adapter=r,n}et();Me();ue();ae();at();ue();Et();function ve(t,e){return xe("ai",t,e)}function by(t){return t!=null&&typeof t.then=="function"}function Bd(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function vy(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Ty=3e4;function kf(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Ty;return new Promise((r,o)=>{let s=new De,i=t.subscribe(a=>{for(let d of a){if(d[0]===_){s.cancel(),i(),r(d[1]);return}if(d[0]===L){s.cancel(),i(),o(d[1]);return}if(d[0]===I){s.cancel(),i(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});s.start(n,()=>{i(),o(new Error(`firstDataFromNode: timed out after ${n}ms`))})})}async function So(t){return by(t)?So(await t):Bd(t)?kf(t):vy(t)?kf(Y(t)):t}function Tr(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function wy(t,e){let n=Y(t),r=e?.refreshTrigger!=null?Y(e.refreshTrigger):null,o=e?.name!==void 0?{name:e.name}:void 0,s=be("frozenContext",o);return r==null?U([n],(i,a,d)=>{if(d.store.emitted===!0)return;let c=i[0],l=c!=null&&c.length>0?c.at(-1):d.prevData[0];if(l!==void 0)return d.store.emitted=!0,a.emit(l),{invalidate:()=>{d.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:ve("frozen_context",{...s})}):U([n,r],(i,a,d)=>{let u=i[1];if(!(u!=null&&u.length>0))return;let l=i[0],p=l!=null&&l.length>0?l.at(-1):d.prevData[0];a.emit(p)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:ve("frozen_context",{...s})})}ne();ae();ne();ue();function xf(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function ky(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function jn(t,e,n,r){let o=r?.format??"text",s=r?.name??"prompt_node";r?.tools!==void 0&&o!=="raw"&&console.warn("promptNode: `tools` is set but `format !== 'raw'`. Tool calls in the response will be silently dropped \u2014 set `format: 'raw'` to receive the full LLMResponse with `toolCalls`.");let i=A(e,d=>{if(d.some(c=>c==null))return[];let u=typeof n=="string"?n:n(...d);return u?[{role:"user",content:u}]:[]},{name:`${s}::messages`,meta:ve("prompt_node")});return me(i,d=>!d||d.length===0?O(null):z(u=>{let c=!1,l=!1,p,f={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,...r?.tools!==void 0?{tools:r.tools}:{}};if(r?.abort){let y=ys(r.abort);f.signal=y.signal,p=y.dispose}let m;try{m=t.invoke(d,f)}catch(y){return c=!0,u.down([[L,y]]),()=>{p?.()}}let g=Y(m).subscribe(y=>{if(!(l||c))for(let b of y){if(c)return;if(b[0]===_){let v=b[1];if(o==="raw")u.emit(v);else try{let T=xf(v),w=o==="json"?JSON.parse(Tr(T)):T;u.emit(w)}catch(T){let w=xf(v),k=new Error(`promptNode: failed to parse LLM response as JSON: ${T.message}
|
|
37
|
+
Raw content (first 200 chars): ${ky(w)}`);c=!0,u.down([[L,k]]);return}}else if(b[0]===L){c=!0,u.down([[L,b[1]]]);return}else if(b[0]===I){c=!0,u.down([[I]]);return}else u.down([b])}});return()=>{l=!0,g(),p?.()}},{name:`${s}::call`,meta:ve("prompt_node::call")}),{name:`${s}::output`,meta:r?.meta?{...ve("prompt_node::output"),...r.meta}:ve("prompt_node::output")})}function Vd(t,e,n,r){let o=n.name??r;return s=>{let i=O(s);return jn(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function Kd(t,e){let n=e.maxExistingKeys??100,r=Vd(t,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,s)=>{let i=n===Number.POSITIVE_INFINITY?[...s.keys()]:[...s.keys()].slice(0,n);return r({raw:o,existingKeys:i})}}function qd(t,e){let n=Vd(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}Ae();Se();et();ne();ue();var ki={};Ne(ki,{MessagingHubGraph:()=>vi,SubscriptionGraph:()=>No,TopicBridgeGraph:()=>yi,TopicGraph:()=>Kt,TopicRegistry:()=>bi,messagingHub:()=>Eo,subscription:()=>Rf,topic:()=>Ti,topicBridge:()=>wi});Me();at();ue();var xy=256;function wr(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function an(t,e){return xe("messaging",t,e)}var Ry=1024,Kt=class extends Q{_log;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=qe([],{name:"events",maxSize:n.retainedLimit??Ry}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=A([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:an("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(te(this.latest)),this.hasLatest=A([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:an("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(te(this.hasLatest)),this.addDisposer(()=>{this.events.down([[I]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._log.append(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},No=class extends Q{cursor;available;topic;_disposed=!1;constructor(e,n,r={}){super(e,r.graph),this.topic=n;let o;if(r.from!==void 0?r.from==="retained"?o=0:r.from==="now"?o=n.events.cache.length:o=wr(r.from,"subscription from"):o=wr(r.cursor??0,"subscription cursor"),this.cursor=O(o,{name:"cursor",describeKind:"state",meta:an("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=n._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(te(this.available)),r.advanceOn!==void 0){let s=r.advanceOn,i=!1,a=U([s],()=>{if(!i){i=!0;return}if(this._disposed)return;let d=this.available.cache;if(d.length===0)return;let u=this.cursor.cache+d.length;this.cursor.emit(u)},{name:"advancePump",describeKind:"effect",meta:an("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(te(a))}}ack(e){if(this._disposed)return this.cursor.cache;let n=this.available.cache,r=e===void 0?n.length:wr(e,"subscription ack count"),o=Math.min(r,n.length);if(o<=0)return this.cursor.cache;let s=this.cursor.cache+o;return this.cursor.emit(s),s}pull(e){if(this._disposed)return[];let n=this.available.cache,r=e===void 0?n.length:wr(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let n=this.available.cache,r=e===void 0?n.length:wr(e,"subscription pullAndAck limit"),o=n.slice(0,r);if(o.length===0)return{items:o,cursor:this.cursor.cache};let s=this.cursor.cache+o.length;return this.cursor.emit(s),{items:o,cursor:s}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[I]]),this.destroy())}},yi=class extends Q{_sourceSub;bridgedCount;output;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=Rf(`${e}-subscription`,n,{cursor:o.cursor}),this.mount("subscription",this._sourceSub);let s=Math.max(1,wr(o.maxPerPump??xy,"topic bridge maxPerPump")),i=o.map??(p=>p);this.output=A([this._sourceSub.available],([p])=>{let f=p,m=[],h=Math.min(f.length,s);for(let g=0;g<h;g++){let y=i(f[g]);y!==void 0&&m.push(y)}return m},{name:"output",describeKind:"derived",meta:an("topic_bridge_output",{targetRef:r.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(te(this.output)),this.bridgedCount=O(0,{name:"bridgedCount",describeKind:"state",meta:an("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(te(this.bridgedCount));let a=this.output,d=this._sourceSub,u=this.bridgedCount,c=U([a],()=>{let p=a.cache;if(p.length===0)return;let f=d.available.cache.length,m=Math.min(f,s);if(m>0){d.ack(m);let h=u.cache??0;u.emit(h+p.length)}},{name:"ackPump",describeKind:"effect",meta:an("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(te(c));let l=Sy(this.output,r);this.addDisposer(l)}};function Sy(t,e){return t.subscribe(n=>{for(let r of n){if(r[0]!==_)continue;let o=r[1];o.length!==0&&Z(()=>{for(let s of o)e.publish(s)})}})}var bi=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,n){this._map.set(e,n)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},vi=class extends Q{_registry;version;_defaultTopicOptions;constructor(e,n={}){super(e,n.graph);let r=O(0,{name:"version",describeKind:"state",meta:an("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new bi(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,n){let r=this._registry.get(e);if(r===void 0){let o={...this._defaultTopicOptions,...n??{}};r=new Kt(e,o),this._registry.set(e,r),this.mount(e,r);let s=this.version.cache??0;this.version.emit(s+1)}return r}publish(e,n){this.topic(e).publish(n)}publishMany(e){Z(()=>{for(let[n,r]of e)this.topic(n).publish(r)})}subscribe(e,n,r){let o=this.topic(n);return new No(e,o,r)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let n=this.version.cache??0;this.version.emit(n+1)}return!0}};function Ti(t,e){return new Kt(t,e)}function Eo(t,e){return new vi(t,e)}function Rf(t,e,n){return new No(t,e,n)}function wi(t,e,n,r){return new yi(t,e,n,r)}var xi={};Ne(xi,{PipelineGraph:()=>Mo,decisionKeyOf:()=>Sf,pipelineGraph:()=>kr});Ae();Se();ae();et();Me();ne();at();function _o(t,e){return xe("orchestration",t,e)}var Sf=t=>t.action,Mo=class extends Q{constructor(e,n){super(e,n)}task(e,n,r={}){let o=(r.deps??[]).map(i=>this._resolveStep(i)),s=A(o,n,{name:e,describeKind:"derived",meta:_o("task",r.meta)});return this.add(s,{name:e}),s}classify(e,n,r,o={}){let s=this._resolveStep(n),i=A([s],([a])=>{try{return{tag:r(a),value:a}}catch(d){return{tag:"error",value:a,error:d}}},{name:e,describeKind:"derived",meta:_o("classify",o.meta)});return this.add(i,{name:e}),i}combine(e,n,r={}){let o=Object.keys(n),s=o.map(a=>this._resolveStep(n[a])),i=A(s,a=>{let d={};for(let u=0;u<o.length;u++)d[o[u]]=a[u];return d},{name:e,describeKind:"derived",meta:_o("combine",r.meta)});return this.add(i,{name:e}),i}approvalGate(e,n,r={}){let o=r.maxPending??1e3;if(o<1&&o!==Number.POSITIVE_INFINITY)throw new RangeError("approvalGate: maxPending must be >= 1");let s=r.startOpen??!1;typeof n!="string"&&this.nameOf(n)===void 0&&this.add(n,{name:`${e}/source`});let i=this._resolveStep(n),a=new Q(`${e}_state`),d=O([],{name:"pending",equals:()=>!1}),u=O(s,{name:"isOpen"}),c=A([d],([F])=>F.length,{name:"count"}),l=O(0,{name:"droppedCount"}),p=ot({name:"decisions",retainedLimit:1024,graph:a});a.add(d,{name:"pending"}),a.add(u,{name:"isOpen"}),a.add(c,{name:"count"}),a.add(l,{name:"droppedCount"}),this.mount(`${e}_state`,a);let f=[],m=!1,h=!1,g=s,y=u.subscribe(F=>{for(let K of F)K[0]===_&&(g=K[1])});this.addDisposer(y);function b(){d.emit([...f])}function v(F,K,P){p.append({action:F,t_ns:oe(),...K!==void 0?{items:K,count:K.length}:{},...P!==void 0?{unflushed:P}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function T(F){if(f.push(F),f.length>o){let K=f.shift();l.emit(l.cache+1),v("drop",[K])}b()}function w(F){let K=f.splice(0,F);return b(),K}let k=U([i],(F,K,P)=>{let j=P.terminalDeps[0];if(j!==void 0){m=!0;let fe=f.length;f=[],b(),v("teardown",void 0,fe),K.down(j===!0?[[I]]:[[L,j]]);return}let re=F[0];if(re==null||re.length===0){K.down([[q]]);return}for(let fe of re)g?K.emit(fe):(T(fe),K.down([[q]]))},{name:e,describeKind:"derived",meta:_o("approval_gate",r.meta)});if(this.add(k,{name:e}),r.approver!=null){r.approver.cache&&(u.emit(!0),g=!0,r.onceOnly&&(h=!0));let K=r.approver.subscribe(P=>{for(let j of P){if(j[0]!==_)continue;let re=!!j[1];if(re&&!g){if(r.onceOnly){if(h)continue;h=!0}Z(()=>{u.emit(!0);let fe=w(f.length);v("open",fe);for(let ee of fe){if(m)break;k.emit(ee)}})}else if(!re&&g){if(r.onceOnly&&h)continue;Z(()=>{u.emit(!1),v("close")})}}});this.addDisposer(K)}let R=F=>{if(m)throw new Error(`approvalGate: ${F}() called after the gate was torn down`)},S=(F=1)=>{R("approve");let K=w(F);for(let P of K){if(m)break;k.emit(P)}},x=(F=1)=>{R("reject"),w(F)},N=(F,K=1)=>{R("modify");let P=[...f],j=w(K);for(let re=0;re<j.length&&!m;re++)k.emit(F(j[re],re,P))},E=()=>{R("open"),u.emit(!0);let F=w(f.length);for(let K of F){if(m)break;k.emit(K)}},D=()=>{R("close"),!(r.onceOnly&&h)&&u.emit(!1)},M=Zt(S,{audit:p,freeze:!1,onSuccess:(F,K,P)=>({action:"approve",count:F[0]??1,t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,K,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),C=Zt(x,{audit:p,freeze:!1,onSuccess:(F,K,P)=>({action:"reject",count:F[0]??1,t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,K,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),$=Zt(N,{audit:p,freeze:!1,onSuccess:(F,K,P)=>({action:"modify",count:F[1]??1,t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,K,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),B=Zt(E,{audit:p,freeze:!1,onSuccess:(F,K,P)=>({action:"open",t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,K,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),G=Zt(D,{audit:p,freeze:!1,onSuccess:(F,K,P)=>({action:"close",t_ns:P.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,K,P)=>({action:"drop",t_ns:P.t_ns,errorType:P.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{node:k,pending:d,count:c,isOpen:u,droppedCount:l,decisions:p,audit:p,approve:M,reject:C,modify:$,open:B,close:G}}approval(e,n,r,o={}){return this.approvalGate(e,n,{...o,approver:r,maxPending:1})}catch(e,n,r,o={}){let s=this._resolveStep(n),i=o.on??"errored",a=U([s],(d,u,c)=>{let l=c.terminalDeps[0];if(l!==void 0){let f=l===!0?{kind:"completed"}:{kind:"errored",error:l};if(i==="terminal"||i===f.kind){u.emit(r(f,u));return}u.down(f.kind==="completed"?[[I]]:[[L,f.error]]);return}let p=d[0];if(p==null||p.length===0){u.down([[q]]);return}for(let f of p)u.emit(f)},{name:e,describeKind:"derived",completeWhenDepsComplete:o.completeWhenDepsComplete??!(i==="completed"||i==="terminal"),errorWhenDepsError:!(i==="errored"||i==="terminal"),meta:_o("catch",o.meta)});return this.add(a,{name:e}),a}_resolveStep(e){if(typeof e=="string")return this.resolve(e);if(this.nameOf(e)===void 0)throw new Error(`PipelineGraph "${this.name}": Node dep is not registered. Pass a string path or call graph.add(node) first.`);return e}};function kr(t,e){let n=new Mo(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("pipelineGraph",We(s)),n}async function Nf(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:oe()}),i.type==="token"&&(o+=i.delta);return o}function Ef(t,e){if(e==="json")try{return JSON.parse(Tr(t))}catch(n){let r=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${n.message}; content preview: ${r}`)}return t}function _f(t,e){return A([t.latest],([n],r)=>{let o=r.store;if(n==null)return o.acc??"";let s=n;return s.seq===0&&(o.acc=""),s.type==="token"&&(o.acc=(o.acc??"")+s.delta),o.acc??""},{name:e,meta:ve("accumulated_text"),initial:""})}function Ny(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=Ti(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=A(e,l=>{if(l.some(f=>f==null))return[];let p=typeof n=="string"?n:n(...l);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:ve("prompt_node::messages"),initial:[]}),d=me(a,l=>{let p=l;if(!p||p.length===0)return O(null);let f=new AbortController;async function*m(){try{let h=await Nf(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield Ef(h,s)}finally{f.abort()}}return Y(m())},{meta:be("streamingPromptNode")}),u=_f(i,`${o}::accumulatedText`),c=te(d);return{output:d,deltaTopic:i,accumulatedText:u,dispose:()=>{c(),i.destroy()}}}function Ey(t,e,n,r,o,s){let i=O(0,{name:`${e}/cancel`}),a=0,d=[...r,i],u=s?.name??e,c=s?.format??"text",l=Ti(`${u}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=A(d,R=>{let S=R.slice(0,-1);if(S.some(N=>N==null))return[];let x=typeof o=="string"?o:o(...S);return x?[{role:"user",content:x}]:[]},{name:`${u}::messages`,meta:ve("prompt_node::messages"),initial:[]}),f=me(p,R=>{let S=R;if(!S||S.length===0)return O(null);let x=new AbortController;async function*N(){try{let E=await Nf(n,S,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:x.signal},l);yield Ef(E,c)}finally{x.abort()}}return Y(N())},{meta:be("gatedStream")}),m=_f(l,`${u}::accumulatedText`),h=st(f,R=>R!=null);t.add(h,{name:`${e}/raw`});let g=kr(`${e}/gate-graph`);t.mount(`${e}/gate-graph`,g),g.add(h,{name:`${e}/raw`});let y=g.approvalGate(`${e}/gate`,`${e}/raw`,s?.gate),b=te(f),v=te(y.node),T=te(m);t.addDisposer(b),t.addDisposer(v),t.addDisposer(T);let w=y.reject.bind(y),k={...y,reject(R=1){Z(()=>{w(R),i.emit(++a)})}};return{output:y.node,deltaTopic:l,accumulatedText:m,gate:k,dispose:()=>{b(),v(),T(),l.destroy()}}}ne();ue();function _y(t,e){let n=e?.separator??`
|
|
38
38
|
|
|
39
|
-
`,r=t.map(i=>typeof i=="string"?A(i):Y(i)),o=C(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:he("system_prompt"),initial:""}),s=te(o);return Object.assign(o,{dispose:s})}ne();var uy=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function cy(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return C([t.latest],([o],s)=>{if(o==null)return r;let i=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let a=s.store;i.type==="token"?(a.chunkCount+=1,a.charCount+=i.delta.length):i.type==="usage"&&(a.sawUsage=!0,a.usageTokens=kt(i.usage)+jt(i.usage));let d=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:d,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:he("cost_meter_extractor"),equals:uy})}ne();var ly=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.label!==o.label||r.pattern!==o.pattern||r.match!==o.match||r.position!==o.position)return!1}return!0};function py(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return C([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,d=s.store.scannedTo,u=Math.max(0,d-n),c=i.slice(u),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let h of c.matchAll(m)){let g=u+(h.index??0);g+h[0].length<=d||(a.push({label:f,pattern:p,match:h[0],position:g}),l=!0)}}return s.store.scannedTo=i.length,l?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:he("keyword_flag_extractor"),equals:ly})}ne();function fy(t,e,n){return C([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:he("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}ne();var my=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.startIndex!==o.startIndex||r.name!==o.name||r.raw!==o.raw)return!1}return!0};function gy(t,e){return C([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let d=o.indexOf("{",i);if(d===-1){r.store.scanFrom=o.length;break}let u=0,c=-1,l=!1;for(let f=d;f<o.length;f++){let m=o[f];if(l)m==="\\"&&f+1<o.length?f++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")u++;else if(m==="}"&&(u--,u===0)){c=f;break}}if(c===-1){r.store.scanFrom=d;break}let p=o.slice(d,c+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:p,startIndex:d}),a=!0)}catch{}i=c+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:he("tool_call_extractor"),equals:my})}ne();function hy(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),C(i,a=>{let d=a[0]??"";if(d.length===0)return"allow";let u=s?a[1]??0:e(d);return u>=o?"block":u>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}ne();function yy(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let d of e){let u=d.global?d:new RegExp(d.source,`${d.flags}g`);a=a.replace(u,c=>o(c,d))}return a}return C([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}Ae();ae();it();Me();ne();ve();ne();var fi=class extends Q{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=Ke([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=C([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:he("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(te(this.latest)),this.messageCount=C([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:he("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(te(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function xd(t,e){return new fi(t,e)}ne();It();function Rd(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,o=t.onError??"rescue",s=(i,a)=>{if(i===a)return!0;if(i.length!==a.length)return!1;for(let d=0;d<i.length;d++){let u=i[d],c=a[d];if(u?.id!==c?.id||u?.content!==c?.content)return!1}return!0};return ke(e,i=>{if(i==null||i.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let a=i.map(d=>by(d,n,r,o));return C(a,d=>d,{name:"toolExecution::batch",equals:s})})}function by(t,e,n,r){let o=St(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=C([o],([i])=>({id:t.id,content:typeof i=="string"?i:JSON.stringify(i)}));return r==="propagate"?s:ro(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}ae();ne();ve();var mi=class extends Q{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=je({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=C([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:he("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(te(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return z(o=>{let s=new AbortController,i;try{let d=r.handler(n,{signal:s.signal});i=vy(d,s.signal)}catch(d){return o.down([[I,d]]),()=>{s.abort()}}let a=i.subscribe(d=>{o.down(d)});return()=>{s.abort(),a()}},{name:`executeReactive::${e}`,meta:he("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function Sd(t,e){return new mi(t,e)}function vy(t,e){return kd(t)?t:t!=null&&typeof t.then=="function"?Xn(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?Br(t,{signal:e}):Xn(Promise.resolve(t),{signal:e})}var gi=class extends Q{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=xd(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=Sd(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let G of n.tools)this.tools.register(G);this.status=A("idle",{name:"status",describeKind:"state",meta:he("agent_status")}),this.add(this.status,{name:"status"}),this.turn=A(0,{name:"turn",describeKind:"state",meta:he("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=A(!1,{name:"aborted",describeKind:"state",meta:he("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(G=>{for(let B of G)B[0]===M&&(r=B[1])}),s=!1,i=this.aborted.subscribe(G=>{for(let B of G)B[0]===M&&(s=B[1])}),a=this.chat.messages.cache??[],d=this.chat.messages.subscribe(G=>{for(let B of G)B[0]===M&&(a=B[1])}),u=this.tools.schemas.cache??[],c=this.tools.schemas.subscribe(G=>{for(let B of G)B[0]===M&&(u=B[1])}),l=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,h=n.maxTokens,g=n.maxTurns??10,y=n.stopWhen,b=this.chat,v=this.tools,T=this.status,w=this.turn,x=this.aborted,k=U([T],(G,B,re)=>{if(So(G,re.prevData,0,"idle")!=="thinking"||s||r>=g){B.down([[q]]);return}if(a.length===0){B.down([[q]]);return}B.emit({messages:a,tools:u})},{name:"promptInput",describeKind:"derived",meta:he("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),S=ke(k,G=>{let B=new AbortController;return this._currentAbortController=B,s&&B.abort(new Error("agentLoop: aborted")),Y(l.invoke(G.messages,{tools:G.tools.length>0?G.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:B.signal}),{signal:B.signal})},{equals:()=>!1}),R=A(null,{name:"lastResponse",describeKind:"state",meta:he("agent_last_response")});this.lastResponse=R;let E=U([R,T],(G,B,re)=>{let pe=So(G,re.prevData,0,null);if(So(G,re.prevData,1,"idle")!=="acting"){B.down([[q]]);return}let ue=pe?.toolCalls;if(ue==null||ue.length===0){B.down([[q]]);return}B.emit(ue)},{name:"toolCallsRaw",describeKind:"derived",meta:he("agent_tool_calls_raw")}),_=n.interceptToolCalls?n.interceptToolCalls(E):E;this.toolCalls=_;let O=Rd({toolCalls:_,tools:v,retryCount:1});this.toolResults=O;let N=ge([S],([G])=>{if(s)return;let B=G,re=r+1,pe=B.toolCalls!=null&&B.toolCalls.length>0,ee=B.finishReason==="end_turn"&&(!B.toolCalls||B.toolCalls.length===0),ue=y?.(B)===!0,Ce=re>=g,Ye=ue||ee||!pe||Ce?"done":"acting";Z(()=>{R.emit(B),T.emit(Ye),w.emit(re),b.append("assistant",B.content,{toolCalls:B.toolCalls})})}),L=ge([O],([G])=>{if(s)return;let B=G;if(B.length===0)return;let re=r>=g?"done":"thinking";Z(()=>{T.emit(re);for(let pe of B)b.appendToolResult(pe.id,pe.content)})}),j=T.cache??"idle",$=T.subscribe(G=>{for(let B of G)B[0]===M&&(j=B[1])}),D=ge([x],([G])=>{G===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),j!=="done"&&T.emit("done"))}),K=te(N),F=te(L),H=te(D);this._terminalResult=U([T,R],(G,B,re)=>{let pe=So(G,re.prevData,0,"idle"),ee=So(G,re.prevData,1,null);if(pe==="done"){if(ee!=null){B.emit(ee);return}let ue=new Error("agentLoop: aborted");ue.name="AbortError",B.down([[I,ue]]);return}if(pe==="error"){B.down([[I,new Error("agentLoop: errored")]]);return}B.down([[q]])},{name:"terminalResult",describeKind:"derived",meta:he("agent_terminal_result")}),this.add(k,{name:"promptInput"}),this.add(S,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===E?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(E,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(O,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer($),this.addDisposer(d),this.addDisposer(c),this.addDisposer(K),this.addDisposer(F),this.addDisposer(H),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r;try{Z(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=as(this._terminalResult,{skipCurrent:!0});if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),r=()=>n.removeEventListener("abort",s)}return n?.aborted!==!0&&this.status.emit("thinking"),await o}finally{r?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function So(t,e,n,r){let o=t[n];if(o!=null&&o.length>0)return o[o.length-1];let s=e[n];return s!==void 0?s:r}function Ty(t,e){let n=new gi(t,e);return n.tagFactory("agentLoop",st(e)),n}it();ne();ve();function wy(t,e,n){let r=Y(t),o=n?.condition!=null?Y(n.condition):null,s=A(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return ke(r,a=>{if(a==null)return s;let d=A(a);return e(d)},{meta:we("handoff")});let i=C([r,o],([a,d])=>({v:a,open:d===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return ke(i,({v:a,open:d})=>{if(a==null)return s;if(!d)return A(a);let u=A(a);return e(u)},{meta:we("handoff")})}it();ne();ve();function ky(t,e,n){let r=Y(t),o=e.map(i=>Y(i)),s=[r,...o];return C(s,i=>{let a=i[0]??[],d=i.slice(1);return a.filter(u=>{for(let c of d)if(c!=null&&!c(u))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:{...he("tool_selector"),...we("toolSelector")},equals:(i,a)=>{let d=i,u=a;if(d.length!==u.length)return!1;for(let c=0;c<d.length;c++)if(d[c]!==u[c])return!1;return!0}})}function of(t){let e=t.thresholds??{};return n=>{let r=t.scoreFn(n);for(let o of Object.keys(e)){let s=e[o];if(s===void 0)continue;let i=r[o];if((Number.isFinite(i)?i:Number.NEGATIVE_INFINITY)<s)return!1}return!0}}function xy(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=of({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?r=>{if(!n(r))return!1;let o=t.scoreFn(r).structure;return Number.isFinite(o)&&o>0}:n}ae();it();ne();ve();ne();function sf(t,e,n,r){let o=n.name??r;return s=>{let i=A(s);return Sn(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function Nd(t,e){let n=e.maxExistingKeys??100,r=sf(t,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,s)=>{let i=n===Number.POSITIVE_INFINITY?[...s.keys()]:[...s.keys()].slice(0,n);return r({raw:o,existingKeys:i})}}function Ed(t,e){let n=sf(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}Ae();Re();ne();ve();var bi={};Se(bi,{collection:()=>Ey,cosineSimilarity:()=>yi,decay:()=>En,knowledgeGraph:()=>Od,lightCollection:()=>_d,vectorIndex:()=>Md});Re();Me();ne();ve();var Ry=1e9;function gt(t,e){return We("memory",t,e)}function fr(t,e){return t instanceof Oe?t:A(t,e?{name:e}:void 0)}function af(t,e){return(t-e)/Ry}function En(t,e,n,r=0){if(!Number.isFinite(t))return r;if(!Number.isFinite(e)||e<=0||!Number.isFinite(n)||n<=0)return Math.max(r,t);let o=t*Math.exp(-n*e);return Math.max(r,o)}function yi(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let a=0;a<n;a+=1){let d=t[a]??0,u=e[a]??0;r+=d*u,o+=d*d,s+=u*u}if(o===0||s===0)return 0;let i=r/Math.sqrt(o*s);return Number.isFinite(i)?i:0}function Sy(t,e){if(t===e)return!0;if(t==null||e==null||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n],o=e[n];if(r.id!==o.id||r.score!==o.score||r.meta!==o.meta)return!1}return!0}function _d(t={}){let e=t.maxSize;if(e!==void 0&&e<1)throw new RangeError("lightCollection: maxSize must be >= 1");let n=je({name:t.name,...e!==void 0?{maxSize:e}:{}}),r=n.entries,o=at({name:t.name?`${t.name}_events`:"events",retainedLimit:1024}),s=(f,m)=>{let h=V(),g=r.cache?.get(f);n.set(f,{id:f,value:m,createdAtNs:g?.createdAtNs??h,lastAccessNs:h})},i=f=>{n.has(f)&&n.delete(f)},a=()=>{n.size!==0&&n.clear()},d=nt(s,{audit:o,onSuccess:([f],m,h)=>({action:"upsert",id:f,t_ns:h.t_ns}),onFailure:(f,m,h)=>({action:"upsert",t_ns:h.t_ns,handlerVersion:{id:"lightCollection.upsert",version:1}})}),u=nt(i,{audit:o,onSuccess:([f],m,h)=>({action:"remove",id:f,t_ns:h.t_ns})}),c=nt(a,{audit:o,onSuccess:(f,m,h)=>({action:"clear",t_ns:h.t_ns})});function l(f){let m=fr(f,"id");return C([r,m],([h,g])=>h?.get(g),{describeKind:"derived",meta:gt("light_collection_item")})}function p(f){let m=fr(f,"id");return C([r,m],([h,g])=>h?.has(g)??!1,{describeKind:"derived",meta:gt("light_collection_has")})}return{entries:r,events:o,upsert:d,remove:u,clear:c,itemNode:l,hasNode:p}}function Ny(t,e){if(t===e)return!0;if(t==null||e==null||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n],o=e[n];if(r.id!==o.id||r.score!==o.score||r.lastAccessNs!==o.lastAccessNs||r.value!==o.value)return!1}return!0}function Ey(t,e={}){let n=e.maxSize,r=e.decayRate??0,o=e.minScore??0;if(n!==void 0&&n<1)throw new RangeError("collection: maxSize must be >= 1");let s=()=>1,i=e.score??s,a=i instanceof Oe?i:void 0,d=()=>a?a.cache??s:i,u=new Q(t),l=je({name:"items",...n!==void 0?{retention:{score:(O,N)=>En(N.baseScore,af(V(),N.lastAccessNs),r,o),maxSize:n}}:{}});u.add(l.entries,{name:"items"});let p;if(r>0){let O=e.refreshIntervalMs??Math.max(1,1e3*Math.LN2/(10*r)),N=Ze(O,{period:O});p=C([N],()=>V(),{name:"refresh_tick_ns",describeKind:"derived",initial:V(),meta:gt("clock")}),u.add(p,{name:"refresh_tick_ns"})}let f=[l.entries];p&&f.push(p),a&&f.push(a);let m=C(f,O=>{let N=O[0],L;if(p){let $=O[1];L=typeof $=="number"?$:V()}else L=V();if(!N||N.size===0)return[];let j=[];for(let $ of N.values())j.push({...$,score:En($.baseScore,af(L,$.lastAccessNs),r,o)});return j.sort(($,D)=>D.score-$.score||D.lastAccessNs-$.lastAccessNs),j},{name:"ranked",describeKind:"derived",equals:Ny,meta:gt("ranked")});u.add(m,{name:"ranked"});let h=C([l.entries],([O])=>(O??new Map).size,{name:"size",describeKind:"derived",initial:0,meta:gt("size")});u.add(h,{name:"size"}),u.addDisposer(te(h));let g=at({name:"events",retainedLimit:1024,graph:u}),y=Yt(u,"seq",0),b=(O,N,L)=>{let j=V(),$=l.get(O),D=L?.score??d()(N);l.set(O,{id:O,value:N,baseScore:D,createdAtNs:$?.createdAtNs??j,lastAccessNs:j})},v=O=>{l.has(O)&&l.delete(O)},T=()=>{l.size!==0&&l.clear()},w=()=>{let O=d(),N=l.entries.cache;if(!N||N.size===0)return;let L=[];for(let j of N.values())L.push([j.id,{...j,baseScore:O(j.value)}]);l.setMany(L)},x=nt(b,{audit:g,seq:y,onSuccess:([O],N,L)=>({action:"upsert",id:O,t_ns:L.t_ns,seq:L.seq})}),k=nt(v,{audit:g,seq:y,onSuccess:([O],N,L)=>({action:"remove",id:O,t_ns:L.t_ns,seq:L.seq})}),S=nt(T,{audit:g,seq:y,onSuccess:(O,N,L)=>({action:"clear",t_ns:L.t_ns,seq:L.seq})}),R=nt(w,{audit:g,seq:y,onSuccess:(O,N,L)=>({action:"rescore",t_ns:L.t_ns,seq:L.seq})});function E(O){let N=fr(O,"id");return C([l.entries,N],([L,j])=>L?.get(j),{describeKind:"derived",meta:gt("collection_item")})}return Object.assign(u,{events:g,items:l.entries,ranked:m,size:h,upsert:x,remove:k,clear:S,rescore:R,itemNode:E})}function Md(t={}){let e=t.backend??"flat",n=t.dimension,r=t.strictDimension??!0,o=t.maxSize,s=t.retentionScore,i;if(e==="hnsw"&&(i=t.hnswFactory?.(),!i))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let a=new Q(t.name??"vector_index"),d;function u(R){if(n!==void 0){if(R.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${R.length}`);return}if(r){if(d===void 0){d=R.length;return}if(R.length!==d)throw new RangeError(`vector dimension mismatch: inferred ${d} from first upsert, got ${R.length}. Pass \`strictDimension: false\` to opt into zero-pad behavior, or set an explicit \`dimension\`.`)}}let c=s??(R=>R.upsertedAtNs),l=!1,p=at({name:"events",retainedLimit:1024,graph:a}),f=Yt(a,"seq",0),m=je({name:"entries",...o!==void 0?{retention:{score:(R,E)=>c(E),maxSize:o,onArchive:R=>{l||(e==="hnsw"&&i.remove(R),p.append({action:"evict",id:R,t_ns:se(),seq:Jr(f)}))}}}:{}});if(a.add(m.entries,{name:"entries"}),a.addDisposer(te(m.entries)),i?.dispose){let R=i.dispose.bind(i);a.addDisposer(()=>R())}let h=(R,E,_)=>{u(E),e==="hnsw"&&i.upsert(R,E,_);let O=(()=>{if(_!==void 0)return _===null||typeof _!="object"?_:Array.isArray(_)?[..._]:{..._}})(),N={id:R,vector:[...E],...O!==void 0?{meta:O}:{},upsertedAtNs:V()};m.set(R,N)},g=R=>{m.has(R)&&(e==="hnsw"&&i.remove(R),m.delete(R))},y=()=>{if(m.size!==0){l=!0;try{m.clear(),e==="hnsw"&&i.clear()}finally{l=!1}d=void 0}},b=()=>{if(e!=="hnsw")return;let R=m.entries.cache;if(R){i.clear();for(let E of R.values())i.upsert(E.id,E.vector,E.meta)}},v=nt(h,{audit:p,freeze:!1,seq:f,onSuccess:([R],E,_)=>({action:"upsert",id:R,t_ns:_.t_ns,seq:_.seq})}),T=nt(g,{audit:p,seq:f,onSuccess:([R],E,_)=>({action:"remove",id:R,t_ns:_.t_ns,seq:_.seq})}),w=nt(y,{audit:p,seq:f,onSuccess:(R,E,_)=>({action:"clear",t_ns:_.t_ns,seq:_.seq})}),x=nt(b,{audit:p,seq:f,onSuccess:(R,E,_)=>({action:"reindex",t_ns:_.t_ns,seq:_.seq})});function k(R,E=5){let _=fr(E,"k");return C([m.entries,R,_],O=>{let N=O[0],L=O[1],j=O[2],$=Number.isFinite(j)?Math.max(0,Math.floor(j)):0;if(!N||N.size===0||$<=0)return[];if(L==null||L.length===0)return[];let D=n??(r?d:void 0);return D!==void 0&&L.length!==D?[]:e==="hnsw"?[...i.search(L,$)]:[...N.values()].map(F=>({id:F.id,score:yi(L,F.vector),...F.meta!==void 0?{meta:F.meta}:{}})).sort((F,H)=>H.score-F.score).slice(0,$)},{describeKind:"derived",equals:(O,N)=>Sy(O,N),meta:gt("vector_search")})}return Object.assign(a,{backend:e,events:p,entries:m.entries,upsert:v,remove:T,clear:w,reindex:x,searchNode:k})}var df="\0";function hi(t,e,n){return`${t}${df}${e}${df}${n}`}function uf(t,e){if(!t||t.size===0)return new Map;let n=new Map;for(let o of t.values()){let s=e==="from"?o.from:o.to,i=n.get(s);i||(i=[],n.set(s,i)),i.push(o)}let r=new Map;for(let[o,s]of n)r.set(o,Object.freeze(s));return r}function cf(t,e){if(t===e)return!0;if(t==null||e==null||t.size!==e.size)return!1;for(let[n,r]of t){let o=e.get(n);if(!o||r.length!==o.length)return!1;for(let s=0;s<r.length;s+=1){let i=r[s],a=o[s];if(i.from!==a.from||i.to!==a.to||i.relation!==a.relation||i.weight!==a.weight)return!1}}return!0}function Od(t,e={}){let n=e.orphanGC??"keep";if(e.entitiesMaxSize!==void 0&&e.entitiesMaxSize<1)throw new RangeError("knowledgeGraph: entitiesMaxSize must be >= 1");if(e.edgesMaxSize!==void 0&&e.edgesMaxSize<1)throw new RangeError("knowledgeGraph: edgesMaxSize must be >= 1");let r=new Q(t),o=je({name:"entities",...e.entitiesMaxSize!==void 0?{maxSize:e.entitiesMaxSize}:{}}),s=je({name:"edges",...e.edgesMaxSize!==void 0?{maxSize:e.edgesMaxSize}:{}});r.add(o.entries,{name:"entities"}),r.add(s.entries,{name:"edges"});let i=C([s.entries],([S])=>uf(S,"from"),{name:"adjacencyOut",describeKind:"derived",initial:new Map,equals:cf,meta:gt("adjacency_out")}),a=C([s.entries],([S])=>uf(S,"to"),{name:"adjacencyIn",describeKind:"derived",initial:new Map,equals:cf,meta:gt("adjacency_in")});r.add(i,{name:"adjacencyOut"}),r.add(a,{name:"adjacencyIn"}),r.addDisposer(te(i)),r.addDisposer(te(a));let d=C([o.entries],([S])=>(S??new Map).size,{name:"entityCount",describeKind:"derived",initial:0,meta:gt("entity_count")}),u=C([s.entries],([S])=>(S??new Map).size,{name:"edgeCount",describeKind:"derived",initial:0,meta:gt("edge_count")});r.add(d,{name:"entityCount"}),r.add(u,{name:"edgeCount"}),r.addDisposer(te(d)),r.addDisposer(te(u));let c=at({name:"events",retainedLimit:1024,graph:r}),l=Yt(r,"seq",0);function p(S){let R=i.cache,E=a.cache;return(R?.get(S)?.length??0)>0||(E?.get(S)?.length??0)>0}function f(S){if(n==="remove")for(let R of S)o.has(R)&&(p(R)||(o.delete(R),c.append({action:"orphanRemove",id:R,t_ns:se(),seq:Jr(l)})))}let m=(S,R)=>{o.set(S,R)},h=S=>{let R=s.entries.cache,E=new Set;if(R){let _=[];for(let[O,N]of R)(N.from===S||N.to===S)&&(_.push(O),N.from!==S&&E.add(N.from),N.to!==S&&E.add(N.to));_.length>0&&s.deleteMany(_)}o.has(S)&&o.delete(S),f([...E])},g=(S,R,E,_=1)=>{s.set(hi(S,R,E),{from:S,to:R,relation:E,weight:_})},y=(S,R,E)=>{if(E!==void 0)s.delete(hi(S,R,E));else{let _=s.entries.cache;if(!_)return;let O=[];for(let[N,L]of _)L.from===S&&L.to===R&&O.push(N);O.length>0&&s.deleteMany(O)}f([S,R])},b=nt(m,{audit:c,seq:l,onSuccess:([S],R,E)=>({action:"upsertEntity",id:S,t_ns:E.t_ns,seq:E.seq})}),v=nt(h,{audit:c,seq:l,onSuccess:([S],R,E)=>({action:"removeEntity",id:S,t_ns:E.t_ns,seq:E.seq})}),T=nt(g,{audit:c,seq:l,onSuccess:([S,R,E,_],O,N)=>({action:"link",from:S,to:R,relation:E,weight:_??1,t_ns:N.t_ns,seq:N.seq})}),w=nt(y,{audit:c,seq:l,onSuccess:([S,R,E],_,O)=>({action:"unlink",from:S,to:R,...E!==void 0?{relation:E}:{},t_ns:O.t_ns,seq:O.seq})});function x(S,R){let E=fr(S,"id"),_=R!==void 0?fr(R,"relation"):void 0;return C(_?[i,a,E,_]:[i,a,E],N=>{let L=N[0],j=N[1],$=N[2],D=_?N[3]:void 0,K=L.get($)??[],F=j.get($)??[],H=new Set,G=[];for(let B of K){let re=hi(B.from,B.to,B.relation);H.has(re)||D!==void 0&&B.relation!==D||(H.add(re),G.push(B))}for(let B of F){let re=hi(B.from,B.to,B.relation);H.has(re)||D!==void 0&&B.relation!==D||(H.add(re),G.push(B))}return G},{describeKind:"derived",equals:(N,L)=>{let j=N,$=L;if(j===$)return!0;if(j==null||$==null||j.length!==$.length)return!1;for(let D=0;D<j.length;D+=1){let K=j[D],F=$[D];if(K.from!==F.from||K.to!==F.to||K.relation!==F.relation||K.weight!==F.weight)return!1}return!0},meta:gt("related")})}return Object.assign(r,{events:c,entities:o.entries,edges:s.entries,adjacencyOut:i,adjacencyIn:a,entityCount:d,edgeCount:u,upsertEntity:b,removeEntity:v,link:T,unlink:w,relatedNode:x})}var Ad=Math.LN2/604800;function mr(t){return t instanceof Map?t:new Map}function Cd(t,e,n){let r=Md({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=ge([e.store.entries],([i])=>{let a=mr(i);for(let[d,u]of a){let c=n.embedFn(u);c&&r.upsert(d,c,u)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function Ld(t,e,n,r){let o=r.mountPath??n,s=Od(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let i=r.entityFn,d=ge([e.store.entries],([u])=>{let c=mr(u);for(let[l,p]of c){let f=i(l,p);if(f){for(let m of f.entities??[])s.upsertEntity(m.id,m.value);for(let m of f.relations??[])s.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return t.addDisposer(d),{kg:s,dispose:()=>d()}}function Id(t,e,n){let r=n.decayRate??Ad,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=_d({name:"permanent"});t.add(a.entries,{name:"permanent"});let d=new Set,u=b=>d.has(b)?"permanent":mr(e.store.entries.cache).has(b)?"active":"archived",c=(b,v)=>{d.add(b),a.upsert(b,v)},l=new Map,p=e.store.entries,f=n.context?Y(n.context):A(null),h=ge([p,f],([b,v])=>{let T=mr(b),w=V(),x=[],k=[];for(let[R,E]of T){if(l.has(R)||l.set(R,w),i(R,E)){k.push({key:R,value:E});continue}let _=n.score(E,v),O=l.get(R)??w,N=Number(w-O)/1e9;En(_,N,r)<s&&x.push(R)}for(let R of l.keys())T.has(R)||l.delete(R);for(let{key:R,value:E}of k)d.has(R)||c(R,E);let S=T.size-d.size;if(S>o){let R=[...T.entries()].filter(([_])=>!d.has(_)).map(([_,O])=>({key:_,score:n.score(O,v)})).sort((_,O)=>_.score-O.score),E=S-o;for(let _=0;_<E&&_<R.length;_++){let O=R[_].key;x.includes(O)||x.push(O)}}x.length>0&&Z(()=>{for(let R of x)e.store.delete(R)})}).subscribe(()=>{}),g=null;n.archiveTier&&(g=t.attachSnapshotStorage([n.archiveTier],n.archiveStorageOptions??{}));let y=()=>{h(),g?.dispose()};return t.addDisposer(y),{tiers:{permanent:a,activeEntries:p,archiveHandle:g,tierOf:u,markPermanent:c},dispose:y}}function _y(t,e){if(!t||!e)return 0;let n=Math.min(t.length,e.length),r=0;for(;r<n&&t[r]===e[r];)r++;return r}function Pd(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,d=o.contextWeight??0,u=o.context?Y(o.context):A(null),c=(g,y,b)=>{let v=new Map,T=[];if(n&&b.vector){let E=b.vector,_=n.entries.cache;if(_&&_.size>0&&s>0){T=[..._.values()].map(N=>({id:N.id,score:yi(E,N.vector),...N.meta!==void 0?{meta:N.meta}:{}})).sort((N,L)=>L.score-N.score).slice(0,s);for(let N of T){let L=g.get(N.id);L&&v.set(N.id,{value:L,sources:new Set(["vector"])})}}}let w=[];if(r){let E=r.adjacencyOut.cache,_=r.adjacencyIn.cache,O=[...b.entityIds??[],...v.keys()],N=new Set,L=O;for(let j=0;j<i;j++){let $=[];for(let D of L){if(N.has(D))continue;N.add(D);let K=E?.get(D)??[],F=_?.get(D)??[];for(let H of K){let G=H.to;if(!N.has(G)){$.push(G);let B=g.get(G);if(B){let re=v.get(G);re?re.sources.add("graph"):v.set(G,{value:B,sources:new Set(["graph"])}),w.push(G)}}}for(let H of F){let G=H.from;if(!N.has(G)){$.push(G);let B=g.get(G);if(B){let re=v.get(G);re?re.sources.add("graph"):v.set(G,{value:B,sources:new Set(["graph"])}),w.push(G)}}}}L=$}}for(let[E,_]of g)v.has(E)||v.set(E,{value:_,sources:new Set(["store"])});let x=b.context?.length??0,k=[];for(let[E,{value:_,sources:O}]of v){let N=o.contextOf?o.contextOf(_):void 0,L=o.score(_,y);if(d>0&&x>0){let $=_y(b.context,N);$>0&&(L=L*(1+d*$/x))}let j=N?{key:E,value:_,score:L,sources:[...O],context:N}:{key:E,value:_,score:L,sources:[...O]};k.push(j)}k.sort((E,_)=>_.score-E.score);let S=[],R=0;for(let E of k){let _=o.cost(E.value);if(R+_>a&&S.length>0)break;S.push(E),R+=_}return{packed:S,trace:{vectorCandidates:T,graphExpanded:w,ranked:k,packed:S}}},l=(g,y)=>{if(g===y)return!0;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b]!==y[b])return!1;return!0},p=A([],{name:"retrieval",describeKind:"state",meta:he("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=A(null,{name:"retrievalTrace",describeKind:"state",meta:he("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let y=mr(e.store.entries.cache),{packed:b,trace:v}=c(y,u.cache,g);return Z(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:g=>{let y=Y(g),b=C([e.store.entries,u,y],([w,x,k])=>{if(k==null)return{packed:[],trace:null};let S=mr(w),{packed:R,trace:E}=c(S,x,k);return{packed:R,trace:E}},{name:"retrievalReactive::result",describeKind:"derived",meta:he("retrieval_reactive_result"),initial:{packed:[],trace:null}}),T=ge([b],([w])=>{let x=w;Z(()=>{p.emit(x.packed),x.trace&&f.emit(x.trace)})}).subscribe(()=>{});return t.addDisposer(T),C([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:he("retrieval_reactive"),initial:[],equals:l})}}}function My(t,e,n){let r=new Q(t,n.graph);r.tagFactory("agentMemory",st(n));let o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=Nd(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,v)=>{let T=v.cache??new Map,w=v.subscribe(x=>{for(let k of x)k[0]===M&&(T=k[1])});return r.addDisposer(w),ke(b,x=>x==null?{upsert:[]}:o(x,T))},i=e;if(n.admissionFilter){let b=Y(e),v=n.admissionFilter;i=C([b],([T])=>{if(v(T))return T},{name:"admissionFilter",describeKind:"derived"})}let a;n.consolidateFn?a=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(a=Ed(n.consolidatePrompt,{adapter:n.adapter}));let d=n.consolidateTrigger;if(!d&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;d=Ze(b,{period:b})}let u={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:d},c=js(i,s,u);r.add(c.store.entries,{name:"store"}),r.add(c.compact,{name:"compact"}),r.add(c.size,{name:"size"});let l=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(l=Cd(r,c,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=Ld(r,c,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=Id(r,c,{...n.tiers,score:n.score,context:n.context}).tiers);let m=null,h=null,g=null,y=null;if(l||p){let b=Pd(r,c,l,p,{score:n.score,cost:n.cost,budget:n.budget,topK:n.retrieval?.topK,graphDepth:n.retrieval?.graphDepth,contextOf:n.contextOf,contextWeight:n.contextWeight,context:n.context});m=b.retrieval,h=b.retrievalTrace,g=b.retrieve,y=b.retrieveReactive}return Object.assign(r,{distillBundle:c,compact:c.compact,size:c.size,vectors:l,kg:p,memoryTiers:f,retrieval:m,retrievalTrace:h,retrieve:g,retrieveReactive:y})}function Oy(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
|
|
40
|
-
`,i=[],a=n?.sinceVersion;for(let[d,u]of Object.entries(r.nodes)){let c=u.meta??{},l=c.description,p=c.format;if(!l&&!p)continue;if(a!=null&&u.v!=null){let y=a.get(d);if(y!=null&&y.id===u.v.id&&u.v.version<=y.version)continue}let f=l??d,m=u.value,h=c.unit,g;p==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:p==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${h}`),i.push({path:d,description:f,formatted:g})}if(i.length===0)return"";if(o){let d=new Map,u=[];for(let l of i){let f=r.nodes[l.path].meta?.tags;if(f&&f.length>0){let m=f[0],h=d.get(m);h||(h=[],d.set(m,h)),h.push(l)}else u.push(l)}if(d.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let c=[];for(let[l,p]of[...d.entries()].sort((f,m)=>f[0].localeCompare(m[0])))c.push(`[${l}]${s}${p.map(f=>`- ${f.description}: ${f.formatted}`).join(s)}`);return u.length>0&&c.push(u.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),c.join(s+s)}return i.map(d=>`- ${d.description}: ${d.formatted}`).join(s)}ae();ne();
|
|
39
|
+
`,r=t.map(i=>typeof i=="string"?O(i):Y(i)),o=A(r,i=>i.filter(a=>a!=null&&a!=="").join(n),{name:e?.name??"systemPrompt",describeKind:"derived",meta:ve("system_prompt"),initial:""}),s=te(o);return Object.assign(o,{dispose:s})}ne();var My=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function Oy(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return A([t.latest],([o],s)=>{if(o==null)return r;let i=o;"chunkCount"in s.store||(s.store.chunkCount=0,s.store.charCount=0,s.store.usageTokens=0,s.store.sawUsage=!1);let a=s.store;i.type==="token"?(a.chunkCount+=1,a.charCount+=i.delta.length):i.type==="usage"&&(a.sawUsage=!0,a.usageTokens=Rt(i.usage)+Vt(i.usage));let d=a.sawUsage?a.usageTokens:Math.ceil(a.charCount/n);return{chunkCount:a.chunkCount,charCount:a.charCount,estimatedTokens:d,estimated:!a.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:r,meta:ve("cost_meter_extractor"),equals:My})}ne();var Ay=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.label!==o.label||r.pattern!==o.pattern||r.match!==o.match||r.position!==o.position)return!1}return!0};function Cy(t,e){let n=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>n)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${n}); raise the option or shorten the pattern.`);let r=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return A([t],([o],s)=>{if(o==null)return[];let i=o;"flags"in s.store||(s.store.flags=[],s.store.scannedTo=0);let a=s.store.flags,d=s.store.scannedTo,u=Math.max(0,d-n),c=i.slice(u),l=!1;for(let{pattern:p,label:f,compiled:m}of r){m.lastIndex=0;for(let h of c.matchAll(m)){let g=u+(h.index??0);g+h[0].length<=d||(a.push({label:f,pattern:p,match:h[0],position:g}),l=!0)}}return s.store.scannedTo=i.length,l?[...a]:a.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:ve("keyword_flag_extractor"),equals:Ay})}ne();function Ly(t,e,n){return A([t],([r])=>r==null?null:e(r),{name:n?.name??"extractor",describeKind:"derived",initial:null,meta:ve("stream_extractor"),...n?.equals?{equals:n.equals}:{}})}ne();var Iy=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.startIndex!==o.startIndex||r.name!==o.name||r.raw!==o.raw)return!1}return!0};function Dy(t,e){return A([t],([n],r)=>{if(n==null)return[];let o=n;"calls"in r.store||(r.store.calls=[],r.store.scanFrom=0);let s=r.store.calls,i=r.store.scanFrom,a=!1;for(;i<o.length;){let d=o.indexOf("{",i);if(d===-1){r.store.scanFrom=o.length;break}let u=0,c=-1,l=!1;for(let f=d;f<o.length;f++){let m=o[f];if(l)m==="\\"&&f+1<o.length?f++:m==='"'&&(l=!1);else if(m==='"')l=!0;else if(m==="{")u++;else if(m==="}"&&(u--,u===0)){c=f;break}}if(c===-1){r.store.scanFrom=d;break}let p=o.slice(d,c+1);try{let f=JSON.parse(p);typeof f.name=="string"&&f.arguments!=null&&typeof f.arguments=="object"&&(s.push({name:f.name,arguments:f.arguments,raw:p,startIndex:d}),a=!0)}catch{}i=c+1,r.store.scanFrom=i}return a?[...s]:s.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:ve("tool_call_extractor"),equals:Iy})}ne();function Py(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),A(i,a=>{let d=a[0]??"";if(d.length===0)return"allow";let u=s?a[1]??0:e(d);return u>=o?"block":u>=n?"review":"allow"},{name:r?.name??"content-gate",initial:"allow"})}ne();function Gy(t,e,n,r){let o=n??(()=>"[REDACTED]");function s(i){let a=i;for(let d of e){let u=d.global?d:new RegExp(d.source,`${d.flags}g`);a=a.replace(u,c=>o(c,d))}return a}return A([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}Ae();ae();et();Me();ne();ue();ne();ue();var Ri=class extends Q{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=qe([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=A([this.messages],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:ve("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(te(this.latest)),this.messageCount=A([this.messages],([r])=>r.length,{name:"messageCount",describeKind:"derived",meta:ve("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(te(this.messageCount))}append(e,n,r){this._log.append({role:e,content:n,...r})}appendToolResult(e,n){this._log.append({role:"tool",content:n,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function zd(t,e){return new Ri(t,e)}ne();Gt();function Hd(t){let{toolCalls:e,tools:n}=t,r=t.retryCount??1,o=t.onError??"rescue",s=(i,a)=>{if(i===a)return!0;if(i.length!==a.length)return!1;for(let d=0;d<i.length;d++){let u=i[d],c=a[d];if(u?.id!==c?.id||u?.content!==c?.content)return!1}return!0};return me(e,i=>{if(i==null||i.length===0)throw new Error("toolExecution: received an empty tool-call batch as DATA \u2014 callers must upstream-filter empty batches (emit RESOLVED) so switchMap is only dispatched for non-empty batches.");let a=i.map(d=>Fy(d,n,r,o));return A(a,d=>d,{name:"toolExecution::batch",equals:s})})}function Fy(t,e,n,r){let o=vt(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=A([o],([i])=>({id:t.id,content:typeof i=="string"?i:JSON.stringify(i)}));return r==="propagate"?s:uo(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}ae();ne();ue();var Si=class extends Q{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Ye({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=A([this.definitions],([r])=>[...(r??new Map).values()],{name:"schemas",describeKind:"derived",meta:ve("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(te(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,n){let r=this._bundle.get(e);if(!r)throw new Error(`toolRegistry: unknown tool "${e}"`);return z(o=>{let s=new AbortController,i;try{let d=r.handler(n,{signal:s.signal});i=$y(d,s.signal)}catch(d){return o.down([[L,d]]),()=>{s.abort()}}let a=i.subscribe(d=>{o.down(d)});return()=>{s.abort(),a()}},{name:`executeReactive::${e}`,meta:ve("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function Wd(t,e){return new Si(t,e)}function $y(t,e){return Bd(t)?t:t!=null&&typeof t.then=="function"?dr(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?Jr(t,{signal:e}):dr(Promise.resolve(t),{signal:e})}var Ni=class extends Q{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=zd(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=Wd(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let P of n.tools)this.tools.register(P);this.status=O("idle",{name:"status",describeKind:"state",meta:ve("agent_status")}),this.add(this.status,{name:"status"}),this.turn=O(0,{name:"turn",describeKind:"state",meta:ve("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=O(!1,{name:"aborted",describeKind:"state",meta:ve("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(P=>{for(let j of P)j[0]===_&&(r=j[1])}),s=!1,i=this.aborted.subscribe(P=>{for(let j of P)j[0]===_&&(s=j[1])}),a=this.chat.messages.cache??[],d=this.chat.messages.subscribe(P=>{for(let j of P)j[0]===_&&(a=j[1])}),u=this.tools.schemas.cache??[],c=this.tools.schemas.subscribe(P=>{for(let j of P)j[0]===_&&(u=j[1])}),l=n.adapter,p=n.systemPrompt,f=n.model,m=n.temperature,h=n.maxTokens,g=n.maxTurns??10,y=n.stopWhen,b=this.chat,v=this.tools,T=this.status,w=this.turn,k=this.aborted,R=U([T],(P,j,re)=>{if(Oo(P,re.prevData,0,"idle")!=="thinking"||s||r>=g){j.down([[q]]);return}if(a.length===0){j.down([[q]]);return}j.emit({messages:a,tools:u})},{name:"promptInput",describeKind:"derived",meta:ve("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),S=me(R,P=>{let j=new AbortController;return this._currentAbortController=j,s&&j.abort(new Error("agentLoop: aborted")),Y(l.invoke(P.messages,{tools:P.tools.length>0?P.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:j.signal}),{signal:j.signal})},{equals:()=>!1}),x=O(null,{name:"lastResponse",describeKind:"state",meta:ve("agent_last_response")});this.lastResponse=x;let N=U([x,T],(P,j,re)=>{let fe=Oo(P,re.prevData,0,null);if(Oo(P,re.prevData,1,"idle")!=="acting"){j.down([[q]]);return}let le=fe?.toolCalls;if(le==null||le.length===0){j.down([[q]]);return}j.emit(le)},{name:"toolCallsRaw",describeKind:"derived",meta:ve("agent_tool_calls_raw")}),E=n.interceptToolCalls?n.interceptToolCalls(N):N;this.toolCalls=E;let D=Hd({toolCalls:E,tools:v,retryCount:1});this.toolResults=D;let M=ye([S],([P])=>{if(s)return;let j=P,re=r+1,fe=j.toolCalls!=null&&j.toolCalls.length>0,ee=j.finishReason==="end_turn"&&(!j.toolCalls||j.toolCalls.length===0),le=y?.(j)===!0,Le=re>=g,Xe=le||ee||!fe||Le?"done":"acting";Z(()=>{x.emit(j),T.emit(Xe),w.emit(re),b.append("assistant",j.content,{toolCalls:j.toolCalls})})}),C=ye([D],([P])=>{if(s)return;let j=P;if(j.length===0)return;let re=r>=g?"done":"thinking";Z(()=>{T.emit(re);for(let fe of j)b.appendToolResult(fe.id,fe.content)})}),$=T.cache??"idle",B=T.subscribe(P=>{for(let j of P)j[0]===_&&($=j[1])}),G=ye([k],([P])=>{P===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),$!=="done"&&T.emit("done"))}),V=te(M),F=te(C),K=te(G);this._terminalResult=U([T,x],(P,j,re)=>{let fe=Oo(P,re.prevData,0,"idle"),ee=Oo(P,re.prevData,1,null);if(fe==="done"){if(ee!=null){j.emit(ee);return}let le=new Error("agentLoop: aborted");le.name="AbortError",j.down([[L,le]]);return}if(fe==="error"){j.down([[L,new Error("agentLoop: errored")]]);return}j.down([[q]])},{name:"terminalResult",describeKind:"derived",meta:ve("agent_terminal_result")}),this.add(R,{name:"promptInput"}),this.add(S,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===N?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(N,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(D,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(B),this.addDisposer(d),this.addDisposer(c),this.addDisposer(V),this.addDisposer(F),this.addDisposer(K),this._disposeRunWiring=()=>{}}async run(e,n){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let r;try{Z(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle"),this.lastResponse.emit(null)}),e!=null&&this.chat.append("user",e);let o=hs(this._terminalResult,{skipCurrent:!0});if(n!=null)if(n.aborted)this.aborted.emit(!0);else{let s=()=>this.aborted.emit(!0);n.addEventListener("abort",s,{once:!0}),r=()=>n.removeEventListener("abort",s)}return n?.aborted!==!0&&this.status.emit("thinking"),await o}finally{r?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function Oo(t,e,n,r){let o=t[n];if(o!=null&&o.length>0)return o[o.length-1];let s=e[n];return s!==void 0?s:r}function jy(t,e){let n=new Ni(t,e);return n.tagFactory("agentLoop",We(e)),n}et();ne();ue();function By(t,e,n){let r=Y(t),o=n?.condition!=null?Y(n.condition):null,s=O(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return me(r,a=>{if(a==null)return s;let d=O(a);return e(d)},{meta:be("handoff")});let i=A([r,o],([a,d])=>({v:a,open:d===!0}),{name:n?.name?`${n.name}::router`:"handoff::router",describeKind:"derived"});return me(i,({v:a,open:d})=>{if(a==null)return s;if(!d)return O(a);let u=O(a);return e(u)},{meta:be("handoff")})}et();ne();ue();function Vy(t,e,n){let r=Y(t),o=e.map(i=>Y(i)),s=[r,...o];return A(s,i=>{let a=i[0]??[],d=i.slice(1);return a.filter(u=>{for(let c of d)if(c!=null&&!c(u))return!1;return!0})},{name:n?.name??"tool-selector",describeKind:"derived",meta:{...ve("tool_selector"),...be("toolSelector")},equals:(i,a)=>{let d=i,u=a;if(d.length!==u.length)return!1;for(let c=0;c<d.length;c++)if(d[c]!==u[c])return!1;return!0}})}function Mf(t){let e=t.thresholds??{};return n=>{let r=t.scoreFn(n);for(let o of Object.keys(e)){let s=e[o];if(s===void 0)continue;let i=r[o];if((Number.isFinite(i)?i:Number.NEGATIVE_INFINITY)<s)return!1}return!0}}function Ky(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=Mf({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?r=>{if(!n(r))return!1;let o=t.scoreFn(r).structure;return Number.isFinite(o)&&o>0}:n}ae();et();ne();ue();Ae();Se();ne();ue();var Mi={};Ne(Mi,{collection:()=>Ud,cosineSimilarity:()=>_i,knowledgeGraph:()=>Yd,vectorIndex:()=>Jd});Se();Me();ne();at();ue();var qy=1e9;function ht(t,e){return xe("memory",t,e)}function Ao(t,e){return t instanceof Ce?t:O(t,e?{name:e}:void 0)}function Of(t,e){return(t-e)/qy}function _i(t,e){let n=Math.max(t.length,e.length),r=0,o=0,s=0;for(let a=0;a<n;a+=1){let d=t[a]??0,u=e[a]??0;r+=d*u,o+=d*d,s+=u*u}if(o===0||s===0)return 0;let i=r/Math.sqrt(o*s);return Number.isFinite(i)?i:0}function zy(t,e){if(t===e)return!0;if(t==null||e==null||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n],o=e[n];if(r.id!==o.id||r.score!==o.score||r.meta!==o.meta)return!1}return!0}function Hy(t,e){if(t===e)return!0;if(t==null||e==null||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){let r=t[n],o=e[n];if(r.id!==o.id||r.score!==o.score||r.lastAccessNs!==o.lastAccessNs||r.value!==o.value)return!1}return!0}function Ud(t,e={}){let n=e.maxSize,r=e.ranked??!0,o=r?e.decayRate??0:0,s=e.minScore??0;if(n!==void 0&&n<1)throw new RangeError("collection: maxSize must be >= 1");let i=()=>r?1:0,a=e.score??i,d=r&&a instanceof Ce?a:void 0,u=()=>d?d.cache??i:a,c=new Q(t),p=Ye({name:"items",...n!==void 0?{retention:{score:(M,C)=>r?Ot(C.baseScore,Of(H(),C.lastAccessNs),o,s):C.lastAccessNs,maxSize:n}}:{}});c.add(p.entries,{name:"items"});let f;if(r&&o>0){let M=e.refreshIntervalMs??Math.max(1,1e3*Math.LN2/(10*o)),C=tt(M,{period:M});f=A([C],()=>H(),{name:"refresh_tick_ns",describeKind:"derived",initial:H(),meta:ht("clock")}),c.add(f,{name:"refresh_tick_ns"})}let m;if(r){let M=[p.entries];f&&M.push(f),d&&M.push(d),m=A(M,C=>{let $=C[0],B;if(f){let V=C[1];B=typeof V=="number"?V:H()}else B=H();if(!$||$.size===0)return[];let G=[];for(let V of $.values())G.push({...V,score:Ot(V.baseScore,Of(B,V.lastAccessNs),o,s)});return G.sort((V,F)=>F.score-V.score||F.lastAccessNs-V.lastAccessNs),G},{name:"ranked",describeKind:"derived",equals:Hy,meta:ht("ranked")}),c.add(m,{name:"ranked"})}else m=O([],{name:"ranked",describeKind:"state",meta:ht("ranked_disabled")}),c.add(m,{name:"ranked"});let h=A([p.entries],([M])=>(M??new Map).size,{name:"size",describeKind:"derived",initial:0,meta:ht("size")});c.add(h,{name:"size"}),c.addDisposer(te(h));let g=ot({name:"events",retainedLimit:1024,graph:c}),y=_t(c,"seq",0),b=(M,C,$)=>{let B=H(),G=p.get(M),V=$?.score??u()(C);p.set(M,{id:M,value:C,baseScore:V,createdAtNs:G?.createdAtNs??B,lastAccessNs:B})},v=M=>{p.has(M)&&p.delete(M)},T=()=>{p.size!==0&&p.clear()},w=()=>{if(!r)return;let M=u(),C=p.entries.cache;if(!C||C.size===0)return;let $=[];for(let B of C.values())$.push([B.id,{...B,baseScore:M(B.value)}]);p.setMany($)},k=dt(b,{audit:g,seq:y,onSuccess:([M],C,$)=>({action:"upsert",id:M,t_ns:$.t_ns,seq:$.seq})}),R=dt(v,{audit:g,seq:y,onSuccess:([M],C,$)=>({action:"remove",id:M,t_ns:$.t_ns,seq:$.seq})}),S=dt(T,{audit:g,seq:y,onSuccess:(M,C,$)=>({action:"clear",t_ns:$.t_ns,seq:$.seq})}),x=dt(w,{audit:g,seq:y,onSuccess:(M,C,$)=>({action:"rescore",t_ns:$.t_ns,seq:$.seq})});function N(M){let C=Ao(M,"id");return A([p.entries,C],([$,B])=>$?.get(B),{describeKind:"derived",meta:ht("collection_item")})}function E(M){let C=Ao(M,"id");return A([p.entries,C],([$,B])=>$?.has(B)??!1,{describeKind:"derived",meta:ht("collection_has")})}return Object.assign(c,{events:g,items:p.entries,ranked:m,size:h,upsert:k,remove:R,clear:S,rescore:x,itemNode:N,hasNode:E})}function Jd(t={}){let e=t.backend??"flat",n=t.dimension,r=t.strictDimension??!0,o=t.maxSize,s=t.retentionScore,i;if(e==="hnsw"&&(i=t.hnswFactory?.(),!i))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let a=new Q(t.name??"vector_index"),d;function u(x){if(n!==void 0){if(x.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${x.length}`);return}if(r){if(d===void 0){d=x.length;return}if(x.length!==d)throw new RangeError(`vector dimension mismatch: inferred ${d} from first upsert, got ${x.length}. Pass \`strictDimension: false\` to opt into zero-pad behavior, or set an explicit \`dimension\`.`)}}let c=s??(x=>x.upsertedAtNs),l=!1,p=ot({name:"events",retainedLimit:1024,graph:a}),f=_t(a,"seq",0),m=Ye({name:"entries",...o!==void 0?{retention:{score:(x,N)=>c(N),maxSize:o,onArchive:x=>{l||(e==="hnsw"&&i.remove(x),p.append({action:"evict",id:x,t_ns:oe(),seq:An(f)}))}}}:{}});if(a.add(m.entries,{name:"entries"}),a.addDisposer(te(m.entries)),i?.dispose){let x=i.dispose.bind(i);a.addDisposer(()=>x())}let h=(x,N,E)=>{u(N),e==="hnsw"&&i.upsert(x,N,E);let D=(()=>{if(E!==void 0)return E===null||typeof E!="object"?E:Array.isArray(E)?[...E]:{...E}})(),M={id:x,vector:[...N],...D!==void 0?{meta:D}:{},upsertedAtNs:H()};m.set(x,M)},g=x=>{m.has(x)&&(e==="hnsw"&&i.remove(x),m.delete(x))},y=()=>{if(m.size!==0){l=!0;try{m.clear(),e==="hnsw"&&i.clear()}finally{l=!1}d=void 0}},b=()=>{if(e!=="hnsw")return;let x=m.entries.cache;if(x){i.clear();for(let N of x.values())i.upsert(N.id,N.vector,N.meta)}},v=dt(h,{audit:p,freeze:!1,seq:f,onSuccess:([x],N,E)=>({action:"upsert",id:x,t_ns:E.t_ns,seq:E.seq})}),T=dt(g,{audit:p,seq:f,onSuccess:([x],N,E)=>({action:"remove",id:x,t_ns:E.t_ns,seq:E.seq})}),w=dt(y,{audit:p,seq:f,onSuccess:(x,N,E)=>({action:"clear",t_ns:E.t_ns,seq:E.seq})}),k=dt(b,{audit:p,seq:f,onSuccess:(x,N,E)=>({action:"reindex",t_ns:E.t_ns,seq:E.seq})});function R(x,N=5){let E=Ao(N,"k");return A([m.entries,x,E],D=>{let M=D[0],C=D[1],$=D[2],B=Number.isFinite($)?Math.max(0,Math.floor($)):0;if(!M||M.size===0||B<=0)return[];if(C==null||C.length===0)return[];let G=n??(r?d:void 0);return G!==void 0&&C.length!==G?[]:e==="hnsw"?[...i.search(C,B)]:[...M.values()].map(F=>({id:F.id,score:_i(C,F.vector),...F.meta!==void 0?{meta:F.meta}:{}})).sort((F,K)=>K.score-F.score).slice(0,B)},{describeKind:"derived",equals:(D,M)=>zy(D,M),meta:ht("vector_search")})}return Object.assign(a,{backend:e,events:p,entries:m.entries,upsert:v,remove:T,clear:w,reindex:k,searchNode:R})}var Af="\0";function Ei(t,e,n){return`${t}${Af}${e}${Af}${n}`}function Cf(t,e){if(!t||t.size===0)return new Map;let n=new Map;for(let o of t.values()){let s=e==="from"?o.from:o.to,i=n.get(s);i||(i=[],n.set(s,i)),i.push(o)}let r=new Map;for(let[o,s]of n)r.set(o,Object.freeze(s));return r}function Lf(t,e){if(t===e)return!0;if(t==null||e==null||t.size!==e.size)return!1;for(let[n,r]of t){let o=e.get(n);if(!o||r.length!==o.length)return!1;for(let s=0;s<r.length;s+=1){let i=r[s],a=o[s];if(i.from!==a.from||i.to!==a.to||i.relation!==a.relation||i.weight!==a.weight)return!1}}return!0}function Yd(t,e={}){let n=e.orphanGC??"keep";if(e.entitiesMaxSize!==void 0&&e.entitiesMaxSize<1)throw new RangeError("knowledgeGraph: entitiesMaxSize must be >= 1");if(e.edgesMaxSize!==void 0&&e.edgesMaxSize<1)throw new RangeError("knowledgeGraph: edgesMaxSize must be >= 1");let r=new Q(t),o=Ye({name:"entities",...e.entitiesMaxSize!==void 0?{maxSize:e.entitiesMaxSize}:{}}),s=Ye({name:"edges",...e.edgesMaxSize!==void 0?{maxSize:e.edgesMaxSize}:{}});r.add(o.entries,{name:"entities"}),r.add(s.entries,{name:"edges"});let i=A([s.entries],([S])=>Cf(S,"from"),{name:"adjacencyOut",describeKind:"derived",initial:new Map,equals:Lf,meta:ht("adjacency_out")}),a=A([s.entries],([S])=>Cf(S,"to"),{name:"adjacencyIn",describeKind:"derived",initial:new Map,equals:Lf,meta:ht("adjacency_in")});r.add(i,{name:"adjacencyOut"}),r.add(a,{name:"adjacencyIn"}),r.addDisposer(te(i)),r.addDisposer(te(a));let d=A([o.entries],([S])=>(S??new Map).size,{name:"entityCount",describeKind:"derived",initial:0,meta:ht("entity_count")}),u=A([s.entries],([S])=>(S??new Map).size,{name:"edgeCount",describeKind:"derived",initial:0,meta:ht("edge_count")});r.add(d,{name:"entityCount"}),r.add(u,{name:"edgeCount"}),r.addDisposer(te(d)),r.addDisposer(te(u));let c=ot({name:"events",retainedLimit:1024,graph:r}),l=_t(r,"seq",0);function p(S){let x=i.cache,N=a.cache;return(x?.get(S)?.length??0)>0||(N?.get(S)?.length??0)>0}function f(S){if(n==="remove")for(let x of S)o.has(x)&&(p(x)||(o.delete(x),c.append({action:"orphanRemove",id:x,t_ns:oe(),seq:An(l)})))}let m=(S,x)=>{o.set(S,x)},h=S=>{let x=s.entries.cache,N=new Set;if(x){let E=[];for(let[D,M]of x)(M.from===S||M.to===S)&&(E.push(D),M.from!==S&&N.add(M.from),M.to!==S&&N.add(M.to));E.length>0&&s.deleteMany(E)}o.has(S)&&o.delete(S),f([...N])},g=(S,x,N,E=1)=>{s.set(Ei(S,x,N),{from:S,to:x,relation:N,weight:E})},y=(S,x,N)=>{if(N!==void 0)s.delete(Ei(S,x,N));else{let E=s.entries.cache;if(!E)return;let D=[];for(let[M,C]of E)C.from===S&&C.to===x&&D.push(M);D.length>0&&s.deleteMany(D)}f([S,x])},b=dt(m,{audit:c,seq:l,onSuccess:([S],x,N)=>({action:"upsertEntity",id:S,t_ns:N.t_ns,seq:N.seq})}),v=dt(h,{audit:c,seq:l,onSuccess:([S],x,N)=>({action:"removeEntity",id:S,t_ns:N.t_ns,seq:N.seq})}),T=dt(g,{audit:c,seq:l,onSuccess:([S,x,N,E],D,M)=>({action:"link",from:S,to:x,relation:N,weight:E??1,t_ns:M.t_ns,seq:M.seq})}),w=dt(y,{audit:c,seq:l,onSuccess:([S,x,N],E,D)=>({action:"unlink",from:S,to:x,...N!==void 0?{relation:N}:{},t_ns:D.t_ns,seq:D.seq})});function k(S,x){let N=Ao(S,"id"),E=x!==void 0?Ao(x,"relation"):void 0;return A(E?[i,a,N,E]:[i,a,N],M=>{let C=M[0],$=M[1],B=M[2],G=E?M[3]:void 0,V=C.get(B)??[],F=$.get(B)??[],K=new Set,P=[];for(let j of V){let re=Ei(j.from,j.to,j.relation);K.has(re)||G!==void 0&&j.relation!==G||(K.add(re),P.push(j))}for(let j of F){let re=Ei(j.from,j.to,j.relation);K.has(re)||G!==void 0&&j.relation!==G||(K.add(re),P.push(j))}return P},{describeKind:"derived",equals:(M,C)=>{let $=M,B=C;if($===B)return!0;if($==null||B==null||$.length!==B.length)return!1;for(let G=0;G<$.length;G+=1){let V=$[G],F=B[G];if(V.from!==F.from||V.to!==F.to||V.relation!==F.relation||V.weight!==F.weight)return!1}return!0},meta:ht("related")})}return Object.assign(r,{events:c,entities:o.entries,edges:s.entries,adjacencyOut:i,adjacencyIn:a,entityCount:d,edgeCount:u,upsertEntity:b,removeEntity:v,link:T,unlink:w,relatedNode:k})}function Qd(t,e,n){let r=Jd({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=ye([e.store.entries],([i])=>{let a=i??new Map;for(let[d,u]of a){let c=n.embedFn(u);c&&r.upsert(d,c,u)}}).subscribe(()=>{});return t.addDisposer(s),{vectors:r,dispose:()=>s()}}function Xd(t,e,n,r){let o=r.mountPath??n,s=Yd(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let i=r.entityFn,d=ye([e.store.entries],([u])=>{let c=u??new Map;for(let[l,p]of c){let f=i(l,p);if(f){for(let m of f.entities??[])s.upsertEntity(m.id,m.value);for(let m of f.relations??[])s.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return t.addDisposer(d),{kg:s,dispose:()=>d()}}function Zd(t,e,n){let r=n.decayRate??oi,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=Ud("permanent",{ranked:!1});t.mount("permanent",a);let d=new Set,u=b=>d.has(b)?"permanent":(e.store.entries.cache??new Map).has(b)?"active":"archived",c=(b,v)=>{d.add(b),a.upsert(b,v)},l=new Map,p=e.store.entries,f=n.context?Y(n.context):O(null),h=ye([p,f],([b,v])=>{let T=b??new Map,w=H(),k=[],R=[];for(let[x,N]of T){if(l.has(x)||l.set(x,w),i(x,N)){R.push({key:x,value:N});continue}let E=n.score(N,v),D=l.get(x)??w,M=Number(w-D)/1e9;Ot(E,M,r)<s&&k.push(x)}for(let x of l.keys())T.has(x)||l.delete(x);for(let{key:x,value:N}of R)d.has(x)||c(x,N);let S=T.size-d.size;if(S>o){let x=[...T.entries()].filter(([E])=>!d.has(E)).map(([E,D])=>({key:E,score:n.score(D,v)})).sort((E,D)=>E.score-D.score),N=S-o;for(let E=0;E<N&&E<x.length;E++){let D=x[E].key;k.includes(D)||k.push(D)}}k.length>0&&Z(()=>{for(let x of k)e.store.delete(x)})}).subscribe(()=>{}),g=null;n.archiveTier&&(g=t.attachSnapshotStorage([n.archiveTier],n.archiveStorageOptions??{}));let y=()=>{h(),g?.dispose()};return t.addDisposer(y),{tiers:{permanent:a,activeEntries:p,archiveHandle:g,tierOf:u,markPermanent:c},dispose:y}}function Wy(t,e){if(!t||!e)return 0;let n=Math.min(t.length,e.length),r=0;for(;r<n&&t[r]===e[r];)r++;return r}function eu(t,e,n,r,o){let s=o.topK??20,i=o.graphDepth??1,a=o.budget??2e3,d=o.contextWeight??0,u=o.context?Y(o.context):O(null),c=(g,y,b)=>{let v=new Map,T=[];if(n&&b.vector){let N=b.vector,E=n.entries.cache;if(E&&E.size>0&&s>0){T=[...E.values()].map(M=>({id:M.id,score:_i(N,M.vector),...M.meta!==void 0?{meta:M.meta}:{}})).sort((M,C)=>C.score-M.score).slice(0,s);for(let M of T){let C=g.get(M.id);C&&v.set(M.id,{value:C,sources:new Set(["vector"])})}}}let w=[];if(r){let N=r.adjacencyOut.cache,E=r.adjacencyIn.cache,D=[...b.entityIds??[],...v.keys()],M=new Set,C=D;for(let $=0;$<i;$++){let B=[];for(let G of C){if(M.has(G))continue;M.add(G);let V=N?.get(G)??[],F=E?.get(G)??[];for(let K of V){let P=K.to;if(!M.has(P)){B.push(P);let j=g.get(P);if(j){let re=v.get(P);re?re.sources.add("graph"):v.set(P,{value:j,sources:new Set(["graph"])}),w.push(P)}}}for(let K of F){let P=K.from;if(!M.has(P)){B.push(P);let j=g.get(P);if(j){let re=v.get(P);re?re.sources.add("graph"):v.set(P,{value:j,sources:new Set(["graph"])}),w.push(P)}}}}C=B}}for(let[N,E]of g)v.has(N)||v.set(N,{value:E,sources:new Set(["store"])});let k=b.context?.length??0,R=[];for(let[N,{value:E,sources:D}]of v){let M=o.contextOf?o.contextOf(E):void 0,C=o.score(E,y);if(d>0&&k>0){let B=Wy(b.context,M);B>0&&(C=C*(1+d*B/k))}let $=M?{key:N,value:E,score:C,sources:[...D],context:M}:{key:N,value:E,score:C,sources:[...D]};R.push($)}R.sort((N,E)=>E.score-N.score);let S=[],x=0;for(let N of R){let E=o.cost(N.value);if(x+E>a&&S.length>0)break;S.push(N),x+=E}return{packed:S,trace:{vectorCandidates:T,graphExpanded:w,ranked:R,packed:S}}},l=(g,y)=>{if(g===y)return!0;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b]!==y[b])return!1;return!0},p=O([],{name:"retrieval",describeKind:"state",meta:ve("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=O(null,{name:"retrievalTrace",describeKind:"state",meta:ve("retrieval_trace")});return t.add(f,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:f,retrieve:g=>{let y=e.store.entries.cache??new Map,{packed:b,trace:v}=c(y,u.cache,g);return Z(()=>{p.emit(b),f.emit(v)}),b},retrieveReactive:g=>{let y=Y(g),b=A([e.store.entries,u,y],([w,k,R])=>{if(R==null)return{packed:[],trace:null};let S=w??new Map,{packed:x,trace:N}=c(S,k,R);return{packed:x,trace:N}},{name:"retrievalReactive::result",describeKind:"derived",meta:ve("retrieval_reactive_result"),initial:{packed:[],trace:null}}),T=ye([b],([w])=>{let k=w;Z(()=>{p.emit(k.packed),k.trace&&f.emit(k.trace)})}).subscribe(()=>{});return t.addDisposer(T),A([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:ve("retrieval_reactive"),initial:[],equals:l})}}}function Uy(t,e,n){let r=new Q(t,n.graph);r.tagFactory("agentMemory",We(n));let o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=Kd(n.extractPrompt,{adapter:n.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,v)=>{let T=v.cache??new Map,w=v.subscribe(k=>{for(let R of k)R[0]===_&&(T=R[1])});return r.addDisposer(w),me(b,k=>k==null?{upsert:[]}:o(k,T))},i=e;if(n.admissionFilter){let b=Y(e),v=n.admissionFilter;i=A([b],([T])=>{if(v(T))return T},{name:"admissionFilter",describeKind:"derived"})}let a;n.consolidateFn?a=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(a=qd(n.consolidatePrompt,{adapter:n.adapter}));let d=n.consolidateTrigger;if(!d&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;d=tt(b,{period:b})}let u={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:d},c=Ys(i,s,u);r.add(c.store.entries,{name:"store"}),r.add(c.compact,{name:"compact"}),r.add(c.size,{name:"size"});let l=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(l=Qd(r,c,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=Xd(r,c,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=Zd(r,c,{...n.tiers,score:n.score,context:n.context}).tiers);let m=null,h=null,g=null,y=null;if(l||p){let b=eu(r,c,l,p,{score:n.score,cost:n.cost,budget:n.budget,topK:n.retrieval?.topK,graphDepth:n.retrieval?.graphDepth,contextOf:n.contextOf,contextWeight:n.contextWeight,context:n.context});m=b.retrieval,h=b.retrievalTrace,g=b.retrieve,y=b.retrieveReactive}return Object.assign(r,{distillBundle:c,compact:c.compact,size:c.size,vectors:l,kg:p,memoryTiers:f,retrieval:m,retrievalTrace:h,retrieve:g,retrieveReactive:y})}function Jy(t,e,n){let r=t.describe({actor:e,detail:"full"}),o=n?.groupByTags??!0,s=n?.separator??`
|
|
40
|
+
`,i=[],a=n?.sinceVersion;for(let[d,u]of Object.entries(r.nodes)){let c=u.meta??{},l=c.description,p=c.format;if(!l&&!p)continue;if(a!=null&&u.v!=null){let y=a.get(d);if(y!=null&&y.id===u.v.id&&u.v.version<=y.version)continue}let f=l??d,m=u.value,h=c.unit,g;p==="currency"&&typeof m=="number"?g=`$${m.toFixed(2)}`:p==="percentage"&&typeof m=="number"?g=`${(m*100).toFixed(1)}%`:m==null?g="(no value)":g=String(m),h&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${h}`),i.push({path:d,description:f,formatted:g})}if(i.length===0)return"";if(o){let d=new Map,u=[];for(let l of i){let f=r.nodes[l.path].meta?.tags;if(f&&f.length>0){let m=f[0],h=d.get(m);h||(h=[],d.set(m,h)),h.push(l)}else u.push(l)}if(d.size===0)return i.map(l=>`- ${l.description}: ${l.formatted}`).join(s);let c=[];for(let[l,p]of[...d.entries()].sort((f,m)=>f[0].localeCompare(m[0])))c.push(`[${l}]${s}${p.map(f=>`- ${f.description}: ${f.formatted}`).join(s)}`);return u.length>0&&c.push(u.map(l=>`- ${l.description}: ${l.formatted}`).join(s)),c.join(s+s)}return i.map(d=>`- ${d.description}: ${d.formatted}`).join(s)}ae();ne();ue();var Li={};Ne(Li,{compileSpec:()=>Do,decompileSpec:()=>nb,extractFnFactory:()=>Pf,extractSourceFactory:()=>Gf,generateCatalogPrompt:()=>Ff,isRichFnEntry:()=>Lo,isRichSourceEntry:()=>Ci,llmCompose:()=>ob,llmRefine:()=>Bf,specDiff:()=>rb,validateSpec:()=>xr,validateSpecAgainstCatalog:()=>Io});ne();var Oi={};Ne(Oi,{feedback:()=>dn,funnel:()=>Yy,scorer:()=>Co});Ae();ae();Me();ne();at();ue();function tu(t,e){return xe("reduction",t,e)}function Yy(t,e,n,r){if(e.length===0)throw new RangeError("funnel requires at least one source");if(n.length===0)throw new RangeError("funnel requires at least one stage");let o=new Q(t,r),s=e.length===1?e[0]:Mt(...e);o.add(s,{name:"merged"});let i="merged";for(let a=0;a<n.length;a++){let d=n[a],u=new Q(d.name);d.build(u);try{u.resolve("input")}catch{throw new Error(`funnel stage "${d.name}" must define an "input" node`)}try{u.resolve("output")}catch{throw new Error(`funnel stage "${d.name}" must define an "output" node`)}o.mount(d.name,u);let c=o.resolve(i),l=`${d.name}::input`,p=o.resolve(l),f=`__bridge_${i}\u2192${d.name}_input`,m=ye([c],([h])=>{p.emit(h)},{name:f});o.add(m,{name:f}),o.addDisposer(te(m)),i=`${d.name}::output`}return o}function dn(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=O(0,{meta:tu("feedback_counter",{maxIterations:o,feedbackFrom:e,feedbackTo:n})});t.add(i,{name:s});let a=t.resolve(e),d=t.resolve(n),u=`__feedback_effect_${e}`,c=U([],(l,p)=>{let f=a.subscribe(m=>{for(let h of m){let g=h[0];if(g===_){let y=h[1];if(y==null)return;Z(()=>{On(i,o)&&d.emit(y)})}else if(g===I||g===L){let y=g===L&&h.length>1?[L,h[1]]:[g];i.down([y])}}});return()=>f()},{name:u,describeKind:"effect",meta:{...tu("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(c,{name:u}),t.addDisposer(te(c)),t}function Co(t,e,n){if(t.length===0)throw new RangeError("scorer requires at least one source");if(t.length!==e.length)throw new RangeError("scorer requires the same number of sources and weights");let r=[...t,...e],o=t.length,s=n?.scoreFns;return A(r,i=>{let a=i.slice(0,o),d=i.slice(o),u=[],c=0;for(let l=0;l<o;l++){let p=a[l]??0,f=d[l]??0,h=(s?.[l]?s[l](p):p)*f;u.push(h),c+=h}return{value:a,score:c,breakdown:u}},{...n?{equals:n.equals,resubscribable:n.resubscribable,resetOnTeardown:n.resetOnTeardown}:{},describeKind:"derived",meta:tu("scorer",n?.meta)})}function un(t){let e=t.meta?.factory;return typeof e=="string"?e:void 0}function cn(t){let e=t.meta?.factoryArgs;return e!=null&&typeof e=="object"?e:{}}function If(t){let e=cn(t);return"initial"in e?e.initial:t.value}function Lo(t){return typeof t=="object"&&t!==null&&"factory"in t}function Ci(t){return typeof t=="object"&&t!==null&&"factory"in t}function Pf(t){return Lo(t)?t.factory:t}function Gf(t){return Ci(t)?t.factory:t}function Ff(t){let e=[];if(t.fns){let n=new Map;for(let[r,o]of Object.entries(t.fns)){let s=Lo(o)?o.tags?.[0]??"Other":"Other";n.has(s)||n.set(s,[]),n.get(s).push(Qy(r,o))}for(let[r,o]of n)e.push(`${r}:
|
|
41
41
|
${o.join(`
|
|
42
|
-
`)}`)}if(t.sources){let n=[];for(let[r,o]of Object.entries(t.sources))n.push(
|
|
42
|
+
`)}`)}if(t.sources){let n=[];for(let[r,o]of Object.entries(t.sources))n.push(Xy(r,o));n.length>0&&e.push(`Sources:
|
|
43
43
|
${n.join(`
|
|
44
44
|
`)}`)}return e.join(`
|
|
45
45
|
|
|
46
|
-
`)}function
|
|
46
|
+
`)}function Qy(t,e){if(!Lo(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.enum&&(i+=` (${s.enum.join("|")})`),s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function Xy(t,e){if(!Ci(e))return`- ${t}`;let n=`- ${t}: ${e.description}`;if(e.configSchema){let r=Object.entries(e.configSchema).map(([o,s])=>{let i=`${o}: ${s.type}`;return s.required===!1&&(i+="?"),i});n+=`. Config: { ${r.join(", ")} }`}return n}function Io(t,e){let n=[],r=new Set(Object.keys(e.fns??{})),o=new Set(Object.keys(e.sources??{}));for(let[s,i]of Object.entries(t.nodes)){if(i.type==="template")continue;let a=i,d=un(a);if(d==null)continue;let u=a.type==="producer";if(a.type==="state"&&d==="state")continue;if(u){let l=o.has(d),p=r.has(d);if(!l&&!p&&(o.size>0||r.size>0)){let f=Ai(d,o)??Ai(d,r);n.push(`Node "${s}": source "${d}" not found in catalog`+(f?`. Did you mean "${f}"?`:""))}}else if(r.size>0&&!r.has(d))if(o.has(d))n.push(`Node "${s}": fn "${d}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...r].join(", ")}`);else{let l=Ai(d,r);n.push(`Node "${s}": fn "${d}" not found in catalog`+(l?`. Did you mean "${l}"?`:""))}let c=cn(a);if(!u&&e.fns?.[d]){let l=e.fns[d];if(Lo(l)&&l.configSchema){for(let[p,f]of Object.entries(l.configSchema))if(f.required!==!1&&!(p in c)&&n.push(`Node "${s}": config missing required field "${p}"`),p in c&&f.enum){let m=c[p];f.enum.includes(m)||n.push(`Node "${s}": config.${p} = ${JSON.stringify(m)}, expected one of: ${f.enum.join(", ")}`)}}}if(u&&e.sources?.[d]){let l=e.sources[d];if(Ci(l)&&l.configSchema){for(let[p,f]of Object.entries(l.configSchema))if(f.required!==!1&&!(p in c)&&n.push(`Node "${s}": config missing required field "${p}"`),p in c&&f.enum){let m=c[p];f.enum.includes(m)||n.push(`Node "${s}": config.${p} = ${JSON.stringify(m)}, expected one of: ${f.enum.join(", ")}`)}}}}if(t.templates)for(let[s,i]of Object.entries(t.templates))for(let[a,d]of Object.entries(i.nodes)){let u=un(d);if(u!=null&&!(d.type==="state"&&u==="state")&&d.type!=="producer"&&r.size>0&&!r.has(u)){let c=Ai(u,r);n.push(`Template "${s}" node "${a}": fn "${u}" not found in catalog`+(c?`. Did you mean "${c}"?`:""))}}return{valid:n.length===0,errors:n,warnings:[]}}function Ai(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=Zy(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function Zy(t,e){let n=t.length,r=e.length,o=Array.from({length:n+1},(s,i)=>Array.from({length:r+1},(a,d)=>i===0?d:d===0?i:0));for(let s=1;s<=n;s++)for(let i=1;i<=r;i++)o[s][i]=t[s-1]===e[i-1]?o[s-1][i-1]:1+Math.min(o[s-1][i],o[s][i-1],o[s-1][i-1]);return o[n][r]}var Df=new Set(["state","producer","derived","effect","operator","template"]),eb=new Set(["state","producer","derived","effect","operator"]);function xr(t){let e=[],n=[];if(t==null||typeof t!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"],warnings:n};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,warnings:n};let o=new Set(Object.keys(r.nodes)),s=new Map,i=new Map;if(r.templates!=null&&typeof r.templates=="object"&&!Array.isArray(r.templates)){for(let[a,d]of Object.entries(r.templates))if(d!=null&&typeof d=="object"){let u=d;i.set(a,{params:Array.isArray(u.params)?u.params:[]})}}if(r.templates!=null)if(typeof r.templates!="object"||Array.isArray(r.templates))e.push("'templates' must be an object");else for(let[a,d]of Object.entries(r.templates)){if(d==null||typeof d!="object"){e.push(`Template "${a}": must be an object`);continue}let u=d;if(Array.isArray(u.params)||e.push(`Template "${a}": missing 'params' array`),u.nodes==null||typeof u.nodes!="object"||Array.isArray(u.nodes))e.push(`Template "${a}": missing or invalid 'nodes' object`);else{let c=new Set(Array.isArray(u.params)?u.params:[]),l=new Set(Object.keys(u.nodes));for(let[p,f]of Object.entries(u.nodes)){if(f==null||typeof f!="object"){e.push(`Template "${a}" node "${p}": must be an object`);continue}let m=f;if((typeof m.type!="string"||!eb.has(m.type))&&e.push(`Template "${a}" node "${p}": invalid type`),Array.isArray(m.deps))for(let h of m.deps)!l.has(h)&&!c.has(h)&&e.push(`Template "${a}" node "${p}": dep "${h}" is not an inner node or param`)}typeof u.output!="string"?e.push(`Template "${a}": missing 'output' string`):u.nodes[u.output]||e.push(`Template "${a}": output "${u.output}" is not a declared node`)}}for(let[a,d]of Object.entries(r.nodes)){if(d==null||typeof d!="object"){e.push(`Node "${a}": must be an object`);continue}let u=d;if(typeof u.type!="string"||!Df.has(u.type)){e.push(`Node "${a}": invalid type "${String(u.type)}" (expected: ${[...Df].join(", ")})`);continue}if(s.set(a,u.type),u.type==="template")if(typeof u.template!="string"||!i.has(u.template))e.push(`Node "${a}": template "${String(u.template)}" not found in templates`);else if(u.bind==null||typeof u.bind!="object"||Array.isArray(u.bind))e.push(`Node "${a}": template ref requires 'bind' object`);else{let c=i.get(u.template),l=u.bind;for(let p of c.params)p in l||e.push(`Node "${a}": template param "${p}" is not bound (template "${u.template}")`);for(let[,p]of Object.entries(l))typeof p=="string"&&!o.has(p)&&e.push(`Node "${a}": bind target "${p}" does not reference an existing node`)}else{if(Array.isArray(u.deps))for(let c of u.deps)c===a?e.push(`Node "${a}": self-referencing dep`):o.has(c)||e.push(`Node "${a}": dep "${c}" does not reference an existing node`);(u.type==="derived"||u.type==="effect"||u.type==="operator")&&!Array.isArray(u.deps)&&e.push(`Node "${a}": ${u.type} node should have a 'deps' array`)}}if(r.feedback!=null)if(!Array.isArray(r.feedback))e.push("'feedback' must be an array");else for(let a=0;a<r.feedback.length;a++){let d=r.feedback[a];if(d==null||typeof d!="object"){e.push(`Feedback [${a}]: must be an object`);continue}let u=d;typeof u.from!="string"||!o.has(u.from)?e.push(`Feedback [${a}]: 'from' "${String(u.from)}" does not reference an existing node`):s.get(u.from)==="effect"&&n.push(`Feedback [${a}]: 'from' "${u.from}" is an effect node \u2014 effects emit no DATA, so the feedback edge will never fire. Did you mean a derived/state node upstream?`),typeof u.from=="string"&&u.from===u.to&&e.push(`Feedback [${a}]: 'from' and 'to' must be different nodes`),typeof u.to!="string"||!o.has(u.to)?e.push(`Feedback [${a}]: 'to' "${String(u.to)}" does not reference an existing node`):typeof u.to=="string"&&s.get(u.to)!=="state"&&e.push(`Feedback [${a}]: 'to' node "${u.to}" must be a state node (got "${s.get(u.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:n}}function Do(t,e){let n=xr(t);if(!n.valid)throw new Error(`compileSpec: invalid GraphSpec:
|
|
47
47
|
${n.errors.join(`
|
|
48
|
-
`)}`);let r=t.factory,o=t.factoryArgs;if(typeof r=="string"){let
|
|
48
|
+
`)}`);let r=t.factory,o=t.factoryArgs;if(typeof r=="string"){let v=e?.catalog?.graphFactories?.[r];if(v)return v(o)}let s=e?.catalog??{},i=e?.onMissing??"placeholder",a=new Q(t.name),d=t.templates??{},u=Io(t,s);if(!u.valid)throw new Error(`compileSpec: catalog validation errors:
|
|
49
49
|
${u.errors.join(`
|
|
50
|
-
`)}`);let c=[],l=(
|
|
51
|
-
${
|
|
52
|
-
`)}`)}if(i==="warn"){let
|
|
50
|
+
`)}`);let c=[],l=(v,T,w)=>{c.push({path:v,kind:T,name:w})},p=v=>{let T=s.fns?.[v];return T?Pf(T):void 0},f=v=>{let T=s.sources?.[v];return T?Gf(T):void 0},m=v=>{if(!v)return;let T={};for(let[w,k]of Object.entries(v))w==="factory"||w==="factoryArgs"||(T[w]=k);return Object.keys(T).length>0?T:void 0},h=new Map,g=[];for(let[v,T]of Object.entries(t.nodes)){if(T.type==="template")continue;let w=T,k=un(w),R=cn(w);if(w.type==="state"){let S=If(w),x=O(S,{name:v,meta:m(w.meta)});a.add(x,{name:v}),h.set(v,x)}else if(w.type==="producer"){let S=k?f(k):void 0,x=k?p(k):void 0;if(S){let N=S(R);a.add(N,{name:v}),h.set(v,N)}else if(x){let N=x([],R);a.add(N,{name:v}),h.set(v,N)}else{k&&l(v,"source",k);let N=z(()=>{},{name:v,meta:{...m(w.meta),_specSource:k}});a.add(N,{name:v}),h.set(v,N)}}else g.push([v,w])}let y=!0,b=new Map(g);for(;b.size>0&&y;){y=!1;for(let[v,T]of[...b.entries()]){let w=T.deps??[];if(!w.every(E=>h.has(E)))continue;let k=w.map(E=>h.get(E)),R=un(T),S=cn(T),x=R?p(R):void 0,N;x?N=x(k,S):T.type==="effect"?(R&&l(v,"fn",R),N=ye(k,()=>{})):(R&&l(v,"fn",R),N=A(k,E=>E[0])),a.add(N,{name:v}),h.set(v,N),b.delete(v),y=!0}}if(b.size>0){let v=[...b.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${v}`)}for(let[v,T]of Object.entries(t.nodes)){if(T.type!=="template")continue;let w=T,k=d[w.template],R=new Q(v),S=new Map,x=[];for(let[M,C]of Object.entries(k.nodes)){let $=(C.deps??[]).map(F=>F.startsWith("$")&&w.bind[F]?w.bind[F]:F),B={...C,deps:$},G=un(C),V=cn(C);if(C.type==="state"){let F=If(C),K=O(F,{name:M,meta:m(C.meta)});R.add(K,{name:M}),S.set(M,K)}else if(C.type==="producer"){let F=G?f(G):void 0,K=G?p(G):void 0;if(F){let P=F(V);R.add(P,{name:M}),S.set(M,P)}else if(K){let P=K([],V);R.add(P,{name:M}),S.set(M,P)}else{G&&l(`${v}.${M}`,"source",G);let P=z(()=>{},{name:M,meta:{...m(C.meta),_specSource:G}});R.add(P,{name:M}),S.set(M,P)}}else x.push([M,B])}let N=!0,E=new Map(x);for(;E.size>0&&N;){N=!1;for(let[M,C]of[...E.entries()]){let $=C.deps??[];if(!$.every(j=>S.has(j)||h.has(j)))continue;let G=$.map(j=>S.get(j)??h.get(j)),V=un(C),F=cn(C),K=V?p(V):void 0,P;K?P=K(G,F):C.type==="effect"?(V&&l(`${v}.${M}`,"fn",V),P=ye(G,()=>{})):(V&&l(`${v}.${M}`,"fn",V),P=A(G,j=>j[0])),R.add(P,{name:M}),S.set(M,P),E.delete(M),N=!0}}if(E.size>0){let M=[...E.keys()].sort().join(", ");throw new Error(`compileSpec: template "${w.template}" has unresolvable deps: ${M}`)}a.mount(v,R);let D=`${v}::${k.output}`;h.set(v,a.resolve(D));try{let M=a.resolve(D);M.meta._templateName?.emit(w.template),M.meta._templateBind?.emit(w.bind)}catch{}}for(let v of t.feedback??[])dn(a,v.from,v.to,{maxIterations:v.maxIterations});if(c.length>0){if(i==="error"){let v=c.map(T=>` - ${T.path}: missing ${T.kind} "${T.name}"`);throw new Error(`compileSpec: ${c.length} catalog entr${c.length===1?"y":"ies"} missing \u2014 pass them via opts.catalog or set opts.onMissing to "warn"/"placeholder":
|
|
51
|
+
${v.join(`
|
|
52
|
+
`)}`)}if(i==="warn"){let v=e?.onWarn??(T=>console.warn(T));for(let T of c)v(`compileSpec: ${T.path} references missing ${T.kind} "${T.name}" \u2014 substituted placeholder`)}}return a}var tb=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function nb(t){let e=t.describe({detail:"spec"}),n=`::${rt}::`,r=/^__feedback_(?!effect_)(.+)$/,o=[],s=new Set;for(let[d,u]of Object.entries(e.nodes))u.meta?.factory!=null&&!d.includes("::")&&s.add(d);let i={};for(let[d,u]of Object.entries(e.nodes)){if(d.includes(n))continue;let c=d.indexOf("::");if(c>0&&s.has(d.slice(0,c)))continue;if(r.exec(d)){let h=u.meta;h?.feedbackFrom&&h?.feedbackTo&&o.push({from:h.feedbackFrom,to:h.feedbackTo,...h.maxIterations?{maxIterations:h.maxIterations}:{}});continue}if(u.meta?._internal||d.startsWith("__feedback_effect_")||d.startsWith("__bridge_"))continue;let p=u.meta,f=p;if(p&&Object.keys(p).length>0){let h={};for(let[g,y]of Object.entries(p))tb.has(g)||(h[g]=y);h.factory==="withStatus"?(delete h.status,delete h.error):h.factory==="withBreaker"?delete h.breakerState:h.factory==="verifiable"&&delete h.sourceVersion,f=Object.keys(h).length>0?h:void 0}let m={...u};f===void 0?delete m.meta:m.meta=f,i[d]=m}let a={...e,nodes:i};return delete a.expand,o.length>0&&(a.feedback=o),a}function rb(t,e){let n=[];t.name!==e.name&&n.push({type:"changed",path:"name",detail:`"${t.name}" \u2192 "${e.name}"`});let r=new Set(Object.keys(t.nodes)),o=new Set(Object.keys(e.nodes));for(let b of o)if(!r.has(b)){let v=e.nodes[b];n.push({type:"added",path:`nodes.${b}`,detail:`type: ${v.type}`})}for(let b of r)o.has(b)||n.push({type:"removed",path:`nodes.${b}`});for(let b of r){if(!o.has(b))continue;let v=t.nodes[b],T=e.nodes[b];if(JSON.stringify(v)!==JSON.stringify(T)){let w=[];v.type!==T.type&&w.push(`type: ${v.type} \u2192 ${T.type}`),JSON.stringify(v.deps)!==JSON.stringify(T.deps)&&w.push("deps changed");let k=v.type==="template"?void 0:un(v),R=T.type==="template"?void 0:un(T);k!==R&&w.push(`fn: ${k} \u2192 ${R}`);let S=v.type==="template"?void 0:cn(v),x=T.type==="template"?void 0:cn(T);JSON.stringify(S)!==JSON.stringify(x)&&w.push("config changed"),n.push({type:"changed",path:`nodes.${b}`,detail:w.join("; ")||"modified"})}}let s=t.templates??{},i=e.templates??{},a=new Set(Object.keys(s)),d=new Set(Object.keys(i));for(let b of d)a.has(b)||n.push({type:"added",path:`templates.${b}`});for(let b of a)d.has(b)||n.push({type:"removed",path:`templates.${b}`});for(let b of a)d.has(b)&&JSON.stringify(s[b])!==JSON.stringify(i[b])&&n.push({type:"changed",path:`templates.${b}`,detail:"template definition changed"});let u=t.feedback??[],c=e.feedback??[],l=new Set(u.map(b=>`${b.from}->${b.to}`)),p=new Set(c.map(b=>`${b.from}->${b.to}`));for(let b of c){let v=`${b.from}->${b.to}`;l.has(v)||n.push({type:"added",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10}`})}for(let b of u){let v=`${b.from}->${b.to}`;p.has(v)||n.push({type:"removed",path:`feedback.${v}`})}for(let b of u){let v=`${b.from}->${b.to}`,T=c.find(w=>w.from===b.from&&w.to===b.to);T&&JSON.stringify(b)!==JSON.stringify(T)&&n.push({type:"changed",path:`feedback.${v}`,detail:`maxIterations: ${b.maxIterations??10} \u2192 ${T.maxIterations??10}`})}let f=n.filter(b=>b.type==="added").length,m=n.filter(b=>b.type==="removed").length,h=n.filter(b=>b.type==="changed").length,g=[];f&&g.push(`${f} added`),m&&g.push(`${m} removed`),h&&g.push(`${h} changed`);let y=g.length>0?g.join(", "):"no changes";return{entries:n,summary:y}}var $f=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
53
53
|
|
|
54
54
|
Given a natural-language description, produce a JSON GraphSpec with this structure:
|
|
55
55
|
|
|
@@ -57,13 +57,14 @@ Given a natural-language description, produce a JSON GraphSpec with this structu
|
|
|
57
57
|
"name": "<graph_name>",
|
|
58
58
|
"nodes": {
|
|
59
59
|
"<node_name>": {
|
|
60
|
-
"type": "state" | "derived" | "producer" | "effect"
|
|
60
|
+
"type": "state" | "derived" | "producer" | "effect",
|
|
61
61
|
"deps": ["<dep_node_name>", ...],
|
|
62
|
-
"
|
|
63
|
-
"
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
62
|
+
"value": <initial_value>,
|
|
63
|
+
"meta": {
|
|
64
|
+
"factory": "<catalog_factory_name>",
|
|
65
|
+
"factoryArgs": { ... },
|
|
66
|
+
"description": "<purpose>"
|
|
67
|
+
}
|
|
67
68
|
},
|
|
68
69
|
"<template_instance>": {
|
|
69
70
|
"type": "template",
|
|
@@ -84,27 +85,30 @@ Given a natural-language description, produce a JSON GraphSpec with this structu
|
|
|
84
85
|
}
|
|
85
86
|
|
|
86
87
|
Rules:
|
|
87
|
-
- "state" nodes hold user/LLM-writable values (knobs).
|
|
88
|
-
|
|
89
|
-
- "
|
|
90
|
-
|
|
88
|
+
- "state" nodes hold user/LLM-writable values (knobs). Stamp the initial value
|
|
89
|
+
in "meta.factoryArgs.initial" (or as the top-level "value" field \u2014 both work).
|
|
90
|
+
- "derived" nodes compute from deps using a catalog function named in
|
|
91
|
+
"meta.factory"; pass any config via "meta.factoryArgs".
|
|
92
|
+
- "effect" nodes produce side effects from deps; same meta.factory shape as derived.
|
|
93
|
+
- "producer" nodes generate values from a catalog source named in "meta.factory";
|
|
94
|
+
pass any config via "meta.factoryArgs".
|
|
91
95
|
- Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
|
|
92
96
|
- Use "feedback" for bounded cycles where a derived value writes back to a state node.
|
|
93
97
|
- meta.description is required for every node.
|
|
94
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;function
|
|
98
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;function jf(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function ob(t,e,n){let r=$f,o=n?.catalogDescription??(n?.catalog?Ff(n.catalog):void 0);o&&(r+=`
|
|
95
99
|
|
|
96
100
|
Available catalog (use ONLY these names):
|
|
97
101
|
${o}`),n?.systemPromptExtra&&(r+=`
|
|
98
102
|
|
|
99
|
-
${n.systemPromptExtra}`);let s=[{role:"system",content:r},{role:"user",content:t}],d=(await e.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens})).content.trim();d.startsWith("```")&&(d=
|
|
103
|
+
${n.systemPromptExtra}`);let s=[{role:"system",content:r},{role:"user",content:t}],d=(await e.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens})).content.trim();d.startsWith("```")&&(d=jf(d));let u;try{u=JSON.parse(d)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${d.slice(0,200)}`)}let c=xr(u);if(!c.valid)throw new Error(`llmCompose: invalid GraphSpec:
|
|
100
104
|
${c.errors.join(`
|
|
101
|
-
`)}`);let l=u;if(n?.catalog){let p=n.maxAutoRefine??0;for(let f=0;f<=p;f++){let m=
|
|
105
|
+
`)}`);let l=u;if(n?.catalog){let p=n.maxAutoRefine??0;for(let f=0;f<=p;f++){let m=Io(l,n.catalog);if(m.valid)break;if(f===p)throw new Error(`llmCompose: catalog validation failed after ${p} refine attempts:
|
|
102
106
|
${m.errors.join(`
|
|
103
|
-
`)}`);l=await
|
|
107
|
+
`)}`);l=await Bf(l,`Fix these catalog errors:
|
|
104
108
|
${m.errors.join(`
|
|
105
109
|
`)}
|
|
106
110
|
|
|
107
|
-
Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function
|
|
111
|
+
Use ONLY functions and sources from the catalog.`,e,{...n,catalogDescription:o})}}return l}async function Bf(t,e,n,r){let o=$f;r?.catalogDescription&&(o+=`
|
|
108
112
|
|
|
109
113
|
Available catalog:
|
|
110
114
|
${r.catalogDescription}`),r?.systemPromptExtra&&(o+=`
|
|
@@ -114,9 +118,9 @@ ${JSON.stringify(t,null,2)}
|
|
|
114
118
|
|
|
115
119
|
Modification request: ${e}
|
|
116
120
|
|
|
117
|
-
Return the complete modified GraphSpec as JSON.`}],d=(await n.invoke(s,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens})).content.trim();d.startsWith("```")&&(d=
|
|
121
|
+
Return the complete modified GraphSpec as JSON.`}],d=(await n.invoke(s,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens})).content.trim();d.startsWith("```")&&(d=jf(d));let u;try{u=JSON.parse(d)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${d.slice(0,200)}`)}let c=xr(u);if(!c.valid)throw new Error(`llmRefine: invalid GraphSpec:
|
|
118
122
|
${c.errors.join(`
|
|
119
|
-
`)}`);return u}var
|
|
123
|
+
`)}`);return u}var Vf=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
120
124
|
|
|
121
125
|
Given a natural-language description, produce a JSON graph specification with this structure:
|
|
122
126
|
|
|
@@ -149,9 +153,9 @@ Rules:
|
|
|
149
153
|
- "operator" nodes are parameterized transformations with deps.
|
|
150
154
|
- Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
|
|
151
155
|
- meta.description is required for every node.
|
|
152
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function
|
|
156
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Kf(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${Vf}
|
|
153
157
|
|
|
154
|
-
${n.systemPromptExtra}`:
|
|
158
|
+
${n.systemPromptExtra}`:Vf},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),a=(await So(s)).content.trim();a.startsWith("```")&&(a=Tr(a));let d;try{d=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return Do(d,{catalog:n?.catalog})}function sb(t,e,n){let r=Y(t);return me(r,o=>!o||typeof o!="string"||o.trim().length===0?O(null):z(s=>{let i=new AbortController,a=!1;return Kf(o,e,{...n,signal:i.signal}).then(d=>{if(a){d.destroy();return}s.emit(d),s.down([[I]])}).catch(d=>{a||s.down([[L,d]])}),()=>{a=!0,i.abort()}},{name:"graphFromSpec::call"}))}function ib(t){let e={},n=t.type;return n==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):n==="integer"?e.type="integer":n==="number"?e.type="number":n==="boolean"?e.type="boolean":n==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function ab(t,e){let n=t.describe({actor:e,detail:"full"}),r=[],o=[],s=[];for(let[i,a]of Object.entries(n.nodes)){if(a.type!=="state"||i.includes("::__meta__::")||a.status==="completed"||a.status==="errored")continue;let d=a.meta??{},u=d.access;if(u==="human"||u==="system")continue;let c=d.description??`Set the value of ${i}`,l=ib(d),p={type:"object",required:["value"],properties:{value:l},additionalProperties:!1},f=i.replace(/::/g,"__");r.push({type:"function",function:{name:f,description:c,parameters:p}}),o.push({name:i,description:c,inputSchema:p});let m=t,h=e,g=a.v;s.push({name:i,description:c,parameters:p,handler(y){return m.set(i,y.value,h?{actor:h}:void 0),y.value},...g!=null?{version:{id:g.id,version:g.version}}:{}})}return{openai:r,mcp:o,definitions:s}}ae();ne();ue();var db=`You are a reactive graph optimizer for GraphReFly.
|
|
155
159
|
|
|
156
160
|
Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
|
|
157
161
|
|
|
@@ -172,8 +176,8 @@ Return ONLY valid JSON with this structure:
|
|
|
172
176
|
Rules:
|
|
173
177
|
- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
|
|
174
178
|
- Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
|
|
175
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function
|
|
176
|
-
`?p="hard-break":p="text",c!==null&&p===c?u+=l:(c!==null&&(i.push(u),a.push(c==="text"&&s),d.push(c)),u=l,c=p)}c!==null&&(i.push(u),a.push(c==="text"&&s),d.push(c)),n.push({texts:i,isWordLike:a,kinds:d})}return n}function Bt(t,e,n,r,o){let s=rb(t);if(s.length===0)return[];let i=ob(s),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),d=[],u=[],c=[];for(let y of i)for(let b=0;b<y.texts.length;b++)d.push(y.texts[b]),u.push(y.kinds[b]),c.push(y.isWordLike[b]);let l=[],p=[],f=[];for(let y=0;y<d.length;y++){let b=d[y],v=u[y],T=c[y];if(v==="text"&&!T&&l.length>0&&p[p.length-1]==="text"&&b.length===1&&(nb.has(b)||Nf.has(b))){l[l.length-1]+=b;continue}if(b==="-"&&l.length>0&&p[p.length-1]==="text"&&f[f.length-1]){l[l.length-1]+=b;continue}l.push(b),p.push(v),f.push(T)}let m=r.get(e);m||(m=new Map,r.set(e,m));function h(y){let b=m.get(y);if(b===void 0){o&&(o.misses+=1);let v=n.measureSegment(y,e).width;b=Number.isFinite(v)&&v>=0?v:0,m.set(y,b)}else o&&(o.hits+=1);return b}let g=[];for(let y=0;y<l.length;y++){let b=l[y],v=p[y];if(v!=="text"){g.push({text:b,width:v==="space"?h(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(tb(b)){let x="";for(let k of a.segment(b)){let S=k.segment;if(x.length>0&&Nf.has(S)){x+=S;continue}if(x.length>0){let R=h(x);g.push({text:x,width:R,kind:"text",graphemeWidths:null})}x=S}if(x.length>0){let k=h(x);g.push({text:x,width:k,kind:"text",graphemeWidths:null})}continue}let T=h(b),w=null;if(f[y]&&b.length>1){let x=[];for(let k of a.segment(b))x.push(h(k.segment));x.length>1&&(w=x)}g.push({text:b,width:T,kind:"text",graphemeWidths:w})}return g}function _n(t,e,n,r,o){if(t.length===0)return{lines:[],lineCount:0};let s=[],i=0,a=!1,d=0,u=0,c=0,l=0,p=-1,f=0,m=o.get(r);m||(m=new Map,o.set(r,m));let h=m.get("-");h===void 0&&(h=n.measureSegment("-",r).width,m.set("-",h));function g(w=c,x=l,k=i){let S="";for(let R=d;R<w;R++){let E=t[R];if(!(E.kind==="soft-hyphen"||E.kind==="hard-break"))if(R===d&&u>0&&E.graphemeWidths){let O=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(E.text)].map(N=>N.segment);S+=O.slice(u).join("")}else S+=E.text}if(x>0&&w<t.length){let R=t[w],_=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(R.text)].map(N=>N.segment),O=d===w?u:0;S+=_.slice(O,x).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(d===w&&u>0)&&(S+="-"),s.push({text:S,width:k,startSegment:d,startGrapheme:u,endSegment:w,endGrapheme:x}),i=0,a=!1,p=-1,f=0}function y(w){return w==="space"||w==="zero-width-break"||w==="soft-hyphen"}function b(w,x,k){a=!0,d=w,u=x,c=w+1,l=0,i=k}function v(w,x,k){a=!0,d=w,u=x,c=w,l=x+1,i=k}for(let w=0;w<t.length;w++){let x=t[w];if(x.kind==="hard-break"){a?g():s.push({text:"",width:0,startSegment:w,startGrapheme:0,endSegment:w,endGrapheme:0}),d=w+1,u=0;continue}let k=x.width;if(!a){k>e&&x.graphemeWidths?T(w,0,x.graphemeWidths):b(w,0,k),y(x.kind)&&(p=w+1,f=x.kind==="space"?i-k:i);continue}let S=i+k;if(S>e+.005){if(y(x.kind)){i+=k,c=w+1,l=0,g(w+1,0,x.kind==="space"?i-k:i);continue}if(p>=0){g(p,0,f),w--;continue}if(k>e&&x.graphemeWidths){g(),T(w,0,x.graphemeWidths);continue}g(),w--;continue}i=S,c=w+1,l=0,y(x.kind)&&(p=w+1,f=x.kind==="space"?i-k:i)}return a&&g(),{lines:s,lineCount:s.length};function T(w,x,k){for(let S=x;S<k.length;S++){let R=k[S];if(!a){v(w,S,R);continue}i+R>e+.005?(g(),v(w,S,R)):(i+=R,c=w,l=S+1)}a&&c===w&&l===k.length&&(c=w+1,l=0)}}function Vd(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var Kd=null;function sb(){return Kd===null&&(Kd=new Intl.Segmenter(void 0,{granularity:"grapheme"})),Kd}function Ef(t,e,n){if(e===0&&n<0)return t.text;let r=[...sb().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function nn(t,e,n,r,o,s){let i="";for(let a=e;a<r;a++){let d=t[a];d.kind==="soft-hyphen"||d.kind==="hard-break"||(a===e&&n>0?i+=Ef(d,n,-1):i+=d.text)}if(o>0&&r<t.length){let a=t[r];i+=Ef(a,e===r?n:0,o)}return s&&(i+="-"),i}function ib(t){if(!t?.adapter||!t.font)return 0;let e=t.cache;if(e){let n=e.get(t.font);n||(n=new Map,e.set(t.font,n));let r=n.get("-");return r===void 0&&(r=t.adapter.measureSegment("-",t.font).width,n.set("-",r)),r}return t.adapter.measureSegment("-",t.font).width}function qd(t,e,n,r){let o=e.segmentIndex,s=e.graphemeIndex;if(o>=t.length)return null;if(s===0){for(;o<t.length;){let w=t[o];if(w.kind==="hard-break")return{text:"",width:0,start:{segmentIndex:e.segmentIndex,graphemeIndex:0},end:{segmentIndex:o+1,graphemeIndex:0}};if(w.kind==="space"||w.kind==="zero-width-break"||w.kind==="soft-hyphen"){o+=1;continue}break}if(o>=t.length)return null}let i=ib(r),a=o,d=o===e.segmentIndex?s:0,u=0,c=a,l=0,p=!1,f=-1,m=0,h=0,g=!1,y=(w,x,k,S)=>{f=w,m=x,h=k,g=S==="soft-hyphen"},b=(w,x,k)=>{for(let S=x;S<k.length;S++){let R=k[S];if(!p){u=R,c=w,l=S+1,p=!0;continue}if(u+R>n+.005)return!0;u+=R,c=w,l=S+1}return c===w&&l===k.length&&(c=w+1,l=0),!1};if(d>0&&a<t.length){let w=t[a];if(w.graphemeWidths){if(b(a,d,w.graphemeWidths))return{text:nn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}};o=c}}for(;o<t.length;){let w=t[o];if(w.kind==="hard-break"){if(p){let S=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:nn(t,a,d,c,l,S),width:u+(S?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}return{text:"",width:0,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:o+1,graphemeIndex:0}}}let x=w.width;if(!p){if(x>n&&w.graphemeWidths){if(b(o,0,w.graphemeWidths))return{text:nn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}};o=c;continue}u=x,c=o+1,l=0,p=!0,Vd(w.kind)&&y(o+1,0,w.kind==="space"?u-x:u,w.kind),o+=1;continue}let k=u+x;if(k>n+.005){if(Vd(w.kind)){c=o+1,l=0;let R=w.kind==="soft-hyphen",E=w.kind==="space"?u:u+(R?i:0);return{text:nn(t,a,d,c,l,R),width:E,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}return f>=0?{text:nn(t,a,d,f,m,g),width:h+(g?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:f,graphemeIndex:m}}:x>n&&w.graphemeWidths?{text:nn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}:{text:nn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}u=k,c=o+1,l=0,Vd(w.kind)&&y(o+1,0,w.kind==="space"?u-x:u,w.kind),o+=1}if(!p)return null;let v=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:nn(t,a,d,c,l,v),width:u+(v?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}function zd(t,e,n=0){let r=[t];for(let o=0;o<e.length;o++){let s=e[o],i=[];for(let a=0;a<r.length;a++){let d=r[a];if(s.right<=d.left||s.left>=d.right){i.push(d);continue}s.left>d.left&&i.push({left:d.left,right:s.left}),s.right<d.right&&i.push({left:s.right,right:d.right})}r=i}return n>0?r.filter(o=>o.right-o.left>=n):r}function Ni(t,e,n){let r=[],o=new Intl.Segmenter(void 0,{granularity:"grapheme"});for(let s=0;s<t.lines.length;s++){let i=t.lines[s],a=s*n,d=0;for(let u=i.startSegment;u<e.length;u++){let c=e[u];if(c.kind==="soft-hyphen"||c.kind==="hard-break"){if(u>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...o.segment(c.text)].map(m=>m.segment);if(l.length===0)continue;let p=u===i.startSegment?i.startGrapheme:0,f;if(u<i.endSegment)f=l.length;else if(u===i.endSegment&&i.endGrapheme>0)f=i.endGrapheme;else break;for(let m=p;m<f;m++){let h=c.graphemeWidths?c.graphemeWidths[m]:c.width/l.length;r.push({x:d,y:a,width:h,height:n,line:s}),d+=h}}}return r}function ab(t){let{adapter:e,name:n="reactive-layout"}=t,r=new Q(n),o=new Map,s=A(t.text??"",{name:"text"}),i=A(t.font??"16px sans-serif",{name:"font"}),a=A(t.lineHeight??20,{name:"line-height"}),d=A(Math.max(0,t.maxWidth??800),{name:"max-width"});function u(m,h){if(m===null||h===null)return m===h;if(m.length!==h.length)return!1;for(let g=0;g<m.length;g++)if(m[g]!==h[g])return!1;return!0}let c=U([s,i],(m,h,g)=>{let y=m[0],b=y!=null&&y.length>0?y.at(-1):g.prevData[0],v=m[1],T=v!=null&&v.length>0?v.at(-1):g.prevData[1],w=V(),x={hits:0,misses:0},k=Bt(b,T,e,o,x),S=V()-w,R=x.hits+x.misses,E=R===0?1:x.hits/R,_=c.meta;_&&(vt(_["cache-hit-rate"],E),vt(_["segment-count"],k.length),vt(_["layout-time-ns"],S)),h.emit(k);let O=()=>{o.clear(),e.clearCache?.()};return{deactivate:O,invalidate:O}},{name:"segments",describeKind:"derived",meta:{"cache-hit-rate":0,"segment-count":0,"layout-time-ns":0},equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++){let v=g[b],T=y[b];if(v.text!==T.text||v.width!==T.width||v.kind!==T.kind||!u(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=C([c,d,i],([m,h,g])=>_n(m,h,e,g,o),{name:"line-breaks",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.lineCount!==y.lineCount)return!1;for(let b=0;b<g.lines.length;b++){let v=g.lines[b],T=y.lines[b];if(v.text!==T.text||v.width!==T.width||v.startSegment!==T.startSegment||v.startGrapheme!==T.startGrapheme||v.endSegment!==T.endSegment||v.endGrapheme!==T.endGrapheme)return!1}return!0}}),p=C([l,a],([m,h])=>m.lineCount*h,{name:"height"}),f=C([l,c,a],([m,h,g])=>Ni(m,h,g),{name:"char-positions",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b].x!==y[b].x||g[b].y!==y[b].y||g[b].width!==y[b].width)return!1;return!0}});return r.add(s,{name:"text"}),r.add(i,{name:"font"}),r.add(a,{name:"line-height"}),r.add(d,{name:"max-width"}),r.add(c,{name:"segments"}),r.add(l,{name:"line-breaks"}),r.add(p,{name:"height"}),r.add(f,{name:"char-positions"}),{graph:r,setText:m=>r.set("text",m),setFont:m=>r.set("font",m),setLineHeight:m=>r.set("line-height",m),setMaxWidth:m=>r.set("max-width",Math.max(0,m)),segments:c,lineBreaks:l,height:p,charPositions:f}}function Oo(t){return Math.max(0,Math.min(1,t))}function db(t){let e=Oo(t?.mainRatio??.65),n=Oo(t?.sideSplit??.5),r=Math.max(0,t?.viewportWidth??1280),o=t?.nodeRegistry??new Map,s=t?.adapter??null,i=t?.layoutFont??"14px monospace",a=t?.onHighlight,d=new Q("demo-shell"),u=A(e,{name:"pane/main-ratio"}),c=A(n,{name:"pane/side-split"}),l=A(null,{name:"pane/fullscreen"}),p=A(r,{name:"viewport/width"});d.add(u,{name:"pane/main-ratio"}),d.add(c,{name:"pane/side-split"}),d.add(l,{name:"pane/fullscreen"}),d.add(p,{name:"viewport/width"});let f=C([u,p,l],([D,K,F])=>{let H=D,G=K,B=F;return B==="main"?G:B==="graph"||B==="code"?0:Math.round(G*H)},{name:"pane/main-width"}),m=C([f,p,l],([D,K,F])=>{let H=F,G=K;return H==="main"?0:H==="graph"||H==="code"?G:G-D},{name:"pane/side-width"}),h=C([c,l],([D,K])=>{let F=K;return F==="graph"?1:F==="code"||F==="main"?0:Oo(D)},{name:"pane/graph-height-ratio"}),g=C([h,l],([D,K])=>{let F=K;return F==="code"?1:F==="graph"||F==="main"?0:1-D},{name:"pane/code-height-ratio"});d.add(f,{name:"pane/main-width"}),d.add(m,{name:"pane/side-width"}),d.add(h,{name:"pane/graph-height-ratio"}),d.add(g,{name:"pane/code-height-ratio"});let y=A(null,{name:"demo/graph-ref"}),b=A(0,{name:"demo/graph-tick"});d.add(y,{name:"demo/graph-ref"}),d.add(b,{name:"demo/graph-tick"});let v=C([y,b],([D,K])=>{let F=D;return F?F.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),T=C([y,b],([D,K])=>{let F=D;if(!F)return null;let{expand:H,...G}=F.describe({detail:"standard"});return G},{name:"graph/describe"});d.add(v,{name:"graph/mermaid"}),d.add(T,{name:"graph/describe"});let w=A(null,{name:"hover/target"});d.add(w,{name:"hover/target"});let x=C([w],([D])=>{let K=D;if(!K)return null;let F=o.get(K.id);return F?F.codeLine:null},{name:"highlight/code-scroll"}),k=C([w],([D])=>{let K=D;if(!K)return null;let F=o.get(K.id);return F?F.visualSelector:null},{name:"highlight/visual"}),S=C([w],([D])=>{let K=D;return K?K.id:null},{name:"highlight/graph"});if(d.add(x,{name:"highlight/code-scroll"}),d.add(k,{name:"highlight/visual"}),d.add(S,{name:"highlight/graph"}),a?.codeScroll){let D=a.codeScroll,K=ge([x],([F])=>{D(F)});d.add(K,{name:"highlight/apply-code-scroll"})}if(a?.visual){let D=a.visual,K=ge([k],([F])=>{D(F)});d.add(K,{name:"highlight/apply-visual"})}if(a?.graph){let D=a.graph,K=ge([S],([F])=>{D(F)});d.add(K,{name:"highlight/apply-graph"})}let R=A(null,{name:"inspect/selected-node"});d.add(R,{name:"inspect/selected-node"});let E=Lt("standard"),_=C([R,y,b],([D,K,F])=>{let H=K,G=D;if(!H||!G)return null;try{let B=H.resolve(G),re=jr(B,E);return{path:G,...re,value:B.cache}}catch{return null}},{name:"inspect/node-detail"}),O=C([y,b],([D,K])=>{let F=D;return F?F.trace():[]},{name:"inspect/trace-log"});d.add(_,{name:"inspect/node-detail"}),d.add(O,{name:"inspect/trace-log"});let N=A(!1,{name:"meta/debug"});d.add(N,{name:"meta/debug"});let L=C([N,b],([D,K])=>D?d.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});d.add(L,{name:"meta/shell-mermaid"});let j=A("",{name:"layout/code-text"});if(d.add(j,{name:"layout/code-text"}),s){let D=new Map,K=C([T],([G])=>{let B=G;if(!B)return new Map;let re=new Map;for(let[pe]of Object.entries(B.nodes)){let ee=Bt(pe,i,s,D),ue=_n(ee,1/0,s,i,D),Ce=ue.lines.reduce((Be,J)=>Math.max(Be,J.width),0),Ye=ue.lineCount*20;re.set(pe,{width:Ce,height:Ye})}return re},{name:"layout/graph-labels",equals:(G,B)=>{if(G===B)return!0;let re=G,pe=B;if(re.size!==pe.size)return!1;for(let[ee,ue]of re){let Ce=pe.get(ee);if(!Ce||Ce.width!==ue.width||Ce.height!==ue.height)return!1}return!0}}),F=C([j,m],([G,B])=>{let re=G;if(!re)return{lineCount:0,lines:[]};let pe=Bt(re,i,s,D),ee=B-40;return _n(pe,Math.max(100,ee),s,i,D)},{name:"layout/code-lines"}),H=C([K],([G])=>{let B=G;if(B.size===0)return 200;let re=0;for(let{width:pe}of B.values())pe>re&&(re=pe);return Math.max(200,Math.round(re+80))},{name:"layout/side-width-hint"});d.add(K,{name:"layout/graph-labels"}),d.add(F,{name:"layout/code-lines"}),d.add(H,{name:"layout/side-width-hint"})}let $=0;return{graph:d,setMainRatio(D){d.set("pane/main-ratio",Oo(D))},setSideSplit(D){d.set("pane/side-split",Oo(D))},setFullscreen(D){d.set("pane/fullscreen",D)},setViewportWidth(D){d.set("viewport/width",Math.max(0,D))},setHoverTarget(D){d.set("hover/target",D)},setDemoGraph(D){d.set("demo/graph-ref",D)},bumpGraphTick(){d.set("demo/graph-tick",++$)},selectNode(D){d.set("inspect/selected-node",D)},setMetaDebug(D){d.set("meta/debug",D)},setCodeText(D){d.set("layout/code-text",D)},batch(D){Z(D)},destroy(){d.destroy()}}}var _i={};Se(_i,{contentModerationGraph:()=>lb,dataQualityGraph:()=>pb,issueTrackerGraph:()=>cb,observabilityGraph:()=>ub});Ae();ne();function Pe(t,e){return We("domain_template",t,e)}function ub(t,e){let n=new Q(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>Hd(T,"error")},{name:"traces",classify:T=>Hd(T,"trace")},{name:"metrics",classify:T=>Hd(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=ho("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return C([w],([x])=>x,{initial:null})}catch{return A(null)}}),d=e.correlate??(T=>T),u=C(a,T=>d(T),{meta:Pe("observability",{stage:"correlate"})});n.add(u,{name:"correlate"});let c=e.sloCheck??(()=>({pass:!0})),l=C([u],T=>T[0],{meta:Pe("observability",{stage:"slo_value"})}),p=C([l],T=>c(T[0]),{meta:Pe("observability",{stage:"slo_verified"})});n.add(l,{name:"slo_value"}),n.add(p,{name:"slo_verified"});let f=e.weights??o.map(()=>1),m=a.map(T=>C([T],w=>w[0]!=null?1:0)),h=f.map(T=>A(T));for(let T=0;T<m.length;T++)n.add(m[T],{name:`__signal_${T}`}),n.add(h[T],{name:`__weight_${T}`});let g=No(m,h);n.add(g,{name:"alerts"});let y=C([g,p],T=>({scored:T[0],slo:T[1]}),{meta:Pe("observability",{stage:"output"})});n.add(y,{name:"output"});let b=A(null,{meta:Pe("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=C([p],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Pe("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),tn(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function cb(t,e){let n=new Q(t,e);n.add(e.source,{name:"source"});let r=0,o=T=>({id:`issue-${++r}`,title:String(T),severity:1,source:"unknown",raw:T}),s=e.extract??o,i=C([e.source],T=>s(T[0]),{meta:Pe("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),d=C([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Pe("issue_tracker",{stage:"verify"})});n.add(d,{name:"verify"});let u=A([],{meta:Pe("issue_tracker",{stage:"known_patterns"})});n.add(u,{name:"known_patterns"});let c=e.detectRegression??(()=>({regression:!1})),l=C([i,u],T=>{let w=T[0],x=T[1];return{issue:w,regression:c(w,x)}},{meta:Pe("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let p=C([i],T=>T[0]?.severity??0),f=C([l],T=>T[0]?.regression?2:0);n.add(p,{name:"__severity_signal"}),n.add(f,{name:"__regression_signal"});let m=A(1),h=A(1.5);n.add(m,{name:"__severity_weight"}),n.add(h,{name:"__regression_weight"});let g=No([p,f],[m,h]);n.add(g,{name:"priority"});let y=C([d,l,g],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Pe("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=A(null,{meta:Pe("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=C([d],T=>{let w=T[0];if(w){let x=w.verification;if(x&&x.valid===!1)return w}return null},{meta:Pe("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),tn(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function lb(t,e){let n=new Q(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),o=e.classify??r,s=C([e.source],v=>o(v[0]),{meta:Pe("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=ho("stratify",s,[{name:"safe",classify:v=>v.label==="safe"},{name:"review",classify:v=>v.label==="review"},{name:"block",classify:v=>v.label==="block"}]);n.mount("stratify",i);let a=Ke([],{name:"review_queue",maxSize:e.maxQueueSize});n.add(a.entries,{name:"review_queue"});let d;try{d=n.resolve("stratify::branch/review")}catch{d=A(null),n.add(d,{name:"__review_fallback"})}let u=ge([d],v=>{let T=v[0];T&&a.append(T)});n.add(u,{name:"__review_accumulator"}),n.addDisposer(te(u));let c=A({},{meta:Pe("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(c,{name:"policy"});let l=e.weights??[.1,1,2],p=C([s],v=>v[0]?.confidence??0),f=C([s],v=>{let T=v[0];return T?T.label==="block"?l[2]:T.label==="review"?l[1]:l[0]:0});n.add(p,{name:"__confidence_signal"}),n.add(f,{name:"__severity_signal"});let m=A(1),h=A(1);n.add(m,{name:"__w_confidence"}),n.add(h,{name:"__w_severity"});let g=No([p,f],[m,h]);n.add(g,{name:"priority"});let y=C([s,g],v=>({classification:v[0],priority:v[1]}),{meta:Pe("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=C([a.entries,c],v=>{let T=v[0];if(T&&T.length>0){let w=T[T.length-1];if(w&&w.falsePositive)return w}return null},{meta:Pe("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),tn(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function pb(t,e){let n=new Q(t,e);n.add(e.source,{name:"source"});let r=e.validate??(g=>({valid:!0,errors:[],record:g})),o=C([e.source],g=>g[0]!=null?r(g[0]):void 0,{meta:Pe("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(g=>({anomaly:!1,score:0,record:g})),i=C([e.source],g=>g[0]!=null?s(g[0]):void 0,{meta:Pe("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=A(null,{meta:Pe("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let d=ge([o],g=>{let y=g[0];y?.valid&&Z(()=>{a.emit(y.record)})});n.add(d,{name:"__baseline_updater"}),te(d);let u=e.detectDrift??(()=>({drift:!1})),c=C([e.source,a],g=>u(g[0],g[1]),{meta:Pe("data_quality",{stage:"drift"})});n.add(c,{name:"drift"});let l=e.suggest??(()=>null),p=C([o,i],g=>l({validation:g[0],anomaly:g[1]}),{meta:Pe("data_quality",{stage:"remediate"})});n.add(p,{name:"remediate"});let f=C([o,i,c,p],g=>({validation:g[0],anomaly:g[1],drift:g[2],remediation:g[3]}),{meta:Pe("data_quality",{stage:"output"})});n.add(f,{name:"output"});let m=A([],{meta:Pe("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let h=C([i],g=>{let y=g[0];return y?.anomaly?y:null},{meta:Pe("data_quality",{stage:"feedback_condition"})});return n.add(h,{name:"feedback_condition"}),tn(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function Hd(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var Oi={};Se(Oi,{GuardedExecutionGraph:()=>Mi,guardedExecution:()=>fb});var Mi=class extends Q{enforcer;violations;_target;_defaultActor;constructor(e,n){super(n.name??`${e.name}_guarded`,n.graph),this._target=e,this._defaultActor=n.actor;let r={mode:n.mode??"enforce",name:"enforcer"};n.violationsLimit!=null&&(r.violationsLimit=n.violationsLimit),this.enforcer=jd(e,n.policies,r),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer)}scopedDescribe(e){let n=e?.actor??this._defaultActor,r={...e,...n!=null?{actor:n}:{}};return this._target.describe(r)}get target(){return this._target}};function fb(t,e){return new Mi(t,e)}var ji={};Se(ji,{DEFAULT_DECAY_RATE:()=>yr,DEFAULT_EXECUTE_PROMPT:()=>Ud,DEFAULT_QUEUE_CONFIGS:()=>Ai,DEFAULT_SEVERITY_WEIGHTS:()=>hr,DEFAULT_TRIAGE_PROMPT:()=>Wd,DEFAULT_VERIFY_PROMPT:()=>Jd,HarnessGraph:()=>$i,QUEUE_NAMES:()=>ct,actuatorExecutor:()=>_f,affectedTaskFilter:()=>Rb,autoSolidify:()=>vb,beforeAfterCompare:()=>xb,codeChangeBridge:()=>Sb,createIntakeBridge:()=>Tb,defaultErrorClassifier:()=>Ci,defaultLlmExecutor:()=>Df,defaultLlmVerifier:()=>Gf,dispatchActuator:()=>bb,evalIntakeBridge:()=>wb,evalSource:()=>kb,evalVerifier:()=>Of,harnessEvalPair:()=>Gb,harnessLoop:()=>qb,harnessProfile:()=>Hb,harnessTrace:()=>Ub,notifyEffect:()=>Nb,priorityScore:()=>Vb,refineExecutor:()=>Xd,resolvePromptFn:()=>Ao,strategyKey:()=>br,strategyModel:()=>Zd});ae();ne();ve();function mb(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${yb(e.summary)}`,artifact:t}}function gb(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function hb(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function yb(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function _f(t){let e=t.name??"actuator-executor",n=t.toOutput??mb,r=t.onError??gb,o=t.skipDetail??hb;return s=>{let i=rt(s,d=>d!=null,{name:`${e}/gate-in`}),a=ke(i,d=>t.shouldApply&&!t.shouldApply(d)?z(u=>(u.down([[M,{outcome:"failure",detail:o(d)}],[P]]),()=>{}),{name:`${e}/skip`}):z(u=>{let c=new AbortController,l=!1,p=null,f=h=>{l||(l=!0,u.down([[M,h],[P]]),p?.(),p=null)},m;try{let h=t.apply(d,{signal:c.signal});m=Y(h,{signal:c.signal})}catch(h){return f(r(h,d)),()=>{c.abort()}}return p=m.subscribe(h=>{for(let g of h){if(l)return;if(g[0]===M){f(n(g[1],d));return}if(g[0]===I){f(r(g[1],d));return}if(g[0]===P){f(r(new Error("actuator inner completed without emitting DATA"),d));return}}}),l&&p&&(p(),p=null),()=>{c.abort(),p?.(),p=null}},{name:`${e}/inner`}),{name:e});return rt(a,d=>d!=null,{name:`${e}/gate-out`})}}function bb(t){let e=t.name??"dispatch-actuator",n=t.default??null,r=n!=null;return _f({apply:(o,s)=>{let i=Object.hasOwn(t.routes,o.intervention)?t.routes[o.intervention]:n;if(!i)throw new Error(`dispatchActuator: no route for intervention '${o.intervention}'`);return i(o,s)},shouldApply:o=>Object.hasOwn(t.routes,o.intervention)||r,skipDetail:o=>`no route for intervention '${o.intervention}'`,name:e})}ae();ne();function vb(t){let e=t.name??"auto-solidify",n=t.extract??(o=>o.execution.artifact??null),r=t.predicate??(()=>!0);return z(o=>{let s=null,i=!1,a=()=>{i||(i=!0,s?.(),s=null)},d=u=>{i||(o.down([[I,u]]),a())};return s=t.verifyResults.subscribe(u=>{if(!i)for(let c of u){if(i)return;if(c[0]!==M){if(c[0]===P){o.down([[P]]),a();return}continue}let l=c[1];if(l==null||!l.verified)continue;let p;try{p=r(l)}catch(m){d(m);return}if(!p)continue;let f;try{f=n(l)}catch(m){d(m);return}if(f!=null){try{t.write(f,l)}catch(m){d(m);return}o.down([[M,f]])}}}),i&&s&&(s(),s=null),()=>{a()}},{name:e})}ne();ve();function Tb(t,e,n,r){return ge([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function wb(t,e,n){let r=n?.defaultSeverity??"medium";return ge([t],([o])=>{if(o==null)return;let s=Array.isArray(o)?o:[o];for(let i of s)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(d=>d.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r});continue}if(a.judge_scores)for(let d of a.judge_scores)d.pass||e.publish({source:"eval",summary:`${a.task_id}: ${d.claim} (model: ${i.model})`,evidence:d.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r})}},{name:n?.name??"eval-intake-bridge"})}function kb(t,e){return ke(t,()=>Y(e()))}function xb(t,e){return C([t,e],([n,r])=>{let o=n,s=r,i=new Map(o.tasks.map(p=>[p.task_id,p])),a=new Map(s.tasks.map(p=>[p.task_id,p])),d=new Set([...i.keys(),...a.keys()]),u=[],c=[],l=[];for(let p of d){let f=i.get(p),m=a.get(p),h=f?.valid??!1,g=m?.valid??!1,y=f?.judge_scores?f.judge_scores.filter(T=>T.pass).length:void 0,b=m?.judge_scores?m.judge_scores.filter(T=>T.pass).length:void 0,v=y!==void 0&&b!==void 0?b-y:void 0;u.push({taskId:p,before:h,after:g,scoreDiff:v}),h&&!g&&c.push(p),!h&&g&&l.push(p)}return{newFailures:c,resolved:l,taskDeltas:u,overallImproved:l.length>c.length}},{name:"eval-delta"})}function Rb(t,e){let n=e==null?null:Array.isArray(e)?A(e):e,r=[t];return n&&r.push(n),C(r,o=>{let s=o[0],i=n?new Set(o[1]):null,a=new Set;for(let d of s)for(let u of d.affectsEvalTasks??[])(i==null||i.has(u))&&a.add(u);return[...a].sort()},{name:"affected-task-filter"})}function Sb(t,e,n,r){let o=r?.defaultSeverity??"high";function s(a){let d=[];for(let u of a.lintErrors??[])d.push({source:"code-change",summary:`Lint: ${u.rule} in ${u.file}:${u.line}`,evidence:u.message,affectsAreas:[u.file],severity:o});for(let u of a.testFailures??[])d.push({source:"test",summary:`Test failure: ${u.testId}`,evidence:u.message,affectsAreas:[u.file],affectsEvalTasks:[u.testId],severity:o});return d}let i=n??s;return ge([t],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:r?.name??"code-change-bridge"})}function Nb(t,e,n){return ge([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var ct=["auto-fix","needs-decision","investigation","backlog"],Ai={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},hr={critical:100,high:70,medium:40,low:10},yr=Math.LN2/(168*3600);function br(t,e){return`${t}\u2192${e}`}var Eb=/\b(parse|json|config|validation|syntax)\b/i,Ci=t=>Eb.test(t.detail)?"self-correctable":"structural",Wd=`You are a triage classifier for a reactive collaboration harness.
|
|
179
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function qf(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:db},{role:"user",content:JSON.stringify({graph:s,problem:e})}],a=n.invoke(i,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens,signal:r?.signal}),u=(await So(a)).content.trim();u.startsWith("```")&&(u=u.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let c;try{c=JSON.parse(u)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${u.slice(0,200)}`)}let l=c;if(typeof l.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof l.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(l.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:l.summary,reasoning:l.reasoning,operations:l.operations}}function ub(t,e,n,r){let o=Y(e),s=jt(o,t);return me(s,i=>{if(i==null)return O(null);let[a,d]=i;return!d||!a||typeof a!="string"||a.trim().length===0?O(null):d.destroyed?O(null):z(u=>{let c=new AbortController,l=!1;return qf(d,a,n,{...r,signal:c.signal}).then(p=>{l||(u.emit(p),u.down([[I]]))}).catch(p=>{l||u.down([[L,p]])}),()=>{l=!0,c.abort()}},{name:"suggestStrategy::call"})})}var zf=new Set(["state","derived","producer","operator","effect"]);function cb(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let n=t;if((typeof n.name!="string"||n.name.length===0)&&e.push("Missing or empty 'name' field"),n.nodes==null||typeof n.nodes!="object"||Array.isArray(n.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let r=new Set(Object.keys(n.nodes));for(let[o,s]of Object.entries(n.nodes)){if(s==null||typeof s!="object"){e.push(`Node "${o}": must be an object`);continue}let i=s;if((typeof i.type!="string"||!zf.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...zf].join(", ")})`),Array.isArray(i.deps))for(let a of i.deps)typeof a=="string"&&!r.has(a)&&e.push(`Node "${o}": dep "${a}" does not reference an existing node`)}if(!Array.isArray(n.edges))n.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let s=0;s<n.edges.length;s++){let i=n.edges[s];if(i==null||typeof i!="object"){e.push(`Edge [${s}]: must be an object`);continue}let a=i;(typeof a.from!="string"||!r.has(a.from))&&e.push(`Edge [${s}]: 'from' "${String(a.from)}" does not reference an existing node`),(typeof a.to!="string"||!r.has(a.to))&&e.push(`Edge [${s}]: 'to' "${String(a.to)}" does not reference an existing node`);let d=`${a.from}->${a.to}`;o.has(d)&&e.push(`Edge [${s}]: duplicate edge ${d}`),o.add(d)}}return{valid:e.length===0,errors:e}}var Gi={};Ne(Gi,{AuditTrailGraph:()=>Di,PolicyGateGraph:()=>Pi,auditTrail:()=>pb,complianceSnapshot:()=>fb,policyGate:()=>ru});Ae();Se();zt();ae();et();Me();ne();Jo();at();ue();function Uf(t,e){return xe("audit",t,e)}var lb=new Set(["data","error","complete","teardown"]),Di=class extends Q{entries;count;_log;_target;constructor(e,n){super(n.name??`${e.name}_audit`,n.graph),this._target=e,this._log=qe([],{name:"entries",...n.maxSize!=null?{maxSize:n.maxSize}:{}}),this.entries=this._log.entries,this.add(this.entries,{name:"entries"}),this.count=A([this.entries],([d])=>d.length,{name:"count",describeKind:"derived",meta:Uf("count")}),this.add(this.count,{name:"count"}),this.addDisposer(te(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):lb,o=n.filter,s=0,i=e.observe({timeline:!0,structured:!0}),a=i.onEvent(d=>{if(d.type==="derived")return;let u=d.type;if(!r.has(u))return;let c=d.path??"",l={seq:s++,timestamp_ns:d.timestamp_ns??H(),wall_clock_ns:oe(),path:c,type:u},f=(c?nu(e,c):void 0)?.lastMutation;f!=null&&(l.actor=f.actor),u==="data"&&(l.value=d.data),u==="error"&&(l.error=d.data);let m=c?mb(e,c):void 0;m!=null&&(l.annotation=m),!(o!=null&&!o(l))&&this._log.append(l)});this.addDisposer(()=>{a(),i.dispose()}),this.addDisposer(()=>this._log.disposeAllViews())}all(){return this.entries.cache??[]}byNode(e){return this.all().filter(n=>n.path===e)}byActor(e){return this.all().filter(n=>n.actor?.id===e)}byActorType(e){return this.all().filter(n=>n.actor?.type===e)}byTimeRange(e,n){return this.all().filter(r=>!(r.timestamp_ns<e||n!=null&&r.timestamp_ns>=n))}get target(){return this._target}};function pb(t,e={}){return new Di(t,e)}var Pi=class extends Q{policies;violations;violationCount;_target;_mode;_currentGuard;constructor(e,n,r){super(r.name??`${e.name}_policy`,r.graph),this._target=e,this._mode=r.mode??"audit";let o=Hf(n)?n:O(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new Kt("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=A([this.violations.events],([m])=>m.length,{name:"violationCount",describeKind:"derived",meta:Uf("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(te(this.violationCount));let i=o.cache??[];this._currentGuard=Br(i);let a=o.subscribe(m=>{for(let h of m)h[0]===_&&(i=h[1]??[],this._currentGuard=Br(i))});this.addDisposer(a);let d=r.paths,u=Hf(d)?d:void 0,c=d!=null,p=u!=null?u.cache??[]:c?[...d]:void 0,f=p??Wf(e);if(this._mode!=="enforce"&&u!=null){let m=u.subscribe(h=>{for(let g of h)g[0]===_&&(p=g[1]??[])});this.addDisposer(m)}if(this._mode==="enforce"){let m=new Map,h=g=>{if(m.has(g))return;let y=nu(e,g);if(!(y instanceof Ce))return;let b=(v,T)=>{let w=this._currentGuard(v,T);return w||this._publishViolation(v,T,g,"blocked"),w};m.set(g,y._pushGuard(b))};for(let g of f)h(g);if(u!=null){let g=u.subscribe(y=>{for(let b of y){if(b[0]!==_)continue;let v=b[1]??[],T=new Set(v),w=new Set(p??[]);Z(()=>{for(let k of w){if(T.has(k))continue;let R=m.get(k);R!=null&&(R(),m.delete(k))}for(let k of T)w.has(k)||h(k);p=v})}});this.addDisposer(g)}if(c){let g=e.topology.subscribe(y=>{for(let b of y){if(b[0]!==_)continue;let v=b[1];if(v.kind!=="removed"||v.nodeKind!=="node")continue;let T=m.get(v.name);T!=null&&(T(),m.delete(v.name))}});this.addDisposer(g)}else{let g=Cn(e,(y,b,v)=>{if(y.kind==="added")if(y.nodeKind==="node")h(`${v}${y.name}`);else{let T=b._mounts.get(y.name);if(!(T instanceof Q))return;let w=`${v}${y.name}::`,k=Wf(T);for(let R of k)h(R===""?`${v}${y.name}`:`${w}${R}`)}else if(y.kind==="removed")if(y.nodeKind==="node"){let T=`${v}${y.name}`,w=m.get(T);w!=null&&(w(),m.delete(T))}else{let T=`${v}${y.name}`,w=`${T}::`;for(let[k,R]of m)(k===T||k.startsWith(w))&&(R(),m.delete(k))}});this.addDisposer(g)}this.addDisposer(()=>{for(let g of m.values())g();m.clear()})}else{let m=e.observe({timeline:!0,structured:!0}),h=m.onEvent(g=>{if(g.type!=="data"&&g.type!=="error")return;let y=g.path??"";if(!y||p!=null&&!p.includes(y))return;let b=g.actor??nu(e,y)?.lastMutation?.actor;if(b==null)return;let v="write";this._currentGuard(b,v)||this._publishViolation(b,v,y,"observed")});this.addDisposer(()=>{h(),m.dispose()})}}_publishViolation(e,n,r,o){this.violations.publish({timestamp_ns:H(),wall_clock_ns:oe(),path:r,actor:e,action:n,mode:this._mode,result:o})}all(){return this.violations.retained()}get mode(){return this._mode}get target(){return this._target}};function ru(t,e,n={}){let r=new Pi(t,e,n);return r.tagFactory("policyGate",We(n)),r}function fb(t,e={}){let n={format_version:1,timestamp_ns:H(),wall_clock_ns:oe(),graph:t.snapshot()};if(e.actor!=null&&(n.actor=e.actor),e.audit!=null){let o=[...e.audit.all()];n.audit={count:o.length,entries:o}}if(e.policies!=null){let o=e.policies.policies.cache??[];n.policies={mode:e.policies.mode,rules:o,violations:[...e.policies.all()]}}let r=gb(n);return{...n,fingerprint:r}}function Hf(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function nu(t,e){try{return t.node(e)}catch{return}}function mb(t,e){try{return t.annotation(e)}catch{return}}function Wf(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function gb(t){return Ht(JSON.stringify(hb(t)))}function hb(t){let e=new Set,n=r=>{if(r===void 0)return{__undefined:!0};if(r===null)return null;let o=typeof r;if(o==="bigint")return{__bigint:r.toString()};if(o!=="object")return r;let s=r;if(e.has(s))return{__circular:!0};e.add(s);try{if(Array.isArray(s))return s.map(n);if(s instanceof Date)return{__date:s.toISOString()};if(s instanceof RegExp)return{__regexp:{source:s.source,flags:s.flags}};if(s instanceof Map)return{__map:[...s.entries()].map(([d,u])=>[n(d),n(u)])};if(s instanceof Set)return{__set:[...s].map(n)};if(ArrayBuffer.isView(s)){let a=s,d=new Array(a.length);for(let u=0;u<a.length;u++)d[u]=a[u]??0;return{__typed_array:{ctor:s.constructor.name,data:d}}}let i={};for(let a of Object.keys(s).sort())i[a]=n(s[a]);return i}finally{e.delete(s)}};return n(t)}var $i={};Ne($i,{demoShell:()=>Rb});Ae();et();ne();Se();Me();ne();Ae();ae();Me();function St(t,e){t!=null&&It(n=>t.down(n),[[_,e]],$e.tierOf)}function Po(t){return t.relatedTo?.[0]??t.summary}function yb(t){for(let e of t){let n=e.codePointAt(0);if(n>=19968&&n<=40959||n>=13312&&n<=19903||n>=12288&&n<=12351||n>=12352&&n<=12447||n>=12448&&n<=12543||n>=44032&&n<=55215||n>=65280&&n<=65519)return!0}return!1}var Jf=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),bb=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function vb(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function Tb(t){let e=new Intl.Segmenter(void 0,{granularity:"word"}),n=[];for(let r of e.segment(t)){let o=r.segment,s=r.isWordLike??!1,i=[],a=[],d=[],u="",c=null;for(let l of o){let p;l===" "?p="space":l==="\u200B"?p="zero-width-break":l==="\xAD"?p="soft-hyphen":l===`
|
|
180
|
+
`?p="hard-break":p="text",c!==null&&p===c?u+=l:(c!==null&&(i.push(u),a.push(c==="text"&&s),d.push(c)),u=l,c=p)}c!==null&&(i.push(u),a.push(c==="text"&&s),d.push(c)),n.push({texts:i,isWordLike:a,kinds:d})}return n}function qt(t,e,n,r,o){let s=vb(t);if(s.length===0)return[];let i=Tb(s),a=new Intl.Segmenter(void 0,{granularity:"grapheme"}),d=[],u=[],c=[];for(let y of i)for(let b=0;b<y.texts.length;b++)d.push(y.texts[b]),u.push(y.kinds[b]),c.push(y.isWordLike[b]);let l=[],p=[],f=[];for(let y=0;y<d.length;y++){let b=d[y],v=u[y],T=c[y];if(v==="text"&&!T&&l.length>0&&p[p.length-1]==="text"&&b.length===1&&(bb.has(b)||Jf.has(b))){l[l.length-1]+=b;continue}if(b==="-"&&l.length>0&&p[p.length-1]==="text"&&f[f.length-1]){l[l.length-1]+=b;continue}l.push(b),p.push(v),f.push(T)}let m=r.get(e);m||(m=new Map,r.set(e,m));function h(y){let b=m.get(y);if(b===void 0){o&&(o.misses+=1);let v=n.measureSegment(y,e).width;b=Number.isFinite(v)&&v>=0?v:0,m.set(y,b)}else o&&(o.hits+=1);return b}let g=[];for(let y=0;y<l.length;y++){let b=l[y],v=p[y];if(v!=="text"){g.push({text:b,width:v==="space"?h(" ")*b.length:0,kind:v,graphemeWidths:null});continue}if(yb(b)){let k="";for(let R of a.segment(b)){let S=R.segment;if(k.length>0&&Jf.has(S)){k+=S;continue}if(k.length>0){let x=h(k);g.push({text:k,width:x,kind:"text",graphemeWidths:null})}k=S}if(k.length>0){let R=h(k);g.push({text:k,width:R,kind:"text",graphemeWidths:null})}continue}let T=h(b),w=null;if(f[y]&&b.length>1){let k=[];for(let R of a.segment(b))k.push(h(R.segment));k.length>1&&(w=k)}g.push({text:b,width:T,kind:"text",graphemeWidths:w})}return g}function Bn(t,e,n,r,o){if(t.length===0)return{lines:[],lineCount:0};let s=[],i=0,a=!1,d=0,u=0,c=0,l=0,p=-1,f=0,m=o.get(r);m||(m=new Map,o.set(r,m));let h=m.get("-");h===void 0&&(h=n.measureSegment("-",r).width,m.set("-",h));function g(w=c,k=l,R=i){let S="";for(let x=d;x<w;x++){let N=t[x];if(!(N.kind==="soft-hyphen"||N.kind==="hard-break"))if(x===d&&u>0&&N.graphemeWidths){let D=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(N.text)].map(M=>M.segment);S+=D.slice(u).join("")}else S+=N.text}if(k>0&&w<t.length){let x=t[w],E=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(x.text)].map(M=>M.segment),D=d===w?u:0;S+=E.slice(D,k).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(d===w&&u>0)&&(S+="-"),s.push({text:S,width:R,startSegment:d,startGrapheme:u,endSegment:w,endGrapheme:k}),i=0,a=!1,p=-1,f=0}function y(w){return w==="space"||w==="zero-width-break"||w==="soft-hyphen"}function b(w,k,R){a=!0,d=w,u=k,c=w+1,l=0,i=R}function v(w,k,R){a=!0,d=w,u=k,c=w,l=k+1,i=R}for(let w=0;w<t.length;w++){let k=t[w];if(k.kind==="hard-break"){a?g():s.push({text:"",width:0,startSegment:w,startGrapheme:0,endSegment:w,endGrapheme:0}),d=w+1,u=0;continue}let R=k.width;if(!a){R>e&&k.graphemeWidths?T(w,0,k.graphemeWidths):b(w,0,R),y(k.kind)&&(p=w+1,f=k.kind==="space"?i-R:i);continue}let S=i+R;if(S>e+.005){if(y(k.kind)){i+=R,c=w+1,l=0,g(w+1,0,k.kind==="space"?i-R:i);continue}if(p>=0){g(p,0,f),w--;continue}if(R>e&&k.graphemeWidths){g(),T(w,0,k.graphemeWidths);continue}g(),w--;continue}i=S,c=w+1,l=0,y(k.kind)&&(p=w+1,f=k.kind==="space"?i-R:i)}return a&&g(),{lines:s,lineCount:s.length};function T(w,k,R){for(let S=k;S<R.length;S++){let x=R[S];if(!a){v(w,S,x);continue}i+x>e+.005?(g(),v(w,S,x)):(i+=x,c=w,l=S+1)}a&&c===w&&l===R.length&&(c=w+1,l=0)}}function ou(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var su=null;function wb(){return su===null&&(su=new Intl.Segmenter(void 0,{granularity:"grapheme"})),su}function Yf(t,e,n){if(e===0&&n<0)return t.text;let r=[...wb().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function ln(t,e,n,r,o,s){let i="";for(let a=e;a<r;a++){let d=t[a];d.kind==="soft-hyphen"||d.kind==="hard-break"||(a===e&&n>0?i+=Yf(d,n,-1):i+=d.text)}if(o>0&&r<t.length){let a=t[r];i+=Yf(a,e===r?n:0,o)}return s&&(i+="-"),i}function kb(t){if(!t?.adapter||!t.font)return 0;let e=t.cache;if(e){let n=e.get(t.font);n||(n=new Map,e.set(t.font,n));let r=n.get("-");return r===void 0&&(r=t.adapter.measureSegment("-",t.font).width,n.set("-",r)),r}return t.adapter.measureSegment("-",t.font).width}function iu(t,e,n,r){let o=e.segmentIndex,s=e.graphemeIndex;if(o>=t.length)return null;if(s===0){for(;o<t.length;){let w=t[o];if(w.kind==="hard-break")return{text:"",width:0,start:{segmentIndex:e.segmentIndex,graphemeIndex:0},end:{segmentIndex:o+1,graphemeIndex:0}};if(w.kind==="space"||w.kind==="zero-width-break"||w.kind==="soft-hyphen"){o+=1;continue}break}if(o>=t.length)return null}let i=kb(r),a=o,d=o===e.segmentIndex?s:0,u=0,c=a,l=0,p=!1,f=-1,m=0,h=0,g=!1,y=(w,k,R,S)=>{f=w,m=k,h=R,g=S==="soft-hyphen"},b=(w,k,R)=>{for(let S=k;S<R.length;S++){let x=R[S];if(!p){u=x,c=w,l=S+1,p=!0;continue}if(u+x>n+.005)return!0;u+=x,c=w,l=S+1}return c===w&&l===R.length&&(c=w+1,l=0),!1};if(d>0&&a<t.length){let w=t[a];if(w.graphemeWidths){if(b(a,d,w.graphemeWidths))return{text:ln(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}};o=c}}for(;o<t.length;){let w=t[o];if(w.kind==="hard-break"){if(p){let S=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:ln(t,a,d,c,l,S),width:u+(S?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}return{text:"",width:0,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:o+1,graphemeIndex:0}}}let k=w.width;if(!p){if(k>n&&w.graphemeWidths){if(b(o,0,w.graphemeWidths))return{text:ln(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}};o=c;continue}u=k,c=o+1,l=0,p=!0,ou(w.kind)&&y(o+1,0,w.kind==="space"?u-k:u,w.kind),o+=1;continue}let R=u+k;if(R>n+.005){if(ou(w.kind)){c=o+1,l=0;let x=w.kind==="soft-hyphen",N=w.kind==="space"?u:u+(x?i:0);return{text:ln(t,a,d,c,l,x),width:N,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}return f>=0?{text:ln(t,a,d,f,m,g),width:h+(g?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:f,graphemeIndex:m}}:k>n&&w.graphemeWidths?{text:ln(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}:{text:ln(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}u=R,c=o+1,l=0,ou(w.kind)&&y(o+1,0,w.kind==="space"?u-k:u,w.kind),o+=1}if(!p)return null;let v=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:ln(t,a,d,c,l,v),width:u+(v?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}function au(t,e,n=0){let r=[t];for(let o=0;o<e.length;o++){let s=e[o],i=[];for(let a=0;a<r.length;a++){let d=r[a];if(s.right<=d.left||s.left>=d.right){i.push(d);continue}s.left>d.left&&i.push({left:d.left,right:s.left}),s.right<d.right&&i.push({left:s.right,right:d.right})}r=i}return n>0?r.filter(o=>o.right-o.left>=n):r}function Fi(t,e,n){let r=[],o=new Intl.Segmenter(void 0,{granularity:"grapheme"});for(let s=0;s<t.lines.length;s++){let i=t.lines[s],a=s*n,d=0;for(let u=i.startSegment;u<e.length;u++){let c=e[u];if(c.kind==="soft-hyphen"||c.kind==="hard-break"){if(u>=i.endSegment&&i.endGrapheme===0)break;continue}let l=[...o.segment(c.text)].map(m=>m.segment);if(l.length===0)continue;let p=u===i.startSegment?i.startGrapheme:0,f;if(u<i.endSegment)f=l.length;else if(u===i.endSegment&&i.endGrapheme>0)f=i.endGrapheme;else break;for(let m=p;m<f;m++){let h=c.graphemeWidths?c.graphemeWidths[m]:c.width/l.length;r.push({x:d,y:a,width:h,height:n,line:s}),d+=h}}}return r}function xb(t){let{adapter:e,name:n="reactive-layout"}=t,r=new Q(n),o=new Map,s=O(t.text??"",{name:"text"}),i=O(t.font??"16px sans-serif",{name:"font"}),a=O(t.lineHeight??20,{name:"line-height"}),d=O(Math.max(0,t.maxWidth??800),{name:"max-width"});function u(m,h){if(m===null||h===null)return m===h;if(m.length!==h.length)return!1;for(let g=0;g<m.length;g++)if(m[g]!==h[g])return!1;return!0}let c=U([s,i],(m,h,g)=>{let y=m[0],b=y!=null&&y.length>0?y.at(-1):g.prevData[0],v=m[1],T=v!=null&&v.length>0?v.at(-1):g.prevData[1],w=H(),k={hits:0,misses:0},R=qt(b,T,e,o,k),S=H()-w,x=k.hits+k.misses,N=x===0?1:k.hits/x,E=c.meta;E&&(St(E["cache-hit-rate"],N),St(E["segment-count"],R.length),St(E["layout-time-ns"],S)),h.emit(R);let D=()=>{o.clear(),e.clearCache?.()};return{deactivate:D,invalidate:D}},{name:"segments",describeKind:"derived",meta:{"cache-hit-rate":0,"segment-count":0,"layout-time-ns":0},equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++){let v=g[b],T=y[b];if(v.text!==T.text||v.width!==T.width||v.kind!==T.kind||!u(v.graphemeWidths??null,T.graphemeWidths??null))return!1}return!0}}),l=A([c,d,i],([m,h,g])=>Bn(m,h,e,g,o),{name:"line-breaks",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.lineCount!==y.lineCount)return!1;for(let b=0;b<g.lines.length;b++){let v=g.lines[b],T=y.lines[b];if(v.text!==T.text||v.width!==T.width||v.startSegment!==T.startSegment||v.startGrapheme!==T.startGrapheme||v.endSegment!==T.endSegment||v.endGrapheme!==T.endGrapheme)return!1}return!0}}),p=A([l,a],([m,h])=>m.lineCount*h,{name:"height"}),f=A([l,c,a],([m,h,g])=>Fi(m,h,g),{name:"char-positions",equals:(m,h)=>{let g=m,y=h;if(g==null||y==null)return g===y;if(g.length!==y.length)return!1;for(let b=0;b<g.length;b++)if(g[b].x!==y[b].x||g[b].y!==y[b].y||g[b].width!==y[b].width)return!1;return!0}});return r.add(s,{name:"text"}),r.add(i,{name:"font"}),r.add(a,{name:"line-height"}),r.add(d,{name:"max-width"}),r.add(c,{name:"segments"}),r.add(l,{name:"line-breaks"}),r.add(p,{name:"height"}),r.add(f,{name:"char-positions"}),{graph:r,setText:m=>r.set("text",m),setFont:m=>r.set("font",m),setLineHeight:m=>r.set("line-height",m),setMaxWidth:m=>r.set("max-width",Math.max(0,m)),segments:c,lineBreaks:l,height:p,charPositions:f}}function Go(t){return Math.max(0,Math.min(1,t))}function Rb(t){let e=Go(t?.mainRatio??.65),n=Go(t?.sideSplit??.5),r=Math.max(0,t?.viewportWidth??1280),o=t?.nodeRegistry??new Map,s=t?.adapter??null,i=t?.layoutFont??"14px monospace",a=t?.onHighlight,d=new Q("demo-shell"),u=O(e,{name:"pane/main-ratio"}),c=O(n,{name:"pane/side-split"}),l=O(null,{name:"pane/fullscreen"}),p=O(r,{name:"viewport/width"});d.add(u,{name:"pane/main-ratio"}),d.add(c,{name:"pane/side-split"}),d.add(l,{name:"pane/fullscreen"}),d.add(p,{name:"viewport/width"});let f=A([u,p,l],([G,V,F])=>{let K=G,P=V,j=F;return j==="main"?P:j==="graph"||j==="code"?0:Math.round(P*K)},{name:"pane/main-width"}),m=A([f,p,l],([G,V,F])=>{let K=F,P=V;return K==="main"?0:K==="graph"||K==="code"?P:P-G},{name:"pane/side-width"}),h=A([c,l],([G,V])=>{let F=V;return F==="graph"?1:F==="code"||F==="main"?0:Go(G)},{name:"pane/graph-height-ratio"}),g=A([h,l],([G,V])=>{let F=V;return F==="code"?1:F==="graph"||F==="main"?0:1-G},{name:"pane/code-height-ratio"});d.add(f,{name:"pane/main-width"}),d.add(m,{name:"pane/side-width"}),d.add(h,{name:"pane/graph-height-ratio"}),d.add(g,{name:"pane/code-height-ratio"});let y=O(null,{name:"demo/graph-ref"}),b=O(0,{name:"demo/graph-tick"});d.add(y,{name:"demo/graph-ref"}),d.add(b,{name:"demo/graph-tick"});let v=A([y,b],([G,V])=>{let F=G;return F?tn(F.describe()):""},{name:"graph/mermaid"}),T=A([y,b],([G,V])=>{let F=G;if(!F)return null;let{expand:K,...P}=F.describe({detail:"standard"});return P},{name:"graph/describe"});d.add(v,{name:"graph/mermaid"}),d.add(T,{name:"graph/describe"});let w=O(null,{name:"hover/target"});d.add(w,{name:"hover/target"});let k=A([w],([G])=>{let V=G;if(!V)return null;let F=o.get(V.id);return F?F.codeLine:null},{name:"highlight/code-scroll"}),R=A([w],([G])=>{let V=G;if(!V)return null;let F=o.get(V.id);return F?F.visualSelector:null},{name:"highlight/visual"}),S=A([w],([G])=>{let V=G;return V?V.id:null},{name:"highlight/graph"});if(d.add(k,{name:"highlight/code-scroll"}),d.add(R,{name:"highlight/visual"}),d.add(S,{name:"highlight/graph"}),a?.codeScroll){let G=a.codeScroll,V=ye([k],([F])=>{G(F)});d.add(V,{name:"highlight/apply-code-scroll"})}if(a?.visual){let G=a.visual,V=ye([R],([F])=>{G(F)});d.add(V,{name:"highlight/apply-visual"})}if(a?.graph){let G=a.graph,V=ye([S],([F])=>{G(F)});d.add(V,{name:"highlight/apply-graph"})}let x=O(null,{name:"inspect/selected-node"});d.add(x,{name:"inspect/selected-node"});let N=Ut("standard"),E=A([x,y,b],([G,V,F])=>{let K=V,P=G;if(!K||!P)return null;try{let j=K.resolve(P),re=Ur(j,N);return{path:P,...re,value:j.cache}}catch{return null}},{name:"inspect/node-detail"}),D=A([y,b],([G,V])=>{let F=G;return F?F.trace():[]},{name:"inspect/trace-log"});d.add(E,{name:"inspect/node-detail"}),d.add(D,{name:"inspect/trace-log"});let M=O(!1,{name:"meta/debug"});d.add(M,{name:"meta/debug"});let C=A([M,b],([G,V])=>G?tn(d.describe()):"",{name:"meta/shell-mermaid"});d.add(C,{name:"meta/shell-mermaid"});let $=O("",{name:"layout/code-text"});if(d.add($,{name:"layout/code-text"}),s){let G=new Map,V=A([T],([P])=>{let j=P;if(!j)return new Map;let re=new Map;for(let[fe]of Object.entries(j.nodes)){let ee=qt(fe,i,s,G),le=Bn(ee,1/0,s,i,G),Le=le.lines.reduce((Be,J)=>Math.max(Be,J.width),0),Xe=le.lineCount*20;re.set(fe,{width:Le,height:Xe})}return re},{name:"layout/graph-labels",equals:(P,j)=>{if(P===j)return!0;let re=P,fe=j;if(re.size!==fe.size)return!1;for(let[ee,le]of re){let Le=fe.get(ee);if(!Le||Le.width!==le.width||Le.height!==le.height)return!1}return!0}}),F=A([$,m],([P,j])=>{let re=P;if(!re)return{lineCount:0,lines:[]};let fe=qt(re,i,s,G),ee=j-40;return Bn(fe,Math.max(100,ee),s,i,G)},{name:"layout/code-lines"}),K=A([V],([P])=>{let j=P;if(j.size===0)return 200;let re=0;for(let{width:fe}of j.values())fe>re&&(re=fe);return Math.max(200,Math.round(re+80))},{name:"layout/side-width-hint"});d.add(V,{name:"layout/graph-labels"}),d.add(F,{name:"layout/code-lines"}),d.add(K,{name:"layout/side-width-hint"})}let B=0;return{graph:d,setMainRatio(G){d.set("pane/main-ratio",Go(G))},setSideSplit(G){d.set("pane/side-split",Go(G))},setFullscreen(G){d.set("pane/fullscreen",G)},setViewportWidth(G){d.set("viewport/width",Math.max(0,G))},setHoverTarget(G){d.set("hover/target",G)},setDemoGraph(G){d.set("demo/graph-ref",G)},bumpGraphTick(){d.set("demo/graph-tick",++B)},selectNode(G){d.set("inspect/selected-node",G)},setMetaDebug(G){d.set("meta/debug",G)},setCodeText(G){d.set("layout/code-text",G)},batch(G){Z(G)},destroy(){d.destroy()}}}var ji={};Ne(ji,{contentModerationGraph:()=>Eb,dataQualityGraph:()=>_b,issueTrackerGraph:()=>Nb,observabilityGraph:()=>Sb});Ae();ne();at();ue();function Pe(t,e){return xe("domain_template",t,e)}function Sb(t,e){let n=new Q(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>du(T,"error")},{name:"traces",classify:T=>du(T,"trace")},{name:"metrics",classify:T=>du(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=wo("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return A([w],([k])=>k,{initial:null})}catch{return O(null)}}),d=e.correlate??(T=>T),u=A(a,T=>d(T),{meta:Pe("observability",{stage:"correlate"})});n.add(u,{name:"correlate"});let c=e.sloCheck??(()=>({pass:!0})),l=A([u],T=>T[0],{meta:Pe("observability",{stage:"slo_value"})}),p=A([l],T=>c(T[0]),{meta:Pe("observability",{stage:"slo_verified"})});n.add(l,{name:"slo_value"}),n.add(p,{name:"slo_verified"});let f=e.weights??o.map(()=>1),m=a.map(T=>A([T],w=>w[0]!=null?1:0)),h=f.map(T=>O(T));for(let T=0;T<m.length;T++)n.add(m[T],{name:`__signal_${T}`}),n.add(h[T],{name:`__weight_${T}`});let g=Co(m,h);n.add(g,{name:"alerts"});let y=A([g,p],T=>({scored:T[0],slo:T[1]}),{meta:Pe("observability",{stage:"output"})});n.add(y,{name:"output"});let b=O(null,{meta:Pe("observability",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=A([p],T=>{let w=T[0];return w&&w.pass===!1?w:null},{meta:Pe("observability",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),dn(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function Nb(t,e){let n=new Q(t,e);n.add(e.source,{name:"source"});let r=0,o=T=>({id:`issue-${++r}`,title:String(T),severity:1,source:"unknown",raw:T}),s=e.extract??o,i=A([e.source],T=>s(T[0]),{meta:Pe("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),d=A([i],T=>{let w=T[0];return{issue:w,verification:a(w)}},{meta:Pe("issue_tracker",{stage:"verify"})});n.add(d,{name:"verify"});let u=O([],{meta:Pe("issue_tracker",{stage:"known_patterns"})});n.add(u,{name:"known_patterns"});let c=e.detectRegression??(()=>({regression:!1})),l=A([i,u],T=>{let w=T[0],k=T[1];return{issue:w,regression:c(w,k)}},{meta:Pe("issue_tracker",{stage:"regression"})});n.add(l,{name:"regression"});let p=A([i],T=>T[0]?.severity??0),f=A([l],T=>T[0]?.regression?2:0);n.add(p,{name:"__severity_signal"}),n.add(f,{name:"__regression_signal"});let m=O(1),h=O(1.5);n.add(m,{name:"__severity_weight"}),n.add(h,{name:"__regression_weight"});let g=Co([p,f],[m,h]);n.add(g,{name:"priority"});let y=A([d,l,g],T=>({verified:T[0],regression:T[1],priority:T[2]}),{meta:Pe("issue_tracker",{stage:"output"})});n.add(y,{name:"output"});let b=O(null,{meta:Pe("issue_tracker",{stage:"feedback_reentry"})});n.add(b,{name:"feedback_reentry"});let v=A([d],T=>{let w=T[0];if(w){let k=w.verification;if(k&&k.valid===!1)return w}return null},{meta:Pe("issue_tracker",{stage:"feedback_condition"})});return n.add(v,{name:"feedback_condition"}),dn(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function Eb(t,e){let n=new Q(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),o=e.classify??r,s=A([e.source],v=>o(v[0]),{meta:Pe("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=wo("stratify",s,[{name:"safe",classify:v=>v.label==="safe"},{name:"review",classify:v=>v.label==="review"},{name:"block",classify:v=>v.label==="block"}]);n.mount("stratify",i);let a=qe([],{name:"review_queue",maxSize:e.maxQueueSize});n.add(a.entries,{name:"review_queue"});let d;try{d=n.resolve("stratify::branch/review")}catch{d=O(null),n.add(d,{name:"__review_fallback"})}let u=ye([d],v=>{let T=v[0];T&&a.append(T)});n.add(u,{name:"__review_accumulator"}),n.addDisposer(te(u));let c=O({},{meta:Pe("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(c,{name:"policy"});let l=e.weights??[.1,1,2],p=A([s],v=>v[0]?.confidence??0),f=A([s],v=>{let T=v[0];return T?T.label==="block"?l[2]:T.label==="review"?l[1]:l[0]:0});n.add(p,{name:"__confidence_signal"}),n.add(f,{name:"__severity_signal"});let m=O(1),h=O(1);n.add(m,{name:"__w_confidence"}),n.add(h,{name:"__w_severity"});let g=Co([p,f],[m,h]);n.add(g,{name:"priority"});let y=A([s,g],v=>({classification:v[0],priority:v[1]}),{meta:Pe("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=A([a.entries,c],v=>{let T=v[0];if(T&&T.length>0){let w=T[T.length-1];if(w&&w.falsePositive)return w}return null},{meta:Pe("content_moderation",{stage:"feedback_condition"})});return n.add(b,{name:"feedback_condition"}),dn(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function _b(t,e){let n=new Q(t,e);n.add(e.source,{name:"source"});let r=e.validate??(g=>({valid:!0,errors:[],record:g})),o=A([e.source],g=>g[0]!=null?r(g[0]):void 0,{meta:Pe("data_quality",{stage:"validate"})});n.add(o,{name:"validate"});let s=e.detectAnomaly??(g=>({anomaly:!1,score:0,record:g})),i=A([e.source],g=>g[0]!=null?s(g[0]):void 0,{meta:Pe("data_quality",{stage:"anomaly"})});n.add(i,{name:"anomaly"});let a=O(null,{meta:Pe("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let d=ye([o],g=>{let y=g[0];y?.valid&&Z(()=>{a.emit(y.record)})});n.add(d,{name:"__baseline_updater"}),te(d);let u=e.detectDrift??(()=>({drift:!1})),c=A([e.source,a],g=>u(g[0],g[1]),{meta:Pe("data_quality",{stage:"drift"})});n.add(c,{name:"drift"});let l=e.suggest??(()=>null),p=A([o,i],g=>l({validation:g[0],anomaly:g[1]}),{meta:Pe("data_quality",{stage:"remediate"})});n.add(p,{name:"remediate"});let f=A([o,i,c,p],g=>({validation:g[0],anomaly:g[1],drift:g[2],remediation:g[3]}),{meta:Pe("data_quality",{stage:"output"})});n.add(f,{name:"output"});let m=O([],{meta:Pe("data_quality",{stage:"validation_rules"})});n.add(m,{name:"validation_rules"});let h=A([i],g=>{let y=g[0];return y?.anomaly?y:null},{meta:Pe("data_quality",{stage:"feedback_condition"})});return n.add(h,{name:"feedback_condition"}),dn(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function du(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var Vi={};Ne(Vi,{GuardedExecutionGraph:()=>Bi,guardedExecution:()=>Ob});Se();ae();ne();at();ue();function uu(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&"down"in t}function Mb(t){return xe("guarded",t)}var Bi=class extends Q{enforcer;violations;lints;scope;scopedDescribe;_target;_actorNode;_mode;_firedLintKinds=new Set;constructor(e,n){super(n.name??`${e.name}_guarded`,n.graph),this._target=e,this._mode=n.mode??"enforce";let r=n.policies,o=uu(r);if(!o&&this._mode==="enforce"&&r.length===0)throw new RangeError('guardedExecution: empty `policies` in `mode: "enforce"` denies every action. Pass at least `{ effect: "allow", action: "*" }` and layer deny rules on top.');this.lints=new Kt("lints",{retainedLimit:n.lintsLimit??64}),this.mount("lints",this.lints);let s=n.actor;s==null?this._actorNode=O(null,{name:"actor"}):uu(s)?this._actorNode=A([s],([d])=>d??null,{name:"actor",initial:null}):this._actorNode=O(s,{name:"actor"});let i={mode:this._mode,name:"enforcer"};if(n.violationsLimit!=null&&(i.violationsLimit=n.violationsLimit),this.enforcer=ru(e,n.policies,i),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer),o&&this._mode==="enforce"){let d=r,u=d.cache;u!=null&&u.length===0&&this._fireLint("empty-policies",'`policies` Node cached an empty array in `mode: "enforce"` \u2014 every action will be denied. Add at least one allow rule.');let c=d.subscribe(l=>{for(let p of l){if(p[0]!==_)continue;let f=p[1];(f==null||f.length===0)&&this._fireLint("empty-policies",'`policies` Node emitted an empty array in `mode: "enforce"` \u2014 every action will be denied. Add at least one allow rule.')}});this.addDisposer(c)}if(this._mode==="audit"){let d=e.describe({detail:"full"});Object.values(d.nodes).some(c=>c.guard!=null)||this._fireLint("audit-no-effect",'`mode: "audit"` + target has no per-node guards \u2014 `scopedDescribeNode` filters by per-node guards only, so policy rules will not affect describe() visibility. Policies still populate the `violations` topic on writes.')}s==null&&this._fireLint("no-actor","no actor configured \u2014 `wrapper.scopedDescribe` and `scopedDescribeNode()` will return an unscoped describe (full visibility) unless a per-call actor is supplied."),this.scope=A([this._actorNode,this.enforcer.policies],([d,u])=>({actor:d??null,mode:this._mode,policiesCount:u.length}),{name:"scope",describeKind:"derived",meta:Mb("scope")}),this.add(this.scope,{name:"scope"}),this.addDisposer(te(this.scope));let a=e.describe({reactive:!0,actor:this._actorNode,reactiveName:"scopedDescribe"});this.scopedDescribe=a.node,this.add(this.scopedDescribe,{name:"scopedDescribe"}),this.addDisposer(a.dispose)}_fireLint(e,n){this._firedLintKinds.has(e)||(this._firedLintKinds.add(e),this.lints.publish({kind:e,message:n,timestamp_ns:H()}))}scopedDescribeNode(e,n){let r=e==null?this._actorNode:uu(e)?e:O(e,{name:"actor_override"}),o=this._target.describe({reactive:!0,actor:r,...n??{}});return this.addDisposer(o.dispose),{node:o.node,dispose:o.dispose}}get target(){return this._target}};function Ob(t,e){return new Bi(t,e)}var Xi={};Ne(Xi,{DEFAULT_DECAY_RATE:()=>Sr,DEFAULT_EXECUTE_PROMPT:()=>lu,DEFAULT_QUEUE_CONFIGS:()=>Ki,DEFAULT_SEVERITY_WEIGHTS:()=>Rr,DEFAULT_TRIAGE_PROMPT:()=>cu,DEFAULT_VERIFY_PROMPT:()=>pu,HarnessGraph:()=>Qi,QUEUE_NAMES:()=>lt,actuatorExecutor:()=>Qf,affectedTaskFilter:()=>Bb,autoSolidify:()=>Pb,beforeAfterCompare:()=>jb,codeChangeBridge:()=>Vb,createIntakeBridge:()=>Gb,defaultErrorClassifier:()=>qi,defaultLlmExecutor:()=>sm,defaultLlmVerifier:()=>im,dispatchActuator:()=>Db,effectivenessTracker:()=>zb,evalIntakeBridge:()=>Fb,evalSource:()=>$b,evalVerifier:()=>Zf,harnessEvalPair:()=>tv,harnessLoop:()=>dv,harnessProfile:()=>cv,harnessTrace:()=>pv,notifyEffect:()=>Kb,priorityScore:()=>iv,refineExecutor:()=>gu,resolvePromptFn:()=>Fo,strategyKey:()=>Nr,strategyModel:()=>hu});ae();ne();ue();function Ab(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${Ib(e.summary)}`,artifact:t}}function Cb(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function Lb(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function Ib(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function Qf(t){let e=t.name??"actuator-executor",n=t.toOutput??Ab,r=t.onError??Cb,o=t.skipDetail??Lb;return s=>{let i=st(s,d=>d!=null,{name:`${e}/gate-in`}),a=me(i,d=>t.shouldApply&&!t.shouldApply(d)?z(u=>(u.down([[_,{outcome:"failure",detail:o(d)}],[I]]),()=>{}),{name:`${e}/skip`}):z(u=>{let c=new AbortController,l=!1,p=null,f=h=>{l||(l=!0,u.down([[_,h],[I]]),p?.(),p=null)},m;try{let h=t.apply(d,{signal:c.signal});m=Y(h,{signal:c.signal})}catch(h){return f(r(h,d)),()=>{c.abort()}}return p=m.subscribe(h=>{for(let g of h){if(l)return;if(g[0]===_){f(n(g[1],d));return}if(g[0]===L){f(r(g[1],d));return}if(g[0]===I){f(r(new Error("actuator inner completed without emitting DATA"),d));return}}}),l&&p&&(p(),p=null),()=>{c.abort(),p?.(),p=null}},{name:`${e}/inner`}),{name:e});return st(a,d=>d!=null,{name:`${e}/gate-out`})}}function Db(t){let e=t.name??"dispatch-actuator",n=t.default??null,r=n!=null;return Qf({apply:(o,s)=>{let i=Object.hasOwn(t.routes,o.intervention)?t.routes[o.intervention]:n;if(!i)throw new Error(`dispatchActuator: no route for intervention '${o.intervention}'`);return i(o,s)},shouldApply:o=>Object.hasOwn(t.routes,o.intervention)||r,skipDetail:o=>`no route for intervention '${o.intervention}'`,name:e})}ae();ne();function Pb(t){let e=t.name??"auto-solidify",n=t.extract??(o=>o.execution.artifact??null),r=t.predicate??(()=>!0);return z(o=>{let s=null,i=!1,a=()=>{i||(i=!0,s?.(),s=null)},d=u=>{i||(o.down([[L,u]]),a())};return s=t.verifyResults.subscribe(u=>{if(!i)for(let c of u){if(i)return;if(c[0]!==_){if(c[0]===I){o.down([[I]]),a();return}continue}let l=c[1];if(l==null||!l.verified)continue;let p;try{p=r(l)}catch(m){d(m);return}if(!p)continue;let f;try{f=n(l)}catch(m){d(m);return}if(f!=null){try{t.write(f,l)}catch(m){d(m);return}o.down([[_,f]])}}}),i&&s&&(s(),s=null),()=>{a()}},{name:e})}ne();ue();function Gb(t,e,n,r){return ye([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function Fb(t,e,n){let r=n?.defaultSeverity??"medium";return ye([t],([o])=>{if(o==null)return;let s=Array.isArray(o)?o:[o];for(let i of s)for(let a of i.tasks)if(!(a.valid&&a.judge_scores?.every(d=>d.pass))){if(!a.valid&&(!a.judge_scores||a.judge_scores.length===0)){e.publish({source:"eval",summary:`Task ${a.task_id} invalid (model: ${i.model})`,evidence:`Run ${i.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r});continue}if(a.judge_scores)for(let d of a.judge_scores)d.pass||e.publish({source:"eval",summary:`${a.task_id}: ${d.claim} (model: ${i.model})`,evidence:d.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[a.task_id],severity:r})}},{name:n?.name??"eval-intake-bridge"})}function $b(t,e){return me(t,()=>Y(e()))}function jb(t,e){return A([t,e],([n,r])=>{let o=n,s=r,i=new Map(o.tasks.map(p=>[p.task_id,p])),a=new Map(s.tasks.map(p=>[p.task_id,p])),d=new Set([...i.keys(),...a.keys()]),u=[],c=[],l=[];for(let p of d){let f=i.get(p),m=a.get(p),h=f?.valid??!1,g=m?.valid??!1,y=f?.judge_scores?f.judge_scores.filter(T=>T.pass).length:void 0,b=m?.judge_scores?m.judge_scores.filter(T=>T.pass).length:void 0,v=y!==void 0&&b!==void 0?b-y:void 0;u.push({taskId:p,before:h,after:g,scoreDiff:v}),h&&!g&&c.push(p),!h&&g&&l.push(p)}return{newFailures:c,resolved:l,taskDeltas:u,overallImproved:l.length>c.length}},{name:"eval-delta"})}function Bb(t,e){let n=e==null?null:Array.isArray(e)?O(e):e,r=[t];return n&&r.push(n),A(r,o=>{let s=o[0],i=n?new Set(o[1]):null,a=new Set;for(let d of s)for(let u of d.affectsEvalTasks??[])(i==null||i.has(u))&&a.add(u);return[...a].sort()},{name:"affected-task-filter"})}function Vb(t,e,n,r){let o=r?.defaultSeverity??"high";function s(a){let d=[];for(let u of a.lintErrors??[])d.push({source:"code-change",summary:`Lint: ${u.rule} in ${u.file}:${u.line}`,evidence:u.message,affectsAreas:[u.file],severity:o});for(let u of a.testFailures??[])d.push({source:"test",summary:`Test failure: ${u.testId}`,evidence:u.message,affectsAreas:[u.file],affectsEvalTasks:[u.testId],severity:o});return d}let i=n??s;return ye([t],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:r?.name??"code-change-bridge"})}function Kb(t,e,n){return ye([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var lt=["auto-fix","needs-decision","investigation","backlog"],Ki={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},Rr={critical:100,high:70,medium:40,low:10},Sr=Math.LN2/(168*3600);function Nr(t,e){return`${t}\u2192${e}`}var qb=/\b(parse|json|config|validation|syntax)\b/i,qi=t=>qb.test(t.detail)?"self-correctable":"structural",cu=`You are a triage classifier for a reactive collaboration harness.
|
|
177
181
|
|
|
178
182
|
Given an intake item, classify it and output JSON:
|
|
179
183
|
{
|
|
@@ -188,7 +192,7 @@ Strategy model (past effectiveness):
|
|
|
188
192
|
{{strategy}}
|
|
189
193
|
|
|
190
194
|
Intake item:
|
|
191
|
-
{{item}}`,
|
|
195
|
+
{{item}}`,lu=`You are an implementation agent.
|
|
192
196
|
|
|
193
197
|
Given a triaged issue with root cause and intervention type, produce a fix.
|
|
194
198
|
|
|
@@ -199,7 +203,7 @@ Output JSON:
|
|
|
199
203
|
{
|
|
200
204
|
"outcome": "success" | "failure" | "partial",
|
|
201
205
|
"detail": "<description of what was done or what failed>"
|
|
202
|
-
}`,
|
|
206
|
+
}`,pu=`You are a QA reviewer.
|
|
203
207
|
|
|
204
208
|
Given an execution result, verify whether the fix is correct.
|
|
205
209
|
|
|
@@ -214,11 +218,11 @@ Output JSON:
|
|
|
214
218
|
"verified": true/false,
|
|
215
219
|
"findings": ["<finding1>", ...],
|
|
216
220
|
"errorClass": "self-correctable" | "structural" // only if verified=false
|
|
217
|
-
}`;function
|
|
221
|
+
}`;function Fo(t,e,n){if(typeof t=="function")return t;let r=t??e;return o=>n(r,o)}ne();ue();function zb(t){let e=Ye({name:t?.name??"effectiveness-entries"}),n=A([e.entries],([i])=>new Map(i),{name:`${t?.name??"effectiveness"}-snapshot`,equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,l]of d){let p=u.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function r(i,a){let d=e.get(i),u=(d?.attempts??0)+1,c=(d?.successes??0)+(a?1:0);e.set(i,{key:i,attempts:u,successes:c,successRate:c/u})}function o(i){return e.get(i)}let s=te(n);return{node:n,record:r,lookup:o,dispose:()=>{s(),e.dispose()}}}ne();ne();var zi={};Ne(zi,{blindVariation:()=>Wb,errorCritique:()=>Yb,refineLoop:()=>mu});Ae();Se();ae();Me();ne();function Hb(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.subscribe=="function"&&typeof e.down=="function"&&typeof e.emit=="function"}function Xf(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let s=fu(e);return{best:t[0],bestScore:s}}if(e.some(s=>typeof s.candidateIndex=="number")){let s=new Array(t.length);for(let d=0;d<t.length;d++)s[d]={sum:0,count:0};for(let d of e){let u=d.candidateIndex;typeof u=="number"&&u>=0&&u<t.length&&(s[u].sum+=d.score,s[u].count+=1)}let i=t[0],a=s[0].count>0?s[0].sum/s[0].count:Number.NEGATIVE_INFINITY;for(let d=1;d<t.length;d++){let u=s[d].count>0?s[d].sum/s[d].count:Number.NEGATIVE_INFINITY;u>a&&(a=u,i=t[d])}return{best:i,bestScore:a}}let r=t[0],o=e[0]?.score??Number.NEGATIVE_INFINITY;for(let s=1;s<t.length;s++){let i=e[s]?.score??Number.NEGATIVE_INFINITY;i>o&&(o=i,r=t[s])}return{best:r,bestScore:o}}function fu(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function mu(t,e,n,r){let o=r.name??"refine-loop",s=new Q(o,r.graph),i=Hb(r.dataset)?r.dataset:O(r.dataset,{name:"dataset"});s.add(i,{name:"dataset"});let a=O(0,{name:"iteration"});s.add(a,{name:"iteration"});let d=O(n,{name:"strategy",equals:()=>!1});s.add(d,{name:"strategy"});let u=O(null,{name:"lastFeedback"});s.add(u,{name:"lastFeedback"});let c=O([],{name:"prevCandidates"});s.add(c,{name:"prevCandidates"});let l=O(!1,{name:"paused"});s.add(l,{name:"paused"});let p=O("running",{name:"status"});s.add(p,{name:"status"});let f=O([],{name:"history",equals:()=>!1});s.add(f,{name:"history"});let m=O(null,{name:"best"});s.add(m,{name:"best"});let h=O(Number.NEGATIVE_INFINITY,{name:"score"});s.add(h,{name:"score"});let g=O(0,{name:"budget-used"});s.add(g,{name:"budget-used"});let y=Eo("stages");s.mount("stages",y);let b=y.topic("generate"),v=y.topic("evaluate"),T=y.topic("analyze"),w=y.topic("decide"),k=n,R=null,S=[];s.addDisposer(d.subscribe(J=>{for(let de of J)de[0]===_&&(k=de[1])})),s.addDisposer(u.subscribe(J=>{for(let de of J)de[0]===_&&(R=de[1])})),s.addDisposer(c.subscribe(J=>{for(let de of J)de[0]===_&&(S=de[1])}));let x=me(a,J=>{let de=k,Ie=J===0||R==null;return U([],(ke,X)=>{let ie=!1;try{let Re=Ie?de.seed(t):de.generate(R,S);if(Re instanceof Promise)return Re.then(W=>{ie||X.emit(W)},W=>{ie||X.down([[L,W]])}),()=>{ie=!0};X.emit(Re)}catch(Re){ie=!0,X.down([[L,Re]])}},{describeKind:"producer"})},{name:"candidates"});s.add(x,{name:"candidates"});let N=ye([x],(J,de,Ie)=>{let ke=Ie.terminalDeps[0];ke!==void 0&&ke!==!0&&p.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});s.add(N,{name:"error-watcher"}),s.addDisposer(N.subscribe(()=>{}));let E=A([x,a],([J,de])=>({iteration:de,candidates:J,timestamp_ns:H()}),{name:"generate-event"});s.add(E,{name:"generate-event"}),s.addDisposer(E.subscribe(()=>{}));let D=ye([E],([J])=>{b.publish(J)},{name:"generate-publish"});s.add(D,{name:"generate-publish"}),s.addDisposer(D.subscribe(()=>{}));let M=ye([x],([J])=>{c.emit(J)},{name:"generate-mirror"});s.add(M,{name:"generate-mirror"}),s.addDisposer(M.subscribe(()=>{}));let C=e(x,i);s.add(C,{name:"scores"});let $=A([C,x,a],([J,de,Ie])=>({iteration:Ie,candidates:de,scores:J,timestamp_ns:H()}),{name:"evaluate-event"});s.add($,{name:"evaluate-event"}),s.addDisposer($.subscribe(()=>{}));let B=ye([$],([J])=>{v.publish(J)},{name:"evaluate-publish"});s.add(B,{name:"evaluate-publish"}),s.addDisposer(B.subscribe(()=>{}));let G=A([C,x],([J,de])=>k.analyze(J,de),{name:"feedback"});s.add(G,{name:"feedback"});let V=A([G,x,a],([J,de,Ie])=>({iteration:Ie,candidates:de,feedback:J,timestamp_ns:H()}),{name:"analyze-event"});s.add(V,{name:"analyze-event"}),s.addDisposer(V.subscribe(()=>{}));let F=ye([V],([J])=>{T.publish(J)},{name:"analyze-publish"});s.add(F,{name:"analyze-publish"}),s.addDisposer(F.subscribe(()=>{}));let K=A([f],([J])=>{let de=J;if(r.patience==null||de.length<=r.patience)return!1;let Ie=de.slice(-(r.patience+1)),ke=Ie[0].bestScore;return Ie.slice(1).every(X=>X.bestScore<=ke)},{name:"patience-check"});s.add(K,{name:"patience-check"});let P=A([h],([J])=>r.minScore!=null&&J>=r.minScore,{name:"min-score-check"});s.add(P,{name:"min-score-check"});let j=A([f],([J])=>{let de=J;if(r.minDelta==null||de.length<2)return!1;let Ie=de[de.length-2].bestScore,ke=de[de.length-1].bestScore;return Math.abs(ke-Ie)<r.minDelta},{name:"min-delta-check"});s.add(j,{name:"min-delta-check"});let re=A([g],([J])=>r.maxEvaluations!=null&&J>=r.maxEvaluations,{name:"max-evaluations-check"});s.add(re,{name:"max-evaluations-check"});let fe=A([a],([J])=>r.maxIterations!=null&&J>=r.maxIterations,{name:"max-iterations-check"});s.add(fe,{name:"max-iterations-check"});let ee=A([g],([J])=>r.budget!=null&&J>=r.budget,{name:"budget-exhausted-check"});s.add(ee,{name:"budget-exhausted-check"}),s.addDisposer(K.subscribe(()=>{})),s.addDisposer(P.subscribe(()=>{})),s.addDisposer(j.subscribe(()=>{})),s.addDisposer(re.subscribe(()=>{})),s.addDisposer(fe.subscribe(()=>{})),s.addDisposer(ee.subscribe(()=>{}));let le=A([K,P,j,re,fe],([J,de,Ie,ke,X])=>J?{converged:!0,reason:"patience"}:de?{converged:!0,reason:"min-score"}:Ie?{converged:!0,reason:"min-delta"}:ke?{converged:!0,reason:"max-evaluations"}:X?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});s.add(le,{name:"converged"}),s.addDisposer(le.subscribe(()=>{}));let Le=-1,Xe=ye([G,C,x],([J,de,Ie])=>{let ke=a.cache,X=J,ie=Ie,Re=de;if(ke<=Le)return;Le=ke;let{best:W,bestScore:ge}=Xf(ie,Re),Ee=f.cache,_e={n:ke,candidates:ie,scores:Re,feedback:X,best:W,bestScore:ge,timestamp_ns:H()},he=[...Ee,_e],Ge=g.cache+ie.length,Te="continue",we,_r=r.budget!=null&&Ge>=r.budget,Vn=l.cache;if(_r)Te="budget",we="budget";else if(r.minScore!=null&&X.score>=r.minScore)Te="converged",we="min-score";else if(r.maxIterations!=null&&ke>=r.maxIterations)Te="converged",we="max-iterations";else if(r.maxEvaluations!=null&&Ge>=r.maxEvaluations)Te="converged",we="max-evaluations";else if(r.minDelta!=null&&he.length>=2){let Ko=he[he.length-2].bestScore,fa=he[he.length-1].bestScore;Math.abs(fa-Ko)<r.minDelta&&(Te="converged",we="min-delta")}else if(r.patience!=null&&he.length>r.patience){let Ko=he.slice(-(r.patience+1)),fa=Ko[0].bestScore;Ko.slice(1).every(vm=>vm.bestScore<=fa)&&(Te="converged",we="patience")}Te==="continue"&&Vn&&(Te="paused"),Z(()=>{m.emit(W),h.emit(X.score),f.emit(he),g.emit(Ge),u.emit(X),w.publish({iteration:ke,decision:Te,reason:we,timestamp_ns:H()}),Te==="continue"?a.emit(ke+1):p.emit(Te==="converged"?"converged":Te==="budget"?"budget":"paused")})},{name:"decide-bridge"});return s.add(Xe,{name:"decide-bridge"}),s.addDisposer(Xe.subscribe(()=>{})),Object.assign(s,{best:m,score:h,status:p,history:f,strategy:d,iteration:a,generate:b,evaluate:v,analyze:T,decide:w,setStrategy(J){d.emit(J)},pause(){l.emit(!0)},resume(){p.cache==="paused"&&Z(()=>{l.emit(!1),p.emit("running"),a.emit(a.cache+1)})}})}function Wb(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,o){let s=fu(r),i=null;for(let a of r)(!i||a.score<i.score)&&(i=a);return{summary:`blindVariation iteration: mean=${s.toFixed(3)}, n=${r.length}`,score:s,weakTasks:i?[i.taskId]:[]}},async generate(r,o){if(o.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let s=o[o.length-1],i=0,d={prior:s,reportCost:u=>{i+=u}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(d)));let u=[];for(let c=0;c<e;c++)u.push(await t.teacher(d));return u}finally{if(t.tokens!=null&&i>0){let u=t.tokens.cache??0;t.tokens.emit(u+i)}}}}}function Ub(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function Jb(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
|
|
218
222
|
${t.map(r=>{let o=r.error!=null?` | error: ${r.error}`:"";return`- ${r.taskId} (score=${r.score.toFixed(3)})${o}`}).join(`
|
|
219
|
-
`)}`}function Cb(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??Ab;return{name:n,seed(s){return[s]},analyze(s,i){let a=Yd(s),d=typeof t.failureThreshold=="function"?t.failureThreshold(s):t.failureThreshold,u=d===void 0&&!Number.isFinite(a),c=d??a,l=u?[...s].sort((v,T)=>v.score-T.score):s.filter(v=>v.score<c).slice().sort((v,T)=>v.score-T.score),p=l.slice(0,r),{best:f,bestScore:m}=Mf(i,s),h={summary:"",score:a,weakTasks:p.map(v=>v.taskId)},g=o(p,h),y={kind:"errorCritique",best:f,failures:p,critiqueText:g},b=l.length>p.length?` (top ${p.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${l.length}${b}/${s.length}, bestScore=${m.toFixed(3)}`,critique:y,weakTasks:p.map(v=>v.taskId),score:a}},async generate(s,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=Ob(s.critique)?s.critique:void 0,d=a!==void 0?a.best:i[i.length-1],u=a?.critiqueText??s.summary,c=a?.failures??[],l=0,f={prior:d,critique:u,failures:c,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(f)));let m=[];for(let h=0;h<e;h++)m.push(await t.teacher(f));return m}finally{if(t.tokens!=null&&l>0){let m=t.tokens.cache??0;t.tokens.emit(m+l)}}}}}function Lb(t){let{best:e,score:n,status:r}=t,o=Number.isFinite(n)?n.toFixed(3):String(n),s=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${o}`,artifact:s}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${o}`,artifact:s}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:s}}function Xd(t){let e=t.name??"refine-executor",n=t.toOutput??Lb;return r=>{let o=rt(r,i=>i!=null,{name:`${e}/gate-in`}),s=ke(o,i=>{let a=Qd(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return C([a.status,a.best,a.score],([d,u,c])=>{let l=d;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:n({best:u,score:c,status:l})},{name:`${e}/output`})},{name:e});return rt(s,i=>i!=null,{name:`${e}/gate-out`})}}function Ib(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Pb(t){let{passCount:e,total:n,meanScore:r,threshold:o,missingArtifact:s}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!s&&n>0&&r>=o,d=s?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${n} eval tasks passed; mean score ${i} \u2265 ${o}`]:n===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${n} eval tasks passed; mean score ${i} < threshold ${o}`];return a?{verified:!0,findings:d}:{verified:!1,findings:d,errorClass:"structural"}}function Db(t){return t.artifact??null}function Of(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??Pb,o=t.extractArtifact??Db;return s=>{let i=rt(s,d=>d!=null&&d[0]!=null&&d[1]!=null,{name:`${e}/gate-in`}),a=ke(i,d=>{let[u,c]=d,l=o(u,c);if(l==null)return A(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let p=A([l],{name:`${e}/candidates`}),f=A(t.datasetFor(c),{name:`${e}/dataset`}),m=t.evaluator(p,f);return C([m],([h])=>{let g=h;if(g==null)return null;let y=Ib(g),b=g.filter(v=>v.score>=n).length;return r({scores:g,meanScore:y,passCount:b,total:g.length,threshold:n})},{name:`${e}/output`})},{name:e});return rt(a,d=>d!=null,{name:`${e}/gate-out`})}}function Gb(t){let e=t.name??"harness-pair",n=Xd({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=Of({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}Re();it();Me();ne();var Fi={};Se(Fi,{JobFlowGraph:()=>Di,JobQueueGraph:()=>Pi,jobEventKeyOf:()=>jb,jobFlow:()=>Bb,jobQueue:()=>Gi});Re();Me();ve();var Fb=256,$b=1024;function Af(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Ii(t,e){return We("job_queue",t,e)}var jb=t=>t.action,Pi=class extends Q{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,n={}){super(e,n.graph),this._pending=Ks([],{name:"pending"}),this._jobs=je({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=C([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Ii("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(te(this.depth)),this.events=at({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=Yt(this,"seq",0)}_bumpSeq(){let n=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(n),n}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,n={}){let r=this._bumpSeq(),o=n.id??`${this.name}-${r}`;if(this._jobs.get(o)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${o}"`);let s={id:o,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(o,s),this._pending.append(o),this.events.append({action:"enqueue",id:o,payload:e,t_ns:se(),seq:r}),o}claim(e=1){let n=Af(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let s=this._pending.pop(0),i=this._jobs.get(s);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(s,a),r.push(a),this.events.append({action:"claim",id:s,attempts:a.attempts,t_ns:se(),seq:this._bumpSeq()})}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:n.attempts,t_ns:se(),seq:this._bumpSeq()}),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:se(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:se(),seq:this._bumpSeq()}),!0)}removeById(e){let n=this._jobs.get(e);if(!n)return!1;if(n.state==="queued"){let o=this.pending.cache.indexOf(e);o>=0&&this._pending.pop(o)}return this._jobs.delete(e),this.events.append({action:"remove",id:e,attempts:n.attempts,t_ns:se(),seq:this._bumpSeq()}),!0}consumeFrom(e,n){return e.subscribe(r=>{for(let o of r){if(o[0]!==M)continue;let s=o[1];this.enqueue(s,n?{metadata:n.metadata}:void 0)}})}},Di=class extends Q{_stageNames;_stageWorkFns;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=n.stages??["incoming","processing","done"],o=[],s=new Map;for(let d of r){let u=typeof d=="string"?d.trim():d.name.trim();typeof d!="string"&&d.work&&s.set(u,d.work),o.push(u)}if(o.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(o).size!==o.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...o]),this._stageWorkFns=s;for(let d of this._stageNames){let u=Gi(`${e}-${d}`);this._queues.set(d,u),this.mount(d,u)}this._completed=Ke([],{name:"completed",maxSize:$b}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=C([this.completed],([d])=>d.length,{name:"completedCount",describeKind:"derived",meta:Ii("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(te(this.completedCount));let a=Math.max(1,Af(n.maxPerPump??Fb,"job flow maxPerPump"));for(let d=0;d<this._stageNames.length;d+=1){let u=this._stageNames[d],c=this.queue(u),l=d+1<this._stageNames.length?this.queue(this._stageNames[d+1]):null,p=this._stageWorkFns.get(u),f=l===null;if(p){let m=U([c.pending],()=>{let h=0;for(;h<a;){let g=c.claim(1);if(g.length===0)break;let y=g[0];if(!y)break;let v=[...y.metadata.job_flow_path??[],u],T;try{T=p(y)}catch{c.nack(y.id,{requeue:!1}),h+=1;continue}let w=Y(T),x=!1,k;k=w.subscribe(S=>{if(!x){for(let R of S)if(R[0]===M){x=!0,k?k():Promise.resolve().then(()=>k?.());let E=R[1],_={...y.metadata,job_flow_path:v};if(f){let O={...y,payload:E,metadata:Object.freeze(_)};Z(()=>{c.ack(y.id),this._completed.append(O)})}else Z(()=>{c.ack(y.id),l.enqueue(E,{metadata:_})});return}else if(R[0]===I){x=!0,k?k():Promise.resolve().then(()=>k?.()),c.nack(y.id,{requeue:!1});return}}}),h+=1}},{name:`pump_${u}`,describeKind:"effect",meta:Ii("job_flow_pump",{stage:u,has_work:!0})});this.add(m,{name:`pump_${u}`}),this.addDisposer(te(m))}else{let m=U([c.pending],()=>{let h=0;for(;h<a;){let g=c.claim(1);if(g.length===0)break;let y=g[0];if(!y)break;let v=[...y.metadata.job_flow_path??[],u],T={...y.metadata,job_flow_path:v};if(f){let w={...y,metadata:Object.freeze(T)};Z(()=>{c.ack(y.id),this._completed.append(w)})}else Z(()=>{c.ack(y.id),l.enqueue(y.payload,{metadata:T})});h+=1}},{name:`pump_${u}`,describeKind:"effect",meta:Ii("job_flow_pump",{stage:u,has_work:!1})});this.add(m,{name:`pump_${u}`}),this.addDisposer(te(m))}}}stages(){return this._stageNames}queue(e){let n=this._queues.get(e);if(!n)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return n}enqueue(e,n={}){return this.queue(this._stageNames[0]).enqueue(e,n)}retainedCompleted(){return this.completed.cache}};function Gi(t,e){return new Pi(t,e)}function Bb(t,e){let n=new Di(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("jobFlow",st(s)),n}Re();ne();function Zd(){let t=je({name:"strategy-entries"}),e=C([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,l]of d){let p=u.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function n(i,a,d){let u=br(i,a),c=t.get(u),l=(c?.attempts??0)+1,p=(c?.successes??0)+(d?1:0);t.set(u,{rootCause:i,intervention:a,attempts:l,successes:p,successRate:p/l})}function r(i,a){return t.get(br(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function Vb(t,e,n,r,o){let s={...hr,...o?.severityWeights},i=o?.decayRate??yr,a=o?.effectivenessThreshold??.7,d=o?.effectivenessBoost??15,u=[t,e,n];return r&&u.push(r),C(u,c=>{let l=c[0],p=c[1],f=c[2],m=r?c[3]:0,h=s[l.severity??"medium"],g=(V()-f)/1e9,y=En(h,g,i,0),b=br(l.rootCause,l.intervention),v=p.get(b);return v&&v.successRate>=a&&(y+=d),y+=m*20,y},{name:"priority-score"})}var Cf="intake",Kb="triage-output",Lf="retry",If="verify-results",Pf="__unrouted";function Df(t,e){let n=Ao(e,Ud,(r,o)=>r.replace("{{item}}",JSON.stringify(o)));return r=>Sn(t,[r],n,{name:"execute",format:"json"})}function Gf(t,e){let n=Ao(e,Jd,(r,o)=>{let[s,i]=o;return r.replace("{{execution}}",JSON.stringify(s)).replace("{{item}}",JSON.stringify(i))});return r=>Sn(t,[r],o=>o==null?"":n(o),{name:"verify",format:"json"})}var $i=class extends Q{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,o,s,i,a,d,u){super(e),this.queues=n,this.queueTopics=r,this.jobs=o,this.gates=s,this.strategy=i,this.totalRetries=a,this.totalReingestions=d,this.priorityScores=u}get intake(){return this.queues.topic(Cf)}get verifyResults(){return this.queues.topic(If)}get retry(){return this.queues.topic(Lf)}get unrouted(){return this.queues.topic(Pf)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],o=ct.flatMap(i=>r(n(i))),s=[];for(let[i]of this.gates)s.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:o},{label:"GATE",paths:s},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:r(n("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function qb(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??Ci,i=new Map;for(let X of ct)i.set(X,{...Ai[X],...e.queues?.[X]});let a=ko(`${t}/queues`,{defaultTopicOptions:{retainedLimit:o}}),d=a.topic(Cf),u=a.topic(Kb),c=a.topic(Lf),l=a.topic(If),p=new Map;for(let X of ct)p.set(X,a.topic(X));let f=a.topic(Pf),m=Zd(),h=Ft(d.latest,m.node),g=Ao(e.triagePrompt,Wd,(X,ie)=>{let[xe,W]=ie;return X.replace("{{strategy}}",JSON.stringify(Array.from(W.entries()))).replace("{{item}}",JSON.stringify(xe))}),y=Sn(n,[h],X=>{let ie=X;return!ie||!ie[0]?"":g(ie)},{name:"triage",format:"json"}),b=Ft(y,h),T=ge([b],([X])=>{if(X==null)return;let[ie,xe]=X;if(!ie?.route)return;let W=xe?.[0],fe={...ie,...W};u.publish(fe)}).subscribe(()=>{}),w=new Set(ct);for(let X of ct)ci(`bridge/${X}`,u,p.get(X),{map:ie=>ie.route===X?ie:void 0});ci("bridge/__unrouted",u,f,{map:X=>w.has(X.route)?void 0:X});let x=new Map,k=new Map;for(let X of ct)x.set(X,Gi(`jobs/${X}`));let S=[];for(let X of ct){let ie=p.get(X),xe=x.get(X),W=new WeakSet,fe=ge([ie.events],([Ne])=>{let Ee=Ne??[];for(let me of Ee){if(W.has(me))continue;W.add(me);let De=xe.enqueue(me);k.set(Qr(me),{route:X,id:De})}},{name:`jobs/${X}-mirror`});S.push(fe.subscribe(()=>{}))}function R(X){let ie=Qr(X),xe=k.get(ie);xe&&(x.get(xe.route)?.removeById(xe.id),k.delete(ie))}let E=pr("gates"),_=new Map;for(let X of ct){let ie=i.get(X);if(!ie.gated)continue;let xe=p.get(X),W=E.gate(`${X}/gate`,xe.latest,{maxPending:ie.maxPending,startOpen:ie.startOpen});_.set(X,W)}let O=[];for(let X of ct)i.get(X).gated&&_.has(X)?O.push(_.get(X).node):O.push(p.get(X).latest);O.push(c.latest);let N=Et(...O),j=(e.executor??Df(n,e.executePrompt))(N),$=Ft(j,N),K=(e.verifier??Gf(n,e.verifyPrompt))($),F=Ft(K,$),H=e.maxReingestions??1,G=Math.min(e.maxTotalRetries??r*10,100),B=Math.min(e.maxTotalReingestions??H*10,100),re=A(0),pe=A(0);function ee(X,ie,xe){let W={item:xe,outcome:ie?.outcome??"failure",detail:ie?.detail??"unknown",artifact:ie?.artifact};return{item:xe,execution:W,verified:X.verified,findings:X.findings??[],errorClass:X.errorClass}}function ue(X,ie){m.record(ie.rootCause,ie.intervention,!0),l.publish(X),R(ie)}function Ce(X,ie){let xe=Qr(ie),W=ie.$retries??0,fe={...ie,$retries:W+1,summary:`[RETRY ${W+1}/${r}] ${xe} \u2014 Previous attempt failed: ${X.findings.join("; ")}`,relatedTo:[xe]};c.publish(fe)}function Ye(X,ie){m.record(ie.rootCause,ie.intervention,!1),l.publish(X),R(ie);let xe=Qr(ie),W=ie.$reingestions??0;W<H&&Yr(pe,B)&&d.publish({source:ie.source,summary:`Verification failed for: ${xe}`,evidence:X.findings.join(`
|
|
220
|
-
`),affectsAreas:ie.affectsAreas,affectsEvalTasks:ie.affectsEvalTasks,severity:ie.severity??"high",relatedTo:[xe],$reingestions:W+1})}let Be=U([F],(X,ie)=>{let xe=X[0];if(xe==null||xe.length===0)return;let W=xe[xe.length-1];if(W==null)return;let[fe,Ne]=W,[Ee,me]=Ne??[null,null];if(!fe||!me)return;if(Ee==null){Ye({item:me,execution:{item:me,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},me);return}let De=ee(fe,Ee,me);if(De.verified){ue(De,me);return}let ye=De.errorClass??s({item:me,outcome:Ee.outcome,detail:De.findings.join("; ")}),be=me.$retries??0;ye==="self-correctable"&&be<r&&Yr(re,G)?Ce(De,me):Ye(De,me)}),J=Be.subscribe(()=>{}),de=C([Be],()=>null,{name:"reflect",equals:()=>!1}),Le;e.priority&&(Le=zb(p,m,e));let Te=new $i(t,a,p,x,_,m,re,pe,Le);Te.addDisposer(T),Te.addDisposer(J),Te.addDisposer(m.dispose);for(let X of S)Te.addDisposer(X);if(Te.add(y,{name:"triage"}),Te.add(N,{name:"execute-input"}),Te.add(j,{name:"execute"}),Te.add($,{name:"execute-context"}),Te.add(K,{name:"verify"}),Te.add(F,{name:"verify-context"}),Te.add(Be,{name:"verify-dispatch"}),Te.add(de,{name:"reflect"}),Te.add(m.node,{name:"strategy"}),Te.addDisposer(de.subscribe(()=>{})),Le)for(let[X,ie]of Le)Te.add(ie,{name:`priority/${X}`}),Te.addDisposer(ie.subscribe(()=>{}));Te.mount("queues",a),Te.mount("gates",E);for(let[X,ie]of x)Te.mount(`jobs/${X}`,ie);return Te.tagFactory("harnessLoop",st(e)),Te}function zb(t,e,n){if(!n.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let r=n.lastInteractionNs,o=n.priority??{},s={...hr,...o.severityWeights},i=o.decayRate??yr,a=o.effectivenessThreshold??.7,d=o.effectivenessBoost??15,u=new Map;for(let[c,l]of t){let p=C([l.latest,e.node,r],f=>{let m=f[0];if(m==null)return 0;let h=s[m.severity??"medium"]??40,g=(V()-f[2])/1e9,y=h*Math.exp(-i*Math.max(0,g)),b=`${m.rootCause}\u2192${m.intervention}`,T=f[1]?.get(b);return T&&T.successRate>=a&&(y+=d),y},{name:`priority/${c}`});u.set(c,p)}return u}function Hb(t,e){let n=hn(t,e),r={};for(let o of ct){let s=t.queues.has(o)?t.queues.topic(o):null;r[o]=s?.retained().length??0}return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}Re();function Wb(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let o of r)e[o]=n;return e}function Ub(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=V(),s=[],i=[],a=Wb(t);function d(){return(V()-o)/1e9}function u(c,l,p){let f={elapsed:d(),stage:c,type:l};r!=="summary"&&(f.summary=Jb(p)),r==="full"&&(f.data=p),i.push(f)}for(let[c,l]of Object.entries(a))try{let p=t.observe(c,{format:"stage-log",stageLabels:a,logger:n?f=>n(f):()=>{},includeTypes:["data","error","complete"]});p.onEvent(f=>{f.type==="data"?u(l,"data",f.data):f.type==="error"?u(l,"error",f.data):f.type==="complete"&&u(l,"complete",void 0)}),s.push(p)}catch(p){let f=p instanceof Error?p.message:String(p);u(l,"error",`observe-unavailable: ${c} \u2014 ${f}`),n&&n(`[${d().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${f}`)}return{get events(){return i},dispose(){for(let c of s)c.dispose();s.length=0}}}function Jb(t){if(t==null)return"null";if(typeof t=="string")return Ff(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return Ff(e,120)}catch{return String(t)}}function Ff(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var Vi={};Se(Vi,{LensGraph:()=>Bi,graphLens:()=>ev,watchTopologyTree:()=>Pt});Re();ne();function $f(t){return We("lens",t)}function Yb(t){let e=Object.keys(t.nodes),n=new Map,r=new Map;for(let h of e){let g=t.nodes[h]?.deps??[];n.set(h,g);for(let y of g)r.has(y)||r.set(y,new Set),r.get(y).add(h)}let o=[],s=[];for(let h of e)(n.get(h)??[]).length===0&&o.push(h),r.has(h)||s.push(h);o.sort(),s.sort();let i=t.edges.length,a=0,d=1,u=2,c=new Map;for(let h of e)c.set(h,a);let l=!1,p=new Map,f=h=>{let g=c.get(h)??a;if(g===d)return l=!0,0;if(g===u)return p.get(h)??0;c.set(h,d);let y=0,b=r.get(h);if(b!=null)for(let v of b){let T=f(v);T+1>y&&(y=T+1)}return c.set(h,u),p.set(h,y),y},m=0;for(let h of o){let g=f(h);g>m&&(m=g)}for(let h of e)c.get(h)===a&&f(h);return{nodeCount:e.length,edgeCount:i,subgraphCount:t.subgraphs.length,sources:o,sinks:s,depth:m,hasCycles:l}}function Qb(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=yn(t,n,"upstream",{});for(let i of s)if(i!==n&&t.nodes[i]?.status==="errored"){o.upstreamCause=i;break}e.push(o)}return e.sort((n,r)=>n.path<r.path?-1:n.path>r.path?1:0),{ok:e.length===0,problems:e}}function Xb(t,e){return t.nodeCount===e.nodeCount&&t.edgeCount===e.edgeCount&&t.subgraphCount===e.subgraphCount&&t.depth===e.depth&&t.hasCycles===e.hasCycles&&jf(t.sources,e.sources)&&jf(t.sinks,e.sinks)}function Zb(t,e){if(t.ok!==e.ok||t.problems.length!==e.problems.length)return!1;for(let n=0;n<t.problems.length;n++){let r=t.problems[n],o=e.problems[n];if(r.path!==o.path||r.status!==o.status||r.upstreamCause!==o.upstreamCause)return!1}return!0}function jf(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}var Bi=class extends Q{stats;health;flow;_target;constructor(e,n={}){super(n.name??`${e.name}_lens`,n.graph),this._target=e;let r=0,o=0,s=A(0,{name:"stats_tick"}),i=A(0,{name:"health_tick"});this.add(s,{name:"stats_tick"}),this.add(i,{name:"health_tick"});let a={name:"flow"};n.maxFlowPaths!=null&&(a.maxSize=n.maxFlowPaths),this.flow=je(a),this.add(this.flow.entries,{name:"flow"});let d=n.pathFilter,u=Pt(e,(p,f,m)=>{if(r+=1,s.emit(r),o+=1,i.emit(o),p.kind==="removed")if(p.nodeKind==="node"){let h=`${m}${p.name}`;this.flow.delete(h)}else{let h=`${m}${p.name}::`,g=[];for(let y of p.audit.nodes){let b=y===""?`${m}${p.name}`:`${h}${y}`;g.push(b)}g.length>0&&this.flow.deleteMany(g)}});this.addDisposer(u);let c=e.observe({timeline:!0,structured:!0}),l=c.onEvent(p=>{let f=p.type;if((f==="error"||f==="complete"||f==="data"||f==="teardown")&&(o+=1,i.emit(o)),f==="data"){let m=p.path??"";if(!m||d!=null&&!d(m))return;let h=this.flow.get(m),g=h!=null?h.count+1:1;this.flow.set(m,{path:m,count:g,lastUpdate_ns:V()})}});this.addDisposer(()=>{l(),c.dispose()}),this.stats=C([s],()=>Yb(e.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:Xb,meta:$f("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(te(this.stats)),this.health=C([i],()=>Qb(e.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:Zb,meta:$f("health")}),this.add(this.health,{name:"health"}),this.addDisposer(te(this.health))}why(e,n,r){let o=Bd(this._target,e,n,r);return this.addDisposer(o.dispose),o}get target(){return this._target}};function ev(t,e){return new Bi(t,e)}var Ki={};Se(Ki,{processInstanceKeyOf:()=>tv,processManager:()=>rv});Re();ae();ve();var tv=t=>t.correlationId;function Bf(t){if(t==null)return Promise.resolve(void 0);let e=Y(t);return new Promise((n,r)=>{let o=!1,s,i=()=>{s&&s()};s=e.subscribe(a=>{if(!o)for(let d of a){if(d[0]===M){o=!0,Promise.resolve().then(i),n(d[1]);return}if(d[0]===I){o=!0,Promise.resolve().then(i),r(d[1]);return}if(d[0]===P){o=!0,Promise.resolve().then(i),n(void 0);return}}})})}async function nv(t,e,n,r,o){let s;for(let i=0;i<=r;i++){if(i>0){let a=o[Math.min(i-1,o.length-1)]??0;a>0&&await new Promise(d=>setTimeout(d,a))}try{return await Bf(t(e,n))}catch(a){s=a}}return{kind:"fail",error:s}}function rv(t,e,n){let r=n.retryMax??0,o=n.backoffMs??[0],s=1024,i=new Map,a=new Set,d=new Map,u=at({name:`${e}_process_instances`,retainedLimit:s,graph:t}),c=0;function l(){return++c}function p(R,E,_){f(R,E,_,void 0)}function f(R,E,_,O){let N=se(),L={correlationId:R,state:E,status:_,startedAt:d.get(R)??N,updatedAt:N,t_ns:N,seq:l(),...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},...O!==void 0?{reason:O}:{}};u.append(L)}let m=`_process_${e}_started`;t.event(m),n.persistence?.eventStorage&&t.attachEventStorage(n.persistence.eventStorage);async function h(R,E,_,O){if(a.delete(R),i.delete(R),d.delete(R),n.compensate)try{await Bf(n.compensate(E,_)),f(R,E,"compensated",O)}catch{p(R,E,"failed")}else p(R,E,"failed")}async function g(R,E){if(a.has(R)){if(E.kind==="fail"){let _=i.get(R)??n.initial;await h(R,_,E.error);return}if(E.kind==="continue"){if(i.set(R,E.state),E.emit)for(let _ of E.emit)try{t._appendEvent(_.type,_.payload,{correlationId:R,aggregateId:R})}catch{}if(p(R,E.state,"running"),n.isTerminal?.(E.state)){a.delete(R),i.delete(R),d.delete(R),p(R,E.state,"terminated");return}if(E.schedule){let{afterMs:_,eventType:O}=E.schedule,N,L=Ze(_),j=$=>{for(let D of $)if(D[0]===M){if(N?N():queueMicrotask(()=>N?.()),!a.has(R))return;let K=i.get(R);if(K===void 0)return;let F=n.steps[O];if(!F)return;let H={type:O,payload:null,timestampNs:se(),seq:Number.NaN,correlationId:R,aggregateId:R};b(R,F,K,H)}};N=L.subscribe(j)}return}if(E.kind==="terminate"){if(i.set(R,E.state),E.emit)for(let _ of E.emit)try{t._appendEvent(_.type,_.payload,{correlationId:R,aggregateId:R})}catch{}a.delete(R),i.delete(R),d.delete(R),p(R,E.state,"terminated")}}}let y=new Map;function b(R,E,_,O){let L=(y.get(R)??Promise.resolve()).then(async()=>{let j=i.get(R);if(j===void 0||!a.has(R))return;let $;try{$=await nv(E,j,O,r,o)}catch(D){await h(R,i.get(R)??n.initial,D);return}await g(R,$)});y.set(R,L),L.finally(()=>{y.get(R)===L&&y.delete(R)})}let v=!1,T=[];for(let R of n.watching){let E=t.event(R),_=0;_=(E.cache??[]).length;let N=E.subscribe(L=>{for(let j of L){if(j[0]!==M)continue;let $=j[1];if($.length<=_)continue;let D=$.slice(_);_=$.length;for(let K of D){let F=K.correlationId;if(F===void 0||!a.has(F))continue;let H=n.steps[R];if(!H)continue;let G=i.get(F);G!==void 0&&b(F,H,G,K)}}});T.push(N)}function w(R,E){if(v||a.has(R))return;let _=se();d.set(R,_),i.set(R,n.initial),a.add(R);try{t._appendEvent(m,E??null,{correlationId:R,aggregateId:R})}catch{}p(R,n.initial,"running")}function x(R,E){if(v||!a.has(R))return;let _=i.get(R)??n.initial;h(R,_,new Error(`cancelled: ${E??"no reason given"}`),E)}function k(R){return i.get(R)}function S(){if(!v){v=!0;for(let R of T)try{R()}catch{}T.length=0}}return{instances:u,audit:u,start:w,cancel:x,getState:k,dispose:S}}var qi={};Se(qi,{CanvasMeasureAdapter:()=>ru,CliMeasureAdapter:()=>eu,ImageSizeAdapter:()=>iu,NodeCanvasMeasureAdapter:()=>ou,PrecomputedAdapter:()=>nu,SvgBoundsAdapter:()=>su,analyzeAndMeasure:()=>Bt,carveTextLineSlots:()=>zd,circleIntervalForBand:()=>Hf,computeBlockFlow:()=>qf,computeCharPositions:()=>Ni,computeFlowLines:()=>Uf,computeLineBreaks:()=>_n,computeTotalHeight:()=>zf,layoutNextLine:()=>qd,measureBlock:()=>Vf,measureBlocks:()=>Kf,reactiveBlockLayout:()=>ov,reactiveFlowLayout:()=>iv,reactiveLayout:()=>ab,rectIntervalForBand:()=>Wf});var eu=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:tr(e)*this.cellPx}}},tu=class extends Error{name="KeyError"},nu=class{metrics;fallback;constructor(e){this.metrics=e.metrics;let n=e.fallback??"per-char";if(n!=="per-char"&&n!=="error")throw new Error(`fallback must be 'per-char' or 'error', got ${JSON.stringify(e.fallback)}`);this.fallback=n}measureSegment(e,n){let r=this.metrics[n];if(r){let s=r[e];if(s!==void 0)return{width:s}}if(this.fallback==="error")throw new tu(`PrecomputedAdapter: no metrics for segment ${JSON.stringify(e)} in font ${JSON.stringify(n)}`);let o=0;if(r)for(let s of e){let i=r[s];i!==void 0&&(o+=i)}return{width:o}}},ru=class{ctx=null;currentFont="";emojiCorrection;constructor(e){this.emojiCorrection=e?.emojiCorrection??1}getContext(){if(!this.ctx){if(typeof OffscreenCanvas>"u")throw new Error("CanvasMeasureAdapter requires a browser environment with OffscreenCanvas support. Use CliMeasureAdapter or NodeCanvasMeasureAdapter for Node.js.");let n=new OffscreenCanvas(0,0).getContext("2d");if(!n)throw new Error("CanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();n!==this.currentFont&&(r.font=n,this.currentFont=n);let o=r.measureText(e).width;return this.emojiCorrection!==1&&new RegExp("\\p{Emoji_Presentation}","u").test(e)&&(o*=this.emojiCorrection),{width:o}}clearCache(){this.currentFont=""}},ou=class{ctx=null;currentFont="";canvasModule;constructor(e){this.canvasModule=e}getContext(){if(!this.ctx){let n=this.canvasModule.createCanvas(0,0).getContext("2d");if(!n)throw new Error("NodeCanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();return n!==this.currentFont&&(r.font=n,this.currentFont=n),{width:r.measureText(e).width}}clearCache(){this.currentFont=""}},su=class{measureSvg(e){let n=e.match(/viewBox\s*=\s*["']([^"']+)["']/);if(n){let s=n[1].trim().split(/[\s,]+/);if(s.length>=4){let i=Number.parseFloat(s[2]),a=Number.parseFloat(s[3]);if(Number.isFinite(i)&&Number.isFinite(a)&&i>0&&a>0)return{width:i,height:a};throw new Error("SvgBoundsAdapter: viewBox width/height are missing, non-finite, or not positive")}}let r=e.match(/<svg[^>]*\bwidth\s*=\s*["']?([\d.]+)/),o=e.match(/<svg[^>]*\bheight\s*=\s*["']?([\d.]+)/);if(r&&o){let s=Number.parseFloat(r[1]),i=Number.parseFloat(o[1]);if(Number.isFinite(s)&&Number.isFinite(i)&&s>0&&i>0)return{width:s,height:i};throw new Error("SvgBoundsAdapter: svg width/height attributes are non-finite or not positive")}throw new Error("SvgBoundsAdapter: cannot determine dimensions \u2014 SVG has no viewBox or width/height attributes")}},iu=class{sizes;constructor(e){this.sizes=new Map(Object.entries(e))}measureImage(e){let n=this.sizes.get(e);if(!n)throw new Error(`ImageSizeAdapter: no dimensions registered for ${JSON.stringify(e)}`);return{width:n.width,height:n.height}}};Re();Me();ne();function Vf(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,d=t.lineHeight??s,u=Bt(t.text,a,n.text,r),c=_n(u,e,n.text,a,r),l=Ni(c,u,d),p=c.lineCount*d,f=0;for(let m of c.lines)m.width>f&&(f=m.width);return{index:i,type:"text",width:Math.min(f,e),height:p,textSegments:u,textLineBreaks:c,textCharPositions:l}}case"image":{let a,d;if(t.naturalWidth!=null&&t.naturalHeight!=null)a=t.naturalWidth,d=t.naturalHeight;else if(n.image){let u=n.image.measureImage(t.src);a=u.width,d=u.height}else throw new Error(`Image block at index ${i} has no naturalWidth/naturalHeight and no ImageMeasurer adapter`);return a>e&&(d=d*e/a,a=e),{index:i,type:"image",width:a,height:d}}case"svg":{let a,d;if(t.viewBox)a=t.viewBox.width,d=t.viewBox.height;else if(n.svg){let u=n.svg.measureSvg(t.content);a=u.width,d=u.height}else throw new Error(`SVG block at index ${i} has no viewBox and no SvgMeasurer adapter`);return a>e&&(d=d*e/a,a=e),{index:i,type:"svg",width:a,height:d}}}}function Kf(t,e,n,r,o,s){return t.map((i,a)=>Vf(i,e,n,r,o,s,a))}function qf(t,e){let n=[],r=0;for(let o=0;o<t.length;o++){let s=t[o];n.push({...s,x:0,y:r}),r+=s.height+(o<t.length-1?e:0)}return n}function zf(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function ov(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new Q(n),i=new Map,a=A(t.blocks??[],{name:"blocks"}),d=A(Math.max(0,t.maxWidth??800),{name:"max-width"}),u=A(t.gap??0,{name:"gap"}),c=U([a,d],(f,m,h)=>{let g=f[0]!=null&&f[0].length>0?f[0].at(-1):h.prevData[0],y=f[1]!=null&&f[1].length>0?f[1].at(-1):h.prevData[1],b=V(),v=Kf(g,y,e,i,r,o),T=V()-b,w=c.meta;w&&(vt(w["block-count"],v.length),vt(w["layout-time-ns"],T)),m.emit(v);let x=()=>{i.clear(),e.text.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"measured-blocks",describeKind:"derived",meta:{"block-count":0,"layout-time-ns":0},equals:(f,m)=>{let h=f,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=C([c,u],([f,m])=>qf(f,m),{name:"block-flow",equals:(f,m)=>{let h=f,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.x!==v.x||b.y!==v.y||b.width!==v.width||b.height!==v.height)return!1}return!0}}),p=C([l],([f])=>zf(f),{name:"total-height"});return s.add(a,{name:"blocks"}),s.add(d,{name:"max-width"}),s.add(u,{name:"gap"}),s.add(c,{name:"measured-blocks"}),s.add(l,{name:"block-flow"}),s.add(p,{name:"total-height"}),{graph:s,setBlocks:f=>s.set("blocks",f),setMaxWidth:f=>s.set("max-width",Math.max(0,f)),setGap:f=>s.set("gap",f),measuredBlocks:c,blockFlow:l,totalHeight:p}}Re();Me();ne();function Hf(t,e,n){let r=t.hPad??0,o=t.vPad??0,s=e-o,i=n+o;if(s>=t.cy+t.r||i<=t.cy-t.r)return null;let a=t.cy>=s&&t.cy<=i?0:t.cy<s?s-t.cy:t.cy-i;if(a>=t.r)return null;let d=Math.sqrt(t.r*t.r-a*a);return{left:t.cx-d-r,right:t.cx+d+r}}function Wf(t,e,n){let r=t.hPad??0,o=t.vPad??0;return n<=t.y-o||e>=t.y+t.h+o?null:{left:t.x-r,right:t.x+t.w+r}}function sv(t,e,n){return t.kind==="circle"?Hf(t,e,n):Wf(t,e,n)}function Uf(t,e,n,r,o,s,i){let a=i?.paragraphSpacing??o,d=[],u={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||o<=0)return{lines:d,cursor:u};let c=e.paddingX??0,l=e.paddingY??0,p=Math.max(0,e.width-c*2),f=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),h=Math.max(0,(p-m)/n.count);if(h<=0)return{lines:d,cursor:u};e:for(let g=0;g<n.count;g++){let y=c+g*(h+n.gap),b=y+h,v=l;for(;v+o<=l+f;){let T=v+o,w=[];for(let S=0;S<r.length;S++){let R=sv(r[S],v,T);R!==null&&w.push(R)}let x=zd({left:y,right:b},w,s);if(x.length===0){v+=o;continue}let k=!1;for(let S=0;S<x.length;S++){let R=x[S],E=R.right-R.left,_=qd(t,u,E);if(_===null)return{lines:d,cursor:u};if(_.text.length===0&&_.width===0){u=_.end,k=!0;break}d.push({x:R.left,y:v,width:_.width,slotWidth:E,text:_.text,columnIndex:g,flushToRight:R.right<b-.5}),u=_.end}if(k){v+=a;continue}if(v+=o,u.segmentIndex>=t.length)break e}if(u.segmentIndex>=t.length)break}return{lines:d,cursor:u}}function iv(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new Q(n),s=new Map,i=A(t.text??"",{name:"text"}),a=A(t.font??"16px sans-serif",{name:"font"}),d=A(t.lineHeight??20,{name:"line-height"}),u=A(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),c=A(t.columns??{count:1,gap:0},{name:"columns"}),l=A(t.obstacles??[],{name:"obstacles"}),p=A(t.paragraphSpacing??null,{name:"paragraph-spacing"}),f=U([i,a],(h,g,y)=>{let b=h[0],v=b!=null&&b.length>0?b.at(-1):y.prevData[0],T=h[1],w=T!=null&&T.length>0?T.at(-1):y.prevData[1],x=Bt(v,w,e,s);g.emit(x);let k=()=>{s.clear(),e.clearCache?.()};return{deactivate:k,invalidate:k}},{name:"segments",describeKind:"derived"}),m=C([f,u,c,l,d,p],([h,g,y,b,v,T])=>{let w=h,x=V(),k=T??v,{lines:S,cursor:R}=Uf(w,g,y,b,v,r,{paragraphSpacing:k}),E=V()-x,_=Math.max(0,w.length-R.segmentIndex),O=m.meta;return O&&(vt(O["line-count"],S.length),vt(O["layout-time-ns"],E),vt(O["overflow-segments"],_)),S},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(h,g)=>{let y=h,b=g;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return o.add(i,{name:"text"}),o.add(a,{name:"font"}),o.add(d,{name:"line-height"}),o.add(u,{name:"container"}),o.add(c,{name:"columns"}),o.add(l,{name:"obstacles"}),o.add(p,{name:"paragraph-spacing"}),o.add(f,{name:"segments"}),o.add(m,{name:"flow-lines"}),{graph:o,setText:h=>o.set("text",h),setFont:h=>o.set("font",h),setLineHeight:h=>o.set("line-height",h),setContainer:h=>o.set("container",h),setColumns:h=>o.set("columns",h),setObstacles:h=>o.set("obstacles",h),setParagraphSpacing:h=>o.set("paragraph-spacing",h),segments:f,flowLines:m}}var zi={};Se(zi,{NS_PER_MS:()=>He,NS_PER_SEC:()=>lt,resilientPipeline:()=>av});Wn();It();function av(t,e={}){let n=t;e.rateLimit!=null&&(n=Jn(n,e.rateLimit)),e.budget!=null&&e.budget.length>0&&(n=Dd(n,e.budget));let r;if(e.breaker!=null){let s=Nt(e.breaker),i=e.breakerOnOpen??"skip",a=Un(s,{onOpen:i})(n);n=a.node,r=a.breakerState}if(e.timeoutMs!=null){if(e.timeoutMs<=0)throw new RangeError("timeoutMs must be > 0");if(e.timeoutMs>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic");n=Qn(n,e.timeoutMs*1e6)}e.retry!=null&&(n=St(n,e.retry)),e.fallback!==void 0&&(n=Yn(n,e.fallback));let o=Ht(n,{initialStatus:e.initialStatus??"pending"});return{node:o.node,status:o.status,error:o.error,breakerState:r}}var ea={};Se(ea,{SNAPSHOT_WIRE_VERSION:()=>Io,SurfaceError:()=>_e,asSurfaceError:()=>Hi,createGraph:()=>vr,deleteSnapshot:()=>Zi,diffSnapshots:()=>Qi,listSnapshots:()=>Xi,restoreSnapshot:()=>Yi,runReduction:()=>Wi,saveSnapshot:()=>Ji});var _e=class extends Error{code;details;constructor(e,n,r){super(n),this.name="SurfaceError",this.code=e,r!==void 0&&(this.details=r)}toJSON(){let e={code:this.code,message:this.message};if(this.details!==void 0){let n=dv(this.details);n!==void 0&&(e.details=n)}return e}};function dv(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function Hi(t,e="internal-error"){if(t instanceof _e)return t;let n=t instanceof Error?t.message:String(t);return new _e(e,n)}function vr(t,e){let n=gr(t);if(!n.valid)throw new _e("invalid-spec",`GraphSpec validation failed:
|
|
223
|
+
`)}`}function Yb(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??Jb;return{name:n,seed(s){return[s]},analyze(s,i){let a=fu(s),d=typeof t.failureThreshold=="function"?t.failureThreshold(s):t.failureThreshold,u=d===void 0&&!Number.isFinite(a),c=d??a,l=u?[...s].sort((v,T)=>v.score-T.score):s.filter(v=>v.score<c).slice().sort((v,T)=>v.score-T.score),p=l.slice(0,r),{best:f,bestScore:m}=Xf(i,s),h={summary:"",score:a,weakTasks:p.map(v=>v.taskId)},g=o(p,h),y={kind:"errorCritique",best:f,failures:p,critiqueText:g},b=l.length>p.length?` (top ${p.length} retained)`:"";return{summary:`errorCritique iteration: mean=${a.toFixed(3)}, failures=${l.length}${b}/${s.length}, bestScore=${m.toFixed(3)}`,critique:y,weakTasks:p.map(v=>v.taskId),score:a}},async generate(s,i){if(i.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let a=Ub(s.critique)?s.critique:void 0,d=a!==void 0?a.best:i[i.length-1],u=a?.critiqueText??s.summary,c=a?.failures??[],l=0,f={prior:d,critique:u,failures:c,reportCost:m=>{l+=m}};try{if(t.parallel!==!1)return await Promise.all(Array.from({length:e},()=>t.teacher(f)));let m=[];for(let h=0;h<e;h++)m.push(await t.teacher(f));return m}finally{if(t.tokens!=null&&l>0){let m=t.tokens.cache??0;t.tokens.emit(m+l)}}}}}function Qb(t){let{best:e,score:n,status:r}=t,o=Number.isFinite(n)?n.toFixed(3):String(n),s=e??void 0;return r==="converged"?{outcome:"success",detail:`refineLoop converged at score ${o}`,artifact:s}:r==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${o}`,artifact:s}:{outcome:"failure",detail:`refineLoop errored (status=${r})`,artifact:s}}function gu(t){let e=t.name??"refine-executor",n=t.toOutput??Qb;return r=>{let o=st(r,i=>i!=null,{name:`${e}/gate-in`}),s=me(o,i=>{let a=mu(t.seedFrom(i),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(i),name:`${e}/inner`});return A([a.status,a.best,a.score],([d,u,c])=>{let l=d;return l!=="converged"&&l!=="budget"&&l!=="errored"?null:n({best:u,score:c,status:l})},{name:`${e}/output`})},{name:e});return st(s,i=>i!=null,{name:`${e}/gate-out`})}}function Xb(t){if(t.length===0)return Number.NEGATIVE_INFINITY;let e=0;for(let n of t)e+=n.score;return e/t.length}function Zb(t){let{passCount:e,total:n,meanScore:r,threshold:o,missingArtifact:s}=t,i=Number.isFinite(r)?r.toFixed(3):String(r),a=!s&&n>0&&r>=o,d=s?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:a?[`${e}/${n} eval tasks passed; mean score ${i} \u2265 ${o}`]:n===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${e}/${n} eval tasks passed; mean score ${i} < threshold ${o}`];return a?{verified:!0,findings:d}:{verified:!1,findings:d,errorClass:"structural"}}function ev(t){return t.artifact??null}function Zf(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??Zb,o=t.extractArtifact??ev;return s=>{let i=st(s,d=>d!=null&&d[0]!=null&&d[1]!=null,{name:`${e}/gate-in`}),a=me(i,d=>{let[u,c]=d,l=o(u,c);if(l==null)return O(r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0}));let p=O([l],{name:`${e}/candidates`}),f=O(t.datasetFor(c),{name:`${e}/dataset`}),m=t.evaluator(p,f);return A([m],([h])=>{let g=h;if(g==null)return null;let y=Xb(g),b=g.filter(v=>v.score>=n).length;return r({scores:g,meanScore:y,passCount:b,total:g.length,threshold:n})},{name:`${e}/output`})},{name:e});return st(a,d=>d!=null,{name:`${e}/gate-out`})}}function tv(t){let e=t.name??"harness-pair",n=gu({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=Zf({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}Se();et();Me();ne();var Yi={};Ne(Yi,{JobFlowGraph:()=>Ui,JobQueueGraph:()=>Wi,jobEventKeyOf:()=>ov,jobFlow:()=>sv,jobQueue:()=>Ji});Se();Me();at();ue();var nv=256,rv=1024;function em(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Hi(t,e){return xe("job_queue",t,e)}var ov=t=>t.action,Wi=class extends Q{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;constructor(e,n={}){super(e,n.graph),this._pending=Zs([],{name:"pending"}),this._jobs=Ye({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=A([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Hi("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(te(this.depth)),this.events=ot({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=_t(this,"seq",0)}_bumpSeq(){let n=(this._seqCursor.cache??0)+1;return this._seqCursor.emit(n),n}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,n={}){let r=this._bumpSeq(),o=n.id??`${this.name}-${r}`;if(this._jobs.get(o)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${o}"`);let s={id:o,payload:e,attempts:0,metadata:Object.freeze({...n.metadata??{}}),state:"queued"};return this._jobs.set(o,s),this._pending.append(o),this.events.append({action:"enqueue",id:o,payload:e,t_ns:oe(),seq:r}),o}claim(e=1){let n=em(e,"job queue claim limit");if(n===0)return[];let r=[];for(;r.length<n&&this.pending.cache.length!==0;){let s=this._pending.pop(0),i=this._jobs.get(s);if(!i||i.state!=="queued")continue;let a={...i,state:"inflight",attempts:i.attempts+1};this._jobs.set(s,a),r.push(a),this.events.append({action:"claim",id:s,attempts:a.attempts,t_ns:oe(),seq:this._bumpSeq()})}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._jobs.delete(e),this.events.append({action:"ack",id:e,attempts:n.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:n.requeue??!0?(this._jobs.set(e,{...r,state:"queued"}),this._pending.append(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0):(this._jobs.delete(e),this.events.append({action:"nack",id:e,attempts:r.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0)}removeById(e){let n=this._jobs.get(e);if(!n)return!1;if(n.state==="queued"){let o=this.pending.cache.indexOf(e);o>=0&&this._pending.pop(o)}return this._jobs.delete(e),this.events.append({action:"remove",id:e,attempts:n.attempts,t_ns:oe(),seq:this._bumpSeq()}),!0}consumeFrom(e,n){return e.subscribe(r=>{for(let o of r){if(o[0]!==_)continue;let s=o[1];this.enqueue(s,n?{metadata:n.metadata}:void 0)}})}},Ui=class extends Q{_stageNames;_stageWorkFns;_queues=new Map;_completed;completed;completedCount;constructor(e,n={}){super(e,n.graph);let r=n.stages??["incoming","processing","done"],o=[],s=new Map;for(let d of r){let u=typeof d=="string"?d.trim():d.name.trim();typeof d!="string"&&d.work&&s.set(u,d.work),o.push(u)}if(o.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(o).size!==o.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...o]),this._stageWorkFns=s;for(let d of this._stageNames){let u=Ji(`${e}-${d}`);this._queues.set(d,u),this.mount(d,u)}this._completed=qe([],{name:"completed",maxSize:rv}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=A([this.completed],([d])=>d.length,{name:"completedCount",describeKind:"derived",meta:Hi("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(te(this.completedCount));let a=Math.max(1,em(n.maxPerPump??nv,"job flow maxPerPump"));for(let d=0;d<this._stageNames.length;d+=1){let u=this._stageNames[d],c=this.queue(u),l=d+1<this._stageNames.length?this.queue(this._stageNames[d+1]):null,p=this._stageWorkFns.get(u),f=l===null;if(p){let m=U([c.pending],()=>{let h=0;for(;h<a;){let g=c.claim(1);if(g.length===0)break;let y=g[0];if(!y)break;let v=[...y.metadata.job_flow_path??[],u],T;try{T=p(y)}catch{c.nack(y.id,{requeue:!1}),h+=1;continue}let w=Y(T),k=!1,R;R=w.subscribe(S=>{if(!k){for(let x of S)if(x[0]===_){k=!0,R?R():Promise.resolve().then(()=>R?.());let N=x[1],E={...y.metadata,job_flow_path:v};if(f){let D={...y,payload:N,metadata:Object.freeze(E)};Z(()=>{c.ack(y.id),this._completed.append(D)})}else Z(()=>{c.ack(y.id),l.enqueue(N,{metadata:E})});return}else if(x[0]===L){k=!0,R?R():Promise.resolve().then(()=>R?.()),c.nack(y.id,{requeue:!1});return}}}),h+=1}},{name:`pump_${u}`,describeKind:"effect",meta:Hi("job_flow_pump",{stage:u,has_work:!0})});this.add(m,{name:`pump_${u}`}),this.addDisposer(te(m))}else{let m=U([c.pending],()=>{let h=0;for(;h<a;){let g=c.claim(1);if(g.length===0)break;let y=g[0];if(!y)break;let v=[...y.metadata.job_flow_path??[],u],T={...y.metadata,job_flow_path:v};if(f){let w={...y,metadata:Object.freeze(T)};Z(()=>{c.ack(y.id),this._completed.append(w)})}else Z(()=>{c.ack(y.id),l.enqueue(y.payload,{metadata:T})});h+=1}},{name:`pump_${u}`,describeKind:"effect",meta:Hi("job_flow_pump",{stage:u,has_work:!1})});this.add(m,{name:`pump_${u}`}),this.addDisposer(te(m))}}}stages(){return this._stageNames}queue(e){let n=this._queues.get(e);if(!n)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return n}enqueue(e,n={}){return this.queue(this._stageNames[0]).enqueue(e,n)}retainedCompleted(){return this.completed.cache}};function Ji(t,e){return new Wi(t,e)}function sv(t,e){let n=new Ui(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("jobFlow",We(s)),n}Se();ne();function hu(){let t=Ye({name:"strategy-entries"}),e=A([t.entries],([i])=>{let a=i;return new Map(a)},{name:"strategy-model",equals:(i,a)=>{let d=i,u=a;if(d.size!==u.size)return!1;for(let[c,l]of d){let p=u.get(c);if(!p||l.attempts!==p.attempts||l.successes!==p.successes)return!1}return!0}});function n(i,a,d){let u=Nr(i,a),c=t.get(u),l=(c?.attempts??0)+1,p=(c?.successes??0)+(d?1:0);t.set(u,{rootCause:i,intervention:a,attempts:l,successes:p,successRate:p/l})}function r(i,a){return t.get(Nr(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function iv(t,e,n,r,o){let s={...Rr,...o?.severityWeights},i=o?.decayRate??Sr,a=o?.effectivenessThreshold??.7,d=o?.effectivenessBoost??15,u=[t,e,n];return r&&u.push(r),A(u,c=>{let l=c[0],p=c[1],f=c[2],m=r?c[3]:0,h=s[l.severity??"medium"],g=(H()-f)/1e9,y=Ot(h,g,i,0),b=Nr(l.rootCause,l.intervention),v=p.get(b);return v&&v.successRate>=a&&(y+=d),y+=m*20,y},{name:"priority-score"})}var tm="intake",av="triage-output",nm="retry",rm="verify-results",om="__unrouted";function sm(t,e){let n=Fo(e,lu,(r,o)=>r.replace("{{item}}",JSON.stringify(o)));return r=>jn(t,[r],n,{name:"execute",format:"json"})}function im(t,e){let n=Fo(e,pu,(r,o)=>{let[s,i]=o;return r.replace("{{execution}}",JSON.stringify(s)).replace("{{item}}",JSON.stringify(i))});return r=>jn(t,[r],o=>o==null?"":n(o),{name:"verify",format:"json"})}var Qi=class extends Q{queues;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,o,s,i,a,d,u){super(e),this.queues=n,this.queueTopics=r,this.jobs=o,this.gates=s,this.strategy=i,this.totalRetries=a,this.totalReingestions=d,this.priorityScores=u}get intake(){return this.queues.topic(tm)}get verifyResults(){return this.queues.topic(rm)}get retry(){return this.queues.topic(nm)}get unrouted(){return this.queues.topic(om)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],o=lt.flatMap(i=>r(n(i))),s=[];for(let[i]of this.gates)s.push(`gates::${i}/gate`);return[{label:"INTAKE",paths:r(n("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:o},{label:"GATE",paths:s},{label:"EXECUTE",paths:["execute"]},{label:"VERIFY",paths:r(n("verify-results"))},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function dv(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??qi,i=new Map;for(let X of lt)i.set(X,{...Ki[X],...e.queues?.[X]});let a=Eo(`${t}/queues`,{defaultTopicOptions:{retainedLimit:o}}),d=a.topic(tm),u=a.topic(av),c=a.topic(nm),l=a.topic(rm),p=new Map;for(let X of lt)p.set(X,a.topic(X));let f=a.topic(om),m=hu(),h=jt(d.latest,m.node),g=Fo(e.triagePrompt,cu,(X,ie)=>{let[Re,W]=ie;return X.replace("{{strategy}}",JSON.stringify(Array.from(W.entries()))).replace("{{item}}",JSON.stringify(Re))}),y=jn(n,[h],X=>{let ie=X;return!ie||!ie[0]?"":g(ie)},{name:"triage",format:"json"}),b=jt(y,h),T=ye([b],([X])=>{if(X==null)return;let[ie,Re]=X;if(!ie?.route)return;let W=Re?.[0],ge={...ie,...W};u.publish(ge)}).subscribe(()=>{}),w=new Set(lt);for(let X of lt)wi(`bridge/${X}`,u,p.get(X),{map:ie=>ie.route===X?ie:void 0});wi("bridge/__unrouted",u,f,{map:X=>w.has(X.route)?void 0:X});let k=new Map,R=new Map;for(let X of lt)k.set(X,Ji(`jobs/${X}`));let S=[];for(let X of lt){let ie=p.get(X),Re=k.get(X),W=new WeakSet,ge=ye([ie.events],([Ee])=>{let _e=Ee??[];for(let he of _e){if(W.has(he))continue;W.add(he);let Ge=Re.enqueue(he);R.set(Po(he),{route:X,id:Ge})}},{name:`jobs/${X}-mirror`});S.push(ge.subscribe(()=>{}))}function x(X){let ie=Po(X),Re=R.get(ie);Re&&(k.get(Re.route)?.removeById(Re.id),R.delete(ie))}let N=kr("gates"),E=new Map;for(let X of lt){let ie=i.get(X);if(!ie.gated)continue;let Re=p.get(X),W=N.approvalGate(`${X}/gate`,Re.latest,{maxPending:ie.maxPending,startOpen:ie.startOpen});E.set(X,W)}let D=[];for(let X of lt)i.get(X).gated&&E.has(X)?D.push(E.get(X).node):D.push(p.get(X).latest);D.push(c.latest);let M=Mt(...D),$=(e.executor??sm(n,e.executePrompt))(M),B=jt($,M),V=(e.verifier??im(n,e.verifyPrompt))(B),F=jt(V,B),K=e.maxReingestions??1,P=Math.min(e.maxTotalRetries??r*10,100),j=Math.min(e.maxTotalReingestions??K*10,100),re=O(0),fe=O(0);function ee(X,ie,Re){let W={item:Re,outcome:ie?.outcome??"failure",detail:ie?.detail??"unknown",artifact:ie?.artifact};return{item:Re,execution:W,verified:X.verified,findings:X.findings??[],errorClass:X.errorClass}}function le(X,ie){m.record(ie.rootCause,ie.intervention,!0),l.publish(X),x(ie)}function Le(X,ie){let Re=Po(ie),W=ie.$retries??0,ge={...ie,$retries:W+1,summary:`[RETRY ${W+1}/${r}] ${Re} \u2014 Previous attempt failed: ${X.findings.join("; ")}`,relatedTo:[Re]};c.publish(ge)}function Xe(X,ie){m.record(ie.rootCause,ie.intervention,!1),l.publish(X),x(ie);let Re=Po(ie),W=ie.$reingestions??0;W<K&&On(fe,j)&&d.publish({source:ie.source,summary:`Verification failed for: ${Re}`,evidence:X.findings.join(`
|
|
224
|
+
`),affectsAreas:ie.affectsAreas,affectsEvalTasks:ie.affectsEvalTasks,severity:ie.severity??"high",relatedTo:[Re],$reingestions:W+1})}let Be=U([F],(X,ie)=>{let Re=X[0];if(Re==null||Re.length===0)return;let W=Re[Re.length-1];if(W==null)return;let[ge,Ee]=W,[_e,he]=Ee??[null,null];if(!ge||!he)return;if(_e==null){Xe({item:he,execution:{item:he,outcome:"failure",detail:"executor returned null"},verified:!1,findings:["executor returned null"],errorClass:"structural"},he);return}let Ge=ee(ge,_e,he);if(Ge.verified){le(Ge,he);return}let Te=Ge.errorClass??s({item:he,outcome:_e.outcome,detail:Ge.findings.join("; ")}),we=he.$retries??0;Te==="self-correctable"&&we<r&&On(re,P)?Le(Ge,he):Xe(Ge,he)}),J=Be.subscribe(()=>{}),de=A([Be],()=>null,{name:"reflect",equals:()=>!1}),Ie;e.priority&&(Ie=uv(p,m,e));let ke=new Qi(t,a,p,k,E,m,re,fe,Ie);ke.addDisposer(T),ke.addDisposer(J),ke.addDisposer(m.dispose);for(let X of S)ke.addDisposer(X);if(ke.add(y,{name:"triage"}),ke.add(M,{name:"execute-input"}),ke.add($,{name:"execute"}),ke.add(B,{name:"execute-context"}),ke.add(V,{name:"verify"}),ke.add(F,{name:"verify-context"}),ke.add(Be,{name:"verify-dispatch"}),ke.add(de,{name:"reflect"}),ke.add(m.node,{name:"strategy"}),ke.addDisposer(de.subscribe(()=>{})),Ie)for(let[X,ie]of Ie)ke.add(ie,{name:`priority/${X}`}),ke.addDisposer(ie.subscribe(()=>{}));ke.mount("queues",a),ke.mount("gates",N);for(let[X,ie]of k)ke.mount(`jobs/${X}`,ie);return ke.tagFactory("harnessLoop",We(e)),ke}function uv(t,e,n){if(!n.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let r=n.lastInteractionNs,o=n.priority??{},s={...Rr,...o.severityWeights},i=o.decayRate??Sr,a=o.effectivenessThreshold??.7,d=o.effectivenessBoost??15,u=new Map;for(let[c,l]of t){let p=A([l.latest,e.node,r],f=>{let m=f[0];if(m==null)return 0;let h=s[m.severity??"medium"]??40,g=(H()-f[2])/1e9,y=h*Math.exp(-i*Math.max(0,g)),b=`${m.rootCause}\u2192${m.intervention}`,T=f[1]?.get(b);return T&&T.successRate>=a&&(y+=d),y},{name:`priority/${c}`});u.set(c,p)}return u}function cv(t,e){let n=En(t,e),r={};for(let o of lt){let s=t.queues.has(o)?t.queues.topic(o):null;r[o]=s?.retained().length??0}return{...n,queueDepths:r,strategyEntries:t.strategy.node.cache?.size??0,totalRetries:t.totalRetries.cache??0,totalReingestions:t.totalReingestions.cache??0}}Se();function lv(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let o of r)e[o]=n;return e}function pv(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=H(),s=[],i=[],a=lv(t);function d(){return(H()-o)/1e9}function u(c,l,p){let f={elapsed:d(),stage:c,type:l};r!=="summary"&&(f.summary=fv(p)),r==="full"&&(f.data=p),i.push(f)}for(let[c,l]of Object.entries(a))try{let p=t.observe(c,{format:"stage-log",stageLabels:a,logger:n?f=>n(f):()=>{},includeTypes:["data","error","complete"]});p.onEvent(f=>{f.type==="data"?u(l,"data",f.data):f.type==="error"?u(l,"error",f.data):f.type==="complete"&&u(l,"complete",void 0)}),s.push(p)}catch(p){let f=p instanceof Error?p.message:String(p);u(l,"error",`observe-unavailable: ${c} \u2014 ${f}`),n&&n(`[${d().toFixed(3)}s] ${l.padEnd(9)} \u2717 observe-unavailable: ${f}`)}return{get events(){return i},dispose(){for(let c of s)c.dispose();s.length=0}}}function fv(t){if(t==null)return"null";if(typeof t=="string")return am(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return am(e,120)}catch{return String(t)}}function am(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var Zi={};Ne(Zi,{computeHealthReport:()=>dm,graphLens:()=>mv,healthReportEqual:()=>um,watchTopologyTree:()=>Cn});ne();at();ue();function dm(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=Mn(t,n,"upstream",{});for(let i of s)if(i!==n&&t.nodes[i]?.status==="errored"){o.upstreamCause=i;break}e.push(o)}return e.sort((n,r)=>n.path<r.path?-1:n.path>r.path?1:0),{ok:e.length===0,problems:e}}function um(t,e){if(t.ok!==e.ok||t.problems.length!==e.problems.length)return!1;for(let n=0;n<t.problems.length;n++){let r=t.problems[n],o=e.problems[n];if(r.path!==o.path||r.status!==o.status||r.upstreamCause!==o.upstreamCause)return!1}return!0}function mv(t){let e=t.describe({reactive:!0,detail:"standard",reactiveName:"graphLens.topology"}),n=e.node,r=A([n],([l])=>dm(l),{name:"graphLens.health",describeKind:"derived",equals:um,meta:xe("lens","health")}),o=te(r),s=new Map,i=-1,a=t.observe({reactive:!0,tiers:["data"]}),d=A([a,n],([l,p])=>{let f=l,m=p;if(f!=null&&f.flushedAt_ns>i){i=f.flushedAt_ns;for(let h of f.events){if(h.type!=="data")continue;let g=h.path;if(g==null||g==="")continue;let y=s.get(g);s.set(g,{path:g,count:(y?.count??0)+1,lastUpdate_ns:f.flushedAt_ns})}}if(m!=null&&s.size>0){let h=new Set(Object.keys(m.nodes));for(let g of[...s.keys()])h.has(g)||s.delete(g)}return new Map(s)},{name:"graphLens.flow",describeKind:"derived",meta:xe("lens","flow")}),u=te(d),c=!1;return{topology:n,health:r,flow:d,dispose(){c||(c=!0,u(),o(),e.dispose())}}}var ea={};Ne(ea,{processInstanceKeyOf:()=>gv,processManager:()=>yv});Se();ae();ue();var gv=t=>t.correlationId;function cm(t){if(t==null)return Promise.resolve(void 0);let e=Y(t);return new Promise((n,r)=>{let o=!1,s,i=()=>{s&&s()};s=e.subscribe(a=>{if(!o)for(let d of a){if(d[0]===_){o=!0,Promise.resolve().then(i),n(d[1]);return}if(d[0]===L){o=!0,Promise.resolve().then(i),r(d[1]);return}if(d[0]===I){o=!0,Promise.resolve().then(i),n(void 0);return}}})})}async function hv(t,e,n,r,o){let s;for(let i=0;i<=r;i++){if(i>0){let a=o[Math.min(i-1,o.length-1)]??0;a>0&&await new Promise(d=>setTimeout(d,a))}try{return await cm(t(e,n))}catch(a){s=a}}return{outcome:"failure",error:s}}function yv(t,e,n){let r=n.retryMax??0,o=n.backoffMs??[0],s=1024,i=new Map,a=new Set,d=new Map,u=ot({name:`${e}_process_instances`,retainedLimit:s,graph:t}),c=0;function l(){return++c}function p(x,N,E){f(x,N,E,void 0)}function f(x,N,E,D){let M=oe(),C={correlationId:x,state:N,status:E,startedAt:d.get(x)??M,updatedAt:M,t_ns:M,seq:l(),...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},...D!==void 0?{reason:D}:{}};u.append(C)}let m=`_process_${e}_started`;t.event(m),n.persistence?.eventStorage&&t.attachEventStorage(n.persistence.eventStorage);async function h(x,N,E,D){if(a.delete(x),i.delete(x),d.delete(x),n.compensate)try{await cm(n.compensate(N,E)),f(x,N,"compensated",D)}catch{p(x,N,"errored")}else p(x,N,"errored")}async function g(x,N){if(a.has(x)){if(N.outcome==="failure"){let E=i.get(x)??n.initial;await h(x,E,N.error);return}if(N.outcome==="success"){if(i.set(x,N.state),N.emit)for(let E of N.emit)try{t._appendEvent(E.type,E.payload,{correlationId:x,aggregateId:x})}catch{}if(p(x,N.state,"running"),n.isTerminal?.(N.state)){a.delete(x),i.delete(x),d.delete(x),p(x,N.state,"terminated");return}if(N.schedule){let{afterMs:E,eventType:D}=N.schedule,M,C=tt(E),$=B=>{for(let G of B)if(G[0]===_){if(M?M():queueMicrotask(()=>M?.()),!a.has(x))return;let V=i.get(x);if(V===void 0)return;let F=n.steps[D];if(!F)return;let K={type:D,payload:null,timestampNs:oe(),seq:Number.NaN,correlationId:x,aggregateId:x};b(x,F,V,K)}};M=C.subscribe($)}return}if(N.outcome==="terminate"){if(i.set(x,N.state),N.emit)for(let E of N.emit)try{t._appendEvent(E.type,E.payload,{correlationId:x,aggregateId:x})}catch{}a.delete(x),i.delete(x),d.delete(x),p(x,N.state,"terminated")}}}let y=new Map;function b(x,N,E,D){let C=(y.get(x)??Promise.resolve()).then(async()=>{let $=i.get(x);if($===void 0||!a.has(x))return;let B;try{B=await hv(N,$,D,r,o)}catch(G){await h(x,i.get(x)??n.initial,G);return}await g(x,B)});y.set(x,C),C.finally(()=>{y.get(x)===C&&y.delete(x)})}let v=!1,T=[];for(let x of n.watching){let N=t.event(x),E=0;E=(N.cache??[]).length;let M=N.subscribe(C=>{for(let $ of C){if($[0]!==_)continue;let B=$[1];if(B.length<=E)continue;let G=B.slice(E);E=B.length;for(let V of G){let F=V.correlationId;if(F===void 0||!a.has(F))continue;let K=n.steps[x];if(!K)continue;let P=i.get(F);P!==void 0&&b(F,K,P,V)}}});T.push(M)}function w(x,N){if(v||a.has(x))return;let E=oe();d.set(x,E),i.set(x,n.initial),a.add(x);try{t._appendEvent(m,N??null,{correlationId:x,aggregateId:x})}catch{}p(x,n.initial,"running")}function k(x,N){if(v||!a.has(x))return;let E=i.get(x)??n.initial;h(x,E,new Error(`cancelled: ${N??"no reason given"}`),N)}function R(x){return i.get(x)}function S(){if(!v){v=!0;for(let x of T)try{x()}catch{}T.length=0}}return{instances:u,audit:u,start:w,cancel:k,getState:R,dispose:S}}var ta={};Ne(ta,{CanvasMeasureAdapter:()=>Tu,CliMeasureAdapter:()=>yu,ImageSizeAdapter:()=>xu,NodeCanvasMeasureAdapter:()=>wu,PrecomputedAdapter:()=>vu,SvgBoundsAdapter:()=>ku,analyzeAndMeasure:()=>qt,carveTextLineSlots:()=>au,circleIntervalForBand:()=>gm,computeBlockFlow:()=>fm,computeCharPositions:()=>Fi,computeFlowLines:()=>ym,computeLineBreaks:()=>Bn,computeTotalHeight:()=>mm,layoutNextLine:()=>iu,measureBlock:()=>lm,measureBlocks:()=>pm,reactiveBlockLayout:()=>bv,reactiveFlowLayout:()=>Tv,reactiveLayout:()=>xb,rectIntervalForBand:()=>hm});var yu=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:pr(e)*this.cellPx}}},bu=class extends Error{name="KeyError"},vu=class{metrics;fallback;constructor(e){this.metrics=e.metrics;let n=e.fallback??"per-char";if(n!=="per-char"&&n!=="error")throw new Error(`fallback must be 'per-char' or 'error', got ${JSON.stringify(e.fallback)}`);this.fallback=n}measureSegment(e,n){let r=this.metrics[n];if(r){let s=r[e];if(s!==void 0)return{width:s}}if(this.fallback==="error")throw new bu(`PrecomputedAdapter: no metrics for segment ${JSON.stringify(e)} in font ${JSON.stringify(n)}`);let o=0;if(r)for(let s of e){let i=r[s];i!==void 0&&(o+=i)}return{width:o}}},Tu=class{ctx=null;currentFont="";emojiCorrection;constructor(e){this.emojiCorrection=e?.emojiCorrection??1}getContext(){if(!this.ctx){if(typeof OffscreenCanvas>"u")throw new Error("CanvasMeasureAdapter requires a browser environment with OffscreenCanvas support. Use CliMeasureAdapter or NodeCanvasMeasureAdapter for Node.js.");let n=new OffscreenCanvas(0,0).getContext("2d");if(!n)throw new Error("CanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();n!==this.currentFont&&(r.font=n,this.currentFont=n);let o=r.measureText(e).width;return this.emojiCorrection!==1&&new RegExp("\\p{Emoji_Presentation}","u").test(e)&&(o*=this.emojiCorrection),{width:o}}clearCache(){this.currentFont=""}},wu=class{ctx=null;currentFont="";canvasModule;constructor(e){this.canvasModule=e}getContext(){if(!this.ctx){let n=this.canvasModule.createCanvas(0,0).getContext("2d");if(!n)throw new Error("NodeCanvasMeasureAdapter: failed to get 2d context");this.ctx=n}return this.ctx}measureSegment(e,n){let r=this.getContext();return n!==this.currentFont&&(r.font=n,this.currentFont=n),{width:r.measureText(e).width}}clearCache(){this.currentFont=""}},ku=class{measureSvg(e){let n=e.match(/viewBox\s*=\s*["']([^"']+)["']/);if(n){let s=n[1].trim().split(/[\s,]+/);if(s.length>=4){let i=Number.parseFloat(s[2]),a=Number.parseFloat(s[3]);if(Number.isFinite(i)&&Number.isFinite(a)&&i>0&&a>0)return{width:i,height:a};throw new Error("SvgBoundsAdapter: viewBox width/height are missing, non-finite, or not positive")}}let r=e.match(/<svg[^>]*\bwidth\s*=\s*["']?([\d.]+)/),o=e.match(/<svg[^>]*\bheight\s*=\s*["']?([\d.]+)/);if(r&&o){let s=Number.parseFloat(r[1]),i=Number.parseFloat(o[1]);if(Number.isFinite(s)&&Number.isFinite(i)&&s>0&&i>0)return{width:s,height:i};throw new Error("SvgBoundsAdapter: svg width/height attributes are non-finite or not positive")}throw new Error("SvgBoundsAdapter: cannot determine dimensions \u2014 SVG has no viewBox or width/height attributes")}},xu=class{sizes;constructor(e){this.sizes=new Map(Object.entries(e))}measureImage(e){let n=this.sizes.get(e);if(!n)throw new Error(`ImageSizeAdapter: no dimensions registered for ${JSON.stringify(e)}`);return{width:n.width,height:n.height}}};Se();Me();ne();function lm(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,d=t.lineHeight??s,u=qt(t.text,a,n.text,r),c=Bn(u,e,n.text,a,r),l=Fi(c,u,d),p=c.lineCount*d,f=0;for(let m of c.lines)m.width>f&&(f=m.width);return{index:i,type:"text",width:Math.min(f,e),height:p,textSegments:u,textLineBreaks:c,textCharPositions:l}}case"image":{let a,d;if(t.naturalWidth!=null&&t.naturalHeight!=null)a=t.naturalWidth,d=t.naturalHeight;else if(n.image){let u=n.image.measureImage(t.src);a=u.width,d=u.height}else throw new Error(`Image block at index ${i} has no naturalWidth/naturalHeight and no ImageMeasurer adapter`);return a>e&&(d=d*e/a,a=e),{index:i,type:"image",width:a,height:d}}case"svg":{let a,d;if(t.viewBox)a=t.viewBox.width,d=t.viewBox.height;else if(n.svg){let u=n.svg.measureSvg(t.content);a=u.width,d=u.height}else throw new Error(`SVG block at index ${i} has no viewBox and no SvgMeasurer adapter`);return a>e&&(d=d*e/a,a=e),{index:i,type:"svg",width:a,height:d}}}}function pm(t,e,n,r,o,s){return t.map((i,a)=>lm(i,e,n,r,o,s,a))}function fm(t,e){let n=[],r=0;for(let o=0;o<t.length;o++){let s=t[o];n.push({...s,x:0,y:r}),r+=s.height+(o<t.length-1?e:0)}return n}function mm(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function bv(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new Q(n),i=new Map,a=O(t.blocks??[],{name:"blocks"}),d=O(Math.max(0,t.maxWidth??800),{name:"max-width"}),u=O(t.gap??0,{name:"gap"}),c=U([a,d],(f,m,h)=>{let g=f[0]!=null&&f[0].length>0?f[0].at(-1):h.prevData[0],y=f[1]!=null&&f[1].length>0?f[1].at(-1):h.prevData[1],b=H(),v=pm(g,y,e,i,r,o),T=H()-b,w=c.meta;w&&(St(w["block-count"],v.length),St(w["layout-time-ns"],T)),m.emit(v);let k=()=>{i.clear(),e.text.clearCache?.()};return{deactivate:k,invalidate:k}},{name:"measured-blocks",describeKind:"derived",meta:{"block-count":0,"layout-time-ns":0},equals:(f,m)=>{let h=f,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.type!==v.type||b.width!==v.width||b.height!==v.height||b.index!==v.index)return!1}return!0}}),l=A([c,u],([f,m])=>fm(f,m),{name:"block-flow",equals:(f,m)=>{let h=f,g=m;if(h==null||g==null)return h===g;if(h.length!==g.length)return!1;for(let y=0;y<h.length;y++){let b=h[y],v=g[y];if(b.x!==v.x||b.y!==v.y||b.width!==v.width||b.height!==v.height)return!1}return!0}}),p=A([l],([f])=>mm(f),{name:"total-height"});return s.add(a,{name:"blocks"}),s.add(d,{name:"max-width"}),s.add(u,{name:"gap"}),s.add(c,{name:"measured-blocks"}),s.add(l,{name:"block-flow"}),s.add(p,{name:"total-height"}),{graph:s,setBlocks:f=>s.set("blocks",f),setMaxWidth:f=>s.set("max-width",Math.max(0,f)),setGap:f=>s.set("gap",f),measuredBlocks:c,blockFlow:l,totalHeight:p}}Se();Me();ne();function gm(t,e,n){let r=t.hPad??0,o=t.vPad??0,s=e-o,i=n+o;if(s>=t.cy+t.r||i<=t.cy-t.r)return null;let a=t.cy>=s&&t.cy<=i?0:t.cy<s?s-t.cy:t.cy-i;if(a>=t.r)return null;let d=Math.sqrt(t.r*t.r-a*a);return{left:t.cx-d-r,right:t.cx+d+r}}function hm(t,e,n){let r=t.hPad??0,o=t.vPad??0;return n<=t.y-o||e>=t.y+t.h+o?null:{left:t.x-r,right:t.x+t.w+r}}function vv(t,e,n){return t.kind==="circle"?gm(t,e,n):hm(t,e,n)}function ym(t,e,n,r,o,s,i){let a=i?.paragraphSpacing??o,d=[],u={segmentIndex:0,graphemeIndex:0};if(t.length===0||n.count<=0||o<=0)return{lines:d,cursor:u};let c=e.paddingX??0,l=e.paddingY??0,p=Math.max(0,e.width-c*2),f=Math.max(0,e.height-l*2),m=n.gap*Math.max(0,n.count-1),h=Math.max(0,(p-m)/n.count);if(h<=0)return{lines:d,cursor:u};e:for(let g=0;g<n.count;g++){let y=c+g*(h+n.gap),b=y+h,v=l;for(;v+o<=l+f;){let T=v+o,w=[];for(let S=0;S<r.length;S++){let x=vv(r[S],v,T);x!==null&&w.push(x)}let k=au({left:y,right:b},w,s);if(k.length===0){v+=o;continue}let R=!1;for(let S=0;S<k.length;S++){let x=k[S],N=x.right-x.left,E=iu(t,u,N);if(E===null)return{lines:d,cursor:u};if(E.text.length===0&&E.width===0){u=E.end,R=!0;break}d.push({x:x.left,y:v,width:E.width,slotWidth:N,text:E.text,columnIndex:g,flushToRight:x.right<b-.5}),u=E.end}if(R){v+=a;continue}if(v+=o,u.segmentIndex>=t.length)break e}if(u.segmentIndex>=t.length)break}return{lines:d,cursor:u}}function Tv(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new Q(n),s=new Map,i=O(t.text??"",{name:"text"}),a=O(t.font??"16px sans-serif",{name:"font"}),d=O(t.lineHeight??20,{name:"line-height"}),u=O(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),c=O(t.columns??{count:1,gap:0},{name:"columns"}),l=O(t.obstacles??[],{name:"obstacles"}),p=O(t.paragraphSpacing??null,{name:"paragraph-spacing"}),f=U([i,a],(h,g,y)=>{let b=h[0],v=b!=null&&b.length>0?b.at(-1):y.prevData[0],T=h[1],w=T!=null&&T.length>0?T.at(-1):y.prevData[1],k=qt(v,w,e,s);g.emit(k);let R=()=>{s.clear(),e.clearCache?.()};return{deactivate:R,invalidate:R}},{name:"segments",describeKind:"derived"}),m=A([f,u,c,l,d,p],([h,g,y,b,v,T])=>{let w=h,k=H(),R=T??v,{lines:S,cursor:x}=ym(w,g,y,b,v,r,{paragraphSpacing:R}),N=H()-k,E=Math.max(0,w.length-x.segmentIndex),D=m.meta;return D&&(St(D["line-count"],S.length),St(D["layout-time-ns"],N),St(D["overflow-segments"],E)),S},{name:"flow-lines",meta:{"line-count":0,"layout-time-ns":0,"overflow-segments":0},equals:(h,g)=>{let y=h,b=g;if(y.length!==b.length)return!1;for(let v=0;v<y.length;v++){let T=y[v],w=b[v];if(T.x!==w.x||T.y!==w.y||T.width!==w.width||T.slotWidth!==w.slotWidth||T.text!==w.text||T.columnIndex!==w.columnIndex||T.flushToRight!==w.flushToRight)return!1}return!0}});return o.add(i,{name:"text"}),o.add(a,{name:"font"}),o.add(d,{name:"line-height"}),o.add(u,{name:"container"}),o.add(c,{name:"columns"}),o.add(l,{name:"obstacles"}),o.add(p,{name:"paragraph-spacing"}),o.add(f,{name:"segments"}),o.add(m,{name:"flow-lines"}),{graph:o,setText:h=>o.set("text",h),setFont:h=>o.set("font",h),setLineHeight:h=>o.set("line-height",h),setContainer:h=>o.set("container",h),setColumns:h=>o.set("columns",h),setObstacles:h=>o.set("obstacles",h),setParagraphSpacing:h=>o.set("paragraph-spacing",h),segments:f,flowLines:m}}var ra={};Ne(ra,{NS_PER_MS:()=>Ue,NS_PER_SEC:()=>pt,ResilientPipelineGraph:()=>na,factoryTag:()=>be,placeholderArgs:()=>We,resilientPipeline:()=>wv});et();ir();at();Gt();function $o(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&"down"in t}function bm(t){if(t<=0)throw new RangeError("timeoutMs must be > 0");if(t>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic")}var na=class extends Q{output;status;lastError;breakerState;droppedCount;rateLimitState;constructor(e,n={}){super(n.name??"resilient_pipeline",n.graph);let r=e,o,s,i;if(n.rateLimit!=null)if($o(n.rateLimit)){let d=r,u=n.rateLimit;r=me(u,c=>{let l={...c,maxBuffer:c.maxBuffer??1/0,meta:xe("resilient","rate-limit")};return Rn(d,l).node}),this.add(r,{name:"rateLimited"})}else{let d={...n.rateLimit,maxBuffer:n.rateLimit.maxBuffer??1/0,meta:xe("resilient","rate-limit")},u=Rn(r,d);r=u.node,o=u.droppedCount,s=u.rateLimitState,this.add(r,{name:"rateLimited"}),this.add(o,{name:"droppedCount"}),this.add(s,{name:"rateLimitState"})}if(n.budget!=null)if($o(n.budget)){let d=r,u=n.budget;r=me(u,c=>c.length>0?Wt(d,c,{meta:xe("resilient","budget")}):d),this.add(r,{name:"budgetGated"})}else n.budget.length>0&&(r=Wt(r,n.budget,{meta:xe("resilient","budget")}),this.add(r,{name:"budgetGated"}));if(n.breaker!=null)if($o(n.breaker)){let d=r,u=n.breaker,c=n.breakerOnOpen??"skip";r=me(u,l=>{let p=Tt(l);return xn(p,{onOpen:c,meta:xe("resilient","breaker")})(d).node}),this.add(r,{name:"breakerWrapped"})}else{let d=Tt(n.breaker),u=n.breakerOnOpen??"skip",c=xn(d,{onOpen:u,meta:xe("resilient","breaker")})(r);r=c.node,i=c.breakerState,this.add(r,{name:"breakerWrapped"}),this.add(i,{name:"breakerState"})}if(n.timeoutMs!=null)if($o(n.timeoutMs)){let d=r,u=n.timeoutMs;r=me(u,c=>(bm(c),Sn(d,c*1e6,{meta:xe("resilient","timeout")}))),this.add(r,{name:"timeoutWrapped"})}else bm(n.timeoutMs),r=Sn(r,n.timeoutMs*1e6,{meta:xe("resilient","timeout")}),this.add(r,{name:"timeoutWrapped"});if(n.retry!=null)if($o(n.retry)){let d=r,u=n.retry;r=me(u,c=>vt(d,{...c,meta:xe("resilient","retry")})),this.add(r,{name:"retryWrapped"})}else r=vt(r,{...n.retry,meta:xe("resilient","retry")}),this.add(r,{name:"retryWrapped"});n.fallback!==void 0&&(r=ar(r,n.fallback,{meta:xe("resilient","fallback")}),this.add(r,{name:"fallbackWrapped"}));let a=Yt(r,{initialStatus:n.initialStatus??"pending",meta:xe("resilient","status")});this.output=a.node,this.status=a.status,this.lastError=a.error,this.breakerState=i,this.droppedCount=o,this.rateLimitState=s,this.add(this.output,{name:"output"}),this.add(this.status,{name:"status"}),this.add(this.lastError,{name:"lastError"})}};function wv(t,e={}){let n=new na(t,e);return n.tagFactory("resilientPipeline",We(e)),n}var pa={};Ne(pa,{SNAPSHOT_WIRE_VERSION:()=>Vo,SurfaceError:()=>Oe,asSurfaceError:()=>oa,createGraph:()=>Er,deleteSnapshot:()=>la,diffSnapshots:()=>ua,listSnapshots:()=>ca,restoreSnapshot:()=>da,runReduction:()=>sa,saveSnapshot:()=>aa});var Oe=class extends Error{code;details;constructor(e,n,r){super(n),this.name="SurfaceError",this.code=e,r!==void 0&&(this.details=r)}toJSON(){let e={code:this.code,message:this.message};if(this.details!==void 0){let n=kv(this.details);n!==void 0&&(e.details=n)}return e}};function kv(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function oa(t,e="internal-error"){if(t instanceof Oe)return t;let n=t instanceof Error?t.message:String(t);return new Oe(e,n)}function Er(t,e){let n=xr(t);if(!n.valid)throw new Oe("invalid-spec",`GraphSpec validation failed:
|
|
221
225
|
${n.errors.join(`
|
|
222
|
-
`)}`,{errors:n.errors});let r=e?.catalog??{},o=
|
|
226
|
+
`)}`,{errors:n.errors});let r=e?.catalog??{},o=Io(t,r);if(!o.valid)throw new Oe("catalog-error",`Catalog validation failed:
|
|
223
227
|
${o.errors.join(`
|
|
224
|
-
`)}`,{errors:o.errors});try{return
|
|
228
|
+
`)}`,{errors:o.errors});try{return Do(t,e)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Oe("catalog-error",i)}}ae();var xv=3e4;async function sa(t,e,n){let r=n?.inputPath??"input",o=n?.outputPath??"output",s=n?.timeoutMs??xv,i=Er(t,{catalog:n?.catalog}),a;try{a=i.resolve(o)}catch{throw i.destroy(),new Oe("node-not-found",`reduce: output path "${o}" is not registered`,{path:o})}try{i.resolve(r)}catch{throw i.destroy(),new Oe("node-not-found",`reduce: input path "${r}" is not registered`,{path:r})}try{return await new Promise((d,u)=>{let c=!1,l=!1,p,f,m=!1,h=g=>{l||(l=!0,p!==void 0&&clearTimeout(p),f!==void 0?(f(),f=void 0):m=!0,g())};f=a.subscribe(g=>{for(let y of g){if(l)return;if(c){if(y[0]===_){h(()=>d(y[1]));return}if(y[0]===q){let b=a.cache;h(()=>d(b));return}if(y[0]===L){let b=y[1],v=b instanceof Error?b.message:String(b),T=b instanceof Error?b:void 0;h(()=>u(new Oe("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===I){h(()=>u(new Oe("internal-error","reduce: output COMPLETEd without a post-push DATA")));return}}}}),m&&(f?.(),f=void 0),c=!0;try{i.set(r,e)}catch(g){let y=g instanceof Error?g.message:String(g),b=g instanceof Error?g:void 0;h(()=>u(new Oe("internal-error",`reduce: failed to set input on "${r}": ${y}`,b!=null?{path:r,cause:b}:{path:r})));return}!l&&Number.isFinite(s)&&s>0&&(p=setTimeout(()=>{h(()=>u(new Oe("reduce-timeout",`reduce: no output emitted within ${s}ms`,{timeoutMs:s,outputPath:o})))},s),p.unref?.())})}finally{i.destroy()}}Se();var Vo=wt,jo="snapshot:";function Bo(t){if(t.startsWith(jo))throw new Oe("snapshot-failed",`snapshot id must not start with "${jo}" (reserved); got "${t}"`,{snapshotId:t})}function ia(t){return`${jo}${t}`}function Rv(t){return t.startsWith(jo)?t.slice(jo.length):void 0}function Ru(t,e){if(t==null||typeof t!="object")throw new Oe("snapshot-not-found",`snapshot "${e}" not found in tier`,{snapshotId:e});let n=t;if("mode"in n){if(n.mode==="full"&&"snapshot"in n)return n.snapshot;throw n.mode==="diff"?new Oe("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new Oe("restore-failed",`snapshot "${e}" has unknown mode "${String(n.mode)}"`,{snapshotId:e,mode:String(n.mode)})}if("nodes"in n&&"edges"in n&&"subgraphs"in n&&"name"in n)return n;throw new Oe("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function aa(t,e,n){Bo(e);let r;try{r=t.snapshot()}catch(s){let i=s instanceof Error?s.message:String(s);throw new Oe("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let o={name:t.name,mode:"full",seq:0,timestamp_ns:oe(),format_version:Vo,snapshot:r};try{await n.save(ia(e),o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new Oe("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:o.timestamp_ns}}async function da(t,e,n){Bo(t);let r=ia(t),o=await e.load(r);o===void 0&&(o=await e.load(t));let s=Ru(o,t);try{return Q.fromSnapshot(s,n?.factories?{factories:n.factories}:void 0)}catch(i){let a=i instanceof Error?i.message:String(i);throw new Oe("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function ua(t,e,n){Bo(t),Bo(e);let r=async d=>{let u=ia(d),c=await n.load(u);return c===void 0&&(c=await n.load(d)),c},[o,s]=await Promise.all([r(t),r(e)]),i=Ru(o,t),a=Ru(s,e);return Q.diff(i,a)}async function ca(t,e){if(typeof t.list!="function")throw new Oe("tier-no-list","KvStorageTier does not implement list(); wrap the tier with an enumerator or use a different backend");let n=await t.list(),r=[],o=e?.includeUnprefixed===!0;for(let s of n){let i=Rv(s);i!==void 0?r.push(i):o&&r.push(s)}return r}async function la(t,e){if(Bo(t),typeof e.delete!="function")throw new Oe("snapshot-failed",`KvStorageTier is append-only (no delete()); cannot delete "${t}"`,{snapshotId:t});try{await e.delete(ia(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new Oe("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var Sv="0.0.0";0&&(module.exports={COMPLETE,COMPLETE_MSG,COMPLETE_ONLY_BATCH,CircuitOpenError,ContentAddressedMissError,DATA,DEFAULT_ACTOR,DEFAULT_AUDIT_GUARD,DIRTY,DIRTY_MSG,DIRTY_ONLY_BATCH,ENVELOPE_VERSION,ERROR,GRAPH_META_SEGMENT,Graph,GraphReFlyConfig,GuardDenied,INVALIDATE,INVALIDATE_MSG,INVALIDATE_ONLY_BATCH,JsonCodec,NS_PER_MS,NS_PER_SEC,NativeIndexBackend,NativeListBackend,NativeLogBackend,NativeMapBackend,NativePubSubBackend,NodeImpl,PAUSE,RESOLVED,RESOLVED_MSG,RESOLVED_ONLY_BATCH,RESUME,RateLimiterOverflowError,ResettableTimer,SIZEOF_OVERHEAD,SIZEOF_SYMBOL,SNAPSHOT_VERSION,SNAPSHOT_WIRE_VERSION,START,START_MSG,SurfaceError,TEARDOWN,TEARDOWN_MSG,TEARDOWN_ONLY_BATCH,TimeoutError,accessHintForGuard,accountability,advanceVersion,ai,appendAudit,appendLogStorage,asSurfaceError,audit,autoTrackNode,awaitSettled,batch,budgetGate,buffer,bufferCount,bufferTime,bumpCursor,cached,canonicalJson,cascadingCache,catchError,checkpointToRedis,checkpointToS3,circuitBreaker,combine,combineLatest,compat,concat,concatMap,configure,constant,contentAddressedStorage,core,cqrs,createAuditLog,createDagCborCodec,createDagCborZstdCodec,createGraph,createTransport,createVersioning,createWatermarkController,csvRows,debounce,debounceTime,decay,decodeEnvelope,decorrelatedJitter,defaultConfig,defaultHash,defer,delay,deleteSnapshot,demoShell,derived,deserializeError,dictKv,dictSnapshot,diffForWAL,diffSnapshots,distill,distinctUntilChanged,domainMeta,domainTemplates,downWithBatch,dynamicNode,effect,elementAt,empty,encodeEnvelope,escapeRegexChar,exhaustMap,explainPath,exponential,externalBundle,externalProducer,extra,factoryTag,fallback,fibonacci,filter,find,first,firstValueFrom,firstWhere,flatMap,forEach,fromAny,fromAsyncIter,fromCSV,fromClickHouseWatch,fromCron,fromDrizzle,fromEvent,fromHTTP,fromHTTPPoll,fromHTTPStream,fromIter,fromKafka,fromKysely,fromMCP,fromNATS,fromNDJSON,fromOTel,fromPrisma,fromPrometheus,fromPromise,fromPulsar,fromRabbitMQ,fromRaf,fromRedisStream,fromSSE,fromSqlite,fromSqliteCursor,fromStatsD,fromSyslog,fromTimer,fromWebSocket,fromWebSocketReconnect,fromWebhook,globToRegExp,graph,graphProfile,graphspec,guarded,harness,interval,isBatching,isV1,jobQueue,jotai,jsonCodec,jsonCodecFor,keepalive,kvStorage,last,layout,lens,lightMutation,linear,listSnapshots,lru,makeHttpError,map,matchesAnyPattern,matchesCron,memory,memoryAppendLog,memoryBackend,memoryKv,memorySnapshot,merge,mergeMap,mergeReactiveLogs,messaging,monotonicNs,nameToSignal,nanostores,ndjsonRows,nestjs,never,node,nodeSignal,normalizeActor,of,onFirstData,orchestration,pairwise,parseCron,parsePrometheusText,parseSSEStream,parseStatsD,parseSyslog,patterns,pausable,pipe,placeholderArgs,policy,policyFromRules,process,producer,pubsub,race,rateLimiter,reachable,react,reactiveCounter,reactiveIndex,reactiveList,reactiveLog,reactiveMap,reactiveSink,reduce,reduction,refine,registerBuiltinCodecs,registerBuiltins,registerCursor,registerCursorMap,repeat,replay,replayWAL,rescue,resilientPipeline,resolveBackoffPreset,resolveDescribeFields,restoreSnapshot,retry,runReduction,sample,saveSnapshot,scan,serializeError,share,shareReplay,signalToName,signals,singleFromAny,singleNodeFromAny,sizeof,skip,snapshotStorage,solid,sortJsonValue,stableJsonString,state,stratify,surface,svelte,switchMap,take,takeUntil,takeWhile,tap,tapFirst,throttle,throttleTime,throwError,timeout,toArray,toCSV,toClickHouse,toFile,toHTTP,toKafka,toLoki,toMongo,toNATS,toObservable,toPostgres,toPulsar,toRabbitMQ,toReadableStream,toRedisStream,toS3,toSSE,toSSEBytes,toSqlite,toTempo,toWebSocket,tokenBucket,topologyDiff,tryIncrementBounded,validateGraphObservability,valve,verifiable,version,vue,wallClockNs,watchTopologyTree,window,windowCount,windowTime,withBreaker,withLatestFrom,withMaxAttempts,withStatus,workerBridge,workerSelf,wrapMutation,zip,zustand});
|