@graphrefly/graphrefly 0.42.0 → 0.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{cascading-CH-_VwG9.d.cts → cascading-BglDkMdX.d.cts} +2 -2
- package/dist/{cascading-OgKQZjsa.d.ts → cascading-MFgxu7Yo.d.ts} +2 -2
- package/dist/chunk-2T7U5EU6.js +1 -0
- package/dist/chunk-5M4CCMMD.js +45 -0
- package/dist/{chunk-YGL7FPVQ.js → chunk-5XJ6B66J.js} +1 -1
- package/dist/{chunk-NWXQIOIB.js → chunk-6X7AFUJV.js} +1 -1
- package/dist/chunk-7K6PWTDQ.js +1 -0
- package/dist/{chunk-D27JNOLZ.js → chunk-7LIAPXJB.js} +1 -1
- package/dist/{chunk-CLD3F4R5.js → chunk-7WPU3UHQ.js} +1 -1
- package/dist/{chunk-NNKJUORL.js → chunk-A5WCQ5NO.js} +1 -1
- package/dist/chunk-APPIWSGD.js +84 -0
- package/dist/{chunk-TZQPPQEQ.js → chunk-BEZWM2SY.js} +1 -1
- package/dist/{chunk-5QRRKBUT.js → chunk-CB676TKJ.js} +1 -1
- package/dist/{chunk-KT5DTRBP.js → chunk-CE6TI2TL.js} +1 -1
- package/dist/{chunk-6YFZMUMR.js → chunk-CLVB32RD.js} +1 -1
- package/dist/{chunk-2K5RXLAH.js → chunk-CRVT7D2P.js} +1 -1
- package/dist/chunk-D7GPHKFH.js +1 -0
- package/dist/{chunk-FUZ6S2DY.js → chunk-DHRX7JX4.js} +1 -1
- package/dist/chunk-FZMYDOWV.js +1 -0
- package/dist/{chunk-35JTVPOX.js → chunk-GHBWHMRZ.js} +1 -1
- package/dist/{chunk-KGKJCHEK.js → chunk-GLERH466.js} +1 -1
- package/dist/{chunk-CISGGAIF.js → chunk-HIDYF36O.js} +1 -1
- package/dist/chunk-HITNVN6B.js +3 -0
- package/dist/{chunk-7ARY3Y3T.js → chunk-HY4DJBA7.js} +1 -1
- package/dist/chunk-KZIEYVXN.js +1 -0
- package/dist/{chunk-IZM3UEH3.js → chunk-N4MQX6JU.js} +1 -1
- package/dist/{chunk-FDZAZNRO.js → chunk-N7FHEL4D.js} +1 -1
- package/dist/chunk-NTEURFZH.js +1 -0
- package/dist/{chunk-4QH6VJF4.js → chunk-OIVP6KFV.js} +1 -1
- package/dist/{chunk-KCACBSJH.js → chunk-OPHBU3LG.js} +1 -1
- package/dist/{chunk-Q7QQQA3I.js → chunk-OYQOZP2F.js} +1 -1
- package/dist/{chunk-7B7ELAT2.js → chunk-PTZK576G.js} +1 -1
- package/dist/{chunk-DEJTNNQC.js → chunk-ST7UXLWR.js} +1 -1
- package/dist/chunk-SVY7VUYU.js +1 -0
- package/dist/{chunk-WHMUB5QB.js → chunk-TK3NWWD4.js} +1 -1
- package/dist/chunk-UNGSTR4X.js +61 -0
- package/dist/{chunk-VRALOYRD.js → chunk-VV4N5P64.js} +1 -1
- package/dist/chunk-W3I423PS.js +1 -0
- package/dist/{chunk-HZKW2AAB.js → chunk-WJR24TAG.js} +1 -1
- package/dist/{chunk-F3IGTWCQ.js → chunk-XTGKMHSW.js} +1 -1
- package/dist/{chunk-LDQ3IUIP.js → chunk-YBB7ZGTY.js} +1 -1
- package/dist/{chunk-G5VBJ5K6.js → chunk-Z4NPUARF.js} +1 -1
- package/dist/{chunk-KRH66M4O.js → chunk-ZGNQRPDT.js} +1 -1
- package/dist/{chunk-AGNM6RS6.js → chunk-ZKPSFFKU.js} +1 -1
- package/dist/{chunk-KY2LMAXU.js → chunk-ZLV5SQSX.js} +1 -1
- package/dist/compat/index.cjs +5 -5
- 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.cjs +1 -1
- package/dist/compat/jotai/index.d.cts +2 -2
- package/dist/compat/jotai/index.d.ts +2 -2
- package/dist/compat/jotai/index.js +1 -1
- package/dist/compat/nanostores/index.cjs +1 -1
- package/dist/compat/nanostores/index.d.cts +2 -2
- package/dist/compat/nanostores/index.d.ts +2 -2
- package/dist/compat/nanostores/index.js +1 -1
- package/dist/compat/nestjs/index.cjs +5 -5
- 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 -3
- 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 +3 -4
- package/dist/core/index.d.ts +3 -4
- package/dist/core/index.js +1 -1
- package/dist/{decay-CdEBmDIs.d.ts → decay-BvOWTZ00.d.ts} +2 -2
- package/dist/{decay-2ZukgQ4o.d.cts → decay-CFlLvXUT.d.cts} +2 -2
- package/dist/extra/browser.cjs +1 -1
- package/dist/extra/browser.d.cts +1 -1
- package/dist/extra/browser.d.ts +1 -1
- package/dist/extra/browser.js +1 -1
- package/dist/extra/index.cjs +15 -15
- package/dist/extra/index.d.cts +10 -10
- package/dist/extra/index.d.ts +10 -10
- 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 +9 -1
- package/dist/extra/operators.d.ts +9 -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.d.cts +3 -3
- package/dist/extra/render/index.d.ts +3 -3
- package/dist/extra/sources.cjs +3 -3
- 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.cjs +1 -1
- package/dist/extra/storage-browser.d.cts +1 -1
- package/dist/extra/storage-browser.d.ts +1 -1
- package/dist/extra/storage-browser.js +1 -1
- package/dist/{fallback-Ctlj2tMY.d.cts → fallback-74oxi34l.d.cts} +1 -1
- package/dist/{fallback-CqYVLL6X.d.ts → fallback-DUyyBTBK.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-C4SHb3Ly.d.cts → graph-CWvEUQAq.d.cts} +196 -3
- package/dist/{graph-7VguS7a4.d.ts → graph-D9LFnda9.d.ts} +196 -3
- package/dist/{index-LIpQQE9f.d.cts → index-5k1T6jl0.d.cts} +9 -9
- package/dist/{index-CPNSy-U0.d.cts → index-9770hRuQ.d.cts} +23 -4
- package/dist/{index-CEMx8n40.d.cts → index-B-_tFaqV.d.cts} +4 -4
- package/dist/{index-2B7u2pVn.d.cts → index-B17QddL1.d.cts} +4 -4
- package/dist/{index-B-i4_g3k.d.ts → index-B1F8Enjf.d.ts} +61 -8
- package/dist/{index-DBevwHj_.d.ts → index-B5S8ULbU.d.ts} +3 -3
- package/dist/{index-Dgs8zcj7.d.ts → index-B8YnZpIR.d.ts} +2 -2
- package/dist/{index-B3OTH1dV.d.ts → index-BHskSB8v.d.ts} +28 -17
- package/dist/{index-sl4NyzQx.d.cts → index-BIYAkbAi.d.cts} +1 -1
- package/dist/{index-C9kSENB4.d.cts → index-BQSKmbuG.d.cts} +1 -1
- package/dist/{index-tJoTcnHh.d.cts → index-BaQaY_IQ.d.cts} +2 -2
- package/dist/{index-CJK1JkYy.d.ts → index-BmZXHqkE.d.ts} +1 -1
- package/dist/{index-pT8sCpOJ.d.ts → index-BoJ5JHxI.d.ts} +12 -3
- package/dist/{index-BeT2r7sk.d.ts → index-BocU7pqs.d.ts} +23 -4
- package/dist/{index-ChOyVLKm.d.cts → index-BrPrLl4e.d.cts} +1 -1
- package/dist/{index-D-Xs74HZ.d.cts → index-BxNs2HB9.d.cts} +33 -9
- package/dist/{index-Bf7eqeSF.d.ts → index-Byu-OpX_.d.ts} +2 -2
- package/dist/{index-BoLv_OfD.d.cts → index-C1T3d7V-.d.cts} +61 -8
- package/dist/{index-BTQtTb_H.d.cts → index-C5ri2Axc.d.cts} +3 -3
- package/dist/{index-z96luz5O.d.cts → index-C5stwKcw.d.cts} +1 -1
- package/dist/{index-CZmcDtFn.d.ts → index-C9l6OEBL.d.ts} +1 -1
- package/dist/{index-CCq87F7t.d.ts → index-CBBLl_rc.d.ts} +1 -1
- package/dist/{index-D6egPFAL.d.ts → index-CBGUK09R.d.ts} +4 -4
- package/dist/{index-C0-Jv1kP.d.cts → index-CC-AvFTy.d.cts} +12 -3
- package/dist/{index-DQo8xBgd.d.ts → index-CJF1URuX.d.ts} +9 -9
- package/dist/{index-BJX94aud.d.cts → index-CK29LV56.d.cts} +1 -1
- package/dist/{index-BP8a88zx.d.ts → index-CMh5Rz1y.d.ts} +4 -4
- package/dist/{index-CvrqGfNS.d.ts → index-CPQlGA29.d.ts} +1 -1
- package/dist/{index-Bbkgpt5t.d.ts → index-CR8QpwX8.d.ts} +49 -24
- package/dist/{index-Du7u1lSf.d.cts → index-CS0LTlB8.d.cts} +4 -4
- package/dist/{index-Bc41FuHp.d.cts → index-CSOmP7xT.d.cts} +2 -2
- package/dist/{index-BsT7F2et.d.ts → index-CYq8vAyV.d.ts} +2 -2
- package/dist/{index-Bn4zHYLj.d.ts → index-CZ3r5Rxp.d.ts} +4 -4
- package/dist/{index-HoU88d5U.d.cts → index-CasX6Pfq.d.cts} +68 -9
- package/dist/{index-BG0BN3PB.d.ts → index-CdAlHFEt.d.ts} +1 -1
- package/dist/{index-CpyNFqkB.d.ts → index-CdTelp1M.d.ts} +8 -4
- package/dist/{index-D8l8hNXn.d.ts → index-CeFiHtAg.d.ts} +4 -4
- package/dist/{index-DmAgG5CI.d.cts → index-Cj3WohTd.d.cts} +8 -4
- package/dist/{index-BtAsBp8K.d.cts → index-Climxqsu.d.cts} +4 -4
- package/dist/{index-CJIuLu2f.d.cts → index-Co7uli2l.d.cts} +28 -17
- package/dist/{index-DIOoAZUX.d.ts → index-CviRnE4K.d.ts} +1 -1
- package/dist/{index-Dhc7a7Xo.d.cts → index-Cwv0KWcU.d.cts} +2 -2
- package/dist/{index-Dn-wI9g4.d.ts → index-CzLVrjxn.d.ts} +2 -2
- package/dist/{index-DO9XxMzS.d.ts → index-D0aciIex.d.cts} +3 -18
- package/dist/{index-4Uz-e_fL.d.ts → index-DHen9Klo.d.ts} +33 -9
- package/dist/{index-3NmAfcH0.d.cts → index-DV_1YuVk.d.cts} +40 -8
- package/dist/{index-BdGtBX-X.d.cts → index-Dc4AYqrJ.d.cts} +3 -3
- package/dist/{index-Dmqp7KjD.d.ts → index-Dgl1HpPn.d.ts} +1 -1
- package/dist/{index-CJQm0g38.d.ts → index-DisjX8a-.d.ts} +40 -8
- package/dist/{index-B11anra4.d.cts → index-UPSiS-X7.d.cts} +49 -24
- package/dist/{index-DBIqYS43.d.cts → index-Yq60JP3s.d.ts} +3 -18
- package/dist/{index-f5IivDUX.d.cts → index-ZVQhLa2i.d.cts} +1 -1
- package/dist/{index-hHcaFlJX.d.cts → index-_6ODbuOu.d.cts} +1 -1
- package/dist/{index-BVpm6noz.d.cts → index-hcDJ8PSI.d.cts} +1 -1
- package/dist/{index-DBHK8O6H.d.ts → index-nozs3fFC.d.ts} +3 -3
- package/dist/{index-BUYXac2c.d.ts → index-p09KSrTN.d.ts} +68 -9
- package/dist/{index-C7O6r5fV.d.ts → index-sqkqlb1p.d.ts} +1 -1
- package/dist/{index-CZjOhcBy.d.cts → index-tRCxuAXF.d.cts} +2 -2
- package/dist/index.cjs +48 -48
- package/dist/index.d.cts +42 -43
- package/dist/index.d.ts +42 -43
- package/dist/index.js +1 -1
- package/dist/{node-ClS5yC-B.d.cts → node-kK3CvTrR.d.cts} +1 -1
- package/dist/{node-ClS5yC-B.d.ts → node-kK3CvTrR.d.ts} +1 -1
- package/dist/{observable-BsBzUrcI.d.ts → observable-DWjNfLvC.d.ts} +1 -1
- package/dist/{observable-DLGPPtb8.d.cts → observable-e3eiPPFy.d.cts} +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 -16
- package/dist/patterns/ai/index.d.cts +16 -17
- package/dist/patterns/ai/index.d.ts +16 -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/cqrs/index.cjs +3 -3
- 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 -5
- 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 -3
- 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 +16 -16
- 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/harness/index.cjs +9 -9
- package/dist/patterns/harness/index.d.cts +10 -11
- package/dist/patterns/harness/index.d.ts +10 -11
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/inspect/index.cjs +3 -3
- package/dist/patterns/inspect/index.d.cts +7 -7
- package/dist/patterns/inspect/index.d.ts +7 -7
- package/dist/patterns/inspect/index.js +1 -1
- package/dist/patterns/job-queue/index.cjs +3 -3
- 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/memory/index.cjs +3 -3
- 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 -3
- 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 -3
- package/dist/patterns/orchestration/index.d.cts +6 -7
- package/dist/patterns/orchestration/index.d.ts +6 -7
- package/dist/patterns/orchestration/index.js +1 -1
- package/dist/patterns/process/index.cjs +3 -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 -4
- 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 -3
- 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/surface/index.cjs +10 -10
- 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-WBlobVhU.d.cts → pipeline-graph-CIKhynsF.d.cts} +11 -6
- package/dist/{pipeline-graph-v8fMvqNk.d.ts → pipeline-graph-Sgj0gCwn.d.ts} +11 -6
- package/dist/{reactive-layout-v7KPvxoc.d.ts → reactive-layout-DOTs9P3X.d.ts} +2 -2
- package/dist/{reactive-layout-Dsvob4zD.d.cts → reactive-layout-DgctbqZo.d.cts} +2 -2
- package/dist/{reactive-log-BezYsbA_.d.ts → reactive-log-BKALbfal.d.ts} +1 -1
- package/dist/{reactive-log-B00laMSQ.d.cts → reactive-log-DIGdYqQ6.d.cts} +1 -1
- package/dist/{reactive-map-48mnZ-nu.d.cts → reactive-map-CEFGp8TK.d.cts} +1 -1
- package/dist/{reactive-map-BVVPdvmi.d.ts → reactive-map-DS_SIAxv.d.ts} +1 -1
- package/dist/resilience-6LYQJAC5.js +1 -0
- package/dist/sugar-DQjFmVqb.d.cts +399 -0
- package/dist/sugar-fhLIE7TT.d.ts +399 -0
- package/dist/{topology-tree-BSdfSwMi.d.cts → topology-tree-Bcz27hpF.d.cts} +1 -1
- package/dist/{topology-tree-BNGvuG82.d.ts → topology-tree-xvaD0fOX.d.ts} +1 -1
- package/dist/{types-B1jDWVsM.d.cts → types-C0_yquda.d.cts} +1 -1
- package/dist/{types-DkzUUs0H.d.ts → types-CWFysE9E.d.ts} +1 -1
- package/package.json +1 -1
- package/dist/chunk-3ERTUW2J.js +0 -45
- package/dist/chunk-3K7HA4Y6.js +0 -1
- package/dist/chunk-3ZZX7M25.js +0 -1
- package/dist/chunk-4I45FVQS.js +0 -1
- package/dist/chunk-5ST42ESJ.js +0 -1
- package/dist/chunk-7VKFXLZQ.js +0 -84
- package/dist/chunk-ACMJ2ZPS.js +0 -3
- package/dist/chunk-AS3TV2TV.js +0 -1
- package/dist/chunk-LPRWATHB.js +0 -61
- package/dist/chunk-LYCLF26R.js +0 -1
- package/dist/chunk-VE5SIZEM.js +0 -1
- package/dist/chunk-XLQPNNIC.js +0 -1
- package/dist/meta-BgVAsg9j.d.ts +0 -102
- package/dist/meta-vE8bxW1E.d.cts +0 -102
- package/dist/resilience-445VFFXQ.js +0 -1
- package/dist/sugar-CH-2ZY90.d.ts +0 -203
- package/dist/sugar-DStZfUEK.d.cts +0 -203
package/dist/index.cjs
CHANGED
|
@@ -1,55 +1,55 @@
|
|
|
1
|
-
"use strict";var Um=Object.create;var Wn=Object.defineProperty;var Hu=Object.getOwnPropertyDescriptor;var Jm=Object.getOwnPropertyNames;var Ym=Object.prototype.hasOwnProperty;var zu=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Ar=t=>{throw TypeError(t)};var Qm=(t,e,n)=>e in t?Wn(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Vu=(t,e)=>Wn(t,"name",{value:e,configurable:!0});var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ee=(t,e)=>{for(var n in e)Wn(t,n,{get:e[n],enumerable:!0})},Xm=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Jm(e))!Ym.call(t,o)&&o!==n&&Wn(t,o,{get:()=>e[o],enumerable:!(r=Hu(e,o))||r.enumerable});return t};var Zm=t=>Xm(Wn({},"__esModule",{value:!0}),t);var Wu=t=>[,,,Um(t?.[zu("metadata")]??null)],Uu=["class","method","getter","setter","accessor","field","value","get","set"],Or=t=>t!==void 0&&typeof t!="function"?Ar("Function expected"):t,eg=(t,e,n,r,o)=>({kind:Uu[t],name:e,metadata:r,addInitializer:s=>n._?Ar("Already initialized"):o.push(Or(s||null))}),tg=(t,e)=>Qm(e,zu("metadata"),t[3]),Ju=(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=Uu[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)&&Hu(l<4?o:{get[n](){return Ku(this,s)},set[n](T){return qu(this,s,T)}},n));l?f&&l<4&&Vu(s,(l>2?"set ":l>1?"get ":"")+n):Vu(o,n);for(var v=r.length-1;v>=0;v--)u=eg(l,n,d={},t[3],y),l&&(u.static=p,u.private=f,c=u.access={has:f?T=>ng(o,T):T=>n in T},l^3&&(c.get=f?T=>(l^1?Ku:rg)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(c.set=f?(T,w)=>qu(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?Or(a)&&(l>4?g.unshift(a):l?f?s=a:b[h]=a:o=a):typeof a!="object"||a===null?Ar("Object expected"):(Or(i=a.get)&&(b.get=i),Or(i=a.set)&&(b.set=i),Or(i=a.init)&&g.unshift(i));return l||tg(t,o),b&&Wn(o,n,b),f?l^4?s:b:o};var ya=(t,e,n)=>e.has(t)||Ar("Cannot "+n),ng=(t,e)=>Object(e)!==e?Ar('Cannot use the "in" operator on this value'):t.has(e),Ku=(t,e,n)=>(ya(t,e,"read from private field"),n?n.call(t):e.get(t));var qu=(t,e,n,r)=>(ya(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),rg=(t,e,n)=>(ya(t,e,"access private method"),n);var mt,_,oe,z,nt,qe,Je,fe,I,L,Dt,Un,Jo,Jn,Yo,Qo,Yn,Cr,Lr,Ir,Qn,se=be(()=>{"use strict";mt=Symbol.for("graphrefly/START"),_=Symbol.for("graphrefly/DATA"),oe=Symbol.for("graphrefly/DIRTY"),z=Symbol.for("graphrefly/RESOLVED"),nt=Symbol.for("graphrefly/INVALIDATE"),qe=Symbol.for("graphrefly/PAUSE"),Je=Symbol.for("graphrefly/RESUME"),fe=Symbol.for("graphrefly/TEARDOWN"),I=Symbol.for("graphrefly/COMPLETE"),L=Symbol.for("graphrefly/ERROR"),Dt=Object.freeze([oe]),Un=Object.freeze([z]),Jo=Object.freeze([nt]),Jn=Object.freeze([mt]),Yo=Object.freeze([I]),Qo=Object.freeze([fe]),Yn=Object.freeze([Dt]),Cr=Object.freeze([Un]),Lr=Object.freeze([Jo]),Ir=Object.freeze([Yo]),Qn=Object.freeze([Qo])});function ba(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function va(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 Pr(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++]=Xn,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<Qu)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${Qu})`);let n=0,r=t[n++];if(r!==Xn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Xn})`);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 Gr(t){t.registerCodec(Xo)}function Ta(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 Xo,Xn,Qu,Zo=be(()=>{"use strict";Xo={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)}};Xn=1,Qu=4});function Gt(t){if(t==null)return Ot;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var Ot,Fr=be(()=>{"use strict";Ot={type:"system",id:""}});function vn(){return Zn>0||$r}function Xu(){return Zn>0}function tr(t){Zn>0?jr.push(t):t()}function Z(t){Zn+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(Zn-=1,Zn===0)if(e){if(!$r){let n=jr.splice(0);for(let r of n)try{r()}catch{}yn.length=0,bn.length=0,er.length=0}}else og()}}function og(){let t=!$r;t&&($r=!0);let e=[],n=0;try{for(;yn.length>0||bn.length>0||er.length>0||t&&jr.length>0;){if(t&&jr.length>0){let s=jr.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw yn.length=0,bn.length=0,er.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(yn.length>0?yn:bn.length>0?bn:er).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&($r=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function Ft(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!vn()){t(e);return}(u>=5?er:u===4?bn:yn).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=vn();if(o>0){let u=e.slice(0,o);t(u)}if(s>o){let u=e.slice(o,s);d?yn.push(()=>t(u)):t(u)}if(i>s){let u=e.slice(s,i);d?bn.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?er.push(()=>t(u)):t(u)}}var Zn,$r,yn,bn,er,jr,Oe=be(()=>{"use strict";Zn=0,$r=!1,yn=[],bn=[],er=[],jr=[]});function W(){return Math.trunc(performance.now()*1e6)}function ie(){return Date.now()*1e6}var Re=be(()=>{"use strict"});function Br(t){t.registerMessageType(mt,{tier:0,wireCrossing:!1}),t.registerMessageType(oe,{tier:1,wireCrossing:!1}),t.registerMessageType(nt,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(qe,{tier:2,wireCrossing:!1}),t.registerMessageType(Je,{tier:2,wireCrossing:!1}),t.registerMessageType(_,{tier:3,wireCrossing:!0}),t.registerMessageType(z,{tier:3,wireCrossing:!0}),t.registerMessageType(I,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(L,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(fe,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var Tn,wa=be(()=>{"use strict";se();Tn=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 Zu(t){return Array.isArray(t)?[...t]:[t]}function sg(t,e){return t.has(e)||t.has("*")}function $t(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(Zu(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(Zu(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let d of e)sg(d.actions,s)&&d.where(o)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function Vr(t){return $t((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 Kr(t){let e=ig.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 ct,ig,Jt=be(()=>{"use strict";ct=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}};ig=["human","llm","wallet","system"]});function ka(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(ka);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=ka(t[n]);return e}return null}function ug(t){let e=dg.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 P=h[E-15],M=h[E-2],C=g(P,7)^g(P,18)^P>>>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 P=g(R,6)^g(R,11)^g(R,25),M=R&S^~R&x,C=N+P+M+ag[E]+h[E]>>>0,$=g(v,2)^g(v,13)^g(v,22),V=v&T^v&w^T&w,G=$+V>>>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 Yt(t){let e=ka(t??null),n=JSON.stringify(e);return ug(n).slice(0,16)}function cg(){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 nr(t,e,n){let r=n?.id??cg();if(t===0)return{id:r,version:0};let s=(n?.hash??Yt)(e);return{id:r,version:0,cid:s,prev:null}}function qr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function xa(t){return"cid"in t}var ag,dg,es=be(()=>{"use strict";ag=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]),dg=new TextEncoder});function nc(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Ra(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function ts(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function Na(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 J(t,e,n){let r=rc(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return rc(t)?s=(Sa(e)?e:n)??{}:Sa(t)?s=t:s=(Sa(e)?e:n)??{},new Ae(r,o,s)}var ec,tc,lg,pg,$e,Ae,rc,Sa,Me=be(()=>{"use strict";Zo();Fr();Oe();Re();wa();Jt();se();es();ec=()=>{},tc=100;lg=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},pg=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[Jn]:[Jn,[_,s]];o._status==="dirty"&&i.push(Dt),Ft(e,i,o._config.tierOf)},$e=new Tn({onMessage:lg,onSubscribe:pg});Br($e);Gr($e);Ae=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??$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??Yt;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?nr(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(nc);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(ts(a))},up(a){i._emitUp(ts(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=nr(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=Gt(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=Gt(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new ct({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new ct({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:ie()}}down(e,n){let r=ts(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=ts(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=Gt(n);if(!this._guard(d,"observe"))throw new ct({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)Ra(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=ec,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{}Ra(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=nc(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Yn),r.unsub=ec;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{}}Ra(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===oe){this._depDirtied(r);return}if(o===nt){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Lr);return}if(o===qe||o===Je){this._emit([n]);return}if(o===fe){this._emit(Qn);return}if(o===_)this._depSettledAsData(r,n[1]);else if(o===z)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===z)&&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(Yn))}_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(Cr),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(Ir)}_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>tc?(this._rerunDepth=0,this._emit([[L,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${tc} \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"?[Dt,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?[Dt,...a]:[...a.slice(0,d),Dt,...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]===fe||d[0]===nt);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!==qe&&u!==Je){o?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===qe?"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===qe)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]===fe))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Qn)}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(Un),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(d<0||c===d)&&qr(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===z)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===nt){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===fe&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let u=s>=0?r??e.slice(0,s):r??e;return o!=null?{finalMessages:u,equalsError:o}:{finalMessages:u}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let n=[...this._sinks];for(let r of n)r(e)};_dispatchOrAccumulate(e){if(Xu()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],tr(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}Ft(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);Ft(this._deliverToSinks,n,this._config.tierOf)}},rc=t=>Array.isArray(t),Sa=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function A(t,e){return J([],{...e,initial:t})}function H(t,e){return J((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function O(t,e,n){return J(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 he(t,e,n){return J(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 Hr(t,e,n){let r=new Map;return t.forEach((o,s)=>{r.set(o,s)}),O(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 wn(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 Ae([],o,{describeKind:"derived",...e}),n}function Ea(t,...e){let n=t;for(let r of e)n=r(n);return n}var ne=be(()=>{"use strict";Me()});function Ur(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 ds(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:Ur(e[0],0,59),hours:Ur(e[1],0,23),daysOfMonth:Ur(e[2],1,31),months:Ur(e[3],1,12),daysOfWeek:Ur(e[4],0,6)}}function us(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 Oa=be(()=>{"use strict"});function we(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}var ut=be(()=>{"use strict"});function Qt(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 Aa,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([[z]]))}return J([],(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:we("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([[qe,d]]))),!0;if(g===oe)return h.down([[oe]]),!0;if(g===z)return s.size===0?h.down([[z]]):a=!0,!0;if(g===I||g===L){for(;s.size>0;)h.emit(s.shift());return a=!1,i&&(i=!1,h.up([[Je,d]])),h.down([f]),!0}return!1}if(g===_&&(u[m-1]=f[1]),g===_||g===z){let y=c();return y&&s.size>0?(l(h),s.size===0&&i&&(i=!1,h.up([[Je,d]]))):!y&&!i&&s.size>0&&(i=!0,h.up([[qe,d]])),!0}return g===oe?!0:g===L?(h.down([f]),!0):g===I}}var Aa,vc=be(()=>{"use strict";se();Me();ut();Aa=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 Xt(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 wg(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function He(t){let e=new WeakSet,n={};for(let[r,o]of Tc(t))n[r]=Ca(o,e);return n}function Ca(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=>Ca(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 Tc(r))o[s]=Ca(i,e);return o}return"<unserializable>"}function Tc(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 Te(t,e){let n={factory:t};return e!==void 0&&(n.factoryArgs=e),n}function kg(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Jr(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 Ae&&(i=wg(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 Ae?t._guard:void 0;if(s){let c={...kg(t)};if(u!=null&&c.access===void 0&&(c.access=Kr(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=Kr(u)),(r||e.has("lastMutation"))&&t.lastMutation!=null&&(d.lastMutation=t.lastMutation),d}var Ze=be(()=>{"use strict";Jt();Me()});function Yr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=xg(s,e,n,r)}return o}function xg(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+Rg(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[cs];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 Rg(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}var je,cs,La=be(()=>{"use strict";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},cs=Symbol.for("sizeof")});function Qr(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return ls(e,n,"no-such-from");if(!s)return ls(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=Sg(t,e,r);if(u!=null)return u}let d=ps(e,t.nodes[e],0,r);return fs(e,n,[d])}if(i===0)return ls(e,n,"no-path");let a=wc(t,e,n,i);return a.found?fs(e,n,kc(t,a.pathOrder,r)):ls(e,n,a.truncated?"max-depth-exceeded":"no-path")}function wc(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 Sg(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=ps(e,r,0,n);a.dep_index=s[0];let d=ps(e,r,1,n);return fs(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=wc(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:fs(e,e,kc(t,i.pathOrder,n))}function kc(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=ps(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 ps(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 fs(t,e,n){return xc(t,e,!0,"ok",n)}function ls(t,e,n){return xc(t,e,!1,n,[])}function xc(t,e,n,r,o){let s=Ng(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 Ng(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: ${Eg(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;s.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return s.join(`
|
|
2
|
-
`)}function
|
|
3
|
-
`)}function _c(t){if(t.version!==vt)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${vt})`);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 Og(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 Ag(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hs(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+=Ag(r)}return e+="$",new RegExp(e)}function Ga(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 Ig(t){return t==="none"?Lg:t==="ansi"||t==null?Cg:{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 Mc(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 Pg(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 Fa(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===ot)throw new Error(`Graph "${e}": ${n} name "${ot}" is reserved for meta companion paths`);Pg(t,e,n)}function Dg(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 Gg(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 Ac(t){for(let e of t._mounts.values())Ac(e);for(let e of t._nodes.values())try{e.down([[fe]],{internal:!0})}catch{}}function ys(t,e){let n=Y.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 Sn(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 Fg(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 Ge,ot,vt,Cg,Lg,Y,Fe=be(()=>{"use strict";Fr();Oe();Re();Jt();se();Ze();Me();ne();Da();ce();At();ms();Zo();Ia();gs();Ge="::",ot="__meta__",vt=1;Cg={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"},Lg={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};Y=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===ot)throw new Error(`Graph name "${ot}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??$e,this._traceRing=new jt(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=H(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(Fa(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:W()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Ae&&n._applyVersioning(e)}remove(e){Fa(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}${ot}${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,Ac(n),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:s}),s}let r=this._nodes.get(e);if(!r)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(r),r.down([[fe]],{internal:!0});let o={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:o}),o}removeAll(e){let n=typeof e=="function"?e:(()=>{let s=hs(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([[_,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([[nt]],{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 Ae)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 Ae)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(Fa(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=Dg(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]===ot)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]!==ot)throw new Error(`Graph "${this.name}": expected ${ot} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${ot} 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=Gg(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 ct)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 ct)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=_g(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=Xt(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 Ae)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 P=2;for(;w.has(`${N}#${P}`);)P++;E=`${N}#${P}`}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=Jr(w,i,s),R=w instanceof Ae?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[P,M]of Object.entries(r)){let C=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;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 Ae)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}${Ge}`;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}${Ge}`))}return n}resourceProfile(e){return xn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?Sn(this.describe(),e,n,{...r,withDetail:!0}):Sn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(Zt(e),Zt(n),{...r?.maxDepth!==void 0?{maxDepth:Nc(r.maxDepth)}:{},...r?.findCycle!==void 0?{findCycle:Ec(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=A(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,tr(()=>{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;Oc(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===fe)&&(T=!0)}v&&u(),T&&(m?.(),m=void 0,u())}));let g;try{g=O([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=A(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([[fe,"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=()=>{a||d||(a=!0,tr(()=>{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&&Rn(e)&&l.push(e),n!=null&&Rn(n)&&l.push(n),r?.maxDepth!=null&&Rn(r.maxDepth)&&l.push(r.maxDepth),r?.findCycle!=null&&Rn(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=Zt(e),v=Zt(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=O([s],()=>{if(!p())return f();let b=Zt(e),v=Zt(n),T={...r?.maxDepth!==void 0?{maxDepth:Nc(r.maxDepth)}:{},...r?.findCycle!==void 0?{findCycle:Ec(r.findCycle)}:{}};return this._explainStatic(b,v,T)},{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:Zt(e),to:Zt(n)},equals:(b,v)=>b.found===v.found&&b.reason===v.reason&&b.steps.length===v.steps.length&&Fg(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===fe)&&(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=hs(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}${ot}${Ge}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Mc(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 ct({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 ct)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 ct)return;throw p}}}}_observeReactive(e,n){let r=n.tiers,o=r!=null?new Set(r):null,s=n.reactiveName??"observe";return H(i=>{let a=[],d=!1,u=!1,c=()=>{if(a.length===0||u)return;let h={events:a.slice(),flushedAt_ns:W()};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,tr(()=>{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 jt(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,P=new Map,M=ee=>{if(!(m!=null&&!m.has(ee.type))){l?l.push(ee):p.push(ee);for(let me of f)me(ee)}},C=ee=>m==null||m.has(ee),$=()=>o?{timestamp_ns:W(),in_batch:vn(),batch_id:x}:{},V=(ee,me)=>{if(!(!u||!(ee instanceof Ae)))return ee._setInspectorHook(Le=>{if(Le.kind==="dep_message")N.set(ee,Le.depIndex);else if(Le.kind==="run"){let rt=Le.batchData.map((U,de)=>U!=null&&U.length>0?U.at(-1):Le.prevData[de]);E.set(ee,rt);let Qe=Le.batchData.map(U=>U!=null?[...U]:void 0);P.set(ee,Qe),i&&M({type:"derived",path:me,dep_values:rt,dep_batches:Qe,...$()})}})},G=ee=>{let me=N.get(ee),Le=E.get(ee);if(!s||Le==null)return{};let Qe=(me!=null&&me>=0&&ee instanceof Ae?ee._deps[me]:void 0)?.node,U=Qe?.v,de=P.get(ee);return{trigger_dep_index:me,trigger_dep_name:Qe?.name,...U!=null?{trigger_version:{id:U.id,version:U.version}}:{},dep_values:[...Le],...de!=null?{dep_batches:de}:{}}},K=[],F=[];for(let[ee,me]of e){let Le=V(me,ee);Le&&K.push(Le),F.push(me.subscribe(rt=>{x++;for(let Qe of rt){let U=Qe[0],de=$();if(U===_){h[ee]=Qe[1];let De=me instanceof Ae?me.lastMutation?.actor??Ot:Ot;M({type:"data",path:ee,data:Qe[1],actor:De,...de,...G(me)})}else if(a)U===oe?C("dirty")&&y++:U===z?C("resolved")&&b++:U===nt?C("invalidate")&&v++:U===qe?C("pause")&&T++:U===Je?C("resume")&&w++:U===fe?C("teardown")&&k++:U===I&&!g.has(ee)?C("complete")&&(R=!0):U===L&&C("error")&&(S=!0,g.add(ee));else if(U===oe)C("dirty")&&y++,M({type:"dirty",path:ee,...de});else if(U===z)C("resolved")&&b++,M({type:"resolved",path:ee,...de,...G(me)});else if(U===nt)C("invalidate")&&v++,M({type:"invalidate",path:ee,...de});else if(U===qe)C("pause")&&T++,M({type:"pause",path:ee,lockId:Qe[1],...de});else if(U===Je)C("resume")&&w++,M({type:"resume",path:ee,lockId:Qe[1],...de});else if(U===I)C("complete")&&!g.has(ee)&&(R=!0),M({type:"complete",path:ee,...de});else if(U===L){C("error")&&(S=!0,g.add(ee));let De=me instanceof Ae?me.lastMutation?.actor??Ot:Ot;M({type:"error",path:ee,data:Qe[1],actor:De,...de})}else U===fe&&(C("teardown")&&k++,M({type:"teardown",path:ee,...de}))}}))}let q=!1,D=()=>{if(!q){q=!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 me=re.shift();me?me({value:ee,done:!1}):B.push(ee)});let ye={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:D,expand(ee){D();let me={...n};return typeof ee=="string"?me.detail=ee:Object.assign(me,ee),r(Mc(me))},[Symbol.asyncIterator](){return{next(){return B.length>0?Promise.resolve({value:B.shift(),done:!1}):q?Promise.resolve({value:void 0,done:!0}):new Promise(ee=>re.push(ee))},return(){return D(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(ye,n),ye}_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=Ig(n.theme),u=r==="stage-log"?W():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(Ga(m.data),120):"",f=m=>{if(r==="stage-log"){let R=(W()-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?` ${Ga(m.data)}`:b?` ${Ga(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(){Sc(this._disposers,this.name),this.signal([[fe]],{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 Pr(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=>hs(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(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:hs(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}${ot}${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=Mg(c.nodes);if(u.lastSnapshot!=null&&l!==""&&l===u.lastFingerprint)return;let p=u.seq+1,f=ie(),g=u.lastSnapshot==null||p%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:f,format_version:vt}:{name:this.name,mode:"diff",diff:ys(u.lastSnapshot,c),seq:p,timestamp_ns:f,format_version:vt};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,Xt("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===vt&&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===vt&&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:W(),...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];Og(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 Nn(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 Y){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 Y){let c=`${s}${d}::`;r(u,c)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}var Cc=be(()=>{"use strict";se();Fe()});function $a(t){let e=t.describe({detail:"minimal"}),n=Object.keys(e.nodes),r=new Set;for(let s of n){let i=e.nodes[s];if(!i)continue;let a=i.deps??[];for(let d of a)r.add(d)}let o=[];for(let s of n){let i=e.nodes[s];if(!i)continue;let d=(i.deps??[]).length,u=r.has(s);if(d===0&&!u){let c=i.type??"unknown";o.push({path:s,kind:c})}}return o.sort((s,i)=>s.path<i.path?-1:s.path>i.path?1:0),{ok:o.length===0,orphans:o,summary(){if(o.length===0)return"validateNoIslands: ok (no islands)";let s=o.slice(0,3).map(i=>`${i.path} (${i.kind})`).join(", ");return`validateNoIslands: ${o.length} island node(s) \u2014 ${s}${o.length>3?", \u2026":""}`}}}var Lc=be(()=>{"use strict"});function ja(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 lr(t){let e=0;for(let n of t)e+=ja(n.codePointAt(0));return e}function Ic(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=ja(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-=ja(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var bs=be(()=>{"use strict"});function Fc(t,e){let n=e.charset==="ascii"?jg:$g,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)Vg(s,i,n,a);for(let a of t.boxes)Bg(s,i,n,a,e.labelOf(a.id));return s.map(a=>zg(a.join(""))).join(`
|
|
4
|
-
`)}function Bg(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}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)$c(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);Pc(t,e,s+1,u,a-2,o)}function en(t,e,n,r,o){$c(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function $c(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=lr(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 Vg(t,e,n,r){let o=r.points;if(o.length<2)return;for(let d=0;d+1<o.length;d+=1)Kg(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=qg(u,c,l,n);p&&Gc(t,e,c.x,c.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=Hg(i,s,n);a&&Gc(t,e,s.x,s.y,a,"arrow")}function Kg(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)Dc(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)Dc(t,e,s,d,n,"v")}}}function Dc(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 Gc(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 qg(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 Hg(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 zg(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}var $g,jg,jc=be(()=>{"use strict";bs();$g={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"},jg={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"}});function Kc(t){let e=Wg(t);Ug(e),Jg(e),Yg(e),Qg(e,t);let n=eh(e,t),{width:r,height:o}=nh(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 Wg(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 Ug(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 Jg(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 Yg(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Bc(t,t.layers[r],"in"),vs(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Bc(t,t.layers[r],"out"),vs(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=Vc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],vs(s),Vc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],vs(s))}}if(!r)break}}function Bc(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 vs(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Vc(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 Qg(t,e){e.direction==="LR"?Xg(t,e):Zg(t,e)}function Xg(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}qc(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}qc(t,e,"x")}function qc(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 eh(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 P=i(t.nodes.get(S.toId)),M=i(t.nodes.get(x.toId));return P-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),P=Math.max(x,N),M=-1;for(let C=0;C<y.length;C+=1){let $=y[C],V=!0;for(let G of $)if(G.lo<=P&&E<=G.hi){V=!1;break}if(V){$.push({lo:E,hi:P}),M=C;break}}M<0&&(y.push([{lo:E,hi:P}]),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&&Ts(c,r,y,v),v!==T&&(Ts(c,r,g,v),Ts(c,r,g,T)),Ts(c,r,b,T)}let l=u[0];d.push({from:l.chainFrom,to:l.chainTo,points:th(c)})}return d}function Ts(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function th(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 nh(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 Hc=be(()=>{"use strict"});function Ba(t,e){let n=ah(e?.direction),r=Math.max(3,e?.maxLabelWidth??rh),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=Ic(p,r);d.set(p,f),u.set(p,lr(f)+4)}let c=Kc({nodes:s,edges:a,widthCells:p=>u.get(p)??3,heightCells:()=>ih,layerGap:oh,nodeGap:sh,direction:n}),l=Fc(c,{charset:o,labelOf:p=>d.get(p)??p});return e?.logger?.(l),l}function ah(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)}`)}var rh,oh,sh,ih,zc=be(()=>{"use strict";jc();bs();Hc();rh=24,oh=4,sh=1,ih=3});function ws(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(ws);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=ws(e[o]);return r}function Wc(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Uc(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Jc(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function ks(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 xs(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 Yc(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]"}}var Xr=be(()=>{"use strict"});function Va(t,e){let n=xs(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: ${Jc(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${Uc(i)}"`)}for(let[i,a]of ks(t)){let d=o.get(i),u=o.get(a);!d||!u||s.push(`${d} -> ${u}`)}return s.join(`
|
|
5
|
-
`)}var
|
|
6
|
-
`)}var
|
|
7
|
-
`);return e?.logger?.(s),s}var tl=be(()=>{"use strict";Xr()});var Wa=be(()=>{"use strict";zc();Qc();Xc();qa();el();tl()});function Ua(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=dh[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 dh,nl=be(()=>{"use strict";Wa();dh={json:t=>Ka(t),pretty:t=>za(t),mermaid:t=>tn(t),"mermaid-url":t=>Ha(t),d2:t=>Va(t),ascii:t=>Ba(t)}});var Ja={};Ee(Ja,{ENVELOPE_VERSION:()=>Xn,GRAPH_META_SEGMENT:()=>ot,Graph:()=>Y,JsonCodec:()=>Xo,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>cs,SNAPSHOT_VERSION:()=>vt,createDagCborCodec:()=>ba,createDagCborZstdCodec:()=>va,decodeEnvelope:()=>Dr,diffForWAL:()=>ys,encodeEnvelope:()=>Pr,explainPath:()=>Qr,graphProfile:()=>xn,reachable:()=>Sn,registerBuiltinCodecs:()=>Gr,replayWAL:()=>Ta,sizeof:()=>Yr,validateGraphObservability:()=>Ua,validateNoIslands:()=>$a,watchTopologyTree:()=>Nn});var Tt=be(()=>{"use strict";La();Zo();Ia();Fe();gs();Cc();Lc();nl()});var rl={};Ee(rl,{NS_PER_MS:()=>et,NS_PER_SEC:()=>wt,constant:()=>Rs,decorrelatedJitter:()=>_s,exponential:()=>Ns,fibonacci:()=>Es,linear:()=>Ss,resolveBackoffPreset:()=>_n,withMaxAttempts:()=>Ya});function En(t){return t<0?0:t}function uh(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function ch(t,e){return t+Math.random()*(e-t)}function Rs(t){let e=En(t);return()=>e}function Ss(t,e){let n=En(t),r=e===void 0?n:En(e);return o=>n+r*Math.max(0,o)}function Ns(t){let e=En(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=En(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 uh(i,o)}}function Es(t=100*1e6,e=30*1e9){let n=En(t),r=En(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 _s(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return ch(t,i)}}function Ya(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function _n(t){if(t==="constant")return Rs(1*1e9);if(t==="linear")return Ss(1*1e9);if(t==="exponential")return Ns();if(t==="fibonacci")return Es();if(t==="decorrelatedJitter")return _s();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var et,wt,Zr=be(()=>{"use strict";et=1e6,wt=1e9});function ge(t){return{describeKind:"derived",...t}}function ol(t){return{describeKind:"derived",partial:!0,...t}}function eo(t,e,n){return J([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[z]]);return}for(let i of s)o.emit(e(i))},{...ge(n),meta:{...Te("map"),...n?.meta??{}}})}function kt(t,e,n){return J([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[z]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[z]])},{...ge(n),meta:{...Te("filter"),...n?.meta??{}}})}function sl(t,e,n,r){return J([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[z]]);return}for(let d of a)i.store.acc=e(i.store.acc,d),s.emit(i.store.acc)},{...ge(r),initial:n,resetOnTeardown:!0,meta:{...Te("scan",{initial:n}),...r?.meta??{}}})}function il(t,e,n,r){return J([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([[z]]);return}for(let d of a)i.store.acc=e(i.store.acc,d)},{...ge(r),completeWhenDepsComplete:!1,meta:{...Te("reduce",{initial:n}),...r?.meta??{}}})}function to(t,e,n){return e<=0?J([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[I]]))},{...ge(n),completeWhenDepsComplete:!1,meta:{...Te("take",{count:e}),...n?.meta??{}}}):J([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[z]]);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([[z]]);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}},{...ge(n),completeWhenDepsComplete:!1,meta:{...Te("take",{count:e}),...n?.meta??{}}})}function Qa(t,e,n){return J([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[z]]);return}let a=!1;for(let d of i)s.store.skipped++,s.store.skipped<=e||(o.emit(d),a=!0);a||o.down([[z]])},ge(n))}function al(t,e,n){return J([t],(r,o,s)=>{if(s.store.done){o.down([[z]]);return}let i=r[0];if(i==null||i.length===0){o.down([[z]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[I]]);return}o.emit(a)}},{...ge(n),completeWhenDepsComplete:!1})}function dl(t,e,n){let r=n?.predicate??(i=>i[0]===_),{predicate:o,...s}=n??{};return H(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()}},ge(s))}function Ms(t,e){return to(t,1,e)}function ul(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return J([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([[z]]);return}a.store.latest=d.at(-1),a.store.has=!0},{...ge(r),completeWhenDepsComplete:!1})}function cl(t,e,n){return to(kt(t,e,n),1,n)}function ll(t,e,n){return to(Qa(t,e,n),1,n)}function pl(t,e,n){if(typeof e=="function")return J([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[z]]);return}for(let a of i)e(a),s.emit(a)},{...ge(n),meta:{...Te("tap"),...n?.meta??{}}});let r=e;return J([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([[z]]);return}for(let d of a)r.data?.(d),s.emit(d)},{...ge(n),completeWhenDepsComplete:!1,meta:{...Te("tap"),...n?.meta??{}}})}function no(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return J([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[z]]);return}for(let d of a)!o&&r(d)&&(o=!0,e(d)),i.emit(d)},ge(n))}function ml(t,e=Object.is,n){return J([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[z]]);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([[z]])},{...ge(n),meta:{...Te("distinctUntilChanged"),...n?.meta??{}}})}function gl(t,e){return J([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[z]]);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([[z]])},ge(e))}function Xa(...t){let e=[...t];return O(e,n=>n,{...ge(),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 Mn(t,e,n){return J([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([[z]]);return}for(let u of i)o.emit([u,d])}else o.down([[z]])},{...ol(n),meta:{...Te("withLatestFrom"),...n?.meta??{}}})}function Ct(...t){return t.length===0?H(e=>{e.down([[I]])},{...ge(),meta:{...Te("merge")}}):H(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()}},{...ge(),meta:{...Te("merge")}})}function hl(...t){let e=t.length;return e===0?H(n=>{n.emit([]),n.down([[I]])},ge()):H(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()}},ge())}function yl(t,e,n){return H(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?.()}},ge(n))}function bl(...t){return t.length===0?H(e=>{e.down([[I]])},ge()):t.length===1?J([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[z]]);return}for(let o of r)n.emit(o)},ge()):H(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()}},ge())}function Os(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]===oe||u[0]===z)&&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 J([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=Os(Q(e(u[u.length-1])),a,()=>{s(),o&&a.down([[I]])}),{deactivate:()=>{s(),o=!1}}},{...ge(n),completeWhenDepsComplete:!1,meta:{...Te("switchMap"),...n?.meta??{}}})}function vl(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return J([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=Os(Q(e(u[0])),a,()=>{s(),o&&a.down([[I]])}):a.down([[z]]),{deactivate:()=>{s(),o=!1}}},{...ge(n),completeWhenDepsComplete:!1})}function Tl(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=Os(Q(e(p)),d,()=>{u(),c()})}function l(p){r&&r>0&&s.length>=r&&s.shift(),s.push(p),c()}return J([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}}}},{...ge(o),completeWhenDepsComplete:!1})}function Za(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=Os(Q(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 J([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}}}},{...ge(o),completeWhenDepsComplete:!1})}function kl(t,e,n){return H(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()}},ge(n))}function ed(t,e,n){return H(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()}},{...ge(n),meta:{...Te("debounce",{ms:e}),...n?.meta??{}}})}function td(t,e,n){let{leading:r,trailing:o,...s}=n??{},i=r!==!1,a=o===!0,d=e*1e6;return H(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=W();if(i&&v-l>=d)l=v,u.emit(b),m(),a&&(c=setTimeout(()=>{c=void 0,f&&(l=W(),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=W(),u.emit(p),f=!1)},Math.max(0,e-T))}}else(y[0]===I||y[0]===L)&&(m(),u.down([y]))});return()=>{h(),m()}},{...ge(s),meta:{...Te("throttle",{ms:e,leading:i,trailing:a}),...s.meta??{}}})}function xl(t,e,n){return H(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()}},ge(n))}function Rl(t,e,n){return H(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()}},ge(n))}function Sl(t,e,n){return H(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}},ge(n))}function Nl(t,e,n){if(e<=0)throw new RangeError("bufferCount expects count > 0");return H(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}},ge(n))}function El(t,e,n){if(e<=0)throw new RangeError("windowCount expects count > 0");return H(r=>{let o,s=0;function i(){let d=H(u=>(o=u.down.bind(u),()=>{o=void 0}),ge());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}},ge(n))}function _l(t,e,n){return H(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}},{...ge(n),meta:{...Te("bufferTime",{ms:e}),...n?.meta??{}}})}function Ml(t,e,n){return H(r=>{let o;function s(){o?.([[I]]),o=void 0}function i(){let u=H(c=>(o=c.down.bind(c),()=>{o=void 0}),ge());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()}},ge(n))}function Ol(t,e,n){return H(r=>{let o;function s(){o?.([[I]]),o=void 0}function i(){let u=H(c=>(o=c.down.bind(c),()=>{o=void 0}),ge());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()}},ge(n))}function Al(t,e){return H((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)},ge(e))}function Cl(t,e,n){if(e<=0)throw new RangeError("repeat expects count > 0");return H(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?.()}},ge(n))}function Ll(t,e){return J([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[z]]);return}for(let s of o)r.emit(s)},ge(e))}function ro(t,e,n){return H(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()}},ge(n))}function Il(t,e,n){return J([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[z]]);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([[z]])},ol(n))}var fl,wl,Pl,Dl,Gl,Fl,$l=be(()=>{"use strict";Re();se();Ze();Me();ne();ce();fl=no;wl=Za;Pl=Xa,Dl=ed,Gl=td,Fl=ro});var ze=be(()=>{"use strict";$l()});function oo(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&"down"in t}function jl(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")}function Bl(t,e={}){let n=new so(t,e);return n.tagFactory("resilientPipeline",He(e)),n}var so,Vl=be(()=>{"use strict";Ze();Tt();ut();ze();nd();so=class extends Y{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(oo(n.rateLimit)){let d=r,u=n.rateLimit;r=ke(u,c=>{let l={...c,maxBuffer:c.maxBuffer??1/0,meta:we("resilient","rate-limit")};return An(d,l).node}),this.add(r,{name:"rateLimited"})}else{let d={...n.rateLimit,maxBuffer:n.rateLimit.maxBuffer??1/0,meta:we("resilient","rate-limit")},u=An(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(oo(n.budget)){let d=r,u=n.budget;r=ke(u,c=>c.length>0?Qt(d,c,{meta:we("resilient","budget")}):d),this.add(r,{name:"budgetGated"})}else n.budget.length>0&&(r=Qt(r,n.budget,{meta:we("resilient","budget")}),this.add(r,{name:"budgetGated"}));if(n.breaker!=null)if(oo(n.breaker)){let d=r,u=n.breaker,c=n.breakerOnOpen??"skip";r=ke(u,l=>{let p=Rt(l);return On(p,{onOpen:c,meta:we("resilient","breaker")})(d).node}),this.add(r,{name:"breakerWrapped"})}else{let d=Rt(n.breaker),u=n.breakerOnOpen??"skip",c=On(d,{onOpen:u,meta:we("resilient","breaker")})(r);r=c.node,i=c.breakerState,this.add(r,{name:"breakerWrapped"}),this.add(i,{name:"breakerState"})}if(n.timeoutMs!=null)if(oo(n.timeoutMs)){let d=r,u=n.timeoutMs;r=ke(u,c=>(jl(c),Cn(d,c*1e6,{meta:we("resilient","timeout")}))),this.add(r,{name:"timeoutWrapped"})}else jl(n.timeoutMs),r=Cn(r,n.timeoutMs*1e6,{meta:we("resilient","timeout")}),this.add(r,{name:"timeoutWrapped"});if(n.retry!=null)if(oo(n.retry)){let d=r,u=n.retry;r=ke(u,c=>xt(d,{...c,meta:we("resilient","retry")})),this.add(r,{name:"retryWrapped"})}else r=xt(r,{...n.retry,meta:we("resilient","retry")}),this.add(r,{name:"retryWrapped"});n.fallback!==void 0&&(r=pr(r,n.fallback,{meta:we("resilient","fallback")}),this.add(r,{name:"fallbackWrapped"}));let a=nn(r,{initialStatus:n.initialStatus??"pending",meta:we("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 Pn(t){return{describeKind:"derived",...t}}function lh(t){return t<0?0:t}function rd(t){return t[1]}function ph(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Kl(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"?_n(n):n;return{maxRetries:r,strategy:o}}function ql(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 Hl(t,e,n){let r=0,o=!1,s=null,i,a=new Ie;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=ph(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===oe)n.down([[oe]]);else if(m===_)r=0,s=null,n.emit(f[1]);else if(m===z)n.down([[z]]);else if(m===I)d(),n.down([[I]]);else if(m===L){u(rd(f));return}else n.down([f])}})}return c(),()=>{o=!0,a.cancel(),d()}}function xt(t,e){return typeof t=="function"?mh(t,e):fh(t,e)}function fh(t,e){let n=Kl(e);return H(r=>Hl(n,()=>t,r),{...Pn(),initial:t.cache,meta:{...e?.meta??{},...Te("retry",ql(e))}})}function mh(t,e){let n=Kl(e);return H(r=>Hl(n,t,r),{...Pn(),initial:e?.initial,meta:{...e?.meta??{},...Te("retry",ql(e))}})}function Rt(t){let e=Math.max(1,t?.failureThreshold??5),n=lh(t?.cooldownNs??30*1e9),r=t?.cooldown??null,o=Math.max(1,t?.halfOpenMax??1),s=t?.now??W,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 On(t,e){let n=e?.onOpen??"skip",r=e?.meta;return o=>{let s=J([],(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===oe?a.down([[oe]]):p===_?t.canExecute()?(d(),a.emit(l[1])):(d(),n==="error"?a.down([[L,new St]]):a.down([[z]])):p===z?a.down([[z]]):p===I?(t.recordSuccess(),d(),a.down([[I]])):p===L?(t.recordFailure(rd(l)),d(),a.down([l])):a.down([l])}});return d(),u},{...Pn(),meta:{...r??{},breakerState:t.state,...Te("withBreaker",{onOpen:n})},completeWhenDepsComplete:!1,initial:o.cache});return{node:s,breakerState:s.meta.breakerState}}}function rn(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??W,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 gh(t,e){return t.droppedCount===e.droppedCount&&t.pendingCount===e.pendingCount&&t.paused===e.paused}function An(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=H(u=>{let c=rn(n,a),l=s?yh():hh(o),p=new Ie,f=!1,m=0,h=1e9/a,g=d.meta.droppedCount,y=d.meta.rateLimitState,b=As;function v(){g.emit(m);let S={droppedCount:m,pendingCount:l.size,paused:l.size>0};gh(b,S)||(b=S,y.emit(S))}b=As,g.emit(0),y.emit(As);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===oe)u.down([[oe]]);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 Ln(o)]]);return}else l.push(x[1]),v();T()}else if(N===z)u.down([[z]]);else if(N===I)k(),u.down([[I]]);else if(N===L)k(),u.down([x]);else if(N===fe){k(),u.down([x]);return}else u.down([x])}});return()=>{f=!0,p.cancel(),R()}},{...Pn(),initial:t.cache,meta:{...e.meta??{},droppedCount:0,rateLimitState:As,...Te("rateLimiter",e)}});return{node:d,droppedCount:d.meta.droppedCount,rateLimitState:d.meta.rateLimitState}}function hh(t){let e=new jt(t);return{push:n=>e.push(n),shift:()=>e.shift(),get size(){return e.size}}}function yh(){let t=[];return{push:e=>{t.push(e)},shift:()=>t.shift(),get size(){return t.length}}}function nn(t,e){let n=e?.initialStatus??"pending",r=e?.meta,o=J([],(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===oe)i.down([[oe]]);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===z)i.down([[z]]);else if(l===I)o.meta.status.down([[_,"completed"]]),a="completed",i.down([[I]]);else if(l===L){let p=rd(c);Z(()=>{o.meta.error.down([[_,p]]),o.meta.status.down([[_,"errored"]])}),a="errored",i.down([c])}else i.down([c])}})},{...Pn(),meta:{...r??{},status:n,error:null,...Te("withStatus",{initialStatus:n})},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:o,status:o.meta.status,error:o.meta.error}}function bh(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function vh(t){return t!=null&&typeof t.then=="function"}function Th(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function pr(t,e,n){let r=n?.meta;return H(o=>{let s,i;function a(){i?.(),i=void 0,bh(e)||vh(e)||Th(e)?s=Q(e).subscribe(u=>{o.down(u);for(let c of u){let l=c[0];if(l===I||l===L||l===fe){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===oe)o.down([[oe]]);else if(c===_)o.emit(u[1]);else if(c===z)o.down([[z]]);else if(c===I)o.down([[I]]);else if(c===L){a();return}else if(c===fe){s?.(),o.down([u]);return}else o.down([u])}}),()=>{i?.(),s?.()}},{...Pn(),initial:t.cache,meta:{...r??{},...Te("fallback")}})}function Cn(t,e,n){if(e<=0)throw new RangeError("timeoutNs must be > 0");let r=n?.meta;return H(o=>{let s=!1,i=new Ie;function a(){let u=e/1e6;i.start(u,()=>{s||(s=!0,d(),o.down([[L,new In(e)]]))})}let d=t.subscribe(u=>{for(let c of u){if(s)return;let l=c[0];if(l===oe)o.down([[oe]]);else if(l===_)a(),o.emit(c[1]);else if(l===z)o.down([[z]]);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===fe){i.cancel(),s=!0,o.down([c]);return}else o.down([c])}});return a(),()=>{s=!0,i.cancel(),d()}},{...Pn(),initial:t.cache,meta:{...r??{},...Te("timeout",{timeoutNs:e})}})}var St,Ln,As,In,nd=be(()=>{"use strict";vc();Vl();Oe();Re();se();Ze();Me();ne();Zr();ce();At();ms();St=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})`)}};As=Object.freeze({droppedCount:0,pendingCount:0,paused:!1});In=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});var zl={};Ee(zl,{CircuitOpenError:()=>St,RateLimiterOverflowError:()=>Ln,ResilientPipelineGraph:()=>so,TimeoutError:()=>In,budgetGate:()=>Qt,circuitBreaker:()=>Rt,fallback:()=>pr,rateLimiter:()=>An,resilientPipeline:()=>Bl,retry:()=>xt,timeout:()=>Cn,tokenBucket:()=>rn,withBreaker:()=>On,withStatus:()=>nn});var on=be(()=>{"use strict";nd()});function ft(t){return{describeKind:"producer",...t}}function sd(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function Ul(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+=sd(r)}return e+="$",new RegExp(e)}function Jl(t,e){for(let n of e)if(n.test(t))return!0;return!1}function wh(t,e){let n=J([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[z]]);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 st(t,e){let{signal:n,period:r,...o}=e??{};return H(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 Yl(t){let{signal:e,...n}=t??{};return H(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 Ls(t,e){let n=ds(t),{tickMs:r,output:o,...s}=e??{},i=r??6e4,a=o==="date";return H(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&&us(n,p)&&(u=f,d.emit(a?p:ie()))};c();let l=setInterval(c,i);return()=>clearInterval(l)},{...ft(s),name:s.name??`cron:${t}`})}function Ql(t,e,n){let{capture:r,passive:o,once:s,...i}=n??{};return H(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 Is(t,e){return H(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 kh(t){return t!=null&&typeof t.then=="function"}function fr(t,e){let{signal:n,...r}=e??{};return H(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 io(t,e){let{signal:n,...r}=e??{};return H(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 xh(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function Q(t,e){if(xh(t))return t;if(kh(t))return fr(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return io(t,e);if(typeof n[Symbol.iterator]=="function")return Is(t,e)}return id(t)}function id(...t){return Is(t,void 0)}function Xl(t){return H(e=>{e.down([[I]])},ft(t))}function Zl(t){return H(()=>{},ft(t))}function ep(t,e){return H(n=>{n.down([[L,t]])},ft(e))}function tp(t,e){let{signal:n,...r}=e??{},o=ft(r),s=o.resubscribable===void 0?{...o,resubscribable:!0}:o;return H(i=>{let a,d=!1;try{let u=t();a=Q(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 sn(t,e,n){return J([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 np(t,e){return J([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([[z]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function rp(t,e){return H(n=>t.subscribe(r=>{n.down(r)}),{...ft(e),initial:t.cache})}function Ps(t,e,n){if(e<1)throw new RangeError("replay expects bufferSize >= 1");let r=[],o=H(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 wh(o,s=>{for(let i of r)s([[_,i]])})}function op(t,e){return Ps(t,1,e)}function it(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 Cs(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 Ds(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Cs(t,n,{skipCurrent:r});if(od===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(on(),zl)),Promise.resolve().then(()=>(Zr(),rl))]);od=s.timeout,Wl=i.NS_PER_MS}let o=od(t,e.timeoutMs*Wl);return await Cs(o,n,{skipCurrent:r})}function Gs(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 ip(t){let e=A(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[oe],[_,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var od,Wl,sp,ap=be(()=>{"use strict";Re();se();Me();ne();Oa();sp=Ps});var ce=be(()=>{"use strict";ap()});var Yv={};Ee(Yv,{COMPLETE:()=>I,COMPLETE_MSG:()=>Yo,COMPLETE_ONLY_BATCH:()=>Ir,CircuitOpenError:()=>St,ContentAddressedMissError:()=>bo,DATA:()=>_,DEFAULT_ACTOR:()=>Ot,DEFAULT_AUDIT_GUARD:()=>pd,DIRTY:()=>oe,DIRTY_MSG:()=>Dt,DIRTY_ONLY_BATCH:()=>Yn,ENVELOPE_VERSION:()=>Xn,ERROR:()=>L,GRAPH_META_SEGMENT:()=>ot,Graph:()=>Y,GraphReFlyConfig:()=>Tn,GuardDenied:()=>ct,INVALIDATE:()=>nt,INVALIDATE_MSG:()=>Jo,INVALIDATE_ONLY_BATCH:()=>Lr,JsonCodec:()=>Xo,NS_PER_MS:()=>et,NS_PER_SEC:()=>wt,NativeIndexBackend:()=>wo,NativeListBackend:()=>ko,NativeLogBackend:()=>co,NativeMapBackend:()=>ho,NativePubSubBackend:()=>To,NodeImpl:()=>Ae,PAUSE:()=>qe,RESOLVED:()=>z,RESOLVED_MSG:()=>Un,RESOLVED_ONLY_BATCH:()=>Cr,RESUME:()=>Je,RateLimiterOverflowError:()=>Ln,ResettableTimer:()=>Ie,SIZEOF_OVERHEAD:()=>je,SIZEOF_SYMBOL:()=>cs,SNAPSHOT_VERSION:()=>vt,SNAPSHOT_WIRE_VERSION:()=>Wo,START:()=>mt,START_MSG:()=>Jn,SurfaceError:()=>_e,TEARDOWN:()=>fe,TEARDOWN_MSG:()=>Qo,TEARDOWN_ONLY_BATCH:()=>Qn,TimeoutError:()=>In,accessHintForGuard:()=>Kr,advanceVersion:()=>qr,ai:()=>Bi,appendAudit:()=>gr,appendLogStorage:()=>_d,asSurfaceError:()=>aa,audit:()=>Rl,autoTrackNode:()=>wn,awaitSettled:()=>Ds,batch:()=>Z,budgetGate:()=>Qt,buffer:()=>Sl,bufferCount:()=>Nl,bufferTime:()=>_l,bumpCursor:()=>Bt,cached:()=>op,canonicalJson:()=>vo,cascadingCache:()=>Tf,catchError:()=>Fl,checkpointToRedis:()=>pf,checkpointToS3:()=>lf,circuitBreaker:()=>Rt,combine:()=>Xa,combineLatest:()=>Pl,compat:()=>Td,concat:()=>yl,concatMap:()=>Tl,configure:()=>Na,constant:()=>Rs,contentAddressedStorage:()=>si,core:()=>cd,cqrs:()=>zs,createAuditLog:()=>at,createDagCborCodec:()=>ba,createDagCborZstdCodec:()=>va,createGraph:()=>Mr,createTransport:()=>cn,createVersioning:()=>nr,createWatermarkController:()=>mr,csvRows:()=>zp,debounce:()=>ed,debounceTime:()=>Dl,decay:()=>It,decodeEnvelope:()=>Dr,decorrelatedJitter:()=>_s,defaultConfig:()=>$e,defaultHash:()=>Yt,defer:()=>tp,delay:()=>kl,deleteSnapshot:()=>ma,demoShell:()=>Ki,derived:()=>O,deserializeError:()=>Bn,dictKv:()=>Lf,dictSnapshot:()=>If,diffForWAL:()=>ys,diffSnapshots:()=>pa,distill:()=>ri,distinctUntilChanged:()=>ml,domainMeta:()=>we,domainTemplates:()=>qi,downWithBatch:()=>Ft,dynamicNode:()=>Hr,effect:()=>he,elementAt:()=>ll,empty:()=>Xl,encodeEnvelope:()=>Pr,escapeRegexChar:()=>sd,exhaustMap:()=>vl,explainPath:()=>Qr,exponential:()=>Ns,externalBundle:()=>ni,externalProducer:()=>Fn,extra:()=>Ad,factoryTag:()=>Te,fallback:()=>pr,fibonacci:()=>Es,filter:()=>kt,find:()=>cl,first:()=>Ms,firstValueFrom:()=>it,firstWhere:()=>Cs,flatMap:()=>wl,forEach:()=>sn,fromAny:()=>Q,fromAsyncIter:()=>io,fromCSV:()=>Hp,fromClickHouseWatch:()=>Yp,fromCron:()=>Ls,fromDrizzle:()=>yf,fromEvent:()=>Ql,fromHTTP:()=>Rd,fromHTTPPoll:()=>Ap,fromHTTPStream:()=>Op,fromIter:()=>Is,fromKafka:()=>Bp,fromKysely:()=>bf,fromMCP:()=>Ip,fromNATS:()=>Zp,fromNDJSON:()=>Jp,fromOTel:()=>Pp,fromPrisma:()=>hf,fromPrometheus:()=>jp,fromPromise:()=>fr,fromPulsar:()=>Qp,fromRabbitMQ:()=>tf,fromRaf:()=>Yl,fromRedisStream:()=>Kp,fromSSE:()=>Mp,fromSqlite:()=>ff,fromSqliteCursor:()=>mf,fromStatsD:()=>Fp,fromSyslog:()=>Dp,fromTimer:()=>st,fromWebSocket:()=>xd,fromWebSocketReconnect:()=>Lp,fromWebhook:()=>kp,globToRegExp:()=>Ul,graph:()=>Ja,graphProfile:()=>xn,graphspec:()=>ji,harness:()=>Zi,inspect:()=>oa,interval:()=>Al,isBatching:()=>vn,isV1:()=>xa,jobQueue:()=>Qi,jotai:()=>ns,jsonCodec:()=>Tr,jsonCodecFor:()=>Of,keepalive:()=>te,kvStorage:()=>ci,last:()=>ul,layout:()=>ia,lightMutation:()=>Ce,linear:()=>Ss,listSnapshots:()=>fa,lru:()=>Ed,makeHttpError:()=>Et,map:()=>eo,matchesAnyPattern:()=>Jl,matchesCron:()=>us,memory:()=>Pi,memoryAppendLog:()=>Cf,memoryBackend:()=>Ro,memoryKv:()=>So,memorySnapshot:()=>Af,merge:()=>Ct,mergeMap:()=>Za,mergeReactiveLogs:()=>mp,messaging:()=>Mi,monotonicNs:()=>W,nameToSignal:()=>$n,nanostores:()=>is,ndjsonRows:()=>Wp,nestjs:()=>Us,never:()=>Zl,node:()=>J,nodeSignal:()=>Gs,normalizeActor:()=>Gt,of:()=>id,onFirstData:()=>no,orchestration:()=>Oi,pairwise:()=>gl,parseCron:()=>ds,parsePrometheusText:()=>Sd,parseSSEStream:()=>qt,parseStatsD:()=>$p,parseSyslog:()=>Gp,patterns:()=>Bu,pausable:()=>Ll,pipe:()=>Ea,placeholderArgs:()=>He,policy:()=>$t,policyFromRules:()=>Vr,process:()=>sa,producer:()=>H,pubsub:()=>Sf,race:()=>bl,rateLimiter:()=>An,reachable:()=>Sn,react:()=>Js,reactiveCounter:()=>ip,reactiveIndex:()=>_f,reactiveList:()=>ii,reactiveLog:()=>We,reactiveMap:()=>Xe,reactiveSink:()=>Ye,reduce:()=>il,reduction:()=>Gi,registerBuiltinCodecs:()=>Gr,registerBuiltins:()=>Br,registerCursor:()=>ht,registerCursorMap:()=>js,repeat:()=>Cl,replay:()=>Ps,replayWAL:()=>Ta,rescue:()=>ro,resolveBackoffPreset:()=>_n,resolveDescribeFields:()=>Xt,restoreSnapshot:()=>la,retry:()=>xt,runReduction:()=>da,sample:()=>xl,saveSnapshot:()=>ca,scan:()=>sl,serializeError:()=>jn,share:()=>rp,shareReplay:()=>sp,signalToName:()=>un,signals:()=>Qs,singleFromAny:()=>ai,singleNodeFromAny:()=>Mf,sizeof:()=>Yr,skip:()=>Qa,snapshotStorage:()=>ui,solid:()=>Xs,sortJsonValue:()=>xo,stableJsonString:()=>di,state:()=>A,stratify:()=>No,surface:()=>ga,svelte:()=>Zs,switchMap:()=>ke,take:()=>to,takeUntil:()=>dl,takeWhile:()=>al,tap:()=>pl,tapFirst:()=>fl,throttle:()=>td,throttleTime:()=>Gl,throwError:()=>ep,timeout:()=>Cn,toArray:()=>np,toCSV:()=>rf,toClickHouse:()=>of,toFile:()=>Nd,toHTTP:()=>xp,toKafka:()=>Vp,toLoki:()=>uf,toMongo:()=>df,toNATS:()=>ef,toObservable:()=>as,toPostgres:()=>af,toPulsar:()=>Xp,toRabbitMQ:()=>nf,toReadableStream:()=>_p,toRedisStream:()=>qp,toS3:()=>sf,toSSE:()=>Np,toSSEBytes:()=>Ep,toSqlite:()=>gf,toTempo:()=>cf,toWebSocket:()=>Cp,tokenBucket:()=>rn,topologyDiff:()=>cr,tryIncrementBounded:()=>Gn,validateGraphObservability:()=>Ua,validateNoIslands:()=>$a,valve:()=>Il,verifiable:()=>xf,version:()=>Jv,vue:()=>ei,wallClockNs:()=>ie,watchTopologyTree:()=>Nn,window:()=>Ol,windowCount:()=>El,windowTime:()=>Ml,withBreaker:()=>On,withLatestFrom:()=>Mn,withMaxAttempts:()=>Ya,withStatus:()=>nn,workerBridge:()=>Md,workerSelf:()=>Od,wrapMutation:()=>Lt,zip:()=>hl,zustand:()=>ti});module.exports=Zm(Yv);var Td={};Ee(Td,{jotai:()=>ns,nanostores:()=>is,nestjs:()=>Us,react:()=>Js,signals:()=>Qs,solid:()=>Xs,svelte:()=>Zs,vue:()=>ei,zustand:()=>ti});var ns={};Ee(ns,{atom:()=>fg});se();ne();function fg(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?oc(r,e,n):oc(r,void 0,e)}return mg(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 mg(t,e){let n=A(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 oc(t,e,n){let r=wn(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 is={};Ee(is,{action:()=>Tg,atom:()=>gg,computed:()=>hg,getValue:()=>bg,map:()=>yg,onMount:()=>vg,onStart:()=>ac,onStop:()=>dc});Oe();se();ne();var os=new WeakMap,ss=new WeakMap;function rs(t,e){let n=e.get(t);if(n)for(let r of n)r()}function _a(t,e={}){let n=0;return{...e,get:()=>ic(t),subscribe:o=>{n===0&&rs(t,os),n++;let s=t.subscribe(i=>{for(let[a,d]of i)a===_&&o(d)});return()=>{s(),n--,n===0&&rs(t,ss)}},listen:o=>{n===0&&rs(t,os),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&&rs(t,ss)}},_node:t}}function sc(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 ic(t){return t.status==="sentinel"?sc(t):t.cache}function gg(t){let e=A(t,{resubscribable:!0,resetOnTeardown:!0});return _a(e,{set:n=>e.emit(n)})}function hg(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=Hr(r,s=>{let i=n.map(a=>{let d=a._node;return d.status==="sentinel"&&sc(d),s(d)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return _a(o)}function yg(t){let e=A(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return _a(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=ic(e);e.emit({...o,[n]:r})}})}function bg(t){return t.get()}function ac(t,e){let n=t._node,r=os.get(n);r||(r=new Set,os.set(n,r)),r.add(e)}function dc(t,e){let n=t._node,r=ss.get(n);r||(r=new Set,ss.set(n,r)),r.add(e)}function vg(t,e){ac(t,()=>{let n=e();typeof n=="function"&&dc(t,n)})}function Tg(t,e,n){return(...r)=>{let o;return Z(()=>{o=n(...r)}),o}}var Us={};Ee(Us,{ACTOR_KEY:()=>$s,COMMAND_HANDLERS:()=>ir,CQRS_EVENT_HANDLERS:()=>ar,CRON_HANDLERS:()=>sr,CommandHandler:()=>gc,EVENT_HANDLERS:()=>rr,EventHandler:()=>hc,GRAPHREFLY_REQUEST_GRAPH:()=>kn,GRAPHREFLY_ROOT_GRAPH:()=>gt,GraphCron:()=>mc,GraphInterval:()=>fc,GraphReflyEventExplorer:()=>Dn,GraphReflyGuard:()=>fp,GraphReflyGuardImpl:()=>ao,GraphReflyModule:()=>Ws,INTERVAL_HANDLERS:()=>or,InjectCqrsGraph:()=>cc,InjectGraph:()=>uc,InjectNode:()=>lc,ObserveGateway:()=>Fs,OnGraphEvent:()=>pc,QUERY_HANDLERS:()=>dr,QueryHandler:()=>yc,SAGA_HANDLERS:()=>ur,SagaHandler:()=>bc,fromHeader:()=>lp,fromJwtPayload:()=>ud,getActor:()=>pp,getGraphToken:()=>lt,getNodeToken:()=>bt,observeSSE:()=>up,observeSubscription:()=>cp,toObservable:()=>as});var Ma=require("rxjs");se();function as(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]===L){n.error(s[1]);return}if(s[0]===I){n.complete();return}}}})):new Ma.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 Wr=require("@nestjs/common");var gt=Symbol.for("graphrefly:root-graph");var kn=Symbol.for("graphrefly:request-graph");function lt(t){return Symbol.for(`graphrefly:graph:${t}`)}function bt(t){return Symbol.for(`graphrefly:node:${t}`)}var rr=new Map,or=new Map,sr=new Map,ir=new Map,ar=new Map,dr=new Map,ur=new Map;function uc(t){return t==="request"?(0,Wr.Inject)(kn):(0,Wr.Inject)(t?lt(t):gt)}function cc(t){return(0,Wr.Inject)(lt(t))}function lc(t){return(0,Wr.Inject)(bt(t))}function pc(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=rr.get(o)??[];s.push({nodeName:t,methodKey:r}),rr.set(o,s)})}}function fc(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=or.get(o)??[];s.push({ms:t,methodKey:r}),or.set(o,s)})}}function mc(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=sr.get(o)??[];s.push({expr:t,methodKey:r}),sr.set(o,s)})}}function gc(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=ir.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),ir.set(s,i)})}}function hc(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=ar.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),ar.set(s,i)})}}function yc(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=dr.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),dr.set(s,i)})}}function bc(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=ur.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),ur.set(i,a)})}}se();ce();var dp=0,Dn=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 rr){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 or){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)}.${dp++}`,d=st(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 sr){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)}.${dp++}`,d=Ls(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 ir){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 ar){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 dr){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 ur){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(lt(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}}};se();se();var Rh=0;function mr(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-${++Rh}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[qe,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[Je,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[Je,n]]))}}}function up(t,e,n){let{actor:r,serialize:o=Sh,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=mr(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(ad("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(ad("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===fe){if(k===I){let R=a.encode(ad("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
|
|
1
|
+
"use strict";var eg=Object.create;var Un=Object.defineProperty;var Qu=Object.getOwnPropertyDescriptor;var tg=Object.getOwnPropertyNames;var ng=Object.prototype.hasOwnProperty;var Xu=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Lr=t=>{throw TypeError(t)};var rg=(t,e,n)=>e in t?Un(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Uu=(t,e)=>Un(t,"name",{value:e,configurable:!0});var be=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ee=(t,e)=>{for(var n in e)Un(t,n,{get:e[n],enumerable:!0})},og=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of tg(e))!ng.call(t,o)&&o!==n&&Un(t,o,{get:()=>e[o],enumerable:!(r=Qu(e,o))||r.enumerable});return t};var sg=t=>og(Un({},"__esModule",{value:!0}),t);var Zu=t=>[,,,eg(t?.[Xu("metadata")]??null)],ec=["class","method","getter","setter","accessor","field","value","get","set"],Cr=t=>t!==void 0&&typeof t!="function"?Lr("Function expected"):t,ig=(t,e,n,r,o)=>({kind:ec[t],name:e,metadata:r,addInitializer:s=>n._?Lr("Already initialized"):o.push(Cr(s||null))}),ag=(t,e)=>rg(e,Xu("metadata"),t[3]),tc=(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},nc=(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=ec[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)&&Qu(l<4?o:{get[n](){return Ju(this,s)},set[n](T){return Yu(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=ig(l,n,d={},t[3],y),l&&(u.static=p,u.private=f,c=u.access={has:f?T=>dg(o,T):T=>n in T},l^3&&(c.get=f?T=>(l^1?Ju:ug)(T,o,l^4?s:b.get):T=>T[n]),l>2&&(c.set=f?(T,w)=>Yu(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?Cr(a)&&(l>4?g.unshift(a):l?f?s=a:b[h]=a:o=a):typeof a!="object"||a===null?Lr("Object expected"):(Cr(i=a.get)&&(b.get=i),Cr(i=a.set)&&(b.set=i),Cr(i=a.init)&&g.unshift(i));return l||ag(t,o),b&&Un(o,n,b),f?l^4?s:b:o};var ka=(t,e,n)=>e.has(t)||Lr("Cannot "+n),dg=(t,e)=>Object(e)!==e?Lr('Cannot use the "in" operator on this value'):t.has(e),Ju=(t,e,n)=>(ka(t,e,"read from private field"),n?n.call(t):e.get(t));var Yu=(t,e,n,r)=>(ka(t,e,"write to private field"),r?r.call(t,n):e.set(t,n),n),ug=(t,e,n)=>(ka(t,e,"access private method"),n);var ht,E,oe,H,nt,ze,Ye,ge,I,L,Gt,Jn,Xo,Yn,Zo,es,Qn,Ir,Pr,Dr,Xn,se=be(()=>{"use strict";ht=Symbol.for("graphrefly/START"),E=Symbol.for("graphrefly/DATA"),oe=Symbol.for("graphrefly/DIRTY"),H=Symbol.for("graphrefly/RESOLVED"),nt=Symbol.for("graphrefly/INVALIDATE"),ze=Symbol.for("graphrefly/PAUSE"),Ye=Symbol.for("graphrefly/RESUME"),ge=Symbol.for("graphrefly/TEARDOWN"),I=Symbol.for("graphrefly/COMPLETE"),L=Symbol.for("graphrefly/ERROR"),Gt=Object.freeze([oe]),Jn=Object.freeze([H]),Xo=Object.freeze([nt]),Yn=Object.freeze([ht]),Zo=Object.freeze([I]),es=Object.freeze([ge]),Qn=Object.freeze([Gt]),Ir=Object.freeze([Jn]),Pr=Object.freeze([Xo]),Dr=Object.freeze([Zo]),Xn=Object.freeze([es])});function xa(t){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>t.encode(e),decode:(e,n)=>t.decode(e)}}function Ra(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 Gr(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++]=Zn,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 Fr(t,e){if(t.length<rc)throw new Error(`decodeEnvelope: bytes too short (${t.length} < ${rc})`);let n=0,r=t[n++];if(r!==Zn)throw new Error(`decodeEnvelope: unsupported envelope version ${r} (expected ${Zn})`);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(ts)}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 ts,Zn,rc,ns=be(()=>{"use strict";ts={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)}};Zn=1,rc=4});function Ft(t){if(t==null)return Ct;let{type:e,id:n,...r}=t;return{type:e??"system",id:n??"",...r}}var Ct,jr=be(()=>{"use strict";Ct={type:"system",id:""}});function Tn(){return er>0||Br}function oc(){return er>0}function nr(t){er>0?Vr.push(t):t()}function Z(t){er+=1;let e=!1;try{t()}catch(n){throw e=!0,n}finally{if(er-=1,er===0)if(e){if(!Br){let n=Vr.splice(0);for(let r of n)try{r()}catch{}bn.length=0,vn.length=0,tr.length=0}}else cg()}}function cg(){let t=!Br;t&&(Br=!0);let e=[],n=0;try{for(;bn.length>0||vn.length>0||tr.length>0||t&&Vr.length>0;){if(t&&Vr.length>0){let s=Vr.splice(0);for(let i of s)try{i()}catch(a){e.push(a)}continue}if(n+=1,n>1e3)throw bn.length=0,vn.length=0,tr.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let o=(bn.length>0?bn:vn.length>0?vn:tr).splice(0);for(let s of o)try{s()}catch(i){e.push(i)}}}finally{t&&(Br=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function $t(t,e,n){if(e.length===0)return;if(e.length===1){let u=n(e[0][0]);if(u<3||!Tn()){t(e);return}(u>=5?tr:u===4?vn:bn).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=Tn();if(o>0){let u=e.slice(0,o);t(u)}if(s>o){let u=e.slice(o,s);d?bn.push(()=>t(u)):t(u)}if(i>s){let u=e.slice(s,i);d?vn.push(()=>t(u)):t(u)}if(r>i){let u=e.slice(i,r);d?tr.push(()=>t(u)):t(u)}}var er,Br,bn,vn,tr,Vr,Oe=be(()=>{"use strict";er=0,Br=!1,bn=[],vn=[],tr=[],Vr=[]});function W(){return Math.trunc(performance.now()*1e6)}function ie(){return Date.now()*1e6}var Re=be(()=>{"use strict"});function Kr(t){t.registerMessageType(ht,{tier:0,wireCrossing:!1}),t.registerMessageType(oe,{tier:1,wireCrossing:!1}),t.registerMessageType(nt,{tier:1,wireCrossing:!1,metaPassthrough:!1}),t.registerMessageType(ze,{tier:2,wireCrossing:!1}),t.registerMessageType(Ye,{tier:2,wireCrossing:!1}),t.registerMessageType(E,{tier:3,wireCrossing:!0}),t.registerMessageType(H,{tier:3,wireCrossing:!0}),t.registerMessageType(I,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(L,{tier:4,wireCrossing:!0,metaPassthrough:!1}),t.registerMessageType(ge,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var wn,Na=be(()=>{"use strict";se();wn=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 sc(t){return Array.isArray(t)?[...t]:[t]}function lg(t,e){return t.has(e)||t.has("*")}function jt(t){let e=[];return t((o,s)=>{e.push({kind:"allow",actions:new Set(sc(o)),where:s?.where??(()=>!0)})},(o,s)=>{e.push({kind:"deny",actions:new Set(sc(o)),where:s?.where??(()=>!0)})}),(o,s)=>{let i=!1,a=!1;for(let d of e)lg(d.actions,s)&&d.where(o)&&(d.kind==="deny"?i=!0:a=!0);return i?!1:a}}function qr(t){return jt((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 zr(t){let e=pg.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 lt,pg,Qt=be(()=>{"use strict";lt=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}};pg=["human","llm","wallet","system"]});function Ea(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(Ea);if(typeof t=="object"&&t!==null){let e={};for(let n of Object.keys(t).sort())e[n]=Ea(t[n]);return e}return null}function gg(t){let e=mg.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 O=0;O<16;O++)h[O]=i.getUint32(b+O*4,!1);for(let O=16;O<64;O++){let D=h[O-15],M=h[O-2],N=g(D,7)^g(D,18)^D>>>3,P=g(M,17)^g(M,19)^M>>>10;h[O]=h[O-16]+N+h[O-7]+P>>>0}let v=a,T=d,w=u,k=c,x=l,R=p,S=f,_=m;for(let O=0;O<64;O++){let D=g(x,6)^g(x,11)^g(x,25),M=x&R^~x&S,N=_+D+M+fg[O]+h[O]>>>0,P=g(v,2)^g(v,13)^g(v,22),j=v&T^v&w^T&w,G=P+j>>>0;_=S,S=R,R=x,x=k+N>>>0,k=w,w=T,T=v,v=N+G>>>0}a=a+v>>>0,d=d+T>>>0,u=u+w>>>0,c=c+k>>>0,l=l+x>>>0,p=p+R>>>0,f=f+S>>>0,m=m+_>>>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 Xt(t){let e=Ea(t??null),n=JSON.stringify(e);return gg(n).slice(0,16)}function hg(){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 rr(t,e,n){let r=n?.id??hg();if(t===0)return{id:r,version:0};let s=(n?.hash??Xt)(e);return{id:r,version:0,cid:s,prev:null}}function Hr(t,e,n){t.version+=1,"cid"in t&&(t.prev=t.cid,t.cid=n(e))}function _a(t){return"cid"in t}var fg,mg,rs=be(()=>{"use strict";fg=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]),mg=new TextEncoder});function dc(t){return{node:t,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function Ma(t){t.prevData=void 0,t.dirty=!1,t.involvedThisWave=!1,t.dataBatch.length=0,t.terminal=void 0}function os(t){return t.length===0?t:typeof t[0]=="symbol"?[t]:t}function Aa(t){if(je._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(je)}function Q(t,e,n){let r=uc(t)?t:[],o=typeof t=="function"?t:typeof e=="function"?e:void 0,s={};return uc(t)?s=(Oa(e)?e:n)??{}:Oa(t)?s=t:s=(Oa(e)?e:n)??{},new Ae(r,o,s)}var ic,ac,yg,bg,je,Ae,uc,Oa,Me=be(()=>{"use strict";ns();jr();Oe();Re();Na();Qt();se();rs();ic=()=>{},ac=100;yg=(t,e,n,r)=>{n.direction==="down-in"&&t._onDepMessage(n.depIndex,e)},bg=(t,e,n,r)=>{let o=t;if(o._status==="completed"||o._status==="errored")return;let s=o._cached,i=s===void 0?[Yn]:[Yn,[E,s]];o._status==="dirty"&&i.push(Gt),$t(e,i,o._config.tierOf)},je=new wn({onMessage:yg,onSubscribe:bg});Kr(je);$r(je);Ae=class t{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,n,r){this._config=r.config??je,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??Xt;let o=r.versioning??this._config.defaultVersioning;this._versioningLevel=o,this._versioning=o!=null?rr(o,this._cached===void 0?void 0:this._cached,{id:r.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(dc);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),r.resubscribable===!0&&(u.resubscribable=!0),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([[E,a]])},down(a){i._emit(os(a))},up(a){i._emitUp(os(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=rr(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=Ft(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=Ft(e?.actor),s=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(o,s))throw new lt({actor:o,action:s,nodeName:this.name});if(this._extraGuards!=null){for(let i of this._extraGuards)if(!i(o,s))throw new lt({actor:o,action:s,nodeName:this.name})}this._lastMutation={actor:o,timestamp_ns:ie()}}down(e,n){let r=os(e);r.length!==0&&(this._checkGuard(n),this._emit(r))}emit(e,n){this._checkGuard(n),this._emit([[E,e]])}up(e,n){if(this._deps.length===0)return;let r=os(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=Ft(n);if(!this._guard(d,"observe"))throw new lt({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)Ma(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=ic,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{}Ma(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=dc(e);if(this._deps.push(r),this._sinks==null)return n;r.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(Qn),r.unsub=ic;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{}}Ma(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!==ht){if(o===oe){this._depDirtied(r);return}if(o===nt){if(this._depInvalidated(r),this._cached===void 0)return;this._emit(Pr);return}if(o===ze||o===Ye){this._emit([n]);return}if(o===ge){this._emit(Xn);return}if(o===E)this._depSettledAsData(r,n[1]);else if(o===H)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===E||o===H)&&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(Qn))}_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(Ir),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(Dr)}_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>ac?(this._rerunDepth=0,this._emit([[L,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${ac} \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"?[Gt,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?[Gt,...a]:[...a.slice(0,d),Gt,...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]===ge||d[0]===nt);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!==ze&&u!==Ye){o?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${u===ze?"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===ze)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]===ge))for(let a of Object.keys(this.meta))try{this.meta[a]._emit(Xn)}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]===E){d=c;break}}for(let c=0;c<e.length;c++){let l=e[c],p=l[0];if(p===E){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(Jn),this._status="resolved";continue}this._cached=l[1],this._versioning!=null&&(d<0||c===d)&&Hr(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===H)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===nt){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===ge&&(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(oc()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],nr(()=>this._flushBatchPending()));for(let n of e)this._batchPendingMessages.push(n);return}$t(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);$t(this._deliverToSinks,n,this._config.tierOf)}},uc=t=>Array.isArray(t),Oa=t=>typeof t=="object"&&t!=null&&!Array.isArray(t)});function C(t,e){return Q([],{...e,initial:t})}function z(t,e){return Q((r,o,s)=>t(o,s)??void 0,{describeKind:"producer",...e})}function A(t,e,n){return Q(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 Ca(t,e,n){return A(t,e,n)}function La(t,e,n){return he(t,e,n)}function he(t,e,n){return Q(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 Wr(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 kn(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 Ae([],o,{describeKind:"derived",...e}),n}function Ia(t,...e){let n=t;for(let r of e)n=r(n);return n}var re=be(()=>{"use strict";Me()});function Yr(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 ls(t){let e=t.trim().split(/\s+/);if(e.length!==5)throw new Error(`Invalid cron: expected 5 fields, got ${e.length}`);return{minutes:Yr(e[0],0,59),hours:Yr(e[1],0,23),daysOfMonth:Yr(e[2],1,31),months:Yr(e[3],1,12),daysOfWeek:Yr(e[4],0,6)}}function ps(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=be(()=>{"use strict"});function we(t,e,n){return{[t]:!0,[`${t}_type`]:e,...n??{}}}var ut=be(()=>{"use strict"});function Zt(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 Fa,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([[H]]))}return Q([],(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:we("resilience","budget_gate",n?.meta)});function p(f,m,h){let g=f[0];if(m===0){if(g===E)return c()&&s.size===0?h.emit(f[1]):(s.push(f[1]),i||(i=!0,h.up([[ze,d]]))),!0;if(g===oe)return h.down([[oe]]),!0;if(g===H)return s.size===0?h.down([[H]]):a=!0,!0;if(g===I||g===L){for(;s.size>0;)h.emit(s.shift());return a=!1,i&&(i=!1,h.up([[Ye,d]])),h.down([f]),!0}return!1}if(g===E&&(u[m-1]=f[1]),g===E||g===H){let y=c();return y&&s.size>0?(l(h),s.size===0&&i&&(i=!1,h.up([[Ye,d]]))):!y&&!i&&s.size>0&&(i=!0,h.up([[ze,d]])),!0}return g===oe?!0:g===L?(h.down([f]),!0):g===I}}var Fa,Sc=be(()=>{"use strict";se();Me();ut();Fa=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 en(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 Eg(t){return t._describeKind!=null?t._describeKind:t._deps.length>0?"derived":t._fn!=null?"producer":"state"}function He(t){let e=new WeakSet,n={};for(let[r,o]of Nc(t))n[r]=$a(o,e);return n}function $a(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=>$a(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 Nc(r))o[s]=$a(i,e);return o}return"<unserializable>"}function Nc(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 Te(t,e){let n={factory:t};return e!==void 0&&(n.factoryArgs=e),n}function _g(t){let e={};for(let[n,r]of Object.entries(t.meta))try{e[n]=r.cache}catch{}return e}function Qr(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 Ae&&(i=Eg(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 Ae?t._guard:void 0;if(s){let c={..._g(t)};if(u!=null&&c.access===void 0&&(c.access=zr(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=zr(u)),(r||e.has("lastMutation"))&&t.lastMutation!=null&&(d.lastMutation=t.lastMutation),d}var Ze=be(()=>{"use strict";Qt();Me()});function Xr(t){let e=new WeakSet,n=new WeakSet,r=[t],o=0;for(;r.length>0;){let s=r.pop();o+=Mg(s,e,n,r)}return o}function Mg(t,e,n,r){if(t==null)return 0;switch(typeof t){case"number":return Be.number;case"boolean":return Be.boolean;case"string":return Be.string+t.length*2;case"bigint":return Be.bigint+Og(t);case"symbol":return Be.symbol;case"function":return e.has(t)?0:(e.add(t),Be.function);case"undefined":return 0}let s=t;if(e.has(s))return 0;e.add(s);let i=s[fs];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 Be.date;if(s instanceof RegExp)return Be.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 Be.error+u+c}if(typeof URL<"u"&&s instanceof URL)return Be.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return Be.promise;if(s instanceof WeakMap)return Be.weakmap;if(s instanceof WeakSet)return Be.weakset;if(s instanceof Map){let u=Be.map;for(let[c,l]of s)u+=Be.mapEntry,r.push(c),r.push(l);return u}if(s instanceof Set){let u=Be.set;for(let c of s)u+=Be.setEntry,r.push(c);return u}if(Array.isArray(s)){let u=Be.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=Be.object,d=Object.keys(s);for(let u of d){a+=Be.string+u.length*2;try{r.push(s[u])}catch{}}return a}function Og(t){let e=t<0n?-t:t;if(e===0n)return 0;let n=e.toString(2).length;return Math.ceil(n/32)*8}var Be,fs,ja=be(()=>{"use strict";Be={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},fs=Symbol.for("sizeof")});function Zr(t,e,n,r={}){let o=e in t.nodes,s=n in t.nodes;if(!o)return ms(e,n,"no-such-from");if(!s)return ms(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=Ag(t,e,r);if(u!=null)return u}let d=gs(e,t.nodes[e],0,r);return hs(e,n,[d])}if(i===0)return ms(e,n,"no-path");let a=Ec(t,e,n,i);return a.found?hs(e,n,_c(t,a.pathOrder,r)):ms(e,n,a.truncated?"max-depth-exceeded":"no-path")}function Ec(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 Ag(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=gs(e,r,0,n);a.dep_index=s[0];let d=gs(e,r,1,n);return hs(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=Ec(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:hs(e,e,_c(t,i.pathOrder,n))}function _c(t,e,n){return e.map((r,o)=>{let s=t.nodes[r.path],i=gs(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 gs(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 hs(t,e,n){return Mc(t,e,!0,"ok",n)}function ms(t,e,n){return Mc(t,e,!1,n,[])}function Mc(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(`
|
|
2
|
+
`)}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)}}var Ba=be(()=>{"use strict"});function Va(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(!Va(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)||!Va(t[s],e[s]))return!1;return!0}function Oc(t,e){return`${t}\0${e}`}function lr(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||Va(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(Oc(g.from,g.to),g);let l=new Map;for(let g of e.edges)l.set(Oc(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:W()}}var Ka=be(()=>{"use strict";Re()});var Ie,Lt=be(()=>{"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 Bt,ys=be(()=>{"use strict";Bt=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 Rn(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 Ae?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 bs=be(()=>{"use strict";Me();ja()});function vs(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 Pc(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function Ig(t){if(t!=null)return Pc(t)?t.cache:t}function Sn(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"&&typeof t.down=="function"}function tn(t){return Sn(t)?t.cache??"":t}function Ac(t){return Sn(t)?t.cache??0:t}function Cc(t){return Sn(t)?t.cache??!1:t}function Pg(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(`
|
|
3
|
+
`)}function Lc(t){if(t.version!==kt)throw new Error(`unsupported snapshot version ${String(t.version)} (expected ${kt})`);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 Dg(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 Gg(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ts(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+=Gg(r)}return e+="$",new RegExp(e)}function qa(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 jg(t){return t==="none"?$g:t==="ansi"||t==null?Fg:{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 Ic(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 Bg(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 za(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===ot)throw new Error(`Graph "${e}": ${n} name "${ot}" is reserved for meta companion paths`);Bg(t,e,n)}function Vg(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 Kg(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 Dc(t){for(let e of t._mounts.values())Dc(e);for(let e of t._nodes.values())try{e.down([[ge]],{internal:!0})}catch{}}function ws(t,e){let n=Y.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 Nn(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 x=i.get(v)??[],R=d.get(v),S=a.get(v),_=u.get(v),O=[...x];return R&&O.push(...R),S&&O.push(...S),_&&O.push(..._),O}if(n==="upstream"){let x=i.get(v)??[],R=d.get(v);return R?[...x,...R]:x}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 qg(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 Ge,ot,kt,Fg,$g,Y,Fe=be(()=>{"use strict";jr();Oe();Re();Qt();se();Ze();Me();re();Ka();pe();Lt();ys();ns();Ba();bs();Ge="::",ot="__meta__",kt=1;Fg={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"},$g={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};Y=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===ot)throw new Error(`Graph name "${ot}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...n??{}}),this.config=n?.config??je,this._traceRing=new Bt(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(za(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:W()})),e}setVersioning(e){if(e!=null)for(let n of this._nodes.values())n instanceof Ae&&n._applyVersioning(e)}remove(e){za(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}${ot}${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,Dc(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([[ge]],{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=Ts(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([[E,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([[nt]],{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"})}_registerSelfPruningKeepalive(e){let n,r,o=()=>{n?.(),n=void 0,r?.(),r=void 0};n=e.subscribe(s=>{for(let i of s){let a=i[0];if(a===ge||a===I||a===L){o();return}}}),r=this.addDisposer(o)}_wireSignalToRemove(e,n){if(n==null)return;let r=()=>{try{this.remove(e)}catch{}};if(n.aborted){r();return}n.addEventListener("abort",r,{once:!0}),this.addDisposer(()=>n.removeEventListener("abort",r))}derived(e,n,r,o){let s=n.map(f=>this.resolve(f)),{keepAlive:i,annotation:a,equals:d,initial:u,meta:c,signal:l}=o??{},p=A(s,r,{name:e,...d!=null?{equals:d}:{},...u!==void 0?{initial:u}:{},...c!=null?{meta:c}:{}});return this.add(p,{name:e,...a!=null?{annotation:a}:{}}),i===!0&&this._registerSelfPruningKeepalive(p),this._wireSignalToRemove(e,l),p}effect(e,n,r,o){let s=n.map(c=>this.resolve(c)),{annotation:i,meta:a,signal:d}=o??{},u=he(s,r,{name:e,...a!=null?{meta:a}:{}});return this.add(u,{name:e,...i!=null?{annotation:i}:{}}),this._wireSignalToRemove(e,d),u}produce(e,n,r){if(n===void 0)throw new Error(`Graph "${this.name}".produce("${e}", \u2026): source must not be \`undefined\` \u2014 undefined is the global SENTINEL (spec \xA71.1). Pass \`null\` for nullary DATA, or a Promise/AsyncIterable/Iterable for async sources.`);if(n!==null&&typeof n=="object"&&"cache"in n&&typeof n.subscribe=="function")throw new Error(`Graph "${this.name}".produce("${e}", \u2026): Node sources are rejected. For Node\u2192Node, use graph.derived(name, [path], ([v]) => v, { keepAlive: true }) \u2014 fromAny passes Nodes through verbatim and silently drops opts.`);let{annotation:o,meta:s,equals:i,signal:a}=r??{},d=X(n,{name:e,...s!=null?{meta:s}:{},...i!=null?{equals:i}:{},...a!=null?{signal:a}:{}});return this.add(d,{name:e,...o!=null?{annotation:o}:{}}),this._wireSignalToRemove(e,a),d}batch(e){Z(e)}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 Ae)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 Ae)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(za(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=Vg(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]===ot)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]!==ot)throw new Error(`Graph "${this.name}": expected ${ot} segment in meta path "${r}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${ot} 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=Kg(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 lt)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 lt)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=Ig(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=en(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(([,x])=>x),w=new Set(d.values()),k=0;for(;T.length>0;){let x=T.shift();if(x instanceof Ae)for(let R of x._deps){let S=R.node;if(d.has(S))continue;let _=S.name??"",O=_;if(!O||w.has(O))if(_){let D=2;for(;w.has(`${_}#${D}`);)D++;O=`${_}#${D}`}else for(O=`__internal__/${k++}`;w.has(O);)O=`__internal__/${k++}`;d.set(S,O),w.add(O),u.push([O,S]),T.push(S)}}}let c=[...a,...u],l={};for(let[T,w]of c){if(n!=null&&!w.allowsObserve(n))continue;let k=Qr(w,i,s),x=w instanceof Ae?w._deps.map(O=>d.get(O.node)??O.node.name??""):[],{name:R,...S}=k,_={...S,deps:x};if(!s){let O=this._annotations.get(T);O!=null&&(_.annotation=O)}if(r!=null)if(typeof r=="function"){let O=r;if(!(O.length>=2?O(T,_):O(_)))continue}else{let O=!0;for(let[D,M]of Object.entries(r)){let N=D==="deps_includes"?"depsIncludes":D==="meta_has"?"metaHas":D;if(N==="depsIncludes"){if(!_.deps.includes(String(M))){O=!1;break}continue}if(N==="metaHas"){if(!Object.hasOwn(_.meta??{},String(M))){O=!1;break}continue}if(_[N]!==M){O=!1;break}}if(!O)continue}l[T]=_}let p=new Set(Object.keys(l)),f=[];for(let[T,w]of c)if(w instanceof Ae)for(let k of w._deps){let x=d.get(k.node);x!=null&&f.push([x,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}${Ge}`;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}${Ge}`))}return n}resourceProfile(e){return Rn(this,e)}reachable(e,n,r={}){return r.withDetail===!0?Nn(this.describe(),e,n,{...r,withDetail:!0}):Nn(this.describe(),e,n,r)}explain(e,n,r){return r?.reactive===!0?this._explainReactive(e,n,r):this._explainStatic(tn(e),tn(n),{...r?.maxDepth!==void 0?{maxDepth:Ac(r.maxDepth)}:{},...r?.findCycle!==void 0?{findCycle:Cc(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 Zr(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=C(o,{name:`${r}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,nr(()=>{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]!==E)continue;let k=w[1];if(u(),k.kind==="added"&&k.nodeKind==="mount"){let x=b._mounts.get(k.name);x!=null&&f(x)}}});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;Pc(h)&&(m=h.subscribe(b=>{let v=!1,T=!1;for(let w of b){let k=w[0];k===E?v=!0:(k===I||k===L||k===ge)&&(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=ne(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=lr(o,s),a=C(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]!==E)continue;let m=f[1],h=lr(s,m);s=m,h.events.length!==0&&a.emit(h)}}),l=ne(a);return{node:a,dispose(){u=!0,c(),d.dispose(),a.down([[ge,"describe-diff disposed"]]),l()}}}_explainReactive(e,n,r){let o=0,s=C(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,d=!1,u=()=>{a||d||(a=!0,nr(()=>{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&&Sn(e)&&l.push(e),n!=null&&Sn(n)&&l.push(n),r?.maxDepth!=null&&Sn(r.maxDepth)&&l.push(r.maxDepth),r?.findCycle!=null&&Sn(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=tn(e),v=tn(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=tn(e),v=tn(n),T={...r?.maxDepth!==void 0?{maxDepth:Ac(r.maxDepth)}:{},...r?.findCycle!==void 0?{findCycle:Cc(r.findCycle)}:{}};return this._explainStatic(b,v,T)},{name:r?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:tn(e),to:tn(n)},equals:(b,v)=>b.found===v.found&&b.reason===v.reason&&b.steps.length===v.steps.length&&qg(b.steps,v.steps)})}catch(b){throw c(),i.dispose(),b}let h=ne(m),g=[],y=b=>{let v;return v=b.subscribe(T=>{let w=!1,k=!1;for(let x of T){let R=x[0];R===E?w=!0:(R===I||R===L||R===ge)&&(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=Ts(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}${ot}${Ge}${o}`;r.push([i,s]),this._appendMetaObserveTargets(i,s,r)}}observe(e,n){let r=typeof e=="string",s=Ic(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 lt({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 lt)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 lt)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:W()};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,nr(()=>{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 Bt(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,x=!1,R=!1,S=0,_=new Map,O=new Map,D=new Map,M=J=>{if(!(m!=null&&!m.has(J.type))){l?l.push(J):p.push(J);for(let ce of f)ce(J)}},N=J=>m==null||m.has(J),P=()=>o?{timestamp_ns:W(),in_batch:Tn(),batch_id:S}:{},j=(J,ce)=>{if(!(!u||!(J instanceof Ae)))return J._setInspectorHook(Ce=>{if(Ce.kind==="dep_message")_.set(J,Ce.depIndex);else if(Ce.kind==="run"){let rt=Ce.batchData.map((U,ue)=>U!=null&&U.length>0?U.at(-1):Ce.prevData[ue]);O.set(J,rt);let Xe=Ce.batchData.map(U=>U!=null?[...U]:void 0);D.set(J,Xe),i&&M({type:"derived",path:ce,dep_values:rt,dep_batches:Xe,...P()})}})},G=J=>{let ce=_.get(J),Ce=O.get(J);if(!s||Ce==null)return{};let Xe=(ce!=null&&ce>=0&&J instanceof Ae?J._deps[ce]:void 0)?.node,U=Xe?.v,ue=D.get(J);return{trigger_dep_index:ce,trigger_dep_name:Xe?.name,...U!=null?{trigger_version:{id:U.id,version:U.version}}:{},dep_values:[...Ce],...ue!=null?{dep_batches:ue}:{}}},V=[],$=[];for(let[J,ce]of e){let Ce=j(ce,J);Ce&&V.push(Ce),$.push(ce.subscribe(rt=>{S++;for(let Xe of rt){let U=Xe[0],ue=P();if(U===E){h[J]=Xe[1];let De=ce instanceof Ae?ce.lastMutation?.actor??Ct:Ct;M({type:"data",path:J,data:Xe[1],actor:De,...ue,...G(ce)})}else if(a)U===oe?N("dirty")&&y++:U===H?N("resolved")&&b++:U===nt?N("invalidate")&&v++:U===ze?N("pause")&&T++:U===Ye?N("resume")&&w++:U===ge?N("teardown")&&k++:U===I&&!g.has(J)?N("complete")&&(x=!0):U===L&&N("error")&&(R=!0,g.add(J));else if(U===oe)N("dirty")&&y++,M({type:"dirty",path:J,...ue});else if(U===H)N("resolved")&&b++,M({type:"resolved",path:J,...ue,...G(ce)});else if(U===nt)N("invalidate")&&v++,M({type:"invalidate",path:J,...ue});else if(U===ze)N("pause")&&T++,M({type:"pause",path:J,lockId:Xe[1],...ue});else if(U===Ye)N("resume")&&w++,M({type:"resume",path:J,lockId:Xe[1],...ue});else if(U===I)N("complete")&&!g.has(J)&&(x=!0),M({type:"complete",path:J,...ue});else if(U===L){N("error")&&(R=!0,g.add(J));let De=ce instanceof Ae?ce.lastMutation?.actor??Ct:Ct;M({type:"error",path:J,data:Xe[1],actor:De,...ue})}else U===ge&&(N("teardown")&&k++,M({type:"teardown",path:J,...ue}))}}))}let q=!1,F=()=>{if(!q){q=!0;for(let J of $)J();for(let J of V)J();for(let J of te)J({value:void 0,done:!0});te.length=0}},B=[],te=[];f.add(J=>{let ce=te.shift();ce?ce({value:J,done:!1}):B.push(J)});let de={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 x},get anyErrored(){return R},get completedWithoutErrors(){return x&&!R},onEvent(J){return f.add(J),()=>f.delete(J)},dispose:F,expand(J){F();let ce={...n};return typeof J=="string"?ce.detail=J:Object.assign(ce,J),r(Ic(ce))},[Symbol.asyncIterator](){return{next(){return B.length>0?Promise.resolve({value:B.shift(),done:!1}):q?Promise.resolve({value:void 0,done:!0}):new Promise(J=>te.push(J))},return(){return F(),Promise.resolve({value:void 0,done:!0})}}}};return n.format!=null&&this._attachFormatLogger(de,n),de}_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=jg(n.theme),u=r==="stage-log"?W():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(qa(m.data),120):"",f=m=>{if(r==="stage-log"){let x=(W()-u)/1e9,R=c(m.path).padEnd(9);if(m.type==="data"){let S=p(m);return`[${x.toFixed(3)}s] ${R} \u2190${S?` ${S}`:""}`}if(m.type==="error"){let S=p(m);return`[${x.toFixed(3)}s] ${R} \u2717${S?` ${S}`:""}`}return m.type==="complete"?`[${x.toFixed(3)}s] ${R} \u25A0 complete`:`[${x.toFixed(3)}s] ${R} ${m.type}`}if(r==="json")try{return JSON.stringify(m)}catch{return JSON.stringify({type:m.type,path:m.path,data:"[unserializable]"})}let 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?` ${qa(m.data)}`:b?` ${qa(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(){vs(this._disposers,this.name),this.signal([[ge]],{internal:!0}),vs(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(){vs(this._disposers,this.name),vs(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}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 Gr(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,n){let r=n?.config??je,{codec:o,codecVersion:s,payload:i}=Fr(e,r);return o.decode(i,s)}restore(e,n){if(Lc(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=>Ts(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){Lc(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:Ts(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}${ot}${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=C(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=Pg(c.nodes);if(u.lastSnapshot!=null&&l!==""&&l===u.lastFingerprint)return;let p=u.seq+1,f=ie(),g=u.lastSnapshot==null||p%u.compactEvery===0?{name:this.name,mode:"full",snapshot:c,seq:p,timestamp_ns:f,format_version:kt}:{name:this.name,mode:"diff",diff:ws(u.lastSnapshot,c),seq:p,timestamp_ns:f,format_version:kt};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=Qr(m,en("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===kt&&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===kt&&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:W(),...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 x=w!=null&&k!=null&&w.id===k.id&&w.version===k.version;for(let R of["type","status","sentinel"]){let S=v[R],_=T[R];S!==_&&a.push({path:b,field:R,from:S,to:_})}if(!x)for(let R of["value","meta"]){let S=v[R],_=T[R];Dg(S,_)||a.push({path:b,field:R,from:S,to:_})}}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 En(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]!==E)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 Y){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 Y){let c=`${s}${d}::`;r(u,c)}};return r(t,""),()=>{for(let o of n.values())o.off();n.clear()}}var Gc=be(()=>{"use strict";se();Fe()});function Ha(t){let e=t.describe({detail:"minimal"}),n=Object.keys(e.nodes),r=new Set;for(let s of n){let i=e.nodes[s];if(!i)continue;let a=i.deps??[];for(let d of a)r.add(d)}let o=[];for(let s of n){let i=e.nodes[s];if(!i||s.startsWith("__internal__/"))continue;let d=(i.deps??[]).length,u=r.has(s);if(d===0&&!u){let c=i.type??"unknown";o.push({path:s,kind:c})}}return o.sort((s,i)=>s.path<i.path?-1:s.path>i.path?1:0),{ok:o.length===0,orphans:o,summary(){if(o.length===0)return"validateNoIslands: ok (no islands)";let s=o.slice(0,3).map(i=>`${i.path} (${i.kind})`).join(", ");return`validateNoIslands: ${o.length} island node(s) \u2014 ${s}${o.length>3?", \u2026":""}`}}}var Fc=be(()=>{"use strict"});function Wa(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+=Wa(n.codePointAt(0));return e}function $c(t,e){if(e<=0)return"";let n=0,r="";for(let o of t){let s=Wa(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-=Wa(i.codePointAt(0))}return`${r}\u2026`}r+=o,n+=s}return r}var ks=be(()=>{"use strict"});function Kc(t,e){let n=e.charset==="ascii"?Hg:zg,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)Ug(s,i,n,a);for(let a of t.boxes)Wg(s,i,n,a,e.labelOf(a.id));return s.map(a=>Xg(a.join(""))).join(`
|
|
4
|
+
`)}function Wg(t,e,n,r,o){let{x:s,y:i,w:a,h:d}=r;if(a<2||d<2){d>0&&jc(t,e,s,i,a,o);return}nn(t,e,s,i,n.boxTL);for(let c=s+1;c<s+a-1;c+=1)nn(t,e,c,i,n.boxH);nn(t,e,s+a-1,i,n.boxTR);for(let c=i+1;c<i+d-1;c+=1){nn(t,e,s,c,n.boxV);for(let l=s+1;l<s+a-1;l+=1)qc(t,e,l,c," ","empty");nn(t,e,s+a-1,c,n.boxV)}nn(t,e,s,i+d-1,n.boxBL);for(let c=s+1;c<s+a-1;c+=1)nn(t,e,c,i+d-1,n.boxH);nn(t,e,s+a-1,i+d-1,n.boxBR);let u=i+Math.floor(d/2);jc(t,e,s+1,u,a-2,o)}function nn(t,e,n,r,o){qc(t,e,n,r,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function qc(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 jc(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 Ug(t,e,n,r){let o=r.points;if(o.length<2)return;for(let d=0;d+1<o.length;d+=1)Jg(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=Yg(u,c,l,n);p&&Vc(t,e,c.x,c.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=Qg(i,s,n);a&&Vc(t,e,s.x,s.y,a,"arrow")}function Jg(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)Bc(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)Bc(t,e,s,d,n,"v")}}}function Bc(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 Vc(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 Yg(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 Qg(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 Xg(t){let e=t.length;for(;e>0&&t.charCodeAt(e-1)===32;)e-=1;return t.slice(0,e)}var zg,Hg,zc=be(()=>{"use strict";ks();zg={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"},Hg={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){let e=Zg(t);eh(e),th(e),nh(e),rh(e,t);let n=ih(e,t),{width:r,height:o}=dh(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 Zg(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 eh(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 th(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 nh(t){for(let n=0;n<4;n+=1){for(let r=1;r<t.layers.length;r+=1)Hc(t,t.layers[r],"in"),xs(t.layers[r]);for(let r=t.layers.length-2;r>=0;r-=1)Hc(t,t.layers[r],"out"),xs(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=Wc(t,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],xs(s),Wc(t,s[i],s[i+1],"in")<a?r=!0:([s[i],s[i+1]]=[s[i+1],s[i]],xs(s))}}if(!r)break}}function Hc(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 xs(t){for(let e=0;e<t.length;e+=1)t[e].order=e}function Wc(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 rh(t,e){e.direction==="LR"?oh(t,e):sh(t,e)}function oh(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}Jc(t,e,"y")}function sh(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}Jc(t,e,"x")}function Jc(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 ih(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 R of c)p=Math.max(p,o(R)+s(R));let f=Number.POSITIVE_INFINITY;for(let R of l)f=Math.min(f,o(R));let m=Number.isFinite(f)?f-1:p,h=Math.max(1,m-p+1),g=[];for(let R of c)for(let S of R.out)g.push(S);g.sort((R,S)=>{let _=i(t.nodes.get(R.fromId)),O=i(t.nodes.get(S.fromId));if(_!==O)return _-O;let D=i(t.nodes.get(R.toId)),M=i(t.nodes.get(S.toId));return D-M});let y=[],b=new Map;for(let R of g){let S=i(t.nodes.get(R.fromId)),_=i(t.nodes.get(R.toId)),O=Math.min(S,_),D=Math.max(S,_),M=-1;for(let N=0;N<y.length;N+=1){let P=y[N],j=!0;for(let G of P)if(G.lo<=D&&O<=G.hi){j=!1;break}if(j){P.push({lo:O,hi:D}),M=N;break}}M<0&&(y.push([{lo:O,hi:D}]),M=y.length-1),b.set(R,M)}let v=y.length,T=h>=Math.max(3,v+2),w=T?p+1:p,k=T?m-1:m,x=Math.max(1,k-w+1);for(let R of g){let S=b.get(R),_;if(v<=1)_=w+Math.floor(x/2);else{let O=(x-1)/(v-1);_=w+Math.floor(S*O)}a.set(R,Math.max(p,Math.min(m,_)))}}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&&Rs(c,r,y,v),v!==T&&(Rs(c,r,g,v),Rs(c,r,g,T)),Rs(c,r,b,T)}let l=u[0];d.push({from:l.chainFrom,to:l.chainTo,points:ah(c)})}return d}function Rs(t,e,n,r){t.push(e?{x:n,y:r}:{x:r,y:n})}function ah(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 dh(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 Yc=be(()=>{"use strict"});function Ua(t,e){let n=fh(e?.direction),r=Math.max(3,e?.maxLabelWidth??uh),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=$c(p,r);d.set(p,f),u.set(p,pr(f)+4)}let c=Uc({nodes:s,edges:a,widthCells:p=>u.get(p)??3,heightCells:()=>ph,layerGap:ch,nodeGap:lh,direction:n}),l=Kc(c,{charset:o,labelOf:p=>d.get(p)??p});return e?.logger?.(l),l}function fh(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)}`)}var uh,ch,lh,ph,Qc=be(()=>{"use strict";zc();ks();Yc();uh=24,ch=4,lh=1,ph=3});function Ss(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(Ss);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=Ss(e[o]);return r}function Xc(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Zc(t){return t.replaceAll("\\","\\\\").replaceAll('"','\\"')}function el(t){return t==="TD"?"down":t==="BT"?"up":t==="RL"?"left":"right"}function Ns(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 Es(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 tl(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]"}}var eo=be(()=>{"use strict"});function Ja(t,e){let n=Es(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: ${el(n)}`];for(let i of r){let a=o.get(i);s.push(`${a}: "${Zc(i)}"`)}for(let[i,a]of Ns(t)){let d=o.get(i),u=o.get(a);!d||!u||s.push(`${d} -> ${u}`)}return s.join(`
|
|
5
|
+
`)}var nl=be(()=>{"use strict";eo()});function Ya(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(Ss(i),null,e?.indent??2);return e?.logger?.(a),a}var rl=be(()=>{"use strict";eo()});function rn(t,e){let n=Es(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}["${Xc(i)}"]`)}for(let[i,a]of Ns(t)){let d=o.get(i),u=o.get(a);!d||!u||s.push(` ${d} --> ${u}`)}return s.join(`
|
|
6
|
+
`)}var Qa=be(()=>{"use strict";eo()});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 Xa(t,e){let n=rn(t,e);return ol(n,e)}var sl=be(()=>{"use strict";Qa()});function Za(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}): ${tl(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(`
|
|
7
|
+
`);return e?.logger?.(s),s}var il=be(()=>{"use strict";eo()});var ed=be(()=>{"use strict";Qc();nl();rl();Qa();sl();il()});function td(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=mh[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 mh,al=be(()=>{"use strict";ed();mh={json:t=>Ya(t),pretty:t=>Za(t),mermaid:t=>rn(t),"mermaid-url":t=>Xa(t),d2:t=>Ja(t),ascii:t=>Ua(t)}});var nd={};Ee(nd,{ENVELOPE_VERSION:()=>Zn,GRAPH_META_SEGMENT:()=>ot,Graph:()=>Y,JsonCodec:()=>ts,SIZEOF_OVERHEAD:()=>Be,SIZEOF_SYMBOL:()=>fs,SNAPSHOT_VERSION:()=>kt,createDagCborCodec:()=>xa,createDagCborZstdCodec:()=>Ra,decodeEnvelope:()=>Fr,diffForWAL:()=>ws,encodeEnvelope:()=>Gr,explainPath:()=>Zr,graphProfile:()=>Rn,reachable:()=>Nn,registerBuiltinCodecs:()=>$r,replayWAL:()=>Sa,sizeof:()=>Xr,validateGraphObservability:()=>td,validateNoIslands:()=>Ha,watchTopologyTree:()=>En});var bt=be(()=>{"use strict";ja();ns();Ba();Fe();bs();Gc();Fc();al()});var dl={};Ee(dl,{NS_PER_MS:()=>et,NS_PER_SEC:()=>ct,constant:()=>_s,decorrelatedJitter:()=>Cs,exponential:()=>Os,fibonacci:()=>As,linear:()=>Ms,resolveBackoffPreset:()=>Mn,withMaxAttempts:()=>rd});function _n(t){return t<0?0:t}function gh(t,e){return e==="none"?t:e==="full"?Math.random()*t:t/2+Math.random()*(t/2)}function hh(t,e){return t+Math.random()*(e-t)}function _s(t){let e=_n(t);return()=>e}function Ms(t,e){let n=_n(t),r=e===void 0?n:_n(e);return o=>n+r*Math.max(0,o)}function Os(t){let e=_n(t?.baseNs??1e8),n=t?.factor!==void 0&&t.factor<1?1:t?.factor??2,r=_n(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 gh(i,o)}}function As(t=100*1e6,e=30*1e9){let n=_n(t),r=_n(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 Cs(t=100*1e6,e=30*1e9){return(n,r,o)=>{let i=Math.min(e,(o??t)*3);return hh(t,i)}}function rd(t,e){return(n,r,o)=>n>=e?null:t(n,r,o)}function Mn(t){if(t==="constant")return _s(1*1e9);if(t==="linear")return Ms(1*1e9);if(t==="exponential")return Os();if(t==="fibonacci")return As();if(t==="decorrelatedJitter")return Cs();throw new Error(`Unknown backoff preset: "${String(t)}". Use one of: constant, linear, exponential, fibonacci, decorrelatedJitter`)}var et,ct,to=be(()=>{"use strict";et=1e6,ct=1e9});function ye(t){return{describeKind:"derived",...t}}function ul(t){return{describeKind:"derived",partial:!0,...t}}function no(t,e,n){return Q([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[H]]);return}for(let i of s)o.emit(e(i))},{...ye(n),meta:{...Te("map"),...n?.meta??{}}})}function xt(t,e,n){return Q([t],(r,o)=>{let s=r[0];if(s==null||s.length===0){o.down([[H]]);return}let i=!1;for(let a of s)e(a)&&(o.emit(a),i=!0);i||o.down([[H]])},{...ye(n),meta:{...Te("filter"),...n?.meta??{}}})}function cl(t,e,n,r){return Q([t],(o,s,i)=>{"acc"in i.store||(i.store.acc=n);let a=o[0];if(a==null||a.length===0){s.down([[H]]);return}for(let d of a)i.store.acc=e(i.store.acc,d),s.emit(i.store.acc)},{...ye(r),initial:n,resetOnTeardown:!0,meta:{...Te("scan",{initial:n}),...r?.meta??{}}})}function ll(t,e,n,r){return Q([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([[H]]);return}for(let d of a)i.store.acc=e(i.store.acc,d)},{...ye(r),completeWhenDepsComplete:!1,meta:{...Te("reduce",{initial:n}),...r?.meta??{}}})}function ro(t,e,n){return e<=0?Q([t],(r,o,s)=>{s.store.completed||(s.store.completed=!0,o.down([[I]]))},{...ye(n),completeWhenDepsComplete:!1,meta:{...Te("take",{count:e}),...n?.meta??{}}}):Q([t],(r,o,s)=>{if("taken"in s.store||(s.store.taken=0),s.store.done){o.down([[H]]);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([[H]]);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}},{...ye(n),completeWhenDepsComplete:!1,meta:{...Te("take",{count:e}),...n?.meta??{}}})}function od(t,e,n){return Q([t],(r,o,s)=>{"skipped"in s.store||(s.store.skipped=0);let i=r[0];if(i==null||i.length===0){o.down([[H]]);return}let a=!1;for(let d of i)s.store.skipped++,s.store.skipped<=e||(o.emit(d),a=!0);a||o.down([[H]])},ye(n))}function pl(t,e,n){return Q([t],(r,o,s)=>{if(s.store.done){o.down([[H]]);return}let i=r[0];if(i==null||i.length===0){o.down([[H]]);return}for(let a of i){if(!e(a)){s.store.done=!0,o.down([[I]]);return}o.emit(a)}},{...ye(n),completeWhenDepsComplete:!1})}function fl(t,e,n){let r=n?.predicate??(i=>i[0]===E),{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]===E?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()}},ye(s))}function Ls(t,e){return ro(t,1,e)}function ml(t,e){let{defaultValue:n,...r}=e??{},o=e!=null&&Object.hasOwn(e,"defaultValue");return Q([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([[H]]);return}a.store.latest=d.at(-1),a.store.has=!0},{...ye(r),completeWhenDepsComplete:!1})}function gl(t,e,n){return ro(xt(t,e,n),1,n)}function hl(t,e,n){return ro(od(t,e,n),1,n)}function yl(t,e,n){if(typeof e=="function")return Q([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[H]]);return}for(let a of i)e(a),s.emit(a)},{...ye(n),meta:{...Te("tap"),...n?.meta??{}}});let r=e;return Q([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([[H]]);return}for(let d of a)r.data?.(d),s.emit(d)},{...ye(n),completeWhenDepsComplete:!1,meta:{...Te("tap"),...n?.meta??{}}})}function oo(t,e,n){let r=n?.where??(s=>s!=null),o=!1;return Q([t],(s,i)=>{let a=s[0];if(a==null||a.length===0){i.down([[H]]);return}for(let d of a)!o&&r(d)&&(o=!0,e(d)),i.emit(d)},ye(n))}function vl(t,e=Object.is,n){return Q([t],(r,o,s)=>{let i=r[0];if(i==null||i.length===0){o.down([[H]]);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([[H]])},{...ye(n),meta:{...Te("distinctUntilChanged"),...n?.meta??{}}})}function Tl(t,e){return Q([t],(n,r,o)=>{let s=n[0];if(s==null||s.length===0){r.down([[H]]);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([[H]])},ye(e))}function sd(...t){let e=[...t];return A(e,n=>n,{...ye(),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 On(t,e,n){return Q([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([[H]]);return}for(let u of i)o.emit([u,d])}else o.down([[H]])},{...ul(n),meta:{...Te("withLatestFrom"),...n?.meta??{}}})}function It(...t){return t.length===0?z(e=>{e.down([[I]])},{...ye(),meta:{...Te("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?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()}},{...ye(),meta:{...Te("merge")}})}function wl(...t){let e=t.length;return e===0?z(n=>{n.emit([]),n.down([[I]])},ye()):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]===E?(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()}},ye())}function kl(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]===E?s.push(u[1]):u[0]===L&&r.down([u]):u[0]===E?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]===E)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?.()}},ye(n))}function xl(...t){return t.length===0?z(e=>{e.down([[I]])},ye()):t.length===1?Q([t[0]],(e,n)=>{let r=e[0];if(r==null||r.length===0){n.down([[H]]);return}for(let o of r)n.emit(o)},ye()):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]===E?(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()}},ye())}function Is(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]!==ht&&(u[0]===E?e.emit(u[1]):u[0]===I?a=!0:u[0]===L?(d=!0,e.down([u])):(u[0]===oe||u[0]===H)&&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 Q([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=Is(X(e(u[u.length-1])),a,()=>{s(),o&&a.down([[I]])}),{deactivate:()=>{s(),o=!1}}},{...ye(n),completeWhenDepsComplete:!1,meta:{...Te("switchMap"),...n?.meta??{}}})}function Rl(t,e,n){let r,o=!1;function s(){r?.(),r=void 0}return Q([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=Is(X(e(u[0])),a,()=>{s(),o&&a.down([[I]])}):a.down([[H]]),{deactivate:()=>{s(),o=!1}}},{...ye(n),completeWhenDepsComplete:!1})}function Sl(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=Is(X(e(p)),d,()=>{u(),c()})}function l(p){r&&r>0&&s.length>=r&&s.shift(),s.push(p),c()}return Q([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}}}},{...ye(o),completeWhenDepsComplete:!1})}function id(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=Is(X(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 Q([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}}}},{...ye(o),completeWhenDepsComplete:!1})}function El(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]===E){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()}},ye(n))}function ad(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]===E?(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()}},{...ye(n),meta:{...Te("debounce",{ms:e}),...n?.meta??{}}})}function dd(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]===E){let b=y[1],v=W();if(i&&v-l>=d)l=v,u.emit(b),m(),a&&(c=setTimeout(()=>{c=void 0,f&&(l=W(),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=W(),u.emit(p),f=!1)},Math.max(0,e-T))}}else(y[0]===I||y[0]===L)&&(m(),u.down([y]))});return()=>{h(),m()}},{...ye(s),meta:{...Te("throttle",{ms:e,leading:i,trailing:a}),...s.meta??{}}})}function _l(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]===E?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]===E?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()}},ye(n))}function Ml(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]===E?(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()}},ye(n))}function Ol(t,e,n){return z(r=>{let o=[],s=t.subscribe(a=>{for(let d of a)d[0]===E?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]===E?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}},ye(n))}function Al(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]===E?(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}},ye(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}),ye());s=0,r.emit(d)}let a=t.subscribe(d=>{for(let u of d)u[0]===E?(o||i(),o?.([[E,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}},ye(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]===E?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}},{...ye(n),meta:{...Te("bufferTime",{ms:e}),...n?.meta??{}}})}function Il(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}),ye());r.emit(u)}i();let a=setInterval(()=>{s(),i()},e),d=t.subscribe(u=>{for(let c of u)c[0]===E?o?.([[E,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()}},ye(n))}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}),ye());r.emit(u)}let a=t.subscribe(u=>{for(let c of u)c[0]===E?(o||i(),o?.([[E,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]===E&&(s(),i())});return()=>{a(),d(),s()}},ye(n))}function Dl(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)},ye(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]===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?.()}},ye(n))}function Fl(t,e){return Q([t],(n,r)=>{let o=n[0];if(o==null||o.length===0){r.down([[H]]);return}for(let s of o)r.emit(s)},ye(e))}function so(t,e,n){return z(r=>{let o=t.subscribe(s=>{for(let i of s)if(i[0]===E)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()}},ye(n))}function $l(t,e,n){return Q([t,e],(r,o,s)=>{let i=r[1];if(!(i!=null&&i.length>0?i.at(-1):s.prevData[1])){o.down([[H]]);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([[H]])},ul(n))}var bl,Nl,jl,Bl,Vl,Kl,ql=be(()=>{"use strict";Re();se();Ze();Me();re();pe();bl=oo;Nl=id;jl=sd,Bl=ad,Vl=dd,Kl=so});var We=be(()=>{"use strict";ql()});function io(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&"down"in t}function zl(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")}function Hl(t,e={}){let n=new ao(t,e);return n.tagFactory("resilientPipeline",He(e)),n}var ao,Wl=be(()=>{"use strict";Ze();bt();ut();We();ud();ao=class extends Y{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(io(n.rateLimit)){let d=r,u=n.rateLimit;r=ke(u,c=>{let l={...c,maxBuffer:c.maxBuffer??1/0,meta:we("resilient","rate-limit")};return Cn(d,l).node}),this.add(r,{name:"rateLimited"})}else{let d={...n.rateLimit,maxBuffer:n.rateLimit.maxBuffer??1/0,meta:we("resilient","rate-limit")},u=Cn(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(io(n.budget)){let d=r,u=n.budget;r=ke(u,c=>c.length>0?Zt(d,c,{meta:we("resilient","budget")}):d),this.add(r,{name:"budgetGated"})}else n.budget.length>0&&(r=Zt(r,n.budget,{meta:we("resilient","budget")}),this.add(r,{name:"budgetGated"}));if(n.breaker!=null)if(io(n.breaker)){let d=r,u=n.breaker,c=n.breakerOnOpen??"skip";r=ke(u,l=>{let p=St(l);return An(p,{onOpen:c,meta:we("resilient","breaker")})(d).node}),this.add(r,{name:"breakerWrapped"})}else{let d=St(n.breaker),u=n.breakerOnOpen??"skip",c=An(d,{onOpen:u,meta:we("resilient","breaker")})(r);r=c.node,i=c.breakerState,this.add(r,{name:"breakerWrapped"}),this.add(i,{name:"breakerState"})}if(n.timeoutMs!=null)if(io(n.timeoutMs)){let d=r,u=n.timeoutMs;r=ke(u,c=>(zl(c),Ln(d,c*1e6,{meta:we("resilient","timeout")}))),this.add(r,{name:"timeoutWrapped"})}else zl(n.timeoutMs),r=Ln(r,n.timeoutMs*1e6,{meta:we("resilient","timeout")}),this.add(r,{name:"timeoutWrapped"});if(n.retry!=null)if(io(n.retry)){let d=r,u=n.retry;r=ke(u,c=>Rt(d,{...c,meta:we("resilient","retry")})),this.add(r,{name:"retryWrapped"})}else r=Rt(r,{...n.retry,meta:we("resilient","retry")}),this.add(r,{name:"retryWrapped"});n.fallback!==void 0&&(r=fr(r,n.fallback,{meta:we("resilient","fallback")}),this.add(r,{name:"fallbackWrapped"}));let a=on(r,{initialStatus:n.initialStatus??"pending",meta:we("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 Dn(t){return{describeKind:"derived",...t}}function yh(t){return t<0?0:t}function cd(t){return t[1]}function bh(t){if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("backoff strategy must return a finite number");return t<0?0:t}function Ds(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"?Mn(n):n;return{maxRetries:r,strategy:o}}function Jl(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 Yl(t,e,n){let r=0,o=!1,s=null,i,a=new Ie;function d(){i?.(),i=void 0}function u(l){if(o)return;let p=t();if(r>=p.maxRetries){d(),n.down([[L,l]]);return}let f=p.strategy===null?0:p.strategy(r,l,s);if(f==null){d(),n.down([[L,l]]);return}let m;try{m=bh(f)}catch{d(),n.down([[L,l]]);return}s=m,r+=1,d();let h=m>0?m/1e6:1;a.start(h,()=>{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===oe)n.down([[oe]]);else if(m===E)r=0,s=null,n.emit(f[1]);else if(m===H)n.down([[H]]);else if(m===I)o=!0,d(),n.down([[I]]);else if(m===L){u(cd(f));return}else n.down([f])}})}return c(),()=>{o=!0,a.cancel(),d()}}function Rt(t,e){return typeof t=="function"?Th(t,e):vh(t,e)}function vh(t,e){t._resubscribable===!1&&!Ul.has(t)&&(Ul.add(t),console.warn("retry(source, opts): source-mode requires `resubscribable: true` on the upstream node. Retries will be silent no-ops after the first ERROR. Either pass `resubscribable: true` to the source factory, OR use factory-mode retry `retry(() => buildSource(), opts)` so each attempt builds a fresh node."));let r=Nt(e)?void 0:e;return Nt(e)||Ds(r),z(o=>{let s=uo(e),a=Yl(()=>Ds(s.current()),()=>t,o);return()=>{a(),s.unsub()}},{...Dn(),initial:t.cache,meta:{...r?.meta??{},...Te("retry",Nt(e)?{reactiveOpts:!0}:Jl(r))}})}function Th(t,e){let n=Nt(e)?void 0:e;return Nt(e)||Ds(n),z(r=>{let o=uo(e),i=Yl(()=>Ds(o.current()),t,r);return()=>{i(),o.unsub()}},{...Dn(),initial:n?.initial,meta:{...n?.meta??{},...Te("retry",Nt(e)?{reactiveOpts:!0}:Jl(n))}})}function St(t){let e=5,n=30*1e9,r=null,o=1,s=W;function i(y){e=Math.max(1,y?.failureThreshold??5),n=yh(y?.cooldownNs??30*1e9),r=y?.cooldown??null,o=Math.max(1,y?.halfOpenMax??1),s=y?.now??W}let a="closed",d=0,u=0,c=0,l=n,p=0,f=uo(t,y=>{i(y),a="closed",d=0,u=0,p=0,l=n});i(f.current()),l=n;function m(){if(!r)return n;let y=r(u);return y!==null?y:n}function h(){a="open",l=m(),c=s(),p=0}return{canExecute(){return a==="closed"?!0:a==="open"?s()-c>=l?(a="half-open",p=1,!0):!1:p<o?(p++,!0):!1},recordSuccess(){a==="half-open"?(a="closed",d=0,u=0):a==="closed"&&(d=0)},recordFailure(y){if(a==="half-open"){u++,h();return}a==="closed"&&(d++,d>=e&&h())},get state(){return a},get failureCount(){return d},reset(){a="closed",d=0,u=0,p=0},dispose(){f.unsub()}}}function An(t,e){let n=e?.onOpen??"skip",r=e?.meta;return o=>{let s=Q([],(i,a)=>{function d(){s.meta.breakerState.down([[E,t.state]])}let u=o.subscribe(c=>{for(let l of c){let p=l[0];p===oe?a.down([[oe]]):p===E?t.canExecute()?(d(),a.emit(l[1])):(d(),n==="error"?a.down([[L,new Et]]):a.down([[H]])):p===H?a.down([[H]]):p===I?(t.recordSuccess(),d(),a.down([[I]])):p===L?(t.recordFailure(cd(l)),d(),a.down([l])):a.down([l])}});return d(),u},{...Dn(),meta:{...r??{},breakerState:t.state,...Te("withBreaker",{onOpen:n})},completeWhenDepsComplete:!1,initial:o.cache});return{node:s,breakerState:s.meta.breakerState}}}function Vt(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??W,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 wh(t,e){return t.droppedCount===e.droppedCount&&t.pendingCount===e.pendingCount&&t.paused===e.paused}function Cn(t,e){let n=Nt(e);if(!n){let a=e;if(a.maxEvents<=0)throw new RangeError("maxEvents must be > 0");if(a.windowNs<=0)throw new RangeError("windowNs must be > 0");if(a.maxBuffer===void 0)throw new RangeError("rateLimiter requires explicit maxBuffer (use Infinity to opt in to unbounded)");if(!(a.maxBuffer===1/0)&&(!Number.isInteger(a.maxBuffer)||a.maxBuffer<1))throw new RangeError("maxBuffer must be a positive integer (or Infinity for unbounded)")}let r=n?e.cache:e,o=r?.maxBuffer,s=o===1/0,i=z(a=>{let d=r?.maxEvents??1,u=r?.windowNs??1e9,c=o??1,l=r?.onOverflow??"drop-newest",p=d*1e9/u,f=1e9/p,m=Vt(d,p),h=s?xh():kh(Math.max(1,c)),g=new Ie,y=!1,b=0,v=i.meta.droppedCount,T=i.meta.rateLimitState,w=Ps;function k(){v.emit(b);let D={droppedCount:b,pendingCount:h.size,paused:h.size>0};wh(w,D)||(w=D,T.emit(D))}w=Ps,v.emit(0),T.emit(Ps);let x=uo(e,D=>{if(y||D==null||!(D.maxEvents>0)||!(D.windowNs>0))return;let M=D.maxBuffer;if(M===void 0)return;let N=M===1/0;if(N===s&&!(!N&&(!Number.isInteger(M)||M<1))){if(!N&&M>c){console.warn(`rateLimiter: reactive maxBuffer grow (${c} \u2192 ${M}) rejected. The pending ring buffer is allocated at construction; reactive maxBuffer is monotonically non-increasing. Recreate the rateLimiter with the larger cap if growth is required.`);return}if(d=D.maxEvents,u=D.windowNs,c=M,l=D.onOverflow??"drop-newest",p=d*1e9/u,f=1e9/p,m=Vt(d,p),!N)for(;h.size>c;)h.shift(),b+=1;k()}});function R(){for(;h.size>0;)if(m.tryConsume(1))a.emit(h.shift()),k();else{g.start(Math.max(1,f/1e6),R);return}}function S(){b+=1,k()}function _(){for(y=!0,g.cancel();h.size>0;)h.shift();b=0}let O=t.subscribe(D=>{for(let M of D){if(y)return;let N=M[0];if(N===oe)a.down([[oe]]);else if(N===E){if(!s&&h.size>=c)if(l==="drop-newest")S();else if(l==="drop-oldest")h.shift(),h.push(M[1]),S();else{S(),_(),a.down([[L,new In(c)]]);return}else h.push(M[1]),k();R()}else if(N===H)a.down([[H]]);else if(N===I)_(),a.down([[I]]);else if(N===L)_(),a.down([M]);else if(N===ge){_(),a.down([M]);return}else a.down([M])}});return()=>{y=!0,g.cancel(),O(),x.unsub()}},{...Dn(),initial:t.cache,meta:{...n?{}:e.meta??{},droppedCount:0,rateLimitState:Ps,...Te("rateLimiter",n?{reactiveOpts:!0}:e)}});return{node:i,droppedCount:i.meta.droppedCount,rateLimitState:i.meta.rateLimitState}}function kh(t){let e=new Bt(t);return{push:n=>e.push(n),shift:()=>e.shift(),get size(){return e.size}}}function xh(){let t=[];return{push:e=>{t.push(e)},shift:()=>t.shift(),get size(){return t.length}}}function on(t,e){let n=e?.initialStatus??"pending",r=e?.meta,o=Q([],(s,i)=>{let a=n;return o.meta.status.down([[E,n]]),o.meta.error.down([[E,null]]),t.subscribe(u=>{for(let c of u){let l=c[0];if(l===oe)i.down([[oe]]);else if(l===E)a==="errored"?Z(()=>{o.meta.error.down([[E,null]]),o.meta.status.down([[E,"running"]])}):o.meta.status.down([[E,"running"]]),a="running",i.emit(c[1]);else if(l===H)i.down([[H]]);else if(l===I)o.meta.status.down([[E,"completed"]]),a="completed",i.down([[I]]);else if(l===L){let p=cd(c);Z(()=>{o.meta.error.down([[E,p]]),o.meta.status.down([[E,"errored"]])}),a="errored",i.down([c])}else i.down([c])}})},{...Dn(),meta:{...r??{},status:n,error:null,...Te("withStatus",{initialStatus:n})},completeWhenDepsComplete:!1,resubscribable:!0,initial:t.cache});return{node:o,status:o.meta.status,error:o.meta.error}}function Nt(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function uo(t,e){if(!Nt(t))return{current:()=>t,unsub:()=>{}};let n=t,r=n.cache,o=n.subscribe(s=>{for(let i of s)i[0]===E&&(r=i[1],e&&e(r))});return{current:()=>r,unsub:o}}function Rh(t){return t!=null&&typeof t.then=="function"}function Sh(t){return t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function"}function fr(t,e,n){let r=n?.meta;return z(o=>{let s,i;function a(){i?.(),i=void 0,Nt(e)||Rh(e)||Sh(e)?s=X(e).subscribe(u=>{o.down(u);for(let c of u){let l=c[0];if(l===I||l===L||l===ge){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===oe)o.down([[oe]]);else if(c===E)o.emit(u[1]);else if(c===H)o.down([[H]]);else if(c===I)o.down([[I]]);else if(c===L){a();return}else if(c===ge){s?.(),o.down([u]);return}else o.down([u])}}),()=>{i?.(),s?.()}},{...Dn(),initial:t.cache,meta:{...r??{},...Te("fallback")}})}function Ln(t,e,n){if(!Nt(e)&&e<=0)throw new RangeError("timeoutNs must be > 0");let r=n?.meta,o=Nt(e)?{timeoutNs:"Node<number>"}:{timeoutNs:e};return z(s=>{let i=!1,a=new Ie,d=uo(e),u=()=>{let p=d.current();return typeof p=="number"&&p>0?p:0};function c(){let p=u();if(p<=0)return;let f=p/1e6;a.start(f,()=>{i||(i=!0,l(),s.down([[L,new Pn(p)]]))})}let l=t.subscribe(p=>{for(let f of p){if(i)return;let m=f[0];if(m===oe)s.down([[oe]]);else if(m===E)c(),s.emit(f[1]);else if(m===H)s.down([[H]]);else if(m===I){a.cancel(),i=!0,s.down([[I]]);return}else if(m===L){a.cancel(),i=!0,s.down([f]);return}else if(m===ge){a.cancel(),i=!0,s.down([f]);return}else s.down([f])}});return c(),()=>{i=!0,a.cancel(),l(),d.unsub()}},{...Dn(),initial:t.cache,meta:{...r??{},...Te("timeout",o)}})}var Ul,Et,In,Ps,Pn,ud=be(()=>{"use strict";Sc();Wl();Oe();Re();se();Ze();Me();re();to();pe();Lt();ys();Ul=new WeakSet;Et=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};In=class extends Error{name="RateLimiterOverflowError";constructor(e){super(`rateLimiter buffer overflow (maxBuffer=${e})`)}};Ps=Object.freeze({droppedCount:0,pendingCount:0,paused:!1});Pn=class extends Error{name="TimeoutError";constructor(e){super(`Timed out after ${e/1e6}ms`)}}});var Ql={};Ee(Ql,{CircuitOpenError:()=>Et,RateLimiterOverflowError:()=>In,ResilientPipelineGraph:()=>ao,TimeoutError:()=>Pn,budgetGate:()=>Zt,circuitBreaker:()=>St,fallback:()=>fr,rateLimiter:()=>Cn,resilientPipeline:()=>Hl,retry:()=>Rt,timeout:()=>Ln,tokenBucket:()=>Vt,withBreaker:()=>An,withStatus:()=>on});var sn=be(()=>{"use strict";ud()});function mt(t){return{describeKind:"producer",...t}}function pd(t){return/[\\^$+?.()|[\]{}]/.test(t)?`\\${t}`:t}function Zl(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+=pd(r)}return e+="$",new RegExp(e)}function ep(t,e){for(let n of e)if(n.test(t))return!0;return!1}function Nh(t,e){let n=Q([t],(o,s)=>{let i=o[0];if(i==null||i.length===0){s.down([[H]]);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 st(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},mt(o))}function tp(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)},mt(n))}function Fs(t,e){let n=ls(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&&ps(n,p)&&(u=f,d.emit(a?p:ie()))};c();let l=setInterval(c,i);return()=>clearInterval(l)},{...mt(s),name:s.name??`cron:${t}`})}function np(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)},mt(i))}function $s(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}},mt(e))}function Eh(t){return t!=null&&typeof t.then=="function"}function mr(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)}},mt(r))}function co(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(()=>{})}},mt(r))}function _h(t){return t!=null&&typeof t=="object"&&"cache"in t&&typeof t.subscribe=="function"}function X(t,e){if(_h(t))return t;if(Eh(t))return mr(t,e);if(t!=null){let n=t;if(typeof n[Symbol.asyncIterator]=="function")return co(t,e);if(typeof n[Symbol.iterator]=="function")return $s(t,e)}return fd(t)}function fd(...t){return $s(t,void 0)}function rp(t){return z(e=>{e.down([[I]])},mt(t))}function op(t){return z(()=>{},mt(t))}function sp(t,e){return z(n=>{n.down([[L,t]])},mt(e))}function ip(t,e){let{signal:n,...r}=e??{},o=mt(r),s=o.resubscribable===void 0?{...o,resubscribable:!0}:o;return z(i=>{let a,d=!1;try{let u=t();a=X(u,e).subscribe(l=>{if(!d)for(let p of l){let f=p[0];if(f!==ht)if(f===E)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 an(t,e,n){return Q([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 ap(t,e){return Q([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([[H]])},{describeKind:"derived",completeWhenDepsComplete:!1,...e})}function dp(t,e){return z(n=>t.subscribe(r=>{n.down(r)}),{...mt(e),initial:t.cache})}function js(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]===E&&(r.push(a[1]),r.length>e&&r.shift());s.down(i)}),{...mt(n),initial:t.cache});return Nh(o,s=>{for(let i of r)s([[E,i]])})}function up(t,e){return js(t,1,e)}function it(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]===E){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 Gs(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]===E)){if(c[0]===E){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 Bs(t,e){let n=e?.predicate??(s=>s!=null),r=e?.skipCurrent;if(e?.timeoutMs==null||e.timeoutMs<=0)return await Gs(t,n,{skipCurrent:r});if(ld===void 0){let[s,i]=await Promise.all([Promise.resolve().then(()=>(sn(),Ql)),Promise.resolve().then(()=>(to(),dl))]);ld=s.timeout,Xl=i.NS_PER_MS}let o=ld(t,e.timeoutMs*Xl);return await Gs(o,n,{skipCurrent:r})}function Vs(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]===E&&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 ne(t){return t.subscribe(()=>{})}function lp(t){let e=C(0);return{node:e,increment(){let n=e.cache??0;return n>=t?!1:(e.down([[oe],[E,n+1]]),!0)},get(){return e.cache??0},atCap(){return(e.cache??0)>=t}}}var ld,Xl,cp,pp=be(()=>{"use strict";Re();se();Me();re();Ga();cp=js});var pe=be(()=>{"use strict";pp()});var nT={};Ee(nT,{COMPLETE:()=>I,COMPLETE_MSG:()=>Zo,COMPLETE_ONLY_BATCH:()=>Dr,CircuitOpenError:()=>Et,ContentAddressedMissError:()=>wo,DATA:()=>E,DEFAULT_ACTOR:()=>Ct,DEFAULT_AUDIT_GUARD:()=>vd,DIRTY:()=>oe,DIRTY_MSG:()=>Gt,DIRTY_ONLY_BATCH:()=>Qn,ENVELOPE_VERSION:()=>Zn,ERROR:()=>L,GRAPH_META_SEGMENT:()=>ot,Graph:()=>Y,GraphReFlyConfig:()=>wn,GuardDenied:()=>lt,INVALIDATE:()=>nt,INVALIDATE_MSG:()=>Xo,INVALIDATE_ONLY_BATCH:()=>Pr,JsonCodec:()=>ts,NS_PER_MS:()=>et,NS_PER_SEC:()=>ct,NativeIndexBackend:()=>Ro,NativeListBackend:()=>So,NativeLogBackend:()=>fo,NativeMapBackend:()=>vo,NativePubSubBackend:()=>xo,NodeImpl:()=>Ae,PAUSE:()=>ze,RESOLVED:()=>H,RESOLVED_MSG:()=>Jn,RESOLVED_ONLY_BATCH:()=>Ir,RESUME:()=>Ye,RateLimiterOverflowError:()=>In,ResettableTimer:()=>Ie,SIZEOF_OVERHEAD:()=>Be,SIZEOF_SYMBOL:()=>fs,SNAPSHOT_VERSION:()=>kt,SNAPSHOT_WIRE_VERSION:()=>Yo,START:()=>ht,START_MSG:()=>Yn,SurfaceError:()=>_e,TEARDOWN:()=>ge,TEARDOWN_MSG:()=>es,TEARDOWN_ONLY_BATCH:()=>Xn,TimeoutError:()=>Pn,accessHintForGuard:()=>zr,advanceVersion:()=>Hr,ai:()=>zi,appendAudit:()=>hr,appendLogStorage:()=>Pd,asSurfaceError:()=>pa,audit:()=>Ml,autoTrackNode:()=>kn,awaitSettled:()=>Bs,batch:()=>Z,budgetGate:()=>Zt,buffer:()=>Ol,bufferCount:()=>Al,bufferTime:()=>Ll,bumpCursor:()=>Kt,cached:()=>up,canonicalJson:()=>ko,cascadingCache:()=>Nf,catchError:()=>Kl,checkpointToRedis:()=>bf,checkpointToS3:()=>yf,circuitBreaker:()=>St,combine:()=>sd,combineLatest:()=>jl,compat:()=>Ed,concat:()=>kl,concatMap:()=>Sl,configure:()=>Aa,constant:()=>_s,contentAddressedStorage:()=>ui,core:()=>yd,cqrs:()=>Qs,createAuditLog:()=>at,createDagCborCodec:()=>xa,createDagCborZstdCodec:()=>Ra,createGraph:()=>Ar,createTransport:()=>ln,createVersioning:()=>rr,createWatermarkController:()=>gr,csvRows:()=>Xp,debounce:()=>ad,debounceTime:()=>Bl,decay:()=>Pt,decodeEnvelope:()=>Fr,decorrelatedJitter:()=>Cs,defaultConfig:()=>je,defaultHash:()=>Xt,defer:()=>ip,delay:()=>El,deleteSnapshot:()=>va,demoShell:()=>Wi,derived:()=>A,derivedT:()=>Ca,deserializeError:()=>Vn,dictKv:()=>$f,dictSnapshot:()=>jf,diffForWAL:()=>ws,diffSnapshots:()=>ya,distill:()=>Tr,distinctUntilChanged:()=>vl,domainMeta:()=>we,domainTemplates:()=>Ui,downWithBatch:()=>$t,dynamicNode:()=>Wr,effect:()=>he,effectT:()=>La,elementAt:()=>hl,empty:()=>rp,encodeEnvelope:()=>Gr,escapeRegexChar:()=>pd,exhaustMap:()=>Rl,explainPath:()=>Zr,exponential:()=>Os,externalBundle:()=>ai,externalProducer:()=>$n,extra:()=>Fd,factoryTag:()=>Te,fallback:()=>fr,fibonacci:()=>As,filter:()=>xt,find:()=>gl,first:()=>Ls,firstValueFrom:()=>it,firstWhere:()=>Gs,flatMap:()=>Nl,forEach:()=>an,fromAny:()=>X,fromAsyncIter:()=>co,fromCSV:()=>Qp,fromClickHouseWatch:()=>nf,fromCron:()=>Fs,fromDrizzle:()=>xf,fromEvent:()=>np,fromHTTP:()=>Ad,fromHTTPPoll:()=>Gp,fromHTTPStream:()=>Dp,fromIter:()=>$s,fromKafka:()=>Wp,fromKysely:()=>Rf,fromMCP:()=>jp,fromNATS:()=>sf,fromNDJSON:()=>tf,fromOTel:()=>Bp,fromPrisma:()=>kf,fromPrometheus:()=>Hp,fromPromise:()=>mr,fromPulsar:()=>rf,fromRabbitMQ:()=>df,fromRaf:()=>tp,fromRedisStream:()=>Jp,fromSSE:()=>Pp,fromSqlite:()=>vf,fromSqliteCursor:()=>Tf,fromStatsD:()=>qp,fromSyslog:()=>Vp,fromTimer:()=>st,fromWebSocket:()=>Od,fromWebSocketReconnect:()=>$p,fromWebhook:()=>_p,globToRegExp:()=>Zl,graph:()=>nd,graphProfile:()=>Rn,graphspec:()=>qi,harness:()=>oa,inspect:()=>ua,interval:()=>Dl,isBatching:()=>Tn,isV1:()=>_a,jobQueue:()=>na,jotai:()=>ss,jsonCodec:()=>kr,jsonCodecFor:()=>Df,keepalive:()=>ne,kvStorage:()=>mi,last:()=>ml,layout:()=>la,lightMutation:()=>Le,linear:()=>Ms,listSnapshots:()=>ba,lru:()=>Id,makeHttpError:()=>Mt,map:()=>no,matchesAnyPattern:()=>ep,matchesCron:()=>ps,memory:()=>$i,memoryAppendLog:()=>Ff,memoryBackend:()=>Eo,memoryKv:()=>_o,memorySnapshot:()=>Gf,merge:()=>It,mergeMap:()=>id,mergeReactiveLogs:()=>vp,messaging:()=>Li,monotonicNs:()=>W,nameToSignal:()=>jn,nanostores:()=>us,ndjsonRows:()=>Zp,nestjs:()=>Zs,never:()=>op,node:()=>Q,nodeSignal:()=>Vs,normalizeActor:()=>Ft,of:()=>fd,onFirstData:()=>oo,orchestration:()=>Ii,pairwise:()=>Tl,parseCron:()=>ls,parsePrometheusText:()=>Cd,parseSSEStream:()=>Ht,parseStatsD:()=>zp,parseSyslog:()=>Kp,patterns:()=>Wu,pausable:()=>Fl,pipe:()=>Ia,placeholderArgs:()=>He,policy:()=>jt,policyFromRules:()=>qr,process:()=>ca,producer:()=>z,pubsub:()=>Af,race:()=>xl,rateLimiter:()=>Cn,reachable:()=>Nn,react:()=>ei,reactiveCounter:()=>lp,reactiveIndex:()=>If,reactiveList:()=>ci,reactiveLog:()=>Ue,reactiveMap:()=>Ke,reactiveSink:()=>Qe,reduce:()=>ll,reduction:()=>Bi,registerBuiltinCodecs:()=>$r,registerBuiltins:()=>Kr,registerCursor:()=>vt,registerCursorMap:()=>zs,repeat:()=>Gl,replay:()=>js,replayWAL:()=>Sa,rescue:()=>so,resolveBackoffPreset:()=>Mn,resolveDescribeFields:()=>en,restoreSnapshot:()=>ha,retry:()=>Rt,runReduction:()=>fa,sample:()=>_l,saveSnapshot:()=>ga,scan:()=>cl,serializeError:()=>Bn,share:()=>dp,shareReplay:()=>cp,signalToName:()=>cn,signals:()=>ni,singleFromAny:()=>li,singleNodeFromAny:()=>Pf,sizeof:()=>Xr,skip:()=>od,snapshotStorage:()=>fi,solid:()=>ri,sortJsonValue:()=>No,stableJsonString:()=>pi,state:()=>C,stratify:()=>Mo,surface:()=>Ta,svelte:()=>oi,switchMap:()=>ke,take:()=>ro,takeUntil:()=>fl,takeWhile:()=>pl,tap:()=>yl,tapFirst:()=>bl,throttle:()=>dd,throttleTime:()=>Vl,throwError:()=>sp,timeout:()=>Ln,toArray:()=>ap,toCSV:()=>cf,toClickHouse:()=>lf,toFile:()=>Ld,toHTTP:()=>Mp,toKafka:()=>Up,toLoki:()=>gf,toMongo:()=>mf,toNATS:()=>af,toObservable:()=>cs,toPostgres:()=>ff,toPulsar:()=>of,toRabbitMQ:()=>uf,toReadableStream:()=>Ip,toRedisStream:()=>Yp,toS3:()=>pf,toSSE:()=>Cp,toSSEBytes:()=>Lp,toSqlite:()=>wf,toTempo:()=>hf,toWebSocket:()=>Fp,tokenBucket:()=>Vt,topologyDiff:()=>lr,tryIncrementBounded:()=>Fn,validateGraphObservability:()=>td,validateNoIslands:()=>Ha,valve:()=>$l,verifiable:()=>Mf,version:()=>tT,vue:()=>si,wallClockNs:()=>ie,watchTopologyTree:()=>En,window:()=>Pl,windowCount:()=>Cl,windowTime:()=>Il,withBreaker:()=>An,withLatestFrom:()=>On,withMaxAttempts:()=>rd,withStatus:()=>on,workerBridge:()=>Dd,workerSelf:()=>Gd,wrapMutation:()=>gt,zip:()=>wl,zustand:()=>ii});module.exports=sg(nT);var Ed={};Ee(Ed,{jotai:()=>ss,nanostores:()=>us,nestjs:()=>Zs,react:()=>ei,signals:()=>ni,solid:()=>ri,svelte:()=>oi,vue:()=>si,zustand:()=>ii});var ss={};Ee(ss,{atom:()=>vg});se();re();function vg(t,e,n){if(typeof t=="function"){let r=t;return typeof e=="function"?cc(r,e,n):cc(r,void 0,e)}return Tg(t,e)}function Ur(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===E&&(e=i),s===L&&(n=i)})(),n)throw n;return e}function Tg(t,e){let n=C(t,{...e,resubscribable:!0,resetOnTeardown:!0});return{get:()=>n.status==="sentinel"?Ur(n):n.cache,set:r=>n.emit(r),update:r=>{let o=n.status==="sentinel"?Ur(n):n.cache;n.emit(r(o))},subscribe:r=>{let o=!0;return n.subscribe(s=>{for(let[i,a]of s)if(i===E){if(o){o=!1;continue}r(a)}})},meta:n.meta,_node:n}}function cc(t,e,n){let r=kn(s=>t(i=>{let a=i._node;return a.status==="sentinel"&&Ur(a),s(a)}),{...n,resubscribable:!0,resetOnTeardown:!0}),o={get:()=>r.status==="sentinel"?Ur(r):r.cache,subscribe:s=>{let i=!0;return r.subscribe(a=>{for(let[d,u]of a)if(d===E){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"?Ur(r):r.cache;return e(s,i,d(u))},a}return o}var us={};Ee(us,{action:()=>Ng,atom:()=>wg,computed:()=>kg,getValue:()=>Rg,map:()=>xg,onMount:()=>Sg,onStart:()=>fc,onStop:()=>mc});Oe();se();re();var as=new WeakMap,ds=new WeakMap;function is(t,e){let n=e.get(t);if(n)for(let r of n)r()}function Pa(t,e={}){let n=0;return{...e,get:()=>pc(t),subscribe:o=>{n===0&&is(t,as),n++;let s=t.subscribe(i=>{for(let[a,d]of i)a===E&&o(d)});return()=>{s(),n--,n===0&&is(t,ds)}},listen:o=>{n===0&&is(t,as),n++;let s=!0,i=t.subscribe(a=>{for(let[d,u]of a)if(d===E){if(s){s=!1;continue}o(u)}});return()=>{i(),n--,n===0&&is(t,ds)}},_node:t}}function lc(t){let e=t.cache,n;if(t.subscribe(o=>{for(let[s,i]of o)s===E&&(e=i),s===L&&(n=i)})(),n)throw n;return e}function pc(t){return t.status==="sentinel"?lc(t):t.cache}function wg(t){let e=C(t,{resubscribable:!0,resetOnTeardown:!0});return Pa(e,{set:n=>e.emit(n)})}function kg(t,e){let n=Array.isArray(t)?t:[t],r=n.map(s=>s._node),o=Wr(r,s=>{let i=n.map(a=>{let d=a._node;return d.status==="sentinel"&&lc(d),s(d)});return e(...i)},{resubscribable:!0,resetOnTeardown:!0,equals:Object.is});return Pa(o)}function xg(t){let e=C(t,{resubscribable:!0,resetOnTeardown:!0,equals:()=>!1});return Pa(e,{set:n=>e.emit(n),setKey:(n,r)=>{let o=pc(e);e.emit({...o,[n]:r})}})}function Rg(t){return t.get()}function fc(t,e){let n=t._node,r=as.get(n);r||(r=new Set,as.set(n,r)),r.add(e)}function mc(t,e){let n=t._node,r=ds.get(n);r||(r=new Set,ds.set(n,r)),r.add(e)}function Sg(t,e){fc(t,()=>{let n=e();typeof n=="function"&&mc(t,n)})}function Ng(t,e,n){return(...r)=>{let o;return Z(()=>{o=n(...r)}),o}}var Zs={};Ee(Zs,{ACTOR_KEY:()=>qs,COMMAND_HANDLERS:()=>ar,CQRS_EVENT_HANDLERS:()=>dr,CRON_HANDLERS:()=>ir,CommandHandler:()=>wc,EVENT_HANDLERS:()=>or,EventHandler:()=>kc,GRAPHREFLY_REQUEST_GRAPH:()=>xn,GRAPHREFLY_ROOT_GRAPH:()=>yt,GraphCron:()=>Tc,GraphInterval:()=>vc,GraphReflyEventExplorer:()=>Gn,GraphReflyGuard:()=>bp,GraphReflyGuardImpl:()=>lo,GraphReflyModule:()=>Xs,INTERVAL_HANDLERS:()=>sr,InjectCqrsGraph:()=>hc,InjectGraph:()=>gc,InjectNode:()=>yc,ObserveGateway:()=>Ks,OnGraphEvent:()=>bc,QUERY_HANDLERS:()=>ur,QueryHandler:()=>xc,SAGA_HANDLERS:()=>cr,SagaHandler:()=>Rc,fromHeader:()=>hp,fromJwtPayload:()=>hd,getActor:()=>yp,getGraphToken:()=>pt,getNodeToken:()=>wt,observeSSE:()=>mp,observeSubscription:()=>gp,toObservable:()=>cs});var Da=require("rxjs");se();function cs(t,e){return e?.raw?new Da.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 Da.Observable(n=>t.subscribe(o=>{for(let s of o){if(n.closed)return;if(s[0]===E)n.next(s[1]);else if(s[0]===L){n.error(s[1]);return}else if(s[0]===I){n.complete();return}}}))}var Jr=require("@nestjs/common");var yt=Symbol.for("graphrefly:root-graph");var xn=Symbol.for("graphrefly:request-graph");function pt(t){return Symbol.for(`graphrefly:graph:${t}`)}function wt(t){return Symbol.for(`graphrefly:node:${t}`)}var or=new Map,sr=new Map,ir=new Map,ar=new Map,dr=new Map,ur=new Map,cr=new Map;function gc(t){return t==="request"?(0,Jr.Inject)(xn):(0,Jr.Inject)(t?pt(t):yt)}function hc(t){return(0,Jr.Inject)(pt(t))}function yc(t){return(0,Jr.Inject)(wt(t))}function bc(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=or.get(o)??[];s.push({nodeName:t,methodKey:r}),or.set(o,s)})}}function vc(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=sr.get(o)??[];s.push({ms:t,methodKey:r}),sr.set(o,s)})}}function Tc(t){return(e,n)=>{let r=n.name;n.addInitializer(function(){let o=this.constructor,s=ir.get(o)??[];s.push({expr:t,methodKey:r}),ir.set(o,s)})}}function wc(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=ar.get(s)??[];i.push({cqrsName:t,commandName:e,methodKey:o}),ar.set(s,i)})}}function kc(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=dr.get(s)??[];i.push({cqrsName:t,eventName:e,methodKey:o}),dr.set(s,i)})}}function xc(t,e){return(n,r)=>{let o=r.name;r.addInitializer(function(){let s=this.constructor,i=ur.get(s)??[];i.push({cqrsName:t,projectionName:e,methodKey:o}),ur.set(s,i)})}}function Rc(t,e,n){return(r,o)=>{let s=o.name;o.addInitializer(function(){let i=this.constructor,a=cr.get(i)??[];a.push({cqrsName:t,eventNames:n,sagaName:e,methodKey:s}),cr.set(i,a)})}}se();pe();var fp=0,Gn=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 or){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]===E&&o(d[1])});this.disposers.push(i)}wireIntervals(){for(let[e,n]of sr){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)}.${fp++}`,d=st(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]===E&&s(p[1])});this.disposers.push(c)}wireCrons(){for(let[e,n]of ir){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)}.${fp++}`,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]===E&&s(p[1])});this.disposers.push(c)}wireCqrsCommands(){for(let[e,n]of ar){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 dr){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]===E){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 ur){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]===E&&o(u[1])});this.disposers.push(a)}wireCqrsSagas(){for(let[e,n]of cr){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(pt(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}}};se();se();var Mh=0;function gr(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-${++Mh}`),r=0,o=!1;return{onEnqueue(){return r+=1,!o&&r>=e.highWaterMark?(o=!0,t([[ze,n]]),!0):!1},onDequeue(){return r>0&&(r-=1),o&&r<=e.lowWaterMark?(o=!1,t([[Ye,n]]),!0):!1},get pending(){return r},get paused(){return o},dispose(){o&&(o=!1,t([[Ye,n]]))}}}function mp(t,e,n){let{actor:r,serialize:o=Oh,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=gr(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===E){let x=a.encode(md("data",o(w[1])));u?(p.push({frame:x,counted:!0}),c.onEnqueue(),l?.(),l=void 0):m.enqueue(x)}else if(k===L){let x=a.encode(md("error",o(w[1])));u?(p.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x),y();return}else if(k===I||k===ge){if(k===I){let x=a.encode(md("complete"));u?(p.push({frame:x,counted:!1}),l?.(),l=void 0):m.enqueue(x)}y();return}}}),s!==void 0&&s>0&&(h=setInterval(()=>{f||(u?(p.push({frame:a.encode(`: keepalive
|
|
8
8
|
|
|
9
9
|
`),counted:!1}),l?.(),l=void 0):m.enqueue(a.encode(`: keepalive
|
|
10
10
|
|
|
11
|
-
`)))},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
|
|
11
|
+
`)))},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 gp(t,e,n){let{actor:r,filter:o}=n??{},s=[],i=[],a=!1,d=t.observe(e,{actor:r}),u=n?.highWaterMark!=null?gr(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===E){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===ge){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 Ks=class{constructor(e,n){this.graph=e;this.extractActor=n?.extractActor??(()=>{}),this.parse=n?.parse??Ah,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??Ch.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?gr(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===E)a?.onEnqueue(),gd(r,{type:"data",path:n,value:l[1]});else if(p===L){let f=l[1]instanceof Error?l[1].message:String(l[1]);gd(r,{type:"error",path:n,error:f}),d();return}else if(p===I||p===ge){gd(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 Oh(t){if(t instanceof Error)return t.message;try{return JSON.stringify(t)}catch{return String(t)}}function md(t,e){let n=`event: ${t}
|
|
12
12
|
`;if(e!==void 0)for(let r of e.split(`
|
|
13
13
|
`))n+=`data: ${r}
|
|
14
14
|
`;return n+=`
|
|
15
|
-
`,n}function Nh(t){return JSON.parse(t)}function Eh(t,e){try{t.send(JSON.stringify(e))}catch{}}function dd(t,e){try{t(e)}catch{}}Fr();var $s="graphReflyActor";function ud(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function lp(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 pp(t){let e=t?.[$s];return e!=null?Gt(e):Ot}var ao=class{constructor(e){this.extractor=e}canActivate(e){let n=Gt(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[$s]=n),!0}};function fp(t){return new ao(t??ud())}var mo=require("@nestjs/common"),bp=require("@nestjs/core");Fe();var zs={};Ee(zs,{CqrsGraph:()=>Hs,cqrs:()=>md,cqrsEventKeyOf:()=>Ah,dispatchKeyOf:()=>Ch,sagaInvocationKeyOf:()=>Lh});Re();Jt();var cd={};Ee(cd,{COMPLETE:()=>I,COMPLETE_MSG:()=>Yo,COMPLETE_ONLY_BATCH:()=>Ir,DATA:()=>_,DEFAULT_ACTOR:()=>Ot,DIRTY:()=>oe,DIRTY_MSG:()=>Dt,DIRTY_ONLY_BATCH:()=>Yn,ERROR:()=>L,GraphReFlyConfig:()=>Tn,GuardDenied:()=>ct,INVALIDATE:()=>nt,INVALIDATE_MSG:()=>Jo,INVALIDATE_ONLY_BATCH:()=>Lr,NodeImpl:()=>Ae,PAUSE:()=>qe,RESOLVED:()=>z,RESOLVED_MSG:()=>Un,RESOLVED_ONLY_BATCH:()=>Cr,RESUME:()=>Je,START:()=>mt,START_MSG:()=>Jn,TEARDOWN:()=>fe,TEARDOWN_MSG:()=>Qo,TEARDOWN_ONLY_BATCH:()=>Qn,accessHintForGuard:()=>Kr,advanceVersion:()=>qr,autoTrackNode:()=>wn,batch:()=>Z,configure:()=>Na,createVersioning:()=>nr,defaultConfig:()=>$e,defaultHash:()=>Yt,derived:()=>O,downWithBatch:()=>Ft,dynamicNode:()=>Hr,effect:()=>he,factoryTag:()=>Te,isBatching:()=>vn,isV1:()=>xa,monotonicNs:()=>W,node:()=>J,normalizeActor:()=>Gt,pipe:()=>Ea,placeholderArgs:()=>He,policy:()=>$t,policyFromRules:()=>Vr,producer:()=>H,registerBuiltins:()=>Br,resolveDescribeFields:()=>Xt,state:()=>A,wallClockNs:()=>ie});Fr();Oe();Re();wa();Jt();se();Ze();Me();ne();es();Oe();Re();Jt();se();ne();Fe();Oe();se();Me();ne();ce();var co=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 uo(t){return t.subscribe(()=>{})}var _h=64;function We(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:i}=e,a=i??new co(t,r),d=A(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([[oe]],{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<_h)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=O([d],([E])=>{let P=E;return R===0||P.length===0?[]:P.slice(Math.max(0,P.length-R))},{initial:a.tail(R),describeKind:"derived"}),N=uo(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=O([d],([M])=>{let C=M;return S===void 0?C.slice(R):C.slice(R,S)},{initial:a.slice(R,S),describeKind:"derived"}),P=uo(E);return l.set(x,{node:E,dispose:P}),E}function b(R){let S=p.get(R);if(S!==void 0)return S.node;let x=O([d,R],([E,P])=>{let M=E,C=Math.max(0,Math.trunc(P??0));return M.slice(C)},{initial:[],describeKind:"derived"}),N=uo(x);return p.set(R,{node:x,dispose:N}),x}let v,T;function w(){v===void 0&&(v=J([d],(R,S,x)=>{let N=R[0],P=N!=null&&N.length>0?N.at(-1):x.prevData[0];if(P==null||P.length===0){S.down([[z]]);return}S.emit(P[P.length-1])},{name:n!=null?`${n}::lastValue`:"lastValue",describeKind:"derived",initial:a.size===0?void 0:a.at(a.size-1)}),T=O([d],([R])=>R.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),uo(v),uo(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 P=E[1];for(let M of R){let C=S.get(M)??0;if(P.length<C){try{let V=M.appendEntries(P);V instanceof Promise&&V.catch(()=>{})}catch{}S.set(M,P.length);continue}if(P.length===C)continue;let $=P.slice(C);S.set(M,P.length);try{let V=M.appendEntries($);V instanceof Promise&&V.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 ld=new WeakMap;function mp(t){let e=ld.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]===_)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(),ld.delete(t)}}};return ld.set(t,u),u}function Gn(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[oe],[_,n+1]]),!0)}var pd=$t((t,e)=>{t("observe"),t("signal"),e("write")});function at(t){let e=We([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??pd,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function fd(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))fd(t[e]);return Object.freeze(t)}function Bt(t){let e=t.cache,r=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return t.down([[oe],[_,r]]),r}function gr(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 Ce(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(fd):o,i=ie(),a=e.seq?Bt(e.seq):void 0;try{let d=t(...s);return e.audit&&e.onSuccess&&gr(e.audit,e.onSuccess,s,d,{t_ns:i,seq:a},e.handlerVersion),d}catch(d){if(e.audit&&e.onFailure){let u=d instanceof Error?d.name:typeof d;gr(e.audit,e.onFailure,s,d,{t_ns:i,seq:a,errorType:u},e.handlerVersion)}throw d}}}function Lt(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(fd):o,i=ie(),a,d,u=!1,c;try{Z(()=>{e.seq&&(c=Bt(e.seq));try{a=t(...s),e.audit&&e.onSuccess&&gr(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.audit&&e.onFailure){let p=d instanceof Error?d.name:typeof d;gr(e.audit,e.onFailure,s,d,{t_ns:i,seq:c,errorType:p},e.handlerVersion)}throw u?d:l}return a}}function ht(t,e,n=0){let r=A(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function js(t,e,n,r=0){let o={},s=new Y(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}Tt();var an=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},Bs=class extends an{constructor(n,r){super(`Duplicate ${n} registration: "${r}"`);this.kind=n;this.registrationName=r}},Vs=class extends an{constructor(n,r,o){super(`Command "${n}" emitted undeclared event "${r}". Declared emits: [${o.join(", ")}]`);this.commandName=n;this.eventName=r;this.declaredEmits=o}},Ks=class extends an{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}},qs=class extends an{constructor(n){super(`Unknown command: "${n}". Register with command() first.`);this.commandName=n}},lo=class extends an{constructor(n,r){super(`Command handler "${n}" threw: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.commandName=n}};var po=class extends an{constructor(n,r){super(`Projection "${n}" rebuild failed: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.projectionName=n}};ut();ce();var Mh=$t((t,e)=>{t("write"),t("signal"),e("observe")}),Oh=$t((t,e)=>{t("observe"),t("signal"),e("write")}),gp=$t((t,e)=>{t("observe"),t("signal"),e("write")});function fo(t,e){return we("cqrs",t,e)}function hp(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))hp(t[e]);return Object.freeze(t)}var Ah=t=>`${t.type}::${t.aggregateId??"__default__"}`,Ch=t=>t.commandName,Lh=t=>t.eventType,Hs=class extends Y{_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=ht(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:ie()})}}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))}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=We([],{name:e,versioning:0,maxSize:this._retainedLimit});o.withLatest();let s=o.entries,i=O([s],([a])=>a,{name:e,describeKind:"state",meta:fo("event",{event_name:e}),guard:gp,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=We([],{name:i,versioning:0,maxSize:this._retainedLimit});a.withLatest();let d=a.entries,u=O([d],([f])=>f,{name:i,describeKind:"state",meta:fo("event_aggregate",{event_name:e,aggregate_id:n}),guard:gp,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?hp(n):n,u={type:e,payload:d,timestampNs:ie(),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 Bs("command",e);let r=typeof n=="function"?{handler:n}:n,o=A(void 0,{name:e,describeKind:"state",meta:{...fo("command",{command_name:e}),error:null},guard:Mh});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 qs(e);if(r?.aggregateId!==void 0&&r.expectedAggregateVersion!==void 0&&o.emits!==void 0){let u=0;for(let c of o.emits){let l=this._aggregateVersions.get(`${c}::${r.aggregateId}`);l!==void 0&&l>u&&(u=l)}if(u!==r.expectedAggregateVersion)throw new Ks(r.aggregateId,r.expectedAggregateVersion,u)}let s=this.resolve(e),i=[],a=!1,d=u=>{s.emit(u,{internal:!0});try{o.handler(u,{emit:(c,l)=>{if(o.emits!==void 0&&!o.emits.includes(c))throw new Vs(e,c,o.emits);i.push(c),this._appendEvent(c,l,{...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})}catch(c){throw a=!0,c}};try{Lt(d,{audit:this.dispatches,seq:this._dispatchSeqCursor,freeze:this._freezeCommandPayload,onSuccess:([u],c,{t_ns:l,seq:p})=>({commandName:e,payload:u,outcome:"success",emittedEvents:[...i],t_ns:l,seq:p??0,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),onFailure:([u],c,{t_ns:l,seq:p,errorType:f})=>{let m=c instanceof lo?c:new lo(e,c);return{commandName:e,payload:u,outcome:"failure",error:m,errorType:f,emittedEvents:[...i],t_ns:l,seq:p??0,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}}})(n)}catch(u){throw a&&s.meta.error.emit(u,{internal:!0}),u}}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,P)=>E.timestampNs-P.timestampNs||E.seq-P.seq||(E.aggregateId??"").localeCompare(P.aggregateId??""))}function l(N){let E=[];for(let P of N)E.push(...P);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=O(u,N=>{let E=l(N),P;if(i==="replay"){let M=a?Object.freeze(E):E;P=o(s,M)}else{let M=E.slice(h);h=E.length;let C=a?Object.freeze(M):M;P=o(g,C),g=P}return k(P),P},{name:n,describeKind:"derived",meta:fo("projection",{projection_name:n,source_events:r}),guard:Oh,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,P=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(!P||!P.loadEntries){let $=l(u.map(G=>G.cache??[])),V=a?Object.freeze($):$;C=o(C,V)}else{let $=new Set(r),V,G=!1;for(;!G;){let K=await P.loadEntries({cursor:V,pageSize:E}),F=[...K.entries].filter(D=>$.has(D.type));c(F);let q=a?Object.freeze(F):F;C=o(C,q),V=K.cursor,G=!V||K.entries.length===0}}if(i==="scan"){let $=l(u.map(G=>G.cache??[])),V=$.slice(M);if(V.length>0){let G=a?Object.freeze(V):V;C=o(C,G)}g=C,h=$.length}return R.emit(C,{internal:!0}),C}catch(E){throw new po(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??[])),P=a?Object.freeze(E):E,M=o(N,P);return i==="scan"&&(g=M,h=E.length),R.emit(M,{internal:!0}),M}catch(N){throw new po(n,N)}}}}saga(e,n,r,o={}){let s=n.map(m=>(this._eventLogs.has(m)||this.event(m),this._eventLogs.get(m).node)),i=js(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 m of n){let h=i[m];c.set(m,h.cache??0);let g=h.subscribe(y=>{for(let b of y)b[0]===_&&c.set(m,b[1])});this._keepaliveDisposers.push(g)}let l=Ce((m,h)=>{r(m)},{audit:a,freeze:!1,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{},onSuccess:([m,h],g,{t_ns:y})=>({eventType:h,outcome:"success",aggregateId:m.aggregateId,event:m,t_ns:y}),onFailure:([m,h],g,{t_ns:y,errorType:b})=>({eventType:h,outcome:"failure",error:g,errorType:b,aggregateId:m.aggregateId,event:m,t_ns:y})}),p={},f=J(s,(m,h)=>{let g=p.n.meta.error;for(let y=0;y<m.length;y++){let b=m[y];if(b==null||b.length===0)continue;let v=b.at(-1);if(!v)continue;let T=n[y],w=i[T],k=c.get(T)??0;if(v.length>k){let R=v.slice(k),S=k;for(let x of R){let N=x;if(d!==void 0&&N.aggregateId!==d){S+=1;continue}try{l(N,T),g.emit(null,{internal:!0}),S+=1}catch(E){if(g.emit(E,{internal:!0}),u==="hold")break;S+=1}}w.emit(S)}}},{name:e,describeKind:"effect",meta:{...fo("saga",{saga_name:e,source_events:n}),error:null}});return p.n=f,this.add(f,{name:e}),this._keepaliveDisposers.push(te(f)),this._sagas.add(e),{node:f,invocations:a,audit:a,cursors:i}}};function md(t,e){let n=new Hs(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("cqrs",He(s)),n}var hd=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},yd=class{graph=new Y("request");onModuleDestroy(){this.graph.destroy()}},yp,gd;yp=[(0,mo.Module)({})];var dn=class dn{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:gt,useFactory:()=>{let s=new Y(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new hd(s),inject:[gt]},{provide:Dn,useFactory:(s,i)=>new Dn(s,i),inject:[gt,bp.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:bt(s),useFactory:i=>i.resolve(s),inject:[gt]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new yd,scope:mo.Scope.REQUEST},{provide:kn,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:mo.Scope.REQUEST}),{module:dn,global:!0,providers:o,exports:[gt,...(n.nodes??[]).map(bt),...n.requestScope?[kn]:[]]}}static forFeature(e){let n=[{provide:lt(e.name),useFactory:r=>{let o=new Y(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:bt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[lt(e.name)]});return{module:dn,providers:n,exports:[lt(e.name),...(e.nodes??[]).map(r=>bt(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:lt(e.name),useFactory:r=>{let o=md(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:bt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[lt(e.name)]});return{module:dn,providers:n,exports:[lt(e.name),...(e.nodes??[]).map(r=>bt(`${e.name}::${r}`))]}}};gd=Wu(null),dn=Yu(gd,0,"GraphReflyModule",yp,dn),Ju(gd,1,dn);var Ws=dn;var Js={};Ee(Js,{useStore:()=>Ih,useSubscribe:()=>vp,useSubscribeRecord:()=>Ph});var Vt=require("react");se();function vp(t){return(0,Vt.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function Ih(t){let e=vp(t),n=(0,Vt.useCallback)(r=>{t.down([[oe],[_,r]])},[t]);return[e,n]}function Ph(t,e){let n=(0,Vt.useRef)(e);n.current=e;let r=(0,Vt.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]===z);!a&&f&&c(t.cache??[])});return c(t.cache??[]),()=>{a=!0,l(),u()}},getSnapshot:()=>s}},[t]);return(0,Vt.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var Qs={};Ee(Qs,{Signal:()=>Dh});Oe();se();ne();var hr=[];function Ys(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===_&&(e=s)})(),e}var bd=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=A(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=hr[hr.length-1];return e?(this._node.status==="sentinel"&&Ys(this._node),e(this._node)):this._node.status==="sentinel"?Ys(this._node):this._node.cache}set(e){this._equals(this.get(),e)||Z(()=>{this._node.down([[oe],[_,e]])})}},vd=class{_node;constructor(e,n){this._node=wn(r=>{hr.push(r);try{return e()}finally{hr.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=hr[hr.length-1];return e?(this._node.status==="sentinel"&&Ys(this._node),e(this._node)):this._node.status==="sentinel"?Ys(this._node):this._node.cache}},Dh={State:bd,Computed:vd,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 Xs={};Ee(Xs,{useStore:()=>Gh,useSubscribe:()=>Tp,useSubscribeRecord:()=>Fh});var Kt=require("solid-js");se();function Tp(t){let[e,n]=(0,Kt.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,Kt.getOwner)()?(0,Kt.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 Gh(t){return[Tp(t),r=>{t.down([[oe],[_,r]])}]}function Fh(t,e){let[n,r]=(0,Kt.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]===z)&&a(t.cache??[])});return a(t.cache??[]),(0,Kt.getOwner)()?(0,Kt.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 Zs={};Ee(Zs,{useStore:()=>jh,useSubscribe:()=>$h,useSubscribeRecord:()=>Bh});se();function $h(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function jh(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[oe],[_,e]])},update(e){let n=e(t.cache);t.down([[oe],[_,n]])}}}function Bh(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]===z)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var ei={};Ee(ei,{useStore:()=>Kh,useSubscribe:()=>Vh,useSubscribeRecord:()=>qh});var Ue=require("vue");se();function Vh(t){let e=(0,Ue.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ue.getCurrentScope)()?(0,Ue.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ue.readonly)(e)}function Kh(t){let e=(0,Ue.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Ue.getCurrentScope)()?(0,Ue.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Ue.computed)({get:()=>e.value,set:r=>{t.down([[oe],[_,r]])}})}function qh(t,e){let n=(0,Ue.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,Ue.watch)(()=>[...(typeof t=="function"?t():(0,Ue.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,Ue.getCurrentScope)()?(0,Ue.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,Ue.readonly)(n)}var ti={};Ee(ti,{create:()=>zh});se();ne();Fe();var Hh=()=>!1;function zh(t){let e=new Y("zustand"),n=A(void 0,{name:"state",equals:Hh});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 Ad={};Ee(Ad,{CircuitOpenError:()=>St,ContentAddressedMissError:()=>bo,DEFAULT_AUDIT_GUARD:()=>pd,NS_PER_MS:()=>et,NS_PER_SEC:()=>wt,NativeIndexBackend:()=>wo,NativeListBackend:()=>ko,NativeLogBackend:()=>co,NativeMapBackend:()=>ho,NativePubSubBackend:()=>To,RateLimiterOverflowError:()=>Ln,ResettableTimer:()=>Ie,TimeoutError:()=>In,appendAudit:()=>gr,appendLogStorage:()=>_d,audit:()=>Rl,awaitSettled:()=>Ds,budgetGate:()=>Qt,buffer:()=>Sl,bufferCount:()=>Nl,bufferTime:()=>_l,bumpCursor:()=>Bt,cached:()=>op,canonicalJson:()=>vo,cascadingCache:()=>Tf,catchError:()=>Fl,checkpointToRedis:()=>pf,checkpointToS3:()=>lf,circuitBreaker:()=>Rt,combine:()=>Xa,combineLatest:()=>Pl,concat:()=>yl,concatMap:()=>Tl,constant:()=>Rs,contentAddressedStorage:()=>si,createAuditLog:()=>at,createTransport:()=>cn,createWatermarkController:()=>mr,csvRows:()=>zp,debounce:()=>ed,debounceTime:()=>Dl,decay:()=>It,decorrelatedJitter:()=>_s,defer:()=>tp,delay:()=>kl,deserializeError:()=>Bn,dictKv:()=>Lf,dictSnapshot:()=>If,distill:()=>ri,distinctUntilChanged:()=>ml,domainMeta:()=>we,elementAt:()=>ll,empty:()=>Xl,escapeRegexChar:()=>sd,exhaustMap:()=>vl,exponential:()=>Ns,externalBundle:()=>ni,externalProducer:()=>Fn,fallback:()=>pr,fibonacci:()=>Es,filter:()=>kt,find:()=>cl,first:()=>Ms,firstValueFrom:()=>it,firstWhere:()=>Cs,flatMap:()=>wl,forEach:()=>sn,fromAny:()=>Q,fromAsyncIter:()=>io,fromCSV:()=>Hp,fromClickHouseWatch:()=>Yp,fromCron:()=>Ls,fromDrizzle:()=>yf,fromEvent:()=>Ql,fromHTTP:()=>Rd,fromHTTPPoll:()=>Ap,fromHTTPStream:()=>Op,fromIter:()=>Is,fromKafka:()=>Bp,fromKysely:()=>bf,fromMCP:()=>Ip,fromNATS:()=>Zp,fromNDJSON:()=>Jp,fromOTel:()=>Pp,fromPrisma:()=>hf,fromPrometheus:()=>jp,fromPromise:()=>fr,fromPulsar:()=>Qp,fromRabbitMQ:()=>tf,fromRaf:()=>Yl,fromRedisStream:()=>Kp,fromSSE:()=>Mp,fromSqlite:()=>ff,fromSqliteCursor:()=>mf,fromStatsD:()=>Fp,fromSyslog:()=>Dp,fromTimer:()=>st,fromWebSocket:()=>xd,fromWebSocketReconnect:()=>Lp,fromWebhook:()=>kp,globToRegExp:()=>Ul,interval:()=>Al,jsonCodec:()=>Tr,jsonCodecFor:()=>Of,keepalive:()=>te,kvStorage:()=>ci,last:()=>ul,lightMutation:()=>Ce,linear:()=>Ss,lru:()=>Ed,makeHttpError:()=>Et,map:()=>eo,matchesAnyPattern:()=>Jl,matchesCron:()=>us,memoryAppendLog:()=>Cf,memoryBackend:()=>Ro,memoryKv:()=>So,memorySnapshot:()=>Af,merge:()=>Ct,mergeMap:()=>Za,mergeReactiveLogs:()=>mp,nameToSignal:()=>$n,ndjsonRows:()=>Wp,never:()=>Zl,nodeSignal:()=>Gs,of:()=>id,onFirstData:()=>no,pairwise:()=>gl,parseCron:()=>ds,parsePrometheusText:()=>Sd,parseSSEStream:()=>qt,parseStatsD:()=>$p,parseSyslog:()=>Gp,pausable:()=>Ll,pubsub:()=>Sf,race:()=>bl,rateLimiter:()=>An,reactiveCounter:()=>ip,reactiveIndex:()=>_f,reactiveList:()=>ii,reactiveLog:()=>We,reactiveMap:()=>Xe,reactiveSink:()=>Ye,reduce:()=>il,registerCursor:()=>ht,registerCursorMap:()=>js,repeat:()=>Cl,replay:()=>Ps,rescue:()=>ro,resolveBackoffPreset:()=>_n,retry:()=>xt,sample:()=>xl,scan:()=>sl,serializeError:()=>jn,share:()=>rp,shareReplay:()=>sp,signalToName:()=>un,singleFromAny:()=>ai,singleNodeFromAny:()=>Mf,skip:()=>Qa,snapshotStorage:()=>ui,sortJsonValue:()=>xo,stableJsonString:()=>di,stratify:()=>No,switchMap:()=>ke,take:()=>to,takeUntil:()=>dl,takeWhile:()=>al,tap:()=>pl,tapFirst:()=>fl,throttle:()=>td,throttleTime:()=>Gl,throwError:()=>ep,timeout:()=>Cn,toArray:()=>np,toCSV:()=>rf,toClickHouse:()=>of,toFile:()=>Nd,toHTTP:()=>xp,toKafka:()=>Vp,toLoki:()=>uf,toMongo:()=>df,toNATS:()=>ef,toObservable:()=>as,toPostgres:()=>af,toPulsar:()=>Xp,toRabbitMQ:()=>nf,toReadableStream:()=>_p,toRedisStream:()=>qp,toS3:()=>sf,toSSE:()=>Np,toSSEBytes:()=>Ep,toSqlite:()=>gf,toTempo:()=>cf,toWebSocket:()=>Cp,tokenBucket:()=>rn,topologyDiff:()=>cr,tryIncrementBounded:()=>Gn,valve:()=>Il,verifiable:()=>xf,window:()=>Ol,windowCount:()=>El,windowTime:()=>Ml,withBreaker:()=>On,withLatestFrom:()=>Mn,withMaxAttempts:()=>Ya,withStatus:()=>nn,workerBridge:()=>Md,workerSelf:()=>Od,wrapMutation:()=>Lt,zip:()=>hl});Oe();Re();se();Me();ne();Oe();se();ne();function wp(t){return{describeKind:"producer",...t}}function Fn(t,e){return H(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{}}},wp(e))}function ni(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=H(y=>(s++,()=>{i++,s>0&&i>=s&&i>=e.length&&u()}),wp({...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())}})}ze();se();Me();ne();Zr();ms();var wd=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new jt(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 go(t){return t instanceof Error?t:new Error(String(t))}function Wh(t){return t===void 0?null:typeof t=="string"?_n(t):t}function Ye(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=Wh(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=f!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=j=>n?`${n}::${j}`:void 0,w=A(void 0,{equals:()=>!1,name:T("sent")}),k=A(null,{name:T("failed")}),R=A(0,{name:T("inFlight")}),S=A(null,{name:T("errors")}),x=v?A(0,{name:T("buffered")}):void 0,N=s?A(!1,{name:T("paused")}):void 0,E=0,P=j=>{E+=j,R.down([[_,E]])},M=j=>{try{r?.(j)}catch{}try{S.down([[_,j]])}catch{}},C=new Set,$=j=>{C.add(j);let ae=()=>C.delete(j);j.then(ae,ae)},V=(j,ae,le)=>{let Ne=y?y(ae-1,le,null):0,xe=Ne==null?0:typeof Ne=="number"&&Ne>0?Ne:0,Ke=Math.max(1,Math.ceil(xe/1e6));return new Promise(pe=>{setTimeout(()=>pe(j()),Ke)})},G=j=>j!=null&&typeof j=="object"&&typeof j.then=="function",K=j=>{let ae;try{ae=d?d(j):j}catch(pe){let ue=go(pe);return M({stage:"serialize",error:ue,value:j}),k.down([[_,{value:j,error:ue,attempts:0}]]),Promise.resolve()}let le=0,Ne=pe=>{P(-1);let ue=go(pe);if(M({stage:"send",error:ue,value:j,attempt:le}),!(le<g&&b(ue,le))){k.down([[_,{value:j,error:ue,attempts:le}]]);return}return V(Ke,le,ue)},xe=()=>{P(-1),w.down([[_,j]])};function Ke(){le+=1,P(1);let pe;try{pe=p(ae,h)}catch(ue){return Ne(ue)??Promise.resolve()}return G(pe)?pe.then(xe,ue=>Ne(ue)):(xe(),Promise.resolve())}return Ke()},F=s?.maxBuffer??Number.POSITIVE_INFINITY,q=new wd(F),D,B=!1,re=()=>{x?.down([[_,q.length]])},ye=j=>{N&&N.down([[_,j]])},ee=s?.strategy??"drop-oldest",me=(j,ae)=>{let le={value:j,payload:ae};if(q.length<F)return q.push(le),re(),!0;if(ee==="drop-oldest"){let xe=q.shift();return q.push(le),re(),ye(!0),k.down([[_,{value:xe.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(ee==="drop-newest")return ye(!0),k.down([[_,{value:j,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Ne=new Error("backpressure: buffer overflow");return M({stage:"send",error:Ne,value:j}),k.down([[_,{value:j,error:Ne,attempts:0}]]),ye(!0),!1},Le=j=>{let ae=0,le=j.map(pe=>pe.payload),Ne=pe=>{P(-1);let ue=go(pe);if(M({stage:"send",error:ue,value:j.map(hn=>hn.value),attempt:ae}),!(ae<g&&b(ue,ae))){for(let{value:hn}of j)k.down([[_,{value:hn,error:ue,attempts:ae}]]);return}return V(Ke,ae,ue)},xe=()=>{P(-1);for(let{value:pe}of j)w.down([[_,pe]])};function Ke(){ae+=1,P(1);let pe;try{pe=f(le,h)}catch(ue){return Ne(ue)??Promise.resolve()}return G(pe)?pe.then(xe,ue=>Ne(ue)):(xe(),Promise.resolve())}return Ke()},rt=async j=>{for(let ae of j)await Qe(ae.value,ae.payload)},Qe=(j,ae)=>{let le=0,Ne=pe=>{P(-1);let ue=go(pe);if(M({stage:"send",error:ue,value:j,attempt:le}),!(le<g&&b(ue,le))){k.down([[_,{value:j,error:ue,attempts:le}]]);return}return V(Ke,le,ue)},xe=()=>{P(-1),w.down([[_,j]])};function Ke(){le+=1,P(1);let pe;try{pe=p(ae,h)}catch(ue){return Ne(ue)??Promise.resolve()}return G(pe)?pe.then(xe,ue=>Ne(ue)):(xe(),Promise.resolve())}return Ke()},U=()=>{if(B||q.length===0)return Promise.resolve();let j=q.drain();if(re(),ye(!1),f!==void 0){let le=Le(j);return $(le),le}let ae=rt(j);return $(ae),ae},de=()=>{D!==void 0||B||a<=0||(D=setTimeout(()=>{D=void 0,U()},a))},De=t.subscribe(j=>{for(let ae of j){let le=ae[0];if(le!==_)try{c?.(ae)}catch{}if(le===_){let Ne=ae[1];if(v){let xe;if(d)try{xe=d(Ne)}catch(pe){let ue=go(pe);M({stage:"serialize",error:ue,value:Ne}),k.down([[_,{value:Ne,error:ue,attempts:0}]]);continue}else xe=Ne;if(!me(Ne,xe))continue;q.length>=i?U():de()}else{let xe=K(Ne);$(xe)}}else $e.messageTier(le)>=3&&v&&(D!==void 0&&(clearTimeout(D),D=void 0),U())}}),Be;if(u){let j=!1;Be=u.subscribe(ae=>{if(!j){j=!0;return}ae.length>0&&!Ve&&Se()})}let Ve=!1,Se=()=>{if(Ve)return;Ve=!0,D!==void 0&&(clearTimeout(D),D=void 0),v&&U(),B=!0,Be?.(),De();let j=ae=>{try{ae.down([[fe]])}catch{}};j(S),j(k),j(w),j(R),x&&j(x),N&&j(N);try{l?.()}catch{}},X={dispose:Se,sent:w,failed:k,inFlight:R,errors:S};return v&&(X.buffered=x,X.flush=async()=>{B||(await U(),await Promise.all(C))}),N&&(X.paused=N),X}on();ce();function Nt(t){return{describeKind:"producer",...t}}function xd(t,e){let{parse:n,closeOnTeardown:r=!1,...o}=e??{};return H(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()}},Nt(o))}function kp(t,e){return Fn(t,e)}function Rd(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([[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([[_,ie()]]),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=H(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{...Nt(c),resubscribable:u});return{...nn(y),fetchCount:l,lastUpdated:p,fetched:f}}function xp(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?Ye(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)}}):
|
|
15
|
+
`,n}function Ah(t){return JSON.parse(t)}function Ch(t,e){try{t.send(JSON.stringify(e))}catch{}}function gd(t,e){try{t(e)}catch{}}jr();var qs="graphReflyActor";function hd(t){return e=>{let r=e.switchToHttp().getRequest()?.user;if(r!=null)return t?t(r):r}}function hp(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 yp(t){let e=t?.[qs];return e!=null?Ft(e):Ct}var lo=class{constructor(e){this.extractor=e}canActivate(e){let n=Ft(this.extractor(e)),r=e.switchToHttp().getRequest();return r!=null&&(r[qs]=n),!0}};function bp(t){return new lo(t??hd())}var yo=require("@nestjs/common"),Rp=require("@nestjs/core");Fe();var Qs={};Ee(Qs,{CqrsGraph:()=>Ys,cqrs:()=>wd,cqrsEventKeyOf:()=>Dh,dispatchKeyOf:()=>Gh,sagaInvocationKeyOf:()=>Fh});Re();Qt();var yd={};Ee(yd,{COMPLETE:()=>I,COMPLETE_MSG:()=>Zo,COMPLETE_ONLY_BATCH:()=>Dr,DATA:()=>E,DEFAULT_ACTOR:()=>Ct,DIRTY:()=>oe,DIRTY_MSG:()=>Gt,DIRTY_ONLY_BATCH:()=>Qn,ERROR:()=>L,GraphReFlyConfig:()=>wn,GuardDenied:()=>lt,INVALIDATE:()=>nt,INVALIDATE_MSG:()=>Xo,INVALIDATE_ONLY_BATCH:()=>Pr,NodeImpl:()=>Ae,PAUSE:()=>ze,RESOLVED:()=>H,RESOLVED_MSG:()=>Jn,RESOLVED_ONLY_BATCH:()=>Ir,RESUME:()=>Ye,START:()=>ht,START_MSG:()=>Yn,TEARDOWN:()=>ge,TEARDOWN_MSG:()=>es,TEARDOWN_ONLY_BATCH:()=>Xn,accessHintForGuard:()=>zr,advanceVersion:()=>Hr,autoTrackNode:()=>kn,batch:()=>Z,configure:()=>Aa,createVersioning:()=>rr,defaultConfig:()=>je,defaultHash:()=>Xt,derived:()=>A,derivedT:()=>Ca,downWithBatch:()=>$t,dynamicNode:()=>Wr,effect:()=>he,effectT:()=>La,factoryTag:()=>Te,isBatching:()=>Tn,isV1:()=>_a,monotonicNs:()=>W,node:()=>Q,normalizeActor:()=>Ft,pipe:()=>Ia,placeholderArgs:()=>He,policy:()=>jt,policyFromRules:()=>qr,producer:()=>z,registerBuiltins:()=>Kr,resolveDescribeFields:()=>en,state:()=>C,wallClockNs:()=>ie});jr();Oe();Re();Na();Qt();se();Ze();Me();re();rs();Oe();Re();Qt();se();re();Fe();Oe();se();Me();re();pe();var fo=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 po(t){return t.subscribe(()=>{})}var Lh=64;function Ue(t,e={}){let{name:n,maxSize:r,versioning:o,guard:s,backend:i}=e,a=i??new fo(t,r),d=C(a.toArray(),{name:n,describeKind:"state",equals:(x,R)=>x===R,...o!=null?{versioning:o}:{},...s!=null?{guard:s}:{}});function u(){let x=a.toArray();Z(()=>{d.down([[oe]],{internal:!0}),d.down([[E,x]],{internal:!0})})}let c=new Map,l=new Map,p=new Map;function f(x,R){return`${x}:${R===void 0?"END":R}`}function m(x){if(x.size<Lh)return;let R=x.keys().next();if(R.done)return;let S=x.get(R.value);S!==void 0&&S.dispose(),x.delete(R.value)}function h(x){let R=a.version;try{return x()}finally{a.version!==R&&u()}}function g(x){if(!Number.isInteger(x)||x<0)throw new RangeError(`tail: n must be a non-negative integer (got ${x})`);let R=c.get(x);if(R!==void 0)return c.delete(x),c.set(x,R),R.node;m(c);let S=A([d],([O])=>{let D=O;return x===0||D.length===0?[]:D.slice(Math.max(0,D.length-x))},{initial:a.tail(x),describeKind:"derived"}),_=po(S);return c.set(x,{node:S,dispose:_}),S}function y(x,R){if(!Number.isInteger(x)||x<0)throw new RangeError(`slice: start must be a non-negative integer (got ${x})`);if(R!==void 0&&(!Number.isInteger(R)||R<0))throw new RangeError(`slice: stop must be a non-negative integer or undefined (got ${R})`);let S=f(x,R),_=l.get(S);if(_!==void 0)return l.delete(S),l.set(S,_),_.node;m(l);let O=A([d],([M])=>{let N=M;return R===void 0?N.slice(x):N.slice(x,R)},{initial:a.slice(x,R),describeKind:"derived"}),D=po(O);return l.set(S,{node:O,dispose:D}),O}function b(x){let R=p.get(x);if(R!==void 0)return R.node;let S=A([d,x],([O,D])=>{let M=O,N=Math.max(0,Math.trunc(D??0));return M.slice(N)},{initial:[],describeKind:"derived"}),_=po(S);return p.set(x,{node:S,dispose:_}),S}let v,T;function w(){v===void 0&&(v=Q([d],(x,R,S)=>{let _=x[0],D=_!=null&&_.length>0?_.at(-1):S.prevData[0];if(D==null||D.length===0){R.down([[H]]);return}R.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],([x])=>x.length>0,{name:n!=null?`${n}::hasLatest`:"hasLatest",describeKind:"derived",initial:a.size>0}),po(v),po(T))}let k={entries:d,get size(){return a.size},at(x){return a.at(x)},append(x){h(()=>a.append(x))},appendMany(x){x.length!==0&&h(()=>a.appendMany(x))},clear(){h(()=>a.clear())},trimHead(x){h(()=>a.trimHead(x))},withLatest(){return w(),d},get lastValue(){return w(),v},get hasLatest(){return w(),T},view(x){switch(x.kind){case"tail":return g(x.n);case"slice":return y(x.start,x.stop);case"fromCursor":return b(x.cursor)}},attach(x){let R=x.subscribe(S=>{for(let _ of S)_[0]===E&&k.append(_[1])});return()=>R()},attachStorage(x){if(x.length===0)return()=>{};let R=new Map;for(let _ of x)R.set(_,a.size);(async()=>{for(let _ of x)if(typeof _.loadEntries=="function")try{let O=await Promise.resolve(_.loadEntries());O.entries.length>0&&a.size===0&&(a.restore(O.entries),R.set(_,O.entries.length),u());break}catch{}})();let S=d.subscribe(_=>{for(let O of _){if(O[0]!==E)continue;let D=O[1];for(let M of x){let N=R.get(M)??0;if(D.length<N){try{let j=M.appendEntries(D);j instanceof Promise&&j.catch(()=>{})}catch{}R.set(M,D.length);continue}if(D.length===N)continue;let P=D.slice(N);R.set(M,D.length);try{let j=M.appendEntries(P);j instanceof Promise&&j.catch(()=>{})}catch{}}}});return()=>S()},disposeAllViews(){for(let x of c.values())x.dispose();c.clear();for(let x of l.values())x.dispose();l.clear();for(let x of p.values())x.dispose();p.clear()},dispose(){for(let x of c.values())x.dispose();c.clear();for(let x of l.values())x.dispose();l.clear();for(let x of p.values())x.dispose();p.clear()}};return k}var bd=new WeakMap;function vp(t){let e=bd.get(t);if(e)return e;let n=t.map(c=>c.cache??[]),r=n.flat(),o=C(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]===E)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=ne(o),d=!1,u={node:o,dispose(){if(!d){d=!0;for(let c of i)c?.();i.length=0,a(),bd.delete(t)}}};return bd.set(t,u),u}function Fn(t,e){let n=t.cache??0;return n>=e?!1:(t.down([[oe],[E,n+1]]),!0)}var vd=jt((t,e)=>{t("observe"),t("signal"),e("write")});function at(t){let e=Ue([],{name:t.name,maxSize:t.retainedLimit??1024,guard:t.guard??vd,...t.versioning!=null?{versioning:t.versioning}:{}});return e.withLatest(),t.graph&&t.graph.add(e.entries,{name:t.name}),e}function Td(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))Td(t[e]);return Object.freeze(t)}var Tp=new WeakSet;function Kt(t){let e=t.cache,n=typeof e=="number"&&Number.isFinite(e);!n&&e!==void 0&&!Tp.has(t)&&(Tp.add(t),console.warn(`bumpCursor: cursor cache held a non-numeric value (${String(e)}); resetting to 0. Causes include: a snapshot codec round-tripping the cursor as a string / null / NaN, OR a malformed initial seed (e.g. state<number>(NaN)). Audit consumers may see colliding seq values after this point.`));let o=(n?e:0)+1;return t.down([[oe],[E,o]]),o}function hr(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 Le(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(Td):o,i=ie(),a=e.seq?Kt(e.seq):void 0;try{let d=t(...s);return e.audit&&e.onSuccess&&hr(e.audit,e.onSuccess,s,d,{t_ns:i,seq:a},e.handlerVersion),d}catch(d){if(e.audit&&e.onFailure){let u=d instanceof Error?d.name:typeof d;hr(e.audit,e.onFailure,s,d,{t_ns:i,seq:a,errorType:u},e.handlerVersion)}throw d}}}function gt(t,e){let n=e.freeze??!0;return function(...o){let s=n?o.map(Td):o,i=ie(),a,d,u=!1,c;try{Z(()=>{e.seq&&(c=Kt(e.seq));try{a=t(...s),e.audit&&e.onSuccess&&hr(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.audit&&e.onFailure){let p=d instanceof Error?d.name:typeof d;hr(e.audit,e.onFailure,s,d,{t_ns:i,seq:c,errorType:p},e.handlerVersion)}throw u?d:l}return a}}function vt(t,e,n=0){let r=C(n,{name:e,describeKind:"state"});return t.add(r,{name:e}),r}function zs(t,e,n,r=0){let o={},s=new Y(e);for(let i of n){let a=C(r,{name:i,describeKind:"state"});s.add(a,{name:i}),o[i]=a}return t.mount(e,s),o}bt();var dn=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},Hs=class extends dn{constructor(n,r){super(`Duplicate ${n} registration: "${r}"`);this.kind=n;this.registrationName=r}},Ws=class extends dn{constructor(n,r,o){super(`Command "${n}" emitted undeclared event "${r}". Declared emits: [${o.join(", ")}]`);this.commandName=n;this.eventName=r;this.declaredEmits=o}},Us=class extends dn{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}},Js=class extends dn{constructor(n){super(`Unknown command: "${n}". Register with command() first.`);this.commandName=n}},mo=class extends dn{constructor(n,r){super(`Command handler "${n}" threw: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.commandName=n}};var go=class extends dn{constructor(n,r){super(`Projection "${n}" rebuild failed: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.projectionName=n}};ut();pe();var Ih=jt((t,e)=>{t("write"),t("signal"),e("observe")}),Ph=jt((t,e)=>{t("observe"),t("signal"),e("write")}),wp=jt((t,e)=>{t("observe"),t("signal"),e("write")});function ho(t,e){return we("cqrs",t,e)}function kp(t){if(t===null||typeof t!="object"||Object.isFrozen(t))return t;for(let e of Object.keys(t))kp(t[e]);return Object.freeze(t)}var Dh=t=>`${t.type}::${t.aggregateId??"__default__"}`,Gh=t=>t.commandName,Fh=t=>t.eventType,Ys=class extends Y{_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=vt(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:ie()})}}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))}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=Ue([],{name:e,versioning:0,maxSize:this._retainedLimit});o.withLatest();let s=o.entries,i=A([s],([a])=>a,{name:e,describeKind:"state",meta:ho("event",{event_name:e}),guard:wp,initial:s.cache});return this.add(i,{name:e}),this._keepaliveDisposers.push(ne(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=Ue([],{name:i,versioning:0,maxSize:this._retainedLimit});a.withLatest();let d=a.entries,u=A([d],([f])=>f,{name:i,describeKind:"state",meta:ho("event_aggregate",{event_name:e,aggregate_id:n}),guard:wp,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(ne(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?kp(n):n,u={type:e,payload:d,timestampNs:ie(),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 Hs("command",e);let r=typeof n=="function"?{handler:n}:n,o=C(void 0,{name:e,describeKind:"state",meta:{...ho("command",{command_name:e}),error:null},guard:Ih});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 Js(e);if(r?.aggregateId!==void 0&&r.expectedAggregateVersion!==void 0&&o.emits!==void 0){let u=0;for(let c of o.emits){let l=this._aggregateVersions.get(`${c}::${r.aggregateId}`);l!==void 0&&l>u&&(u=l)}if(u!==r.expectedAggregateVersion)throw new Us(r.aggregateId,r.expectedAggregateVersion,u)}let s=this.resolve(e),i=[],a=!1,d=u=>{s.emit(u,{internal:!0});try{o.handler(u,{emit:(c,l)=>{if(o.emits!==void 0&&!o.emits.includes(c))throw new Ws(e,c,o.emits);i.push(c),this._appendEvent(c,l,{...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})}catch(c){throw a=!0,c}};try{gt(d,{audit:this.dispatches,seq:this._dispatchSeqCursor,freeze:this._freezeCommandPayload,onSuccess:([u],c,{t_ns:l,seq:p})=>({commandName:e,payload:u,outcome:"success",emittedEvents:[...i],t_ns:l,seq:p??0,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}),onFailure:([u],c,{t_ns:l,seq:p,errorType:f})=>{let m=c instanceof mo?c:new mo(e,c);return{commandName:e,payload:u,outcome:"failure",error:m,errorType:f,emittedEvents:[...i],t_ns:l,seq:p??0,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{}}}})(n)}catch(u){throw a&&s.meta.error.emit(u,{internal:!0}),u}}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(_=>(this._eventLogs.has(_)||this.event(_),this._eventLogs.get(_).node));function c(_){_.sort((O,D)=>O.timestampNs-D.timestampNs||O.seq-D.seq||(O.aggregateId??"").localeCompare(D.aggregateId??""))}function l(_){let O=[];for(let D of _)O.push(...D);return c(O),O}let p=u.map(_=>_.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(_){if(d?.save){if(w+=1,w>=v){w=0,T!==void 0&&(clearTimeout(T),T=void 0);let O=d.save(_);O instanceof Promise&&O.catch(()=>{});return}T!==void 0&&clearTimeout(T),T=setTimeout(()=>{T=void 0,w=0;let O=d.save(_);O instanceof Promise&&O.catch(()=>{})},b)}}let x=A(u,_=>{let O=l(_),D;if(i==="replay"){let M=a?Object.freeze(O):O;D=o(s,M)}else{let M=O.slice(h);h=O.length;let N=a?Object.freeze(M):M;D=o(g,N),g=D}return k(D),D},{name:n,describeKind:"derived",meta:ho("projection",{projection_name:n,source_events:r}),guard:Ph,initial:y});return this.add(x,{name:n}),this._keepaliveDisposers.push(ne(x)),this._keepaliveDisposers.push(()=>{T!==void 0&&(clearTimeout(T),T=void 0)}),this._projections.add(n),{node:x,rebuild:async _=>{try{let O=_?.pageSize??1e3,D=_?.fromTier??this._attachedEventTiers[0]?.[0],M=l(u.map(P=>P.cache??[])).length,N=s;if(d?.load){let P=await d.load();P!==void 0&&(N=P)}if(!D||!D.loadEntries){let P=l(u.map(G=>G.cache??[])),j=a?Object.freeze(P):P;N=o(N,j)}else{let P=new Set(r),j,G=!1;for(;!G;){let V=await D.loadEntries({cursor:j,pageSize:O}),$=[...V.entries].filter(F=>P.has(F.type));c($);let q=a?Object.freeze($):$;N=o(N,q),j=V.cursor,G=!j||V.entries.length===0}}if(i==="scan"){let P=l(u.map(G=>G.cache??[])),j=P.slice(M);if(j.length>0){let G=a?Object.freeze(j):j;N=o(N,G)}g=N,h=P.length}return x.emit(N,{internal:!0}),N}catch(O){throw new go(n,O)}},reset:async()=>{try{let _=s;if(d?.load){let N=await d.load();N!==void 0&&(_=N)}let O=l(u.map(N=>N.cache??[])),D=a?Object.freeze(O):O,M=o(_,D);return i==="scan"&&(g=M,h=O.length),x.emit(M,{internal:!0}),M}catch(_){throw new go(n,_)}}}}saga(e,n,r,o={}){let s=n.map(m=>(this._eventLogs.has(m)||this.event(m),this._eventLogs.get(m).node)),i=zs(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 m of n){let h=i[m];c.set(m,h.cache??0);let g=h.subscribe(y=>{for(let b of y)b[0]===E&&c.set(m,b[1])});this._keepaliveDisposers.push(g)}let l=Le((m,h)=>{r(m)},{audit:a,freeze:!1,...o.handlerVersion!==void 0?{handlerVersion:o.handlerVersion}:{},onSuccess:([m,h],g,{t_ns:y})=>({eventType:h,outcome:"success",aggregateId:m.aggregateId,event:m,t_ns:y}),onFailure:([m,h],g,{t_ns:y,errorType:b})=>({eventType:h,outcome:"failure",error:g,errorType:b,aggregateId:m.aggregateId,event:m,t_ns:y})}),p={},f=Q(s,(m,h)=>{let g=p.n.meta.error;for(let y=0;y<m.length;y++){let b=m[y];if(b==null||b.length===0)continue;let v=b.at(-1);if(!v)continue;let T=n[y],w=i[T],k=c.get(T)??0;if(v.length>k){let x=v.slice(k),R=k;for(let S of x){let _=S;if(d!==void 0&&_.aggregateId!==d){R+=1;continue}try{l(_,T),g.emit(null,{internal:!0}),R+=1}catch(O){if(g.emit(O,{internal:!0}),u==="hold")break;R+=1}}w.emit(R)}}},{name:e,describeKind:"effect",meta:{...ho("saga",{saga_name:e,source_events:n}),error:null}});return p.n=f,this.add(f,{name:e}),this._keepaliveDisposers.push(ne(f)),this._sagas.add(e),{node:f,invocations:a,audit:a,cursors:i}}};function wd(t,e){let n=new Ys(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("cqrs",He(s)),n}var xd=class{constructor(e){this.graph=e}onModuleDestroy(){this.graph.destroy()}},Rd=class{graph=new Y("request");onModuleDestroy(){this.graph.destroy()}},xp,kd;xp=[(0,yo.Module)({})];var un=class un{static forRoot(e){let n=e??{},r=n.name??"root",o=[{provide:yt,useFactory:()=>{let s=new Y(r);return n.build&&n.build(s),n.snapshot&&s.restore(n.snapshot),s}},{provide:Symbol.for("graphrefly:root-lifecycle"),useFactory:s=>new xd(s),inject:[yt]},{provide:Gn,useFactory:(s,i)=>new Gn(s,i),inject:[yt,Rp.ModuleRef]}];if(n.nodes)for(let s of n.nodes)o.push({provide:wt(s),useFactory:i=>i.resolve(s),inject:[yt]});return n.requestScope&&o.push({provide:Symbol.for("graphrefly:request-lifecycle"),useFactory:()=>new Rd,scope:yo.Scope.REQUEST},{provide:xn,useFactory:s=>s.graph,inject:[Symbol.for("graphrefly:request-lifecycle")],scope:yo.Scope.REQUEST}),{module:un,global:!0,providers:o,exports:[yt,...(n.nodes??[]).map(wt),...n.requestScope?[xn]:[]]}}static forFeature(e){let n=[{provide:pt(e.name),useFactory:r=>{let o=new Y(e.name);return e.build&&e.build(o),e.snapshot&&o.restore(e.snapshot),r.mount(e.name,o),o},inject:[yt]}];if(e.nodes)for(let r of e.nodes)n.push({provide:wt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[pt(e.name)]});return{module:un,providers:n,exports:[pt(e.name),...(e.nodes??[]).map(r=>wt(`${e.name}::${r}`))]}}static forCqrs(e){let n=[{provide:pt(e.name),useFactory:r=>{let o=wd(e.name,e.cqrs);return e.eventStorage&&o.attachEventStorage(e.eventStorage),e.build&&e.build(o),r.mount(e.name,o),o},inject:[yt]}];if(e.nodes)for(let r of e.nodes)n.push({provide:wt(`${e.name}::${r}`),useFactory:o=>o.resolve(r),inject:[pt(e.name)]});return{module:un,providers:n,exports:[pt(e.name),...(e.nodes??[]).map(r=>wt(`${e.name}::${r}`))]}}};kd=Zu(null),un=nc(kd,0,"GraphReflyModule",xp,un),tc(kd,1,un);var Xs=un;var ei={};Ee(ei,{useStore:()=>$h,useSubscribe:()=>Sp,useSubscribeRecord:()=>jh});var qt=require("react");se();function Sp(t){return(0,qt.useSyncExternalStore)(e=>{let n=!1,r=t.subscribe(()=>{n||e()});return()=>{n=!0,r()}},()=>t.cache,()=>t.cache)}function $h(t){let e=Sp(t),n=(0,qt.useCallback)(r=>{t.down([[oe],[E,r]])},[t]);return[e,n]}function jh(t,e){let n=(0,qt.useRef)(e);n.current=e;let r=(0,qt.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]===E||m[0]===H);!a&&f&&c(t.cache??[])});return c(t.cache??[]),()=>{a=!0,l(),u()}},getSnapshot:()=>s}},[t]);return(0,qt.useSyncExternalStore)(r.subscribe,r.getSnapshot,r.getSnapshot)}var ni={};Ee(ni,{Signal:()=>Bh});Oe();se();re();var yr=[];function ti(t){let e=t.cache;return t.subscribe(r=>{for(let[o,s]of r)o===E&&(e=s)})(),e}var Sd=class{_node;_equals;constructor(e,n){this._equals=n?.equals??Object.is,this._node=C(e,{...n,resubscribable:!0,resetOnTeardown:!0})}get(){let e=yr[yr.length-1];return e?(this._node.status==="sentinel"&&ti(this._node),e(this._node)):this._node.status==="sentinel"?ti(this._node):this._node.cache}set(e){this._equals(this.get(),e)||Z(()=>{this._node.down([[oe],[E,e]])})}},Nd=class{_node;constructor(e,n){this._node=kn(r=>{yr.push(r);try{return e()}finally{yr.pop()}},{...n,describeKind:"derived",resubscribable:!0,resetOnTeardown:!0})}get(){let e=yr[yr.length-1];return e?(this._node.status==="sentinel"&&ti(this._node),e(this._node)):this._node.status==="sentinel"?ti(this._node):this._node.cache}},Bh={State:Sd,Computed:Nd,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===E){if(r){r=!1;continue}n.data?.(i)}s===L&&n.error?.(i),s===I&&n.complete?.()}})}};var ri={};Ee(ri,{useStore:()=>Vh,useSubscribe:()=>Np,useSubscribeRecord:()=>Kh});var zt=require("solid-js");se();function Np(t){let[e,n]=(0,zt.createSignal)(t.cache,{equals:!1}),r=t.subscribe(()=>{n(()=>t.cache)});return(0,zt.getOwner)()?(0,zt.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 Vh(t){return[Np(t),r=>{t.down([[oe],[E,r]])}]}function Kh(t,e){let[n,r]=(0,zt.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]===E||c[0]===H)&&a(t.cache??[])});return a(t.cache??[]),(0,zt.getOwner)()?(0,zt.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 oi={};Ee(oi,{useStore:()=>zh,useSubscribe:()=>qh,useSubscribeRecord:()=>Hh});se();function qh(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n}}}function zh(t){return{subscribe(e){let n=t.subscribe(()=>{e(t.cache)});return e(t.cache),n},set(e){t.down([[oe],[E,e]])},update(e){let n=e(t.cache);t.down([[oe],[E,n]])}}}function Hh(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]===E||u[0]===H)&&i(t.cache??[])});return i(t.cache??[]),()=>{a(),o()}}}}var si={};Ee(si,{useStore:()=>Uh,useSubscribe:()=>Wh,useSubscribeRecord:()=>Jh});var Je=require("vue");se();function Wh(t){let e=(0,Je.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Je.getCurrentScope)()?(0,Je.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useSubscribe called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Je.readonly)(e)}function Uh(t){let e=(0,Je.shallowRef)(t.cache),n=t.subscribe(()=>{e.value=t.cache});return(0,Je.getCurrentScope)()?(0,Je.onScopeDispose)(()=>n()):typeof console<"u"&&console.warn("[graphrefly-ts] useStore called outside a Vue scope \u2014 subscription will not be auto-disposed."),(0,Je.computed)({get:()=>e.value,set:r=>{t.down([[oe],[E,r]])}})}function Jh(t,e){let n=(0,Je.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,Je.watch)(()=>[...(typeof t=="function"?t():(0,Je.isRef)(t)?t.value:t)??[]],a=>s(a??[]),{immediate:!0}),(0,Je.getCurrentScope)()?(0,Je.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,Je.readonly)(n)}var ii={};Ee(ii,{create:()=>Qh});se();re();Fe();var Yh=()=>!1;function Qh(t){let e=new Y("zustand"),n=C(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===E){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 Fd={};Ee(Fd,{CircuitOpenError:()=>Et,ContentAddressedMissError:()=>wo,DEFAULT_AUDIT_GUARD:()=>vd,NS_PER_MS:()=>et,NS_PER_SEC:()=>ct,NativeIndexBackend:()=>Ro,NativeListBackend:()=>So,NativeLogBackend:()=>fo,NativeMapBackend:()=>vo,NativePubSubBackend:()=>xo,RateLimiterOverflowError:()=>In,ResettableTimer:()=>Ie,TimeoutError:()=>Pn,appendAudit:()=>hr,appendLogStorage:()=>Pd,audit:()=>Ml,awaitSettled:()=>Bs,budgetGate:()=>Zt,buffer:()=>Ol,bufferCount:()=>Al,bufferTime:()=>Ll,bumpCursor:()=>Kt,cached:()=>up,canonicalJson:()=>ko,cascadingCache:()=>Nf,catchError:()=>Kl,checkpointToRedis:()=>bf,checkpointToS3:()=>yf,circuitBreaker:()=>St,combine:()=>sd,combineLatest:()=>jl,concat:()=>kl,concatMap:()=>Sl,constant:()=>_s,contentAddressedStorage:()=>ui,createAuditLog:()=>at,createTransport:()=>ln,createWatermarkController:()=>gr,csvRows:()=>Xp,debounce:()=>ad,debounceTime:()=>Bl,decay:()=>Pt,decorrelatedJitter:()=>Cs,defer:()=>ip,delay:()=>El,deserializeError:()=>Vn,dictKv:()=>$f,dictSnapshot:()=>jf,distill:()=>Tr,distinctUntilChanged:()=>vl,domainMeta:()=>we,elementAt:()=>hl,empty:()=>rp,escapeRegexChar:()=>pd,exhaustMap:()=>Rl,exponential:()=>Os,externalBundle:()=>ai,externalProducer:()=>$n,fallback:()=>fr,fibonacci:()=>As,filter:()=>xt,find:()=>gl,first:()=>Ls,firstValueFrom:()=>it,firstWhere:()=>Gs,flatMap:()=>Nl,forEach:()=>an,fromAny:()=>X,fromAsyncIter:()=>co,fromCSV:()=>Qp,fromClickHouseWatch:()=>nf,fromCron:()=>Fs,fromDrizzle:()=>xf,fromEvent:()=>np,fromHTTP:()=>Ad,fromHTTPPoll:()=>Gp,fromHTTPStream:()=>Dp,fromIter:()=>$s,fromKafka:()=>Wp,fromKysely:()=>Rf,fromMCP:()=>jp,fromNATS:()=>sf,fromNDJSON:()=>tf,fromOTel:()=>Bp,fromPrisma:()=>kf,fromPrometheus:()=>Hp,fromPromise:()=>mr,fromPulsar:()=>rf,fromRabbitMQ:()=>df,fromRaf:()=>tp,fromRedisStream:()=>Jp,fromSSE:()=>Pp,fromSqlite:()=>vf,fromSqliteCursor:()=>Tf,fromStatsD:()=>qp,fromSyslog:()=>Vp,fromTimer:()=>st,fromWebSocket:()=>Od,fromWebSocketReconnect:()=>$p,fromWebhook:()=>_p,globToRegExp:()=>Zl,interval:()=>Dl,jsonCodec:()=>kr,jsonCodecFor:()=>Df,keepalive:()=>ne,kvStorage:()=>mi,last:()=>ml,lightMutation:()=>Le,linear:()=>Ms,lru:()=>Id,makeHttpError:()=>Mt,map:()=>no,matchesAnyPattern:()=>ep,matchesCron:()=>ps,memoryAppendLog:()=>Ff,memoryBackend:()=>Eo,memoryKv:()=>_o,memorySnapshot:()=>Gf,merge:()=>It,mergeMap:()=>id,mergeReactiveLogs:()=>vp,nameToSignal:()=>jn,ndjsonRows:()=>Zp,never:()=>op,nodeSignal:()=>Vs,of:()=>fd,onFirstData:()=>oo,pairwise:()=>Tl,parseCron:()=>ls,parsePrometheusText:()=>Cd,parseSSEStream:()=>Ht,parseStatsD:()=>zp,parseSyslog:()=>Kp,pausable:()=>Fl,pubsub:()=>Af,race:()=>xl,rateLimiter:()=>Cn,reactiveCounter:()=>lp,reactiveIndex:()=>If,reactiveList:()=>ci,reactiveLog:()=>Ue,reactiveMap:()=>Ke,reactiveSink:()=>Qe,reduce:()=>ll,registerCursor:()=>vt,registerCursorMap:()=>zs,repeat:()=>Gl,replay:()=>js,rescue:()=>so,resolveBackoffPreset:()=>Mn,retry:()=>Rt,sample:()=>_l,scan:()=>cl,serializeError:()=>Bn,share:()=>dp,shareReplay:()=>cp,signalToName:()=>cn,singleFromAny:()=>li,singleNodeFromAny:()=>Pf,skip:()=>od,snapshotStorage:()=>fi,sortJsonValue:()=>No,stableJsonString:()=>pi,stratify:()=>Mo,switchMap:()=>ke,take:()=>ro,takeUntil:()=>fl,takeWhile:()=>pl,tap:()=>yl,tapFirst:()=>bl,throttle:()=>dd,throttleTime:()=>Vl,throwError:()=>sp,timeout:()=>Ln,toArray:()=>ap,toCSV:()=>cf,toClickHouse:()=>lf,toFile:()=>Ld,toHTTP:()=>Mp,toKafka:()=>Up,toLoki:()=>gf,toMongo:()=>mf,toNATS:()=>af,toObservable:()=>cs,toPostgres:()=>ff,toPulsar:()=>of,toRabbitMQ:()=>uf,toReadableStream:()=>Ip,toRedisStream:()=>Yp,toS3:()=>pf,toSSE:()=>Cp,toSSEBytes:()=>Lp,toSqlite:()=>wf,toTempo:()=>hf,toWebSocket:()=>Fp,tokenBucket:()=>Vt,topologyDiff:()=>lr,tryIncrementBounded:()=>Fn,valve:()=>$l,verifiable:()=>Mf,window:()=>Pl,windowCount:()=>Cl,windowTime:()=>Il,withBreaker:()=>An,withLatestFrom:()=>On,withMaxAttempts:()=>rd,withStatus:()=>on,workerBridge:()=>Dd,workerSelf:()=>Gd,wrapMutation:()=>gt,zip:()=>wl});Oe();Re();se();Me();re();Oe();se();re();function Ep(t){return{describeKind:"producer",...t}}function $n(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{}}},Ep(e))}function ai(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()}),Ep({...h,name:m}));a[f]=g,d.push(g)}let c={};for(let f of e)c[f]=m=>{r&&a[f].down([[E,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())}})}We();se();Me();re();to();ys();var _d=class{ring;arr;constructor(e){e===Number.POSITIVE_INFINITY||e<=0?(this.arr=[],this.ring=null):(this.ring=new Bt(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 bo(t){return t instanceof Error?t:new Error(String(t))}function Xh(t){return t===void 0?null:typeof t=="string"?Mn(t):t}function Qe(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=Xh(o?.backoff??(g>1?"exponential":void 0)),b=o?.shouldRetry??(()=>!0),v=f!==void 0||i<Number.POSITIVE_INFINITY||a>0,T=K=>n?`${n}::${K}`:void 0,w=C(void 0,{equals:()=>!1,name:T("sent")}),k=C(null,{name:T("failed")}),x=C(0,{name:T("inFlight")}),R=C(null,{name:T("errors")}),S=v?C(0,{name:T("buffered")}):void 0,_=s?C(!1,{name:T("paused")}):void 0,O=0,D=K=>{O+=K,x.down([[E,O]])},M=K=>{try{r?.(K)}catch{}try{R.down([[E,K]])}catch{}},N=new Set,P=K=>{N.add(K);let ae=()=>N.delete(K);K.then(ae,ae)},j=(K,ae,fe)=>{let Ne=y?y(ae-1,fe,null):0,xe=Ne==null?0:typeof Ne=="number"&&Ne>0?Ne:0,qe=Math.max(1,Math.ceil(xe/1e6));return new Promise(me=>{setTimeout(()=>me(K()),qe)})},G=K=>K!=null&&typeof K=="object"&&typeof K.then=="function",V=K=>{let ae;try{ae=d?d(K):K}catch(me){let le=bo(me);return M({stage:"serialize",error:le,value:K}),k.down([[E,{value:K,error:le,attempts:0}]]),Promise.resolve()}let fe=0,Ne=me=>{D(-1);let le=bo(me);if(M({stage:"send",error:le,value:K,attempt:fe}),!(fe<g&&b(le,fe))){k.down([[E,{value:K,error:le,attempts:fe}]]);return}return j(qe,fe,le)},xe=()=>{D(-1),w.down([[E,K]])};function qe(){fe+=1,D(1);let me;try{me=p(ae,h)}catch(le){return Ne(le)??Promise.resolve()}return G(me)?me.then(xe,le=>Ne(le)):(xe(),Promise.resolve())}return qe()},$=s?.maxBuffer??Number.POSITIVE_INFINITY,q=new _d($),F,B=!1,te=()=>{S?.down([[E,q.length]])},de=K=>{_&&_.down([[E,K]])},J=s?.strategy??"drop-oldest",ce=(K,ae)=>{let fe={value:K,payload:ae};if(q.length<$)return q.push(fe),te(),!0;if(J==="drop-oldest"){let xe=q.shift();return q.push(fe),te(),de(!0),k.down([[E,{value:xe.value,error:new Error("backpressure: buffer overflow \u2014 dropped oldest"),attempts:0}]]),!0}if(J==="drop-newest")return de(!0),k.down([[E,{value:K,error:new Error("backpressure: buffer overflow \u2014 dropped newest"),attempts:0}]]),!1;let Ne=new Error("backpressure: buffer overflow");return M({stage:"send",error:Ne,value:K}),k.down([[E,{value:K,error:Ne,attempts:0}]]),de(!0),!1},Ce=K=>{let ae=0,fe=K.map(me=>me.payload),Ne=me=>{D(-1);let le=bo(me);if(M({stage:"send",error:le,value:K.map(yn=>yn.value),attempt:ae}),!(ae<g&&b(le,ae))){for(let{value:yn}of K)k.down([[E,{value:yn,error:le,attempts:ae}]]);return}return j(qe,ae,le)},xe=()=>{D(-1);for(let{value:me}of K)w.down([[E,me]])};function qe(){ae+=1,D(1);let me;try{me=f(fe,h)}catch(le){return Ne(le)??Promise.resolve()}return G(me)?me.then(xe,le=>Ne(le)):(xe(),Promise.resolve())}return qe()},rt=async K=>{for(let ae of K)await Xe(ae.value,ae.payload)},Xe=(K,ae)=>{let fe=0,Ne=me=>{D(-1);let le=bo(me);if(M({stage:"send",error:le,value:K,attempt:fe}),!(fe<g&&b(le,fe))){k.down([[E,{value:K,error:le,attempts:fe}]]);return}return j(qe,fe,le)},xe=()=>{D(-1),w.down([[E,K]])};function qe(){fe+=1,D(1);let me;try{me=p(ae,h)}catch(le){return Ne(le)??Promise.resolve()}return G(me)?me.then(xe,le=>Ne(le)):(xe(),Promise.resolve())}return qe()},U=()=>{if(B||q.length===0)return Promise.resolve();let K=q.drain();if(te(),de(!1),f!==void 0){let fe=Ce(K);return P(fe),fe}let ae=rt(K);return P(ae),ae},ue=()=>{F!==void 0||B||a<=0||(F=setTimeout(()=>{F=void 0,U()},a))},De=t.subscribe(K=>{for(let ae of K){let fe=ae[0];if(fe!==E)try{c?.(ae)}catch{}if(fe===E){let Ne=ae[1];if(v){let xe;if(d)try{xe=d(Ne)}catch(me){let le=bo(me);M({stage:"serialize",error:le,value:Ne}),k.down([[E,{value:Ne,error:le,attempts:0}]]);continue}else xe=Ne;if(!ce(Ne,xe))continue;q.length>=i?U():ue()}else{let xe=V(Ne);P(xe)}}else je.messageTier(fe)>=3&&v&&(F!==void 0&&(clearTimeout(F),F=void 0),U())}}),$e;if(u){let K=!1;$e=u.subscribe(ae=>{if(!K){K=!0;return}ae.length>0&&!Ve&&Se()})}let Ve=!1,Se=()=>{if(Ve)return;Ve=!0,F!==void 0&&(clearTimeout(F),F=void 0),v&&U(),B=!0,$e?.(),De();let K=ae=>{try{ae.down([[ge]])}catch{}};K(R),K(k),K(w),K(x),S&&K(S),_&&K(_);try{l?.()}catch{}},ee={dispose:Se,sent:w,failed:k,inFlight:x,errors:R};return v&&(ee.buffered=S,ee.flush=async()=>{B||(await U(),await Promise.all(N))}),_&&(ee.paused=_),ee}sn();pe();function _t(t){return{describeKind:"producer",...t}}function Od(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()}},_t(o))}function _p(t,e){return $n(t,e)}function Ad(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=C(0,{name:`${c.name??"http"}/fetchCount`}),p=C(0,{name:`${c.name??"http"}/lastUpdated`}),f=C(!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 x=>{if(clearTimeout(k),!w)return;if(!x.ok)throw new Error(`HTTP ${x.status}: ${x.statusText}`);let R=await s(x);w&&(Z(()=>{m+=1,l.down([[E,m]]),p.down([[E,ie()]]),f.down([[E,!0]]),v.emit(R)}),d&&v.down([[I]]))}).catch(x=>{clearTimeout(k),w&&(x&&x.name==="AbortError"||v.down([[L,x]]))}),()=>{w=!1,T.abort()}},y=z(v=>g({emit:T=>v.emit(T),down:T=>v.down(T)}),{..._t(c),resubscribable:u});return{...on(y),fetchCount:l,lastUpdated:p,fetched:f}}function Mp(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?Qe(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)}}):Qe(t,{onTransportError:l,retry:c,serialize:s,send:async m=>{await p(m)}})}function Op(t){return Symbol.keyFor(t)??t.description??"message"}function br(t,e){return typeof t=="string"?t:e(t)}function Ap(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 Cp(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=Op}=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(Ap(T,w)))},v=()=>{m||y()};g=t.subscribe(T=>{for(let w of T){let k=w[0];if(!(je.isLocalOnly(k)&&!(k===oe&&a))){if(k===E){b(r,br(w[1],n));continue}if(k===L){b(o,br(w[1],n)),y();return}if(k===I){b(s),y();return}!i&&k===H||b(c(k),w.length>1?br(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 Lp(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=Op}=e??{},l=new TextEncoder;return z(p=>{let f=!0,m,h=(b,v)=>{f&&p.emit(l.encode(Ap(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(!(je.isLocalOnly(T)&&!(T===oe&&a))){if(T===E){h(r,br(v[1],n));continue}if(T===L){h(o,br(v[1],n)),f=!1,p.down([[I]]);return}if(T===I){h(s),f=!1,p.down([[I]]);return}!i&&T===H||h(c(T),v.length>1?br(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 k=w.indexOf(":"),
|
|
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 Ip(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===E)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*Ht(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(":"),x=k<0?w:w.slice(0,k),R=k<0?"":w.slice(k+1);switch(R.startsWith(" ")&&(R=R.slice(1)),x){case"event":i=R;break;case"data":a.push(R);break;case"id":R.includes("\0")||(d=R);break;case"retry":{let S=Number(R);Number.isFinite(S)&&(u=S);break}}},f=(w,k)=>{s+=o.decode(w,{stream:!k});let x=s.split(/\r?\n/);s=x.pop()??"";for(let R of x)p(R)},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 Pp(t,e){let{parse:n,...r}=e??{};return z(o=>{let s=!0,i=new AbortController;return(async()=>{try{for await(let d of Ht(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()}},_t(r))}function Dp(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()}},_t(i))}function Gp(t,e){let{intervalMs:n=5e3,...r}=e??{};return ke(st(n,{period:n}),()=>Ad(t,{...r,completeAfterFetch:!0}).node)}function Fp(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=Qe(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 $p(t,e){let{parse:n,maxRetries:r,backoff:o="exponential",closeOnTeardown:s=!0,...i}=e??{};return Rt(()=>Od(t(),{parse:n,closeOnTeardown:s,...i}),{count:r,backoff:o})}function jp(t,e){let{method:n="notifications/message",onDisconnect:r,...o}=e??{};return $n(({emit:s,error:i})=>(t.setNotificationHandler(n,a=>s(a)),r?.(a=>i(a??new Error("MCP client disconnected"))),()=>t.setNotificationHandler(n,()=>{})),o)}function Bp(t,e){return ai(({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 Vp(t,e){return $n(t,e)}function Kp(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=ie();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:ie()}}function qp(t,e){return $n(t,e)}var Zh={c:"counter",g:"gauge",ms:"timer",h:"histogram",s:"set",d:"distribution"};function zp(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=Zh[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:ie()}}function Hp(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 ke(st(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=Cd(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 Cd(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=ey(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:ie()})}return e}function ey(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 Wp(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:ie()})}})}catch(u){a&&i.down([[L,u]])}})(),()=>{a=!1}},_t(s))}function Up(t,e,n,r){let{serialize:o=a=>JSON.stringify(a),keyExtractor:s,onTransportError:i}=r??{};return Qe(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 Jp(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:ie()})}catch(l){if(!d)return;a.down([[L,l]]);return}})(),()=>{d=!1}},_t(i))}function Yp(t,e,n,r){let{serialize:o=a=>["data",JSON.stringify(a)],maxLen:s,onTransportError:i}=r??{};return Qe(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 Qp(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(d=>ef(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}},_t(i))}function Xp(t,e){let{delimiter:n=",",hasHeader:r=!0,columns:o,parseLine:s,...i}=e??{},a=s??(d=>ef(d,n));return Q([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 Zp(t,e){return Q([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 ef(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 tf(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}},_t(e))}function nf(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 ke(st(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 rf(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:ie()};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}},_t(s))}function of(t,e,n){let{serialize:r=a=>Buffer.from(JSON.stringify(a)),keyExtractor:o,propertiesExtractor:s,onTransportError:i}=n??{};return Qe(t,{onTransportError:i,send:async a=>{await e.send({data:r(a),partitionKey:o?.(a),properties:s?.(a)})}})}function sf(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:ie()})}d&&a.down([[I]])}catch(l){d&&a.down([[L,l]])}})(),()=>{d=!1}},_t(i))}function af(t,e,n,r){let o=new TextEncoder,{serialize:s=a=>o.encode(JSON.stringify(a)),onTransportError:i}=r??{};return Qe(t,{onTransportError:i,send:a=>{e.publish(n,s(a))}})}function df(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:ie()};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)}},_t(i))}function uf(t,e,n,r){let{serialize:o=a=>Buffer.from(JSON.stringify(a)),routingKeyExtractor:s=()=>"",onTransportError:i}=r??{};return Qe(t,{onTransportError:i,send:a=>{let d=s(a),u=o(a);e.publish(n,d,u)}})}function Ld(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?Qe(t,{onTransportError:i,batchSize:s,flushIntervalMs:o,serialize:r,sendBatch:l=>{e.write(l.join(""))}}):Qe(t,{onTransportError:i,serialize:r,send:l=>{e.write(l)}}),c=u.dispose;return u.dispose=()=>{c();try{e.end()}catch{}},u}function Md(t,e){return t.includes(e)||t.includes('"')||t.includes(`
|
|
27
|
+
`)?`"${t.replace(/"/g,'""')}"`:t}function cf(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 Ld(t,e,{serialize:f=>{if(!l&&s){l=!0;let m=r.map(g=>Md(g,o)).join(o),h=r.map(g=>Md(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=>Md(i(f,m),o)).join(o)}
|
|
30
|
+
`},flushIntervalMs:a,batchSize:d,onTransportError:u,...c})}function lf(t,e,n,r){let{batchSize:o=1e3,flushIntervalMs:s=5e3,format:i="JSONEachRow",transform:a=u=>u,onTransportError:d}=r??{};return Qe(t,{onTransportError:d,batchSize:o,flushIntervalMs:s,serialize:a,sendBatch:async u=>{await e.insert({table:n,values:u,format:i})}})}function pf(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 Qe(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,ie());await e.putObject({Bucket:n,Key:m,Body:f,ContentType:c})}})}function af(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 Ye(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function df(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return Ye(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function uf(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return Ye(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:d,labels:u}=a,c=`${ie()}`;await e.push({streams:[{stream:u,values:[[c,d]]}]})}})}function cf(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return Ye(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function lf(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(ie()/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 pf(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 ff(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return H(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 mf(t,e,n){let{mapRow:r=i=>i,params:o,...s}=n??{};return H(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 gf(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 Ye(t,{onTransportError:s,serialize:u,send:M=>{let C=M;e.query(C.sql,C.params)}});let c=A(null),l=A(void 0,{equals:()=>!1}),p=A(null),f=A(0),m=A(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(V){y=!1,R(0),S({stage:"send",error:V instanceof Error?V:new Error(String(V)),value:void 0});return}let M=g;g=[],T();let C,$=0;for(let V of M)try{e.query(V.query.sql,V.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 V of M)k({value:V.value,error:C,attempts:1})}else try{e.query("COMMIT",[]);for(let V of M)w(V.value)}catch(V){let G=V instanceof Error?V:new Error(String(V));S({stage:"send",error:G,value:void 0});for(let K=0;K<$;K++)k({value:M[K].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 V=C[1],G;try{G=u(V)}catch(K){let F=K instanceof Error?K:new Error(String(K));h({stage:"serialize",error:F,value:V}),p.down([[_,{value:V,error:F,attempts:0}]]);continue}g.push({value:V,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([[fe]])}catch{}}},sent:l,failed:p,inFlight:f,errors:c,buffered:m,flush:async()=>{v||x()}}}function hf(t,e){let{args:n,mapRow:r=s=>s,...o}=e??{};return H(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 yf(t,e){let{mapRow:n=o=>o,...r}=e??{};return H(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 bf(t,e){let{mapRow:n=o=>o,...r}=e??{};return H(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})}Zr();se();ne();function Ed(){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 vf(t){return t!=null&&typeof t.then=="function"}function br(t){vf(t)&&t.catch(()=>{})}function Tf(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Ed():null,s=e?.writeThrough??!1;function i(u,c,l){for(let p=0;p<l;p++)try{br(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(vf(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{br(t[f].save(c,p))}catch{}for(let m=0;m<f;m++)try{let h=t[m].delete;h&&br(h.call(t[m],c))}catch{}}l.down([[fe]])}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{br(p.save(u,c))}catch{}else if(t[0])try{br(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=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([[fe]]),n.delete(u);for(let l of t)try{let p=l.delete;p&&br(p.call(l,u))}catch{}},has(u){return n.has(u)},get size(){return n.size}}}Oe();se();Ze();ne();ze();Oe();Re();se();ne();var ho=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=W(),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=W(),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 W()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??W())>=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 Xe(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 ho({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([[_,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(){}}}ce();function Yh(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function xf(t,e,n){let r=Q(t),o=r.v!=null,s=A(n?.initialVerified??null,{meta:{...Te("verifiable"),...o?{sourceVersion:null}:{}}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=Ct(Q(n.trigger),r):i?a=Q(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]===_&&(u=l[1])}),d=ke(a,()=>e(u))}sn(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 wf(t){t.subscribe(()=>{})}function yo(t){return t instanceof Map?t:new Map}function kf(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 ri(t,e,n){let r=Q(t),o=Xe(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?Q(n.context):A(null),d=yo(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===_&&(d=yo(m[1]))});let u=Q(e(r,o.entries));if(sn(u,f=>{kf(o,f)}),n.evict){let f=new Map,m=O([o.entries],([h])=>{let g=[],y=yo(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(Yh(T)){if(!f.has(b)){let w=sn(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});sn(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=Q(n.consolidateTrigger),m=ke(f,()=>n.consolidate(d));sn(m,h=>{kf(o,h)})}let l=O([o.entries,a],([f,m])=>{let g=[...yo(f).entries()].map(([v,T])=>({key:v,value:T,score:n.score(T,m),cost:n.cost(T)}));g.sort((v,T)=>T.score-v.score);let y=[],b=s;for(let v of g)v.cost<=b&&(y.push({key:v.key,value:v.value,score:v.score}),b-=v.cost);return y},{meta:{...Te("distill",{budget:s})}}),p=O([o.entries],([f])=>yo(f).size);return wf(l),wf(p),{store:o,compact:l,size:p}}Da();async function oi(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+=Rf[r[s]];return o}var Rf=new Array(256);for(let t=0;t<256;t++)Rf[t]=t.toString(16).padStart(2,"0");var bo=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 vo(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 si(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let d=vo(s(a)),u=await oi(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 bo(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)}}}Oa();async function Et(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}ut();ze();Oe();se();Me();var To=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 Sf(t={}){let{backend:e}=t,n=e??new To,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=J({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([[fe]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Oe();se();ne();function Nf(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 Qh(t,e){let n=Nf(t[0],e[0]);return n!==0?n:Nf(t[1],e[1])}function Ef(t){return[t.secondary,t.primary]}function vr(t,e){let n=Ef(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;Qh(n,Ef(t[s]))>0?r=s+1:o=s}return r}var wo=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=vr(this._buf,s);this._buf.splice(d,1)}let a=vr(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=vr(this._buf,s);this._buf.splice(d,1)}let a=vr(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=vr(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=vr(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 Xh(t){return t.subscribe(()=>{})}function _f(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new wo;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=O([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=Xh(d),c=!1;function l(){let f=s.toArray();Z(()=>{a.down([[oe]]),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())}}}Oe();se();ne();var ko=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 ii(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new ko(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([[_,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(){}}}on();se();ce();function ai(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=it(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 Mf(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=Q(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}}ce();function xo(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(xo);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=xo(e[o]);return r}function di(t){return JSON.stringify(xo(t),void 0,0)}var Zh=new TextEncoder,ey=new TextDecoder("utf-8",{fatal:!0}),Tr={name:"json",version:1,encode(t){return Zh.encode(di(t))},decode(t){return JSON.parse(ey.decode(t))}};function Of(){return Tr}function Ro(){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 ui(t,e={}){let n=e.codec??Tr,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 _d(t,e={}){let n=e.codec??Tr,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 ci(t,e={}){let n=e.codec??Tr,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 Af(t){return ui(Ro(),t)}function Cf(t){return _d(Ro(),t)}function So(t){return ci(Ro(),t)}function Lf(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 ci(n,e)}function If(t,e){return ui({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)}se();Me();ne();Fe();function No(t,e,n,r){let o=new Y(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)ty(o,e,s,i);return o}function ty(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],[z]]))}else c?(c=!1,h.down([[oe],[z]])):h.down([[z]])}}let f=J([],(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===_||b===z?(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===fe?(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})}}At();var li=Math.LN2/604800;function It(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)}Oe();se();Me();ne();ze();ce();se();var ny=new Map([[nt,"INVALIDATE"],[qe,"PAUSE"],[Je,"RESUME"],[fe,"TEARDOWN"],[I,"COMPLETE"],[L,"ERROR"]]),ry=new Map([["INVALIDATE",nt],["PAUSE",qe],["RESUME",Je],["TEARDOWN",fe],["COMPLETE",I],["ERROR",L]]);function un(t){let e=ny.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function $n(t){let e=ry.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function jn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function Bn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function cn(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 cn(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 oy(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Md(t,e){let n=oy(t)?t:cn(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=J(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=he([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,Bn(v.err)]]);break}case"s":{let T=$n(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:jn(k[1])}):n.post({t:"s",s:b,sig:un(R),d:k.length>1?k[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=st(e.timeoutMs),v=kt(a,w=>w==="connected");h=Ms(Ct(eo(b,()=>"timeout"),eo(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:un(fe)}),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}Oe();se();Me();ne();function sy(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Od(t,e){let n=sy(t)?t:cn(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=J(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=he([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:jn(T[1])}):n.post({t:"s",s:g,sig:un(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,Bn(y.err)]]);break}case"s":{let b=$n(y.sig);if(!b)break;if(b===fe&&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}}Tt();Tt();var Bu={};Ee(Bu,{SNAPSHOT_WIRE_VERSION:()=>Wo,SurfaceError:()=>_e,ai:()=>Bi,asSurfaceError:()=>aa,cqrs:()=>zs,createGraph:()=>Mr,deleteSnapshot:()=>ma,demoShell:()=>Ki,diffSnapshots:()=>pa,domainTemplates:()=>qi,graphspec:()=>ji,harness:()=>Zi,inspect:()=>oa,jobQueue:()=>Qi,layout:()=>ia,listSnapshots:()=>fa,memory:()=>Pi,messaging:()=>Mi,orchestration:()=>Oi,process:()=>sa,reduction:()=>Gi,restoreSnapshot:()=>la,runReduction:()=>da,saveSnapshot:()=>ca,surface:()=>ga});var Bi={};Ee(Bi,{AgentLoopGraph:()=>Di,AllTiersExhaustedError:()=>Mo,BudgetExhaustedError:()=>Ti,ChatStreamGraph:()=>Ai,CircuitOpenError:()=>St,DEFAULT_DECAY_RATE:()=>li,FallbackMissError:()=>fy,LLMTimeoutError:()=>kr,ReplayCacheMissError:()=>qn,ToolRegistryGraph:()=>Ci,admissionFilter3D:()=>hb,admissionScored:()=>sm,agentLoop:()=>wb,agentMemory:()=>kb,anthropicAdapter:()=>Cd,canonicalJson:()=>Id,cascadingLlmAdapter:()=>Wd,chatStream:()=>tu,composePricing:()=>Cy,computePrice:()=>jd,contentGate:()=>cb,costMeterExtractor:()=>ob,createAdapter:()=>Ey,createCapabilitiesRegistry:()=>iy,createPricingRegistry:()=>Oy,dryRunAdapter:()=>Vn,fallbackAdapter:()=>Pd,frozenContext:()=>Jy,gatedStream:()=>tb,gaugesAsContext:()=>xb,googleAdapter:()=>Dd,graphFromSpec:()=>vm,graphFromSpecReactive:()=>Lb,handoff:()=>pb,keywordFlagExtractor:()=>ib,knobsAsTools:()=>Pb,llmConsolidator:()=>eu,llmExtractor:()=>Zd,memoryRetrieval:()=>cu,memoryWithKG:()=>du,memoryWithTiers:()=>uu,memoryWithVectors:()=>au,observableAdapter:()=>_y,openAICompatAdapter:()=>Fd,parseRateLimitFromError:()=>qd,pricingFor:()=>Ly,promptCall:()=>Xd,promptNode:()=>Ao,redactor:()=>lb,registryPricing:()=>Ay,resilientAdapter:()=>Hy,streamExtractor:()=>ab,streamingPromptNode:()=>eb,suggestStrategy:()=>Tm,suggestStrategyReactive:()=>Gb,systemPromptBuilder:()=>nb,tier:()=>Ky,toolCallExtractor:()=>ub,toolExecution:()=>nu,toolRegistry:()=>ru,toolSelector:()=>gb,validateGraphDef:()=>Fb,withBreaker:()=>Bd,withBudgetGate:()=>Kd,withDryRun:()=>Py,withRateLimiter:()=>zd,withReplayCache:()=>_o,withRetry:()=>Ud,withTimeout:()=>Jd,zeroPrice:()=>vi});ne();function Eo(t,e){return`${t}::${e}`}function iy(t){let e=Xe({name:"capabilitiesRegistry"}),n=u=>{e.set(Eo(u.provider,u.id),u)};if(t)for(let u of t)n(u);let r=(u,c)=>{let l=e.get(Eo(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=O([e.entries],([u])=>u instanceof Map?Array.from(u.values()):[],{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(u,c){let l=e.has(Eo(u,c));return l&&e.delete(Eo(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=Eo(u,c),p=s.get(l);if(p)return s.delete(l),s.set(l,p),p;let f=O([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=O([d],([p])=>p.filter(f=>f.provider===u),{name:`capabilitiesRegistry/byProvider/${u}`,initial:[]});return a(i,u,l,o),l}}}Re();function Cd(t={}){return t.sdk?ly(t):cy(t)}function pi(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}=ay(t,e?.systemPrompt),a={model:o,messages:i.map(dy),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(uy)),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 ay(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,ie());await e.putObject({Bucket:n,Key:m,Body:f,ContentType:c})}})}function ff(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 Qe(t,{onTransportError:s,serialize:i=>o(i,n),send:async i=>{let a=i;await e.query(a.sql,a.params)}})}function mf(t,e,n){let{toDocument:r=s=>s,onTransportError:o}=n??{};return Qe(t,{onTransportError:o,serialize:r,send:async s=>{await e.insertOne(s)}})}function gf(t,e,n){let{labels:r={},toLine:o=a=>JSON.stringify(a),toLabels:s,onTransportError:i}=n??{};return Qe(t,{onTransportError:i,serialize:a=>({line:o(a),labels:s?{...r,...s(a)}:r}),send:async a=>{let{line:d,labels:u}=a,c=`${ie()}`;await e.push({streams:[{stream:u,values:[[c,d]]}]})}})}function hf(t,e,n){let{toResourceSpans:r=s=>[s],onTransportError:o}=n??{};return Qe(t,{onTransportError:o,serialize:r,send:async s=>{await e.push({resourceSpans:s})}})}function yf(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(ie()/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 bf(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 vf(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 Tf(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 wf(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,N)=>({sql:`INSERT INTO "${N.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 Qe(t,{onTransportError:s,serialize:u,send:M=>{let N=M;e.query(N.sql,N.params)}});let c=C(null),l=C(void 0,{equals:()=>!1}),p=C(null),f=C(0),m=C(0),h=M=>{try{s?.(M)}catch{}try{c.down([[E,M]])}catch{}},g=[],y=!1,b,v=!1,T=()=>m.down([[E,g.length]]),w=M=>{v||l.down([[E,M]])},k=M=>{v||p.down([[E,M]])},x=M=>{v||f.down([[E,M]])},R=M=>{v||h(M)},S=()=>{if(g.length===0||y)return;y=!0,x(1);try{e.query("BEGIN",[])}catch(j){y=!1,x(0),R({stage:"send",error:j instanceof Error?j:new Error(String(j)),value:void 0});return}let M=g;g=[],T();let N,P=0;for(let j of M)try{e.query(j.query.sql,j.query.params),P+=1}catch(G){N=G instanceof Error?G:new Error(String(G));break}if(N){try{e.query("ROLLBACK",[])}catch{}R({stage:"send",error:N,value:void 0});for(let j of M)k({value:j.value,error:N,attempts:1})}else try{e.query("COMMIT",[]);for(let j of M)w(j.value)}catch(j){let G=j instanceof Error?j:new Error(String(j));R({stage:"send",error:G,value:void 0});for(let V=0;V<P;V++)k({value:M[V].value,error:G,attempts:1})}y=!1,x(0)},_=()=>{d>0&&b===void 0&&!v&&(b=setTimeout(()=>{b=void 0,S()},d))},O=t.subscribe(M=>{for(let N of M){let P=N[0];if(P===E){let j=N[1],G;try{G=u(j)}catch(V){let $=V instanceof Error?V:new Error(String(V));h({stage:"serialize",error:$,value:j}),p.down([[E,{value:j,error:$,attempts:0}]]);continue}g.push({value:j,query:G}),T(),g.length>=a?S():_()}else je.messageTier(P)>=3&&S()}});return{dispose:()=>{if(!v){b!==void 0&&(clearTimeout(b),b=void 0),S(),v=!0,O();for(let M of[c,l,p,f,m])try{M.down([[ge]])}catch{}}},sent:l,failed:p,inFlight:f,errors:c,buffered:m,flush:async()=>{v||S()}}}function kf(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 xf(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 Rf(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})}to();se();re();function Id(){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 Sf(t){return t!=null&&typeof t.then=="function"}function vr(t){Sf(t)&&t.catch(()=>{})}function Nf(t,e){let n=new Map,r=e?.maxSize??0,o=r>0?e?.eviction??Id():null,s=e?.writeThrough??!1;function i(u,c,l){for(let p=0;p<l;p++)try{vr(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(Sf(f)){let m=p;f.then(h=>{h!==void 0?(c.down([[E,h]]),i(u,h,m)):a(u,c,m+1)},()=>{a(u,c,m+1)});return}if(f!==void 0){c.down([[E,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{vr(t[f].save(c,p))}catch{}for(let m=0;m<f;m++)try{let h=t[m].delete;h&&vr(h.call(t[m],c))}catch{}}l.down([[ge]])}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=C(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{vr(p.save(u,c))}catch{}else if(t[0])try{vr(t[0].save(u,c))}catch{}let l=n.get(u);if(l)l.down([[E,c]]),o?.touch(u);else{o&&r>0&&o.size()>=r&&d();let p=C(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([[ge]]),n.delete(u);for(let l of t)try{let p=l.delete;p&&vr(p.call(l,u))}catch{}},has(u){return n.has(u)},get size(){return n.size}}}Oe();se();Ze();re();We();Oe();Re();se();re();var vo=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=W(),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=W(),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 W()+n*1e9}}_isExpired(e,n){return e.expiresAt===void 0?!1:(n??W())>=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 Ke(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 vo({maxSize:n,defaultTtl:r}),d=C(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([[E,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(){}}}pe();function ty(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function Mf(t,e,n){let r=X(t),o=r.v!=null,s=C(n?.initialVerified??null,{meta:{...Te("verifiable"),...o?{sourceVersion:null}:{}}}),i=n?.trigger!==void 0&&n.trigger!==null,a=null;if(i&&n?.autoVerify?a=It(X(n.trigger),r):i?a=X(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]===E&&(u=l[1])}),d=ke(a,()=>e(u))}an(d,u=>{Z(()=>{if(s.down([[E,u]]),o){let c=r.v;c!=null&&s.meta.sourceVersion.down([[E,{id:c.id,version:c.version}]])}})})}return{node:r,verified:s,trigger:a}}function Ef(t){t.subscribe(()=>{})}function To(t){return t instanceof Map?t:new Map}function _f(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 Tr(t,e,n){let r=X(t),o=Ke(n.mapOptions??{}),s=n.budget??2e3,a=n.context!==void 0&&n.context!==null?X(n.context):C(null),d=To(o.entries.cache);o.entries.subscribe(f=>{for(let m of f)m[0]===E&&(d=To(m[1]))});let u=X(e(r,o.entries));if(an(u,f=>{_f(o,f)}),n.evict){let f=new Map,m=A([o.entries],([h])=>{let g=[],y=To(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(ty(T)){if(!f.has(b)){let w=an(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});an(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=X(n.consolidateTrigger),m=ke(f,()=>n.consolidate(d));an(m,h=>{_f(o,h)})}let l=A([o.entries,a],([f,m])=>{let g=[...To(f).entries()].map(([v,T])=>({key:v,value:T,score:n.score(T,m),cost:n.cost(T)}));g.sort((v,T)=>T.score-v.score);let y=[],b=s;for(let v of g)v.cost<=b&&(y.push({key:v.key,value:v.value,score:v.score}),b-=v.cost);return y},{meta:{...Te("distill",{budget:s})}}),p=A([o.entries],([f])=>To(f).size);return Ef(l),Ef(p),{store:o,compact:l,size:p}}Ka();async function di(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+=Of[r[s]];return o}var Of=new Array(256);for(let t=0;t<256;t++)Of[t]=t.toString(16).padStart(2,"0");var wo=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 ko(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 ui(t){let{storage:e,keyContext:n,keyPrefix:r,mode:o="read-write"}=t,s=n??(a=>a);async function i(a){let d=ko(s(a)),u=await di(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 wo(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 Mt(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}ut();We();Oe();se();Me();var xo=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 Af(t={}){let{backend:e}=t,n=e??new xo,r=new Map;function o(s){let i=r.get(s);return i===void 0&&(i=Q({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([[ge]]),!0)},has(s){return n.hasTopic(s)},get size(){return n.topicCount},topicNames(){return n.topicNames()}}}Oe();se();re();function Cf(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 ny(t,e){let n=Cf(t[0],e[0]);return n!==0?n:Cf(t[1],e[1])}function Lf(t){return[t.secondary,t.primary]}function wr(t,e){let n=Lf(e),r=0,o=t.length;for(;r<o;){let s=r+o>>1;ny(n,Lf(t[s]))>0?r=s+1:o=s}return r}var Ro=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=wr(this._buf,s);this._buf.splice(d,1)}let a=wr(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=wr(this._buf,s);this._buf.splice(d,1)}let a=wr(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=wr(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=wr(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 ry(t){return t.subscribe(()=>{})}function If(t={}){let{name:e,versioning:n,equals:r,backend:o}=t,s=o??new Ro;function i(f){return f?.equals!==void 0||r===void 0?f:{...f,equals:r}}let a=C([],{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=ry(d),c=!1;function l(){let f=s.toArray();Z(()=>{a.down([[oe]]),a.down([[E,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())}}}Oe();se();re();var So=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 ci(t,e={}){let{name:n,versioning:r,backend:o}=e,s=o??new So(t),i=C(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([[E,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(){}}}sn();se();pe();function li(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=it(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 Pf(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=X(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}}pe();function No(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(No);let e=t,n=Object.keys(e).sort(),r={};for(let o of n)r[o]=No(e[o]);return r}function pi(t){return JSON.stringify(No(t),void 0,0)}var oy=new TextEncoder,sy=new TextDecoder("utf-8",{fatal:!0}),kr={name:"json",version:1,encode(t){return oy.encode(pi(t))},decode(t){return JSON.parse(sy.decode(t))}};function Df(){return kr}function Eo(){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 fi(t,e={}){let n=e.codec??kr,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 Pd(t,e={}){let n=e.codec??kr,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 mi(t,e={}){let n=e.codec??kr,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 Gf(t){return fi(Eo(),t)}function Ff(t){return Pd(Eo(),t)}function _o(t){return mi(Eo(),t)}function $f(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 mi(n,e)}function jf(t,e){return fi({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)}se();Me();re();Fe();function Mo(t,e,n,r){let o=new Y(t,r);o.add(e,{name:"source"});let s=C(n,{meta:{kind:"stratify_rules"}});o.add(s,{name:"rules"});for(let i of n)iy(o,e,s,i);return o}function iy(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],[H]]))}else c?(c=!1,h.down([[oe],[H]])):h.down([[H]])}}let f=Q([],(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===E||b===H?(g===0?(i=!1,d=!0,u=b===E?h[1]:s):(b===E&&(l=h[1]),a=!1),i||a||p(y),!0):b===I||b===L||b===ge?(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})}}Lt();var gi=Math.LN2/604800;function Pt(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)}Oe();se();Me();re();We();pe();se();var ay=new Map([[nt,"INVALIDATE"],[ze,"PAUSE"],[Ye,"RESUME"],[ge,"TEARDOWN"],[I,"COMPLETE"],[L,"ERROR"]]),dy=new Map([["INVALIDATE",nt],["PAUSE",ze],["RESUME",Ye],["TEARDOWN",ge],["COMPLETE",I],["ERROR",L]]);function cn(t){let e=ay.get(t);return e||(Symbol.keyFor(t)??"UNKNOWN")}function jn(t){let e=dy.get(t);if(e)return e;if(t&&t!=="UNKNOWN")return Symbol.for(t)}function Bn(t){return t instanceof Error?{message:t.message,name:t.name,stack:t.stack}:{message:String(t),name:"Error"}}function Vn(t){let e=new Error(t.message);return e.name=t.name,t.stack&&(e.stack=t.stack),e}function ln(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 ln(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 uy(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Dd(t,e){let n=uy(t)?t:ln(t),r=e.name??"workerBridge",o=Object.entries(e.expose??{}),s=e.import??[],i=e.transfer??{},a=C("connecting",{name:`${r}::meta::status`}),d=C(null,{name:`${r}::meta::error`}),u=new Map,c=new Map;for(let b of s){let v=C(void 0,{name:`${r}::${b}`});u.set(b,v)}let l;if(o.length>0){let b=o.map(([,w])=>w),v=Q(b,(w,k)=>{let x={};for(let R=0;R<o.length;R++){let[S]=o[R],_=w[R];_!=null&&_.length>0&&(x[S]=_.at(-1))}Object.keys(x).length!==0&&k.emit(x)},{name:`${r}::aggregated`,partial:!0});l=he([v],w=>{let k=w[0];if(k==null||Object.keys(k).length===0)return;let x=[];for(let _ of Object.keys(k)){let O=i[_];O&&x.push(...O(k[_]))}let R;for(let[_,O]of o)_ in k&&O.v!=null&&(R==null&&(R={}),R[_]=O.v.version);let S={t:"b",u:k,...R?{v:R}:{}};try{n.post(S,x.length>0?x:void 0)}catch(_){d.down([[E,_ instanceof Error?_:new Error(String(_))]])}}).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 x=u.get(w);x&&x.down([[E,k]])}}),a.down([[E,"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([[E,v.d]]);break}case"b":{Z(()=>{for(let[T,w]of Object.entries(v.u)){let k=v.v?.[T];if(k!=null){let R=c.get(T);if(R!=null&&k<=R)continue;c.set(T,k)}let x=u.get(T);x&&x.down([[E,w]])}});break}case"e":{let T=u.get(v.s);T&&T.down([[L,Vn(v.err)]]);break}case"s":{let T=jn(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 x=k[0];x!==E&&(je.isLocalOnly(x)||(x===L?n.post({t:"e",s:b,err:Bn(k[1])}):n.post({t:"s",s:b,sig:cn(x),d:k.length>1?k[1]:void 0})))}}));m.push(T)}let h;if(e.timeoutMs!=null&&e.timeoutMs>0){let b=st(e.timeoutMs),v=xt(a,w=>w==="connected");h=Ls(It(no(b,()=>"timeout"),no(v,()=>"ready"))).subscribe(w=>{for(let k of w)k[0]===E&&k[1]==="timeout"&&(d.down([[E,new Error("Worker bridge handshake timeout")]]),g())})}function g(){if(!p){p=!0,h?.(),n.post({t:"s",s:"*",sig:cn(ge)}),l&&l();for(let b of m)b();m.length=0,f(),a.down([[E,"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}Oe();se();Me();re();function cy(t){return typeof t=="object"&&t!==null&&typeof t.post=="function"&&typeof t.listen=="function"}function Gd(t,e){let n=cy(t)?t:ln(t),r=e.import??[],o=e.transfer??{},s=new Map,i=new Map,a={};for(let g of r){let y=C(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=Q(g,(v,T)=>{let w={};for(let k=0;k<u.length;k++){let[x]=u[k],R=v[k];R!=null&&R.length>0&&(w[x]=R.at(-1))}Object.keys(w).length!==0&&T.emit(w)},{name:"workerSelf::aggregated",partial:!0});c=he([y],v=>{if(l)return;let T=v[0];if(T==null||Object.keys(T).length===0)return;let w=[];for(let R of Object.keys(T)){let S=o[R];S&&w.push(...S(T[R]))}let k;for(let[R,S]of u)R in T&&S.v!=null&&(k==null&&(k={}),k[R]=S.v.version);let x={t:"b",u:T,...k?{v:k}:{}};try{n.post(x,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&&(je.isLocalOnly(w)||(w===L?n.post({t:"e",s:g,err:Bn(T[1])}):n.post({t:"s",s:g,sig:cn(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([[E,v]])}});break}case"v":{let b=s.get(y.s);b&&b.down([[E,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([[E,v]])}});break}case"e":{let b=s.get(y.s);b&&b.down([[L,Vn(y.err)]]);break}case"s":{let b=jn(y.sig);if(!b)break;if(b===ge&&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}}bt();bt();var Wu={};Ee(Wu,{SNAPSHOT_WIRE_VERSION:()=>Yo,SurfaceError:()=>_e,ai:()=>zi,asSurfaceError:()=>pa,cqrs:()=>Qs,createGraph:()=>Ar,deleteSnapshot:()=>va,demoShell:()=>Wi,diffSnapshots:()=>ya,domainTemplates:()=>Ui,graphspec:()=>qi,harness:()=>oa,inspect:()=>ua,jobQueue:()=>na,layout:()=>la,listSnapshots:()=>ba,memory:()=>$i,messaging:()=>Li,orchestration:()=>Ii,process:()=>ca,reduction:()=>Bi,restoreSnapshot:()=>ha,runReduction:()=>fa,saveSnapshot:()=>ga,surface:()=>Ta});var zi={};Ee(zi,{AgentLoopGraph:()=>ji,AllTiersExhaustedError:()=>Co,BudgetExhaustedError:()=>Ri,ChatStreamGraph:()=>Pi,CircuitOpenError:()=>Et,DEFAULT_DECAY_RATE:()=>gi,FallbackMissError:()=>by,LLMTimeoutError:()=>Rr,ReplayCacheMissError:()=>zn,ToolRegistryGraph:()=>Di,admissionFilter3D:()=>wb,admissionScored:()=>lm,agentLoop:()=>Nb,agentMemory:()=>Eb,anthropicAdapter:()=>$d,canonicalJson:()=>Bd,cascadingLlmAdapter:()=>eu,chatStream:()=>du,composePricing:()=>Gy,computePrice:()=>Wd,contentGate:()=>gb,costMeterExtractor:()=>ub,createAdapter:()=>Cy,createCapabilitiesRegistry:()=>ly,createPricingRegistry:()=>Py,dryRunAdapter:()=>Kn,fallbackAdapter:()=>Vd,frozenContext:()=>eb,gatedStream:()=>ib,gaugesAsContext:()=>_b,googleAdapter:()=>Kd,graphFromSpec:()=>Sm,graphFromSpecReactive:()=>Fb,handoff:()=>yb,keywordFlagExtractor:()=>lb,knobsAsTools:()=>jb,llmConsolidator:()=>au,llmExtractor:()=>iu,memoryRetrieval:()=>yu,memoryWithKG:()=>gu,memoryWithTiers:()=>hu,memoryWithVectors:()=>mu,observableAdapter:()=>Ly,openAICompatAdapter:()=>zd,parseRateLimitFromError:()=>Qd,pricingFor:()=>Fy,promptCall:()=>su,promptNode:()=>Io,redactor:()=>hb,registryPricing:()=>Dy,resilientAdapter:()=>Yy,streamExtractor:()=>pb,streamingPromptNode:()=>sb,suggestStrategy:()=>Nm,suggestStrategyReactive:()=>Vb,systemPromptBuilder:()=>ab,tier:()=>Uy,toolCallExtractor:()=>mb,toolExecution:()=>uu,toolRegistry:()=>cu,toolSelector:()=>Tb,validateGraphDef:()=>Kb,withBreaker:()=>Ud,withBudgetGate:()=>Yd,withDryRun:()=>jy,withRateLimiter:()=>Zd,withReplayCache:()=>Ao,withRetry:()=>tu,withTimeout:()=>nu,zeroPrice:()=>xi});re();function Oo(t,e){return`${t}::${e}`}function ly(t){let e=Ke({name:"capabilitiesRegistry"}),n=u=>{e.set(Oo(u.provider,u.id),u)};if(t)for(let u of t)n(u);let r=(u,c)=>{let l=e.get(Oo(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])=>u instanceof Map?Array.from(u.values()):[],{name:"capabilitiesRegistry/entries",initial:[]});return{register:n,lookup:r,remove(u,c){let l=e.has(Oo(u,c));return l&&e.delete(Oo(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=Oo(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}}}Re();function $d(t={}){return t.sdk?hy(t):gy(t)}function hi(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}=py(t,e?.systemPrompt),a={model:o,messages:i.map(fy),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(my)),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 py(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 dy(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 uy(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function fi(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 Ld(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 Pf(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:Ld(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function cy(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=pi(i,a,t.model,!1),u=W(),c=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(d),signal:a?.signal});if(!c.ok)throw await Et(c,"Anthropic");let l=await c.json(),p=Math.max(0,(W()-u)/1e6);return Pf(l,p)},async*stream(i,a){let d=pi(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 Et(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 qt(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=fi(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=fi(c,g.delta.usage));break}case"message_stop":break}}c&&(yield{type:"usage",usage:Ld(c)}),yield{type:"finish",reason:l??"stop"}}}}function ly(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=pi(n,r,t.model,!1),s=W(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(W()-s)/1e6);return Pf(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=pi(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=fi(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=fi(s,d.delta.usage));break}}s&&(yield{type:"usage",usage:Ld(s)}),yield{type:"finish",reason:i??"stop"}}}}At();function mi(){let t=new Error("aborted");return t.name="AbortError",t}function Df(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(mi()):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(mi())},e.addEventListener("abort",s,{once:!0}))})}function Vn(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 Df(r,d?.signal),d?.signal?.aborted)throw mi();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 mi();await Df(p,d?.signal),yield{type:"token",delta:u.slice(f,f+o)}}yield{type:"usage",usage:c},yield{type:"finish",reason:"stop"}}}}Re();Re();ce();At();function Gf(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=si({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();se();ne();ze();ce();function dt(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 gi(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=Q(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=no(s,u=>{i=n(u),a=!0});return O([d],([u])=>u==null?null:a?i:n(u),{name:o??"adapt/invokeTap"})}function Kn(t){let e=t.endNs??W();return{timestamp:e,wallClock:t.startWallClockNs??ie(),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 Pt(){return{input:{regular:0},output:{regular:0}}}var Ff=Symbol.for("graphrefly.adapter.middlewareLayers");function tt(t,e,n){let o=[...n?py(n):[],e];return Object.defineProperty(t,Ff,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function py(t){let e=t[Ff];return Array.isArray(e)?e:[]}var qn=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 _o(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=Gf({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=ai(async({messages:p,invokeOpts:f})=>await it(Q(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=dt(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 qn(m,"invoke");let g=await c({messages:p,invokeOpts:f,_precomputedKey:m});return a||await d.store(p,f,{response:g,storedAtNs:ie()}),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 qn(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=W(),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:ie(),...o?{streamChunks:v,streamCadenceMs:T}:{}};await d.store(p,f,R)}}});return tt(l,"withReplayCache",t),l}var Id=vo;var fy=qn;function $f(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 jf(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 my(t,e){if("key"in t)return t.key;let n=Id({messages:t.messages,opts:t.invokeOpts??{}}),r=await oi(n);return`${e}:${r}`}function gy(t){let e={response:t.response,storedAtNs:ie()};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 hy(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=So(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await my(i,e);await r.save(a,gy(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Pd(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"?Vn({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):$f(e,n);return jf(p,e,n)},async*stream(c,l){let p=t.respond?t.respond(c,l):$f(e,n),f=jf(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=hy(t,o);i=c.tier??So(),a=c.seedReady}let d=t.record?"read-write":r==="throw"?"read-strict":"read",u=_o(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?Ty(t):vy(t)}function hi(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 fy(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 my(t){return{name:t.name,description:t.description,input_schema:t.parameters}}function yi(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 jd(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 Bf(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:jd(t.usage),finishReason:t.stop_reason,latencyMs:e,model:t.model,provider:"anthropic"}}function gy(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=hi(i,a,t.model,!1),u=W(),c=await o(`${n}/v1/messages`,{method:"POST",headers:s(),body:JSON.stringify(d),signal:a?.signal});if(!c.ok)throw await Mt(c,"Anthropic");let l=await c.json(),p=Math.max(0,(W()-u)/1e6);return Bf(l,p)},async*stream(i,a){let d=hi(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 Mt(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 Ht(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=yi(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=yi(c,g.delta.usage));break}case"message_stop":break}}c&&(yield{type:"usage",usage:jd(c)}),yield{type:"finish",reason:l??"stop"}}}}function hy(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=hi(n,r,t.model,!1),s=W(),i=await e.messages.create(o,{signal:r?.signal}),a=Math.max(0,(W()-s)/1e6);return Bf(i,a)},async*stream(n,r){if(!e.messages.stream)throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");let o=hi(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=yi(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=yi(s,d.delta.usage));break}}s&&(yield{type:"usage",usage:jd(s)}),yield{type:"finish",reason:i??"stop"}}}}Lt();function bi(){let t=new Error("aborted");return t.name="AbortError",t}function Vf(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(bi()):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(bi())},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 Vf(r,d?.signal),d?.signal?.aborted)throw bi();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 bi();await Vf(p,d?.signal),yield{type:"token",delta:u.slice(f,f+o)}}yield{type:"usage",usage:c},yield{type:"finish",reason:"stop"}}}}Re();Re();pe();Lt();function Kf(t){let{storage:e,mode:n="read-write",keyFn:r,keyPrefix:o="llm-replay"}=t,i=ui({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();se();re();We();pe();function dt(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 vi(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=X(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=oo(s,u=>{i=n(u),a=!0});return A([d],([u])=>u==null?null:a?i:n(u),{name:o??"adapt/invokeTap"})}function qn(t){let e=t.endNs??W();return{timestamp:e,wallClock:t.startWallClockNs??ie(),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 Dt(){return{input:{regular:0},output:{regular:0}}}var qf=Symbol.for("graphrefly.adapter.middlewareLayers");function tt(t,e,n){let o=[...n?yy(n):[],e];return Object.defineProperty(t,qf,{value:Object.freeze(o),enumerable:!1,writable:!1,configurable:!1}),t}function yy(t){let e=t[qf];return Array.isArray(e)?e:[]}var zn=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 Ao(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=Kf({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=li(async({messages:p,invokeOpts:f})=>await it(X(t.invoke(p,f))),{keyFn:({_precomputedKey:p})=>p}),l=dt(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 zn(m,"invoke");let g=await c({messages:p,invokeOpts:f,_precomputedKey:m});return a||await d.store(p,f,{response:g,storedAtNs:ie()}),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 x=0;x<h.streamChunks.length;x++){let R=h.streamCadenceMs[x]??0,S=s>0?R/s:0;S>0&&await u(S),yield{type:"token",delta:h.streamChunks[x]?.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 zn(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 x=W(),R=w===void 0?0:(x-w)/1e6;T.push(R),w=x,v.push({delta:k.delta})}k.type==="usage"&&(y=k.usage),k.type==="finish"&&(b=k.reason),yield k}if((g||y)&&!a){let x={response:{content:g,usage:y??{input:{regular:0},output:{regular:0}},finishReason:b,model:t.model??f?.model??"",provider:t.provider},storedAtNs:ie(),...o?{streamChunks:v,streamCadenceMs:T}:{}};await d.store(p,f,x)}}});return tt(l,"withReplayCache",t),l}var Bd=ko;var by=zn;function zf(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 Hf(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 vy(t,e){if("key"in t)return t.key;let n=Bd({messages:t.messages,opts:t.invokeOpts??{}}),r=await di(n);return`${e}:${r}`}function Ty(t){let e={response:t.response,storedAtNs:ie()};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 wy(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=_o(),o=t.fixtures,s=(async()=>{for(let i of o){let a=await vy(i,e);await r.save(a,Ty(i))}})();return s.catch(()=>{}),{tier:r,seedReady:s}}return t.fixturesStorage?{tier:t.fixturesStorage,seedReady:Promise.resolve()}:{tier:void 0,seedReady:Promise.resolve()}}function Vd(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):zf(e,n);return Hf(p,e,n)},async*stream(c,l){let p=t.respond?t.respond(c,l):zf(e,n),f=Hf(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=wy(t,o);i=c.tier??_o(),a=c.seedReady}let d=t.record?"read-write":r==="throw"?"read-strict":"read",u=Ao(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 Kd(t={}){return t.sdk?Sy(t):Ry(t)}function Ti(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(yy)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function yy(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Bf(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 Gd(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 Vf(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:Gd(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function by(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function vy(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=by(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=hi(s,i),u=W(),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 Et(l,"Google");let p=await l.json(),f=Math.max(0,(W()-u)/1e6);return Vf(p,f)},async*stream(s,i){let a=r(i),d=hi(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 Et(c,"Google");if(!c.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of qt(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:Gd(l)}),yield{type:"finish",reason:p??"stop"}}}}function Ty(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=hi(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=Bf(o,s,r?.signal),a=W(),d=await e.models.generateContent(i),u=Math.max(0,(W()-a)/1e6);return Vf(d,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=hi(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=Bf(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:Gd(a)}),yield{type:"finish",reason:d??"stop"}}}}Re();var wy={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 Fd(t={}){return t.sdk?Ny(t):Sy(t)}function yi(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(ky);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(xy)),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 ky(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 xy(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function $d(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 Kf(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:Ry(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:$d(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function Ry(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function qf(t){let e=t.preset??"openai",n=wy[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 Sy(t){let{provider:e,baseURL:n,apiKey:r}=qf(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=yi(a,d,t.model,!1,t.bodyExtras),c=W(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(u),signal:d?.signal});if(!l.ok)throw await Et(l,e);let p=await l.json(),f=Math.max(0,(W()-c)/1e6);return Kf(p,f,e)},async*stream(a,d){let u=yi(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 Et(c,e);if(!c.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of qt(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:$d(l)})}yield{type:"finish",reason:p??"stop"}}}}function Ny(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=qf(t);return{provider:n,model:t.model,async invoke(r,o){let s=yi(r,o,t.model,!1,t.bodyExtras),i=W(),a=await e.chat.completions.create(s,{signal:o?.signal}),d=Math.max(0,(W()-i)/1e6);return Kf(a,d,n)},async*stream(r,o){let s=yi(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:$d(l)})}yield{type:"finish",reason:d??"stop"}}}}function Ey(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 Cd(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 Vn(e)}case"fallback":{let e={provider:t.provider,model:t.model,...t.extras};return Pd(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 Fd(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}Re();ne();ce();function _t(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 Ht(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 Hf(){return{input:{regular:0},output:{regular:0}}}function _y(t,e){let n=e?.logMax??1e3,r=We(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=A(null,{name:"adapterStats/lastCall"}),s=O([r.entries],([h])=>h.length,{name:"adapterStats/totalCalls",initial:0}),i=O([r.entries],([h])=>h.reduce((g,y)=>g+_t(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=O([r.entries],([h])=>h.reduce((g,y)=>g+Ht(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=dt(t,{invoke(h,g){let y=W(),b=ie(),v=t.model??g?.model??"",T=k=>(u(Kn({provider:t.provider,model:t.model??g?.model??k.model??"",tier:g?.tier??k.tier,usage:k.usage??Pt(),startNs:y,startWallClockNs:b,method:"invoke"})),k),w=k=>{let R=k;u(Kn({provider:t.provider,model:v,tier:g?.tier,usage:Pt(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:R?.name??"Error",message:R?.message??String(k)}}))};return gi(t.invoke(h,g),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=W(),b=ie(),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(Kn({provider:t.provider,model:v,tier:g?.tier,usage:T??Pt(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let k=w;throw u(Kn({provider:t.provider,model:v,tier:g?.tier,usage:T??Pt(),startNs:y,startWallClockNs:b,method:"stream",error:{type:k?.name??"Error",message:k?.message??String(w)}})),w}}});tt(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 My(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function vi(t="USD"){return{total:0,currency:t}}function jd(t,e,n){let r=_t(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=My(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 bi(t,e){return`${t}::${e}`}function Oy(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(bi(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(bi(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(bi(o,u));c&&(d={key:u,pricing:c.pricing})}return d?.pricing},remove(o,s){let i=e.delete(bi(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 Ay(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?jd(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):vi(e)}}function Cy(...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):vi()}}function Ly(t,e,n){return t?.pricing?jd(e,t.pricing,n):vi()}on();ce();function Bd(t,e={}){let n=e.breaker??Rt(e),r=dt(t,{async invoke(o,s){if(!n.canExecute())throw new St;try{let i=await it(Q(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new St;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return tt(r,"withBreaker",t),{adapter:r,breaker:n}}Re();se();ne();ce();var Ti=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"},Vd=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),zf=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Kd(t,e){let n=We(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=A(zf(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=O([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=Wf(r.cache??Vd,e.caps);h&&u(h)}l=m,c=!0}})}let s=()=>{if(o.cache===!1){let u=r.cache??Vd,c=Wf(u,e.caps);return new Ti(c??"budget",e.caps[c??"calls"]??0,Iy(u,c??"calls"))}},i=(u,c)=>{let l=t.provider,p=Kn({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??Vd,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+_t(u),outputTokens:f.outputTokens+Ht(u),usd:m})},a=()=>{n.clear(),r.emit(zf())},d=dt(t,{invoke(u,c){let l=s();if(l)return Promise.reject(l);let p=W(),f=t.model??c?.model??"",m=g=>(i(g.usage??Pt(),{model:t.model??c?.model??g.model??"",tier:c?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;i(Pt(),{model:f,tier:c?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return gi(t.invoke(u,c),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(u,c){let l=s();if(l)throw l;let p=W(),f;try{for await(let m of t.stream(u,c))m.type==="usage"&&(f=m.usage),yield m;i(f??Pt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw i(f??Pt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return tt(d,"withBudgetGate",t),{adapter:d,budget:{totals:r,isOpen:o,log:n,reset:a}}}function Wf(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}}ce();function Py(t,e){let n=e.mock??Vn({provider:t.provider,model:t.model}),r=typeof e.enabled=="boolean"?e.enabled:void 0,o=r===void 0?Q(e.enabled):void 0,s;o&&(s=te(o));let i=()=>r!==void 0?r:!!o?.cache,a=dt(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 tt(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function qd(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=Dy(e.headers);if(n!==429&&n!==503&&!Vy(e.message))return;let o={},s=r("retry-after"),i=Fy(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=Uf(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=r("anthropic-ratelimit-tokens-reset");if(d){let f=Uf(d);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=wi(r,"x-ratelimit-limit-requests");u!=null&&(o.rpmCap=u);let c=wi(r,"x-ratelimit-limit-tokens");c!=null&&(o.tpmCap=c);let l=wi(r,"x-ratelimit-remaining-requests"),p=wi(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=jy(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:Gy(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 Gy(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 wi(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Fy(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 Uf(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var $y=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function jy(t){let e=$y.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 By=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Vy(t){return!!t&&By.test(t)}Re();se();ne();on();ce();At();function Hd(t){let e=new Error(t);return e.name="AbortError",e}function Yf(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?Q(t.rpm):A(Number.POSITIVE_INFINITY),o=t.tpm!=null?Q(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=O([r,s],([M,C])=>Math.min(Number(M??1/0),Number(C??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),u=O([o,i],([M,C])=>Math.min(Number(M??1/0),Number(C??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),c=wr(Number(r.cache??Number.POSITIVE_INFINITY),e),l=wr(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=wr($,e),p=!1):$===1/0?(c=wr(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=wr($,e),f=!1):$===1/0?(l=wr(1/0,e),f=!1):$<=0&&(f=!0)}}),g=0,y=new Ie,b=new Ie,v;t.adaptation!=null&&(v=Q(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=W()+M.retryAfterMs*1e6;C>g&&(g=C)}}let w=A(0,{name:"adaptiveRateLimiter/pending"}),k=A(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),R=A(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,V=M.signal;S(1);try{for(;;){if(V?.aborted)throw Hd("AdaptiveRateLimiter.acquire aborted");let G=W();if(g>G){let B=Math.ceil((g-G)/1e6);await ki(B,V);continue}if(C>0&&p||$>0&&f){await ki(250,V);continue}let K=c,F=l;if(!K.tryConsume(C)){await ki(Jf(K,C),V);continue}if(!($>0?F.tryConsume($):!0)){K.putBack(C),await ki(Jf(F,$),V);continue}x();return}}finally{S(-1)}}function E(M){M>0?l.tryConsume(M):M<0&&l.putBack(-M),x()}function P(){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:P}}function wr(t,e){if(!Number.isFinite(t)||t===1/0)return rn(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return rn(n,r)}function Jf(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 ki(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Hd("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(Hd("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}ce();function zd(t,e={}){let n=e.limiter??Yf({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=qd(i);a&&n.recordSignal(a)},s=dt(t,{async invoke(i,a){let d=r(i,a);await n.acquire({requestCost:1,tokenCost:d,signal:a?.signal});try{let u=await it(Q(t.invoke(i,a))),c=u.usage??Hf(),p=_t(c)+Ht(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=_t(l.usage)+Ht(l.usage)),yield l;let c=u-d;c>0&&n.recordUsage(c)}catch(u){throw o(u),u}}});return tt(s,"withRateLimiter",t),{adapter:s,limiter:n}}on();ce();var Mo=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 Wd(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:Rt(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 it(Q(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 Mo(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 Mo(u)}};return tt(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function Ky(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}ce();At();function xi(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Qf(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(xi()):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(xi())},e.addEventListener("abort",s,{once:!0}))})}function Ud(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??qy,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=dt(t,{async invoke(l,p){if(p?.signal?.aborted)throw xi();let f,m=r;for(let h=1;h<=n;h++)try{return await it(Q(t.invoke(l,p)))}catch(g){if(f=g,h>=n||!a(g,h))throw g;let y=u(h,m);m=y,await Qf(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw xi();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 Qf(b,p?.signal)}}throw f}});return tt(c,"withRetry",t),c}function qy(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}ce();At();var kr=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 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 kr(e))}),{signal:i.signal,cancel:()=>{u.cancel(),s&&d&&s.removeEventListener("abort",d)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof kr)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let u=new kr(e);throw u.cause=s,u}throw s},o=dt(t,{async invoke(s,i){let{signal:a,cancel:d,timedOut:u}=n(i?.signal);try{return await it(Q(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 tt(o,"withTimeout",t),o}function Hy(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=zd(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=Kd(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=Bd(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=Jd(r,e.timeoutMs)),e.retry&&(r=Ud(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=Wd([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=_o(r,e.cache)),n.adapter=r,n}Ze();Me();ce();se();ne();ut();ce();At();function ve(t,e){return we("ai",t,e)}function zy(t){return t!=null&&typeof t.then=="function"}function Yd(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Wy(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Uy=3e4;function Xf(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Uy;return new Promise((r,o)=>{let s=new Ie,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 Oo(t){return zy(t)?Oo(await t):Yd(t)?Xf(t):Wy(t)?Xf(Q(t)):t}function zt(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function Qd(t,e,n){return H(r=>{let o=new AbortController,s=!1,i=null,a=c=>{s||(s=!0,r.down([[_,c],[I]]),i?.(),i=null)},d;try{d=t.invoke(e,{...n.invokeOpts,signal:o.signal})}catch(c){return a(n.onFailure("throw",c)),()=>o.abort()}return i=Q(d,{signal:o.signal}).subscribe(c=>{for(let l of c){if(s)return;if(l[0]===_){try{a(n.onSuccess(l[1]))}catch(p){a(n.onFailure("onSuccess-threw",p))}return}if(l[0]===L){a(n.onFailure("error",l[1]));return}if(l[0]===I){a(n.onFailure("complete",void 0));return}}}),s&&i&&(i(),i=null),()=>{o.abort(),i?.(),i=null}})}function Jy(t,e){let n=Q(t),r=e?.refreshTrigger!=null?Q(e.refreshTrigger):null,o=e?.name!==void 0?{name:e.name}:void 0,s=Te("frozenContext",o);return r==null?J([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})}):J([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();se();ne();ze();ce();function Zf(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function Yy(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Ao(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=e.length,a=r?.tools!==void 0?[...e,r.tools]:e,d=O(a,c=>{let l=c.slice(0,i),p=r?.tools!==void 0?c[i]:void 0;if(l.some(m=>m==null))return{messages:[],tools:p};let f=typeof n=="string"?n:n(...l);return f?{messages:[{role:"user",content:f}],tools:p}:{messages:[],tools:p}},{name:`${s}::messages`,meta:ve("prompt_node")});return ke(d,c=>{let{messages:l,tools:p}=c;return!l||l.length===0?A(null):H(f=>{let m=!1,h=!1,g,y={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,...p!==void 0?{tools:p}:{}};if(r?.abort){let w=Gs(r.abort);y.signal=w.signal,g=w.dispose}let b;try{b=t.invoke(l,y)}catch(w){return m=!0,f.down([[L,w]]),()=>{g?.()}}let T=Q(b).subscribe(w=>{if(!(h||m))for(let k of w){if(m)return;if(k[0]===_){let R=k[1];if(o==="raw")f.emit(R);else try{let S=Zf(R),x=o==="json"?JSON.parse(zt(S)):S;f.emit(x)}catch(S){let x=Zf(R),N=new Error(`promptNode: failed to parse LLM response as JSON: ${S.message}
|
|
37
|
-
Raw content (first 200 chars): ${Yy(x)}`);m=!0,f.down([[L,N]]);return}}else if(k[0]===L){m=!0,f.down([[L,k[1]]]);return}else if(k[0]===I){m=!0,f.down([[I]]);return}else f.down([k])}});return()=>{h=!0,T(),g?.()}},{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 Xd(t,e,n,r){let o=n.name??r;return s=>{let i=A(s);return Ao(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function Zd(t,e){let n=e.maxExistingKeys??100,r=Xd(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 eu(t,e){let n=Xd(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}Oe();Re();Ze();ne();ze();ce();var Mi={};Ee(Mi,{MessagingHubGraph:()=>Ni,SubscriptionGraph:()=>Co,TopicBridgeGraph:()=>Ri,TopicGraph:()=>Wt,TopicRegistry:()=>Si,messagingHub:()=>Lo,subscription:()=>em,topic:()=>Ei,topicBridge:()=>_i});Me();ut();ce();Tt();var Qy=256;function xr(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function ln(t,e){return we("messaging",t,e)}var Xy=1024,Wt=class extends Y{_log;_publishImpl;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=We([],{name:"events",maxSize:n.retainedLimit??Xy}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=O([this.events],([r])=>{let o=r;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:ln("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(te(this.latest)),this.hasLatest=O([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:ln("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()),this._publishImpl=Ce(r=>{this._log.append(r)},{freeze:!1})}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._publishImpl(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},Co=class extends Y{cursor;available;topic;_disposed=!1;_ackImpl;_pullAndAckImpl;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=xr(r.from,"subscription from"):o=xr(r.cursor??0,"subscription cursor"),this.cursor=A(o,{name:"cursor",describeKind:"state",meta:ln("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=J([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:ln("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(te(a))}this._ackImpl=Ce(s=>{let i=this.available.cache,a=s===void 0?i.length:xr(s,"subscription ack count"),d=Math.min(a,i.length);if(d<=0)return this.cursor.cache;let u=this.cursor.cache+d;return this.cursor.emit(u),u},{freeze:!1}),this._pullAndAckImpl=Ce(s=>{let i=this.available.cache,a=s===void 0?i.length:xr(s,"subscription pullAndAck limit"),d=i.slice(0,a);if(d.length===0)return{items:d,cursor:this.cursor.cache};let u=this.cursor.cache+d.length;return this.cursor.emit(u),{items:d,cursor:u}},{freeze:!1})}ack(e){return this._disposed?this.cursor.cache:this._ackImpl(e)}pull(e){if(this._disposed)return[];let n=this.available.cache,r=e===void 0?n.length:xr(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){return this._disposed?{items:[],cursor:this.cursor.cache}:this._pullAndAckImpl(e)}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[I]]),this.destroy())}},Ri=class extends Y{_sourceSub;bridgedCount;output;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=em(`${e}-subscription`,n,{cursor:o.cursor}),this.mount("subscription",this._sourceSub);let s=Math.max(1,xr(o.maxPerPump??Qy,"topic bridge maxPerPump")),i=o.map??(p=>p);this.output=O([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:ln("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:ln("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=J([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:ln("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(te(c));let l=Zy(this.output,r);this.addDisposer(l)}};function Zy(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 Si=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()}},Ni=class extends Y{_registry;version;_defaultTopicOptions;_removeTopicImpl;constructor(e,n={}){super(e,n.graph);let r=A(0,{name:"version",describeKind:"state",meta:ln("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new Si(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}},this._removeTopicImpl=Ce(o=>{try{this.remove(o)}finally{this._registry.delete(o);let s=this.version.cache??0;this.version.emit(s+1)}},{freeze:!1})}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 Wt(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 Co(e,o,r)}removeTopic(e){return this._registry.has(e)?(this._removeTopicImpl(e),!0):!1}};function Ei(t,e){return new Wt(t,e)}function Lo(t,e){return new Ni(t,e)}function em(t,e,n){return new Co(t,e,n)}function _i(t,e,n,r){return new Ri(t,e,n,r)}var Oi={};Ee(Oi,{PipelineGraph:()=>Po,decisionKeyOf:()=>tm,pipelineGraph:()=>Rr});Oe();Re();se();Ze();Me();ne();ut();Fe();function Io(t,e){return we("orchestration",t,e)}var tm=t=>t.action,Po=class extends Y{constructor(e,n){super(e,n)}task(e,n,r={}){let o=(r.deps??[]).map(i=>this._resolveStep(i)),s=O(o,n,{name:e,describeKind:"derived",meta:Io("task",r.meta)});return this.add(s,{name:e}),s}classify(e,n,r,o={}){let s=this._resolveStep(n),i=O([s],([a])=>{try{return{tag:r(a),value:a}}catch(d){return{tag:"error",value:a,error:d}}},{name:e,describeKind:"derived",meta:Io("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=O(s,a=>{let d={};for(let u=0;u<o.length;u++)d[o[u]]=a[u];return d},{name:e,describeKind:"derived",meta:Io("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 Y(`${e}_state`),d=A([],{name:"pending",equals:()=>!1}),u=A(s,{name:"isOpen"}),c=O([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 q of F)q[0]===_&&(g=q[1])});this.addDisposer(y);function b(){d.emit([...f])}function v(F,q,D){p.append({action:F,t_ns:ie(),...q!==void 0?{items:q,count:q.length}:{},...D!==void 0?{unflushed:D}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function T(F){if(f.push(F),f.length>o){let q=f.shift();l.emit(l.cache+1),v("drop",[q])}b()}function w(F){let q=f.splice(0,F);return b(),q}let k=J([i],(F,q,D)=>{let B=D.terminalDeps[0];if(B!==void 0){m=!0;let ye=f.length;f=[],b(),v("teardown",void 0,ye),q.down(B===!0?[[I]]:[[L,B]]);return}let re=F[0];if(re==null||re.length===0){q.down([[z]]);return}for(let ye of re)g?q.emit(ye):(T(ye),q.down([[z]]))},{name:e,describeKind:"derived",meta:Io("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 q=r.approver.subscribe(D=>{for(let B of D){if(B[0]!==_)continue;let re=!!B[1];if(re&&!g){if(r.onceOnly){if(h)continue;h=!0}Z(()=>{u.emit(!0);let ye=w(f.length);v("open",ye);for(let ee of ye){if(m)break;k.emit(ee)}})}else if(!re&&g){if(r.onceOnly&&h)continue;Z(()=>{u.emit(!1),v("close")})}}});this.addDisposer(q)}let R=F=>{if(m)throw new Error(`approvalGate: ${F}() called after the gate was torn down`)},S=(F=1)=>{R("approve");let q=w(F);for(let D of q){if(m)break;k.emit(D)}},x=(F=1)=>{R("reject"),w(F)},N=(F,q=1)=>{R("modify");let D=[...f],B=w(q);for(let re=0;re<B.length&&!m;re++)k.emit(F(B[re],re,D))},E=()=>{R("open"),u.emit(!0);let F=w(f.length);for(let q of F){if(m)break;k.emit(q)}},P=()=>{R("close"),!(r.onceOnly&&h)&&u.emit(!1)},M=Lt(S,{audit:p,freeze:!1,onSuccess:(F,q,D)=>({action:"approve",count:F[0]??1,t_ns:D.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,q,D)=>({action:"drop",t_ns:D.t_ns,errorType:D.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),C=Lt(x,{audit:p,freeze:!1,onSuccess:(F,q,D)=>({action:"reject",count:F[0]??1,t_ns:D.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,q,D)=>({action:"drop",t_ns:D.t_ns,errorType:D.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),$=Lt(N,{audit:p,freeze:!1,onSuccess:(F,q,D)=>({action:"modify",count:F[1]??1,t_ns:D.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,q,D)=>({action:"drop",t_ns:D.t_ns,errorType:D.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),V=Lt(E,{audit:p,freeze:!1,onSuccess:(F,q,D)=>({action:"open",t_ns:D.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,q,D)=>({action:"drop",t_ns:D.t_ns,errorType:D.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),G=Lt(P,{audit:p,freeze:!1,onSuccess:(F,q,D)=>({action:"close",t_ns:D.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:(F,q,D)=>({action:"drop",t_ns:D.t_ns,errorType:D.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:V,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=J([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([[z]]);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:Io("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 Rr(t,e){let n=new Po(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("pipelineGraph",He(s)),n}async function nm(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:ie()}),i.type==="token"&&(o+=i.delta);return o}function rm(t,e){if(e==="json")try{return JSON.parse(zt(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 om(t,e){return O([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 eb(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=Ei(`${o}/stream`,{...r?.retainedLimit!=null?{retainedLimit:r.retainedLimit}:{}}),a=O(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=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 nm(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield rm(h,s)}finally{f.abort()}}return Q(m())},{meta:Te("streamingPromptNode")}),u=om(i,`${o}::accumulatedText`),c=te(d);return{output:d,deltaTopic:i,accumulatedText:u,dispose:()=>{c(),i.destroy()}}}function tb(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=Ei(`${u}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=O(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=ke(p,R=>{let S=R;if(!S||S.length===0)return A(null);let x=new AbortController;async function*N(){try{let E=await nm(n,S,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:x.signal},l);yield rm(E,c)}finally{x.abort()}}return Q(N())},{meta:Te("gatedStream")}),m=om(l,`${u}::accumulatedText`),h=kt(f,R=>R!=null);t.add(h,{name:`${e}/raw`});let g=Rr(`${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();ce();function nb(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(ky)}]),e?.providerExtras&&Object.assign(o,e.providerExtras),o}function ky(t){return{name:t.name,description:t.description,parameters:t.parameters}}function Wf(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 qd(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 Uf(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:qd(t.usageMetadata),finishReason:n?.finishReason,latencyMs:e,model:t.modelVersion,provider:"google"}}function xy(t){if(t.apiKey)return t.apiKey;let e=globalThis.process?.env;return e?.GOOGLE_API_KEY??e?.GEMINI_API_KEY}function Ry(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=xy(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=Ti(s,i),u=W(),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 Mt(l,"Google");let p=await l.json(),f=Math.max(0,(W()-u)/1e6);return Uf(p,f)},async*stream(s,i){let a=r(i),d=Ti(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 Mt(c,"Google");if(!c.body)throw new Error("googleAdapter: streaming response has no body");let l,p;for await(let f of Ht(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:qd(l)}),yield{type:"finish",reason:p??"stop"}}}}function Sy(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=Ti(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=Wf(o,s,r?.signal),a=W(),d=await e.models.generateContent(i),u=Math.max(0,(W()-a)/1e6);return Uf(d,u)},async*stream(n,r){if(!e.models.generateContentStream)throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");let o=Ti(n,r),s=r?.model??t.model;if(!s)throw new Error("googleAdapter: model required");let i=Wf(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:qd(a)}),yield{type:"finish",reason:d??"stop"}}}}Re();var Ny={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 zd(t={}){return t.sdk?Ay(t):Oy(t)}function wi(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(Ey);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(_y)),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 Ey(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 _y(t){return{type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}}function Hd(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 Jf(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:My(a.function.arguments)}));return{content:s,toolCalls:i.length>0?i:void 0,usage:Hd(t.usage),finishReason:r?.finish_reason,latencyMs:e,model:t.model,provider:n}}function My(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!=null?e:{_raw:t}}catch{return{_raw:t}}}function Yf(t){let e=t.preset??"openai",n=Ny[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 Oy(t){let{provider:e,baseURL:n,apiKey:r}=Yf(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=wi(a,d,t.model,!1,t.bodyExtras),c=W(),l=await o(`${n}/chat/completions`,{method:"POST",headers:i(),body:JSON.stringify(u),signal:d?.signal});if(!l.ok)throw await Mt(l,e);let p=await l.json(),f=Math.max(0,(W()-c)/1e6);return Jf(p,f,e)},async*stream(a,d){let u=wi(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 Mt(c,e);if(!c.body)throw new Error(`openAICompatAdapter[${e}]: streaming response has no body`);let l,p;for await(let f of Ht(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:Hd(l)})}yield{type:"finish",reason:p??"stop"}}}}function Ay(t){let e=t.sdk;if(!e)throw new Error("sdkBackedOpenAI: sdk instance required");let{provider:n}=Yf(t);return{provider:n,model:t.model,async invoke(r,o){let s=wi(r,o,t.model,!1,t.bodyExtras),i=W(),a=await e.chat.completions.create(s,{signal:o?.signal}),d=Math.max(0,(W()-i)/1e6);return Jf(a,d,n)},async*stream(r,o){let s=wi(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:Hd(l)})}yield{type:"finish",reason:d??"stop"}}}}function Cy(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 $d(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 Kd(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 Vd(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 zd(e)}default:{let e=t.provider;throw new Error(`createAdapter: unknown provider: ${String(e)}`)}}}Re();re();pe();function Ot(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 Wt(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 Qf(){return{input:{regular:0},output:{regular:0}}}function Ly(t,e){let n=e?.logMax??1e3,r=Ue(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:n}),o=C(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+Ot(y.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),a=A([r.entries],([h])=>h.reduce((g,y)=>g+Wt(y.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),d=[ne(s),ne(i),ne(a)],u=h=>{r.append(h),o.emit(h)},c=()=>{r.clear(),o.emit(null)},l=dt(t,{invoke(h,g){let y=W(),b=ie(),v=t.model??g?.model??"",T=k=>(u(qn({provider:t.provider,model:t.model??g?.model??k.model??"",tier:g?.tier??k.tier,usage:k.usage??Dt(),startNs:y,startWallClockNs:b,method:"invoke"})),k),w=k=>{let x=k;u(qn({provider:t.provider,model:v,tier:g?.tier,usage:Dt(),startNs:y,startWallClockNs:b,method:"invoke",error:{type:x?.name??"Error",message:x?.message??String(k)}}))};return vi(t.invoke(h,g),{onResp:T,onError:w,name:"adapterStats/invokeTap"})},async*stream(h,g){let y=W(),b=ie(),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(qn({provider:t.provider,model:v,tier:g?.tier,usage:T??Dt(),startNs:y,startWallClockNs:b,method:"stream"}))}catch(w){let k=w;throw u(qn({provider:t.provider,model:v,tier:g?.tier,usage:T??Dt(),startNs:y,startWallClockNs:b,method:"stream",error:{type:k?.name??"Error",message:k?.message??String(w)}})),w}}});tt(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 Iy(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function xi(t="USD"){return{total:0,currency:t}}function Wd(t,e,n){let r=Ot(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=Iy(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 ki(t,e){return`${t}::${e}`}function Py(t){let e=new Map,n=new Map,r=(o,s,i)=>{e.set(ki(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(ki(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(ki(o,u));c&&(d={key:u,pricing:c.pricing})}return d?.pricing},remove(o,s){let i=e.delete(ki(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 Dy(t,e="USD"){return(n,r)=>{let o=t.lookup(r.provider,r.model);return o?Wd(n,o,{tier:r.tier,withBreakdown:r.withBreakdown}):xi(e)}}function Gy(...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):xi()}}function Fy(t,e,n){return t?.pricing?Wd(e,t.pricing,n):xi()}sn();pe();function Ud(t,e={}){let n=e.breaker??St(e),r=dt(t,{async invoke(o,s){if(!n.canExecute())throw new Et;try{let i=await it(X(t.invoke(o,s)));return n.recordSuccess(),i}catch(i){throw n.recordFailure(i),i}},async*stream(o,s){if(!n.canExecute())throw new Et;try{for await(let i of t.stream(o,s))yield i;n.recordSuccess()}catch(i){throw n.recordFailure(i),i}}});return tt(r,"withBreaker",t),{adapter:r,breaker:n}}Re();se();re();pe();var Ri=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"},Jd=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),Xf=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Yd(t,e){let n=Ue(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),r=C(Xf(),{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(ne(o),e.onExhausted!=null){let u=e.onExhausted,c=!1,l=!0;o.subscribe(p=>{for(let f of p)if(f[0]===E){let m=f[1];if(c&&l&&m===!1){let h=Zf(r.cache??Jd,e.caps);h&&u(h)}l=m,c=!0}})}let s=()=>{if(o.cache===!1){let u=r.cache??Jd,c=Zf(u,e.caps);return new Ri(c??"budget",e.caps[c??"calls"]??0,$y(u,c??"calls"))}},i=(u,c)=>{let l=t.provider,p=qn({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??Jd,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+Ot(u),outputTokens:f.outputTokens+Wt(u),usd:m})},a=()=>{n.clear(),r.emit(Xf())},d=dt(t,{invoke(u,c){let l=s();if(l)return Promise.reject(l);let p=W(),f=t.model??c?.model??"",m=g=>(i(g.usage??Dt(),{model:t.model??c?.model??g.model??"",tier:c?.tier??g.tier,startNs:p,method:"invoke"}),g),h=g=>{let y=g;i(Dt(),{model:f,tier:c?.tier,startNs:p,method:"invoke",error:{type:y?.name??"Error",message:y?.message??String(g)}})};return vi(t.invoke(u,c),{onResp:m,onError:h,name:"budgetGate/invokeTap"})},async*stream(u,c){let l=s();if(l)throw l;let p=W(),f;try{for await(let m of t.stream(u,c))m.type==="usage"&&(f=m.usage),yield m;i(f??Dt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream"})}catch(m){let h=m;throw i(f??Dt(),{model:t.model??c?.model??"",tier:c?.tier,startNs:p,method:"stream",error:{type:h?.name??"Error",message:h?.message??String(m)}}),m}}});return tt(d,"withBudgetGate",t),{adapter:d,budget:{totals:r,isOpen:o,log:n,reset:a}}}function Zf(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 $y(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}pe();function jy(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?X(e.enabled):void 0,s;o&&(s=ne(o));let i=()=>r!==void 0?r:!!o?.cache,a=dt(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 tt(a,"withDryRun",t),{adapter:a,dispose:()=>{s&&(s(),s=void 0)}}}function Qd(t){if(t==null||typeof t!="object")return;let e=t,n=e.status,r=By(e.headers);if(n!==429&&n!==503&&!Wy(e.message))return;let o={},s=r("retry-after"),i=Ky(s);i!=null&&(o.retryAfterMs=i);let a=r("anthropic-ratelimit-requests-reset");if(a){let f=em(a);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let d=r("anthropic-ratelimit-tokens-reset");if(d){let f=em(d);f!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,f))}let u=Si(r,"x-ratelimit-limit-requests");u!=null&&(o.rpmCap=u);let c=Si(r,"x-ratelimit-limit-tokens");c!=null&&(o.tpmCap=c);let l=Si(r,"x-ratelimit-remaining-requests"),p=Si(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=zy(e.message);f!=null&&(o.retryAfterMs=f)}return e.headers&&(o.metadata={headers:Vy(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function By(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 Vy(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 Si(t,e){let n=t(e);if(n==null)return;let r=Number(n);return Number.isFinite(r)?r:void 0}function Ky(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 em(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var qy=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function zy(t){let e=qy.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 Hy=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Wy(t){return!!t&&Hy.test(t)}Re();se();re();sn();pe();Lt();function Xd(t){let e=new Error(t);return e.name="AbortError",e}function nm(t={}){let e=Math.max(1,t.burstMultiplier??1),n=t.clampCooldownMs??6e4,r=t.rpm!=null?X(t.rpm):C(Number.POSITIVE_INFINITY),o=t.tpm!=null?X(t.tpm):C(Number.POSITIVE_INFINITY),s=C(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),i=C(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),a=C({},{name:"adaptiveRateLimiter/lastSignal"}),d=A([r,s],([M,N])=>Math.min(Number(M??1/0),Number(N??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),u=A([o,i],([M,N])=>Math.min(Number(M??1/0),Number(N??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),c=xr(Number(r.cache??Number.POSITIVE_INFINITY),e),l=xr(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,f=!1,m=d.subscribe(M=>{for(let N of M)if(N[0]===E){let P=Number(N[1]);Number.isFinite(P)&&P>0?(c=xr(P,e),p=!1):P===1/0?(c=xr(1/0,e),p=!1):P<=0&&(p=!0)}}),h=u.subscribe(M=>{for(let N of M)if(N[0]===E){let P=Number(N[1]);Number.isFinite(P)&&P>0?(l=xr(P,e),f=!1):P===1/0?(l=xr(1/0,e),f=!1):P<=0&&(f=!0)}}),g=0,y=new Ie,b=new Ie,v;t.adaptation!=null&&(v=X(t.adaptation).subscribe(N=>{for(let P of N)P[0]===E&&T(P[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 N=W()+M.retryAfterMs*1e6;N>g&&(g=N)}}let w=C(0,{name:"adaptiveRateLimiter/pending"}),k=C(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),x=C(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),R=M=>{w.emit((w.cache??0)+M)},S=()=>{k.emit(c.available()),x.emit(l.available())};async function _(M={}){let N=M.requestCost??1,P=M.tokenCost??0,j=M.signal;R(1);try{for(;;){if(j?.aborted)throw Xd("AdaptiveRateLimiter.acquire aborted");let G=W();if(g>G){let B=Math.ceil((g-G)/1e6);await Ni(B,j);continue}if(N>0&&p||P>0&&f){await Ni(250,j);continue}let V=c,$=l;if(!V.tryConsume(N)){await Ni(tm(V,N),j);continue}if(!(P>0?$.tryConsume(P):!0)){V.putBack(N),await Ni(tm($,P),j);continue}S();return}}finally{R(-1)}}function O(M){M>0?l.tryConsume(M):M<0&&l.putBack(-M),S()}function D(){m(),h(),v?.(),y.cancel(),b.cancel()}return{effectiveRpm:d,effectiveTpm:u,lastSignal:a,pending:w,rpmAvailable:k,tpmAvailable:x,acquire:_,recordUsage:O,recordSignal:T,dispose:D}}function xr(t,e){if(!Number.isFinite(t)||t===1/0)return Vt(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let n=Math.max(1,t*e),r=t/60;return Vt(n,r)}function tm(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 Ni(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Xd("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(Xd("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",s,{once:!0}))})}pe();function Zd(t,e={}){let n=e.limiter??nm({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=Qd(i);a&&n.recordSignal(a)},s=dt(t,{async invoke(i,a){let d=r(i,a);await n.acquire({requestCost:1,tokenCost:d,signal:a?.signal});try{let u=await it(X(t.invoke(i,a))),c=u.usage??Qf(),p=Ot(c)+Wt(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=Ot(l.usage)+Wt(l.usage)),yield l;let c=u-d;c>0&&n.recordUsage(c)}catch(u){throw o(u),u}}});return tt(s,"withRateLimiter",t),{adapter:s,limiter:n}}sn();pe();var Co=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 eu(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:St(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 it(X(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 Co(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 Co(u)}};return tt(o,`cascade[${n.map(s=>s.name).join(",")}]`),o}function Uy(t,e,n){let r={name:t,adapter:e};return n?.breaker&&(r.breaker=n.breaker),n?.filter&&(r.filter=n.filter),r}pe();Lt();function Ei(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function rm(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ei()):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(Ei())},e.addEventListener("abort",s,{once:!0}))})}function tu(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??Jy,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=dt(t,{async invoke(l,p){if(p?.signal?.aborted)throw Ei();let f,m=r;for(let h=1;h<=n;h++)try{return await it(X(t.invoke(l,p)))}catch(g){if(f=g,h>=n||!a(g,h))throw g;let y=u(h,m);m=y,await rm(y,p?.signal)}throw f},async*stream(l,p){if(p?.signal?.aborted)throw Ei();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 rm(b,p?.signal)}}throw f}});return tt(c,"withRetry",t),c}function Jy(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}pe();Lt();var Rr=class extends Error{constructor(n){super(`LLM call timed out after ${n}ms`);this.ms=n}name="LLMTimeoutError"};function nu(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 Rr(e))}),{signal:i.signal,cancel:()=>{u.cancel(),s&&d&&s.removeEventListener("abort",d)},timedOut:()=>a}},r=(s,i)=>{if(!i||s instanceof Rr)throw s;let a=s;if(a?.name==="AbortError"||a?.name==="DOMException"&&Number(a.code)===20||s?.message==="aborted"){let u=new Rr(e);throw u.cause=s,u}throw s},o=dt(t,{async invoke(s,i){let{signal:a,cancel:d,timedOut:u}=n(i?.signal);try{return await it(X(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 tt(o,"withTimeout",t),o}function Yy(t,e={}){let n={adapter:t},r=t;if(e.rateLimit){let o=Zd(r,e.rateLimit);r=o.adapter,n.rateLimiter=o.limiter}if(e.budget){let o=Yd(r,e.budget);r=o.adapter,n.budget=o.budget}if(e.breaker){let o=Ud(r,e.breaker);r=o.adapter,n.breaker=o.breaker}if(e.timeoutMs!=null&&(r=nu(r,e.timeoutMs)),e.retry&&(r=tu(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=eu([{name:e.name??"primary",adapter:r},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(r=Ao(r,e.cache)),n.adapter=r,n}Ze();Me();pe();se();re();ut();pe();Lt();function ve(t,e){return we("ai",t,e)}function Qy(t){return t!=null&&typeof t.then=="function"}function ru(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function Xy(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Zy=3e4;function om(t,e){if(t.status==="settled"){let r=t.cache;if(r!==void 0)return Promise.resolve(r)}let n=e?.timeoutMs??Zy;return new Promise((r,o)=>{let s=new Ie,i=t.subscribe(a=>{for(let d of a){if(d[0]===E){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 Lo(t){return Qy(t)?Lo(await t):ru(t)?om(t):Xy(t)?om(X(t)):t}function Ut(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function ou(t,e,n){return z(r=>{let o=new AbortController,s=n.parentSignal,i=()=>{};if(s)if(s.aborted)o.abort();else{let p=()=>o.abort();s.addEventListener("abort",p,{once:!0}),i=()=>s.removeEventListener("abort",p)}let a=!1,d=null,u=p=>{a||(a=!0,r.down([[E,p],[I]]),d?.(),d=null)},c;try{c=t.invoke(e,{...n.invokeOpts,signal:o.signal})}catch(p){return u(n.onFailure("throw",p)),()=>{i(),o.abort()}}return d=X(c,{signal:o.signal}).subscribe(p=>{for(let f of p){if(a)return;if(f[0]===E){try{u(n.onSuccess(f[1]))}catch(m){u(n.onFailure("onSuccess-threw",m))}return}if(f[0]===L){u(n.onFailure("error",f[1]));return}if(f[0]===I){u(n.onFailure("complete",void 0));return}}}),a&&d&&(d(),d=null),()=>{i(),o.abort(),d?.(),d=null}})}function eb(t,e){let n=X(t),r=e?.refreshTrigger!=null?X(e.refreshTrigger):null,o=e?.name!==void 0?{name:e.name}:void 0,s=Te("frozenContext",o);return r==null?Q([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})}):Q([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})})}re();se();re();We();pe();function sm(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function tb(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Io(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=e.length,a=r?.tools!==void 0?[...e,r.tools]:e,d=A(a,c=>{let l=c.slice(0,i),p=r?.tools!==void 0?c[i]:void 0;if(l.some(m=>m==null))return{messages:[],tools:p};let f=typeof n=="string"?n:n(...l);return f?{messages:[{role:"user",content:f}],tools:p}:{messages:[],tools:p}},{name:`${s}::messages`,meta:ve("prompt_node")});return ke(d,c=>{let{messages:l,tools:p}=c;return!l||l.length===0?C(null):z(f=>{let m=!1,h=!1,g,y={model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,...p!==void 0?{tools:p}:{}};if(r?.abort){let w=Vs(r.abort);y.signal=w.signal,g=w.dispose}let b;try{b=t.invoke(l,y)}catch(w){return m=!0,f.down([[L,w]]),()=>{g?.()}}let T=X(b).subscribe(w=>{if(!(h||m))for(let k of w){if(m)return;if(k[0]===E){let x=k[1];if(o==="raw")f.emit(x);else try{let R=sm(x),S=o==="json"?JSON.parse(Ut(R)):R;f.emit(S)}catch(R){let S=sm(x),_=new Error(`promptNode: failed to parse LLM response as JSON: ${R.message}
|
|
37
|
+
Raw content (first 200 chars): ${tb(S)}`);m=!0,f.down([[L,_]]);return}}else if(k[0]===L){m=!0,f.down([[L,k[1]]]);return}else if(k[0]===I){m=!0,f.down([[I]]);return}else f.down([k])}});return()=>{h=!0,T(),g?.()}},{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 su(t,e,n,r){let o=n.name??r;return s=>{let i=C(s);return Io(n.adapter,[i],a=>e(a),{name:o,format:"json",systemPrompt:t,model:n.model,temperature:n.temperature??0,maxTokens:n.maxTokens})}}function iu(t,e){let n=e.maxExistingKeys??100,r=su(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 au(t,e){let n=su(t,r=>JSON.stringify({memories:r}),e,"llmConsolidator");return r=>{let o=[...r.entries()].map(([s,i])=>({key:s,value:i}));return n(o)}}Oe();Re();Ze();re();We();pe();var Li={};Ee(Li,{MessagingHubGraph:()=>Oi,SubscriptionGraph:()=>Po,TopicBridgeGraph:()=>_i,TopicGraph:()=>Jt,TopicRegistry:()=>Mi,messagingHub:()=>Do,subscription:()=>im,topic:()=>Ai,topicBridge:()=>Ci});Me();ut();pe();bt();var nb=256;function Sr(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function pn(t,e){return we("messaging",t,e)}var rb=1024,Jt=class extends Y{_log;_publishImpl;events;latest;hasLatest;constructor(e,n={}){super(e,n.graph),this._log=Ue([],{name:"events",maxSize:n.retainedLimit??rb}),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:pn("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(ne(this.latest)),this.hasLatest=A([this.events],([r])=>r.length>0,{name:"hasLatest",describeKind:"derived",meta:pn("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(ne(this.hasLatest)),this.addDisposer(()=>{this.events.down([[I]])}),this.addDisposer(()=>this._log.disposeAllViews()),this._publishImpl=Le(r=>{this._log.append(r)},{freeze:!1})}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._publishImpl(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},Po=class extends Y{cursor;available;topic;_disposed=!1;_ackImpl;_pullAndAckImpl;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=Sr(r.from,"subscription from"):o=Sr(r.cursor??0,"subscription cursor"),this.cursor=C(o,{name:"cursor",describeKind:"state",meta:pn("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(ne(this.available)),r.advanceOn!==void 0){let s=r.advanceOn,i=!1,a=Q([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:pn("subscription_advance_pump")});this.add(a,{name:"advancePump"}),this.addDisposer(ne(a))}this._ackImpl=Le(s=>{let i=this.available.cache,a=s===void 0?i.length:Sr(s,"subscription ack count"),d=Math.min(a,i.length);if(d<=0)return this.cursor.cache;let u=this.cursor.cache+d;return this.cursor.emit(u),u},{freeze:!1}),this._pullAndAckImpl=Le(s=>{let i=this.available.cache,a=s===void 0?i.length:Sr(s,"subscription pullAndAck limit"),d=i.slice(0,a);if(d.length===0)return{items:d,cursor:this.cursor.cache};let u=this.cursor.cache+d.length;return this.cursor.emit(u),{items:d,cursor:u}},{freeze:!1})}ack(e){return this._disposed?this.cursor.cache:this._ackImpl(e)}pull(e){if(this._disposed)return[];let n=this.available.cache,r=e===void 0?n.length:Sr(e,"subscription pull limit");return n.slice(0,r)}pullAndAck(e){return this._disposed?{items:[],cursor:this.cursor.cache}:this._pullAndAckImpl(e)}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[I]]),this.destroy())}},_i=class extends Y{_sourceSub;bridgedCount;output;constructor(e,n,r,o={}){super(e,o.graph),this._sourceSub=im(`${e}-subscription`,n,{cursor:o.cursor}),this.mount("subscription",this._sourceSub);let s=Math.max(1,Sr(o.maxPerPump??nb,"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:pn("topic_bridge_output",{targetRef:r.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(ne(this.output)),this.bridgedCount=C(0,{name:"bridgedCount",describeKind:"state",meta:pn("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(ne(this.bridgedCount));let a=this.output,d=this._sourceSub,u=this.bridgedCount,c=Q([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:pn("topic_bridge_ack_pump")});this.add(c,{name:"ackPump"}),this.addDisposer(ne(c));let l=ob(this.output,r);this.addDisposer(l)}};function ob(t,e){return t.subscribe(n=>{for(let r of n){if(r[0]!==E)continue;let o=r[1];o.length!==0&&Z(()=>{for(let s of o)e.publish(s)})}})}var Mi=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()}},Oi=class extends Y{_registry;version;_defaultTopicOptions;_removeTopicImpl;constructor(e,n={}){super(e,n.graph);let r=C(0,{name:"version",describeKind:"state",meta:pn("hub_version")});this.add(r,{name:"version"}),this.version=r,this._registry=new Mi(r),this._defaultTopicOptions={...n.defaultTopicOptions??{}},this._removeTopicImpl=Le(o=>{try{this.remove(o)}finally{this._registry.delete(o);let s=this.version.cache??0;this.version.emit(s+1)}},{freeze:!1})}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 Jt(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 Po(e,o,r)}removeTopic(e){return this._registry.has(e)?(this._removeTopicImpl(e),!0):!1}};function Ai(t,e){return new Jt(t,e)}function Do(t,e){return new Oi(t,e)}function im(t,e,n){return new Po(t,e,n)}function Ci(t,e,n,r){return new _i(t,e,n,r)}var Ii={};Ee(Ii,{PipelineGraph:()=>Fo,decisionKeyOf:()=>am,pipelineGraph:()=>Nr});Oe();Re();se();Ze();Me();re();ut();Fe();function Go(t,e){return we("orchestration",t,e)}var am=t=>t.action,Fo=class extends Y{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:Go("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:Go("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:Go("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 Y(`${e}_state`),d=C([],{name:"pending",equals:()=>!1}),u=C(s,{name:"isOpen"}),c=A([d],([$])=>$.length,{name:"count"}),l=C(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($=>{for(let q of $)q[0]===E&&(g=q[1])});this.addDisposer(y);function b(){d.emit([...f])}function v($,q,F){p.append({action:$,t_ns:ie(),...q!==void 0?{items:q,count:q.length}:{},...F!==void 0?{unflushed:F}:{},...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}function T($){if(f.push($),f.length>o){let q=f.shift();l.emit(l.cache+1),v("drop",[q])}b()}function w($){let q=f.splice(0,$);return b(),q}let k=Q([i],($,q,F)=>{let B=F.terminalDeps[0];if(B!==void 0){m=!0;let de=f.length;f=[],b(),v("teardown",void 0,de),q.down(B===!0?[[I]]:[[L,B]]);return}let te=$[0];if(te==null||te.length===0){q.down([[H]]);return}for(let de of te)g?q.emit(de):(T(de),q.down([[H]]))},{name:e,describeKind:"derived",meta:Go("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 q=r.approver.subscribe(F=>{for(let B of F){if(B[0]!==E)continue;let te=!!B[1];if(te&&!g){if(r.onceOnly){if(h)continue;h=!0}Z(()=>{u.emit(!0);let de=w(f.length);v("open",de);for(let J of de){if(m)break;k.emit(J)}})}else if(!te&&g){if(r.onceOnly&&h)continue;Z(()=>{u.emit(!1),v("close")})}}});this.addDisposer(q)}let x=$=>{if(m)throw new Error(`approvalGate: ${$}() called after the gate was torn down`)},R=($=1)=>{x("approve");let q=w($);for(let F of q){if(m)break;k.emit(F)}},S=($=1)=>{x("reject"),w($)},_=($,q=1)=>{x("modify");let F=[...f],B=w(q);for(let te=0;te<B.length&&!m;te++)k.emit($(B[te],te,F))},O=()=>{x("open"),u.emit(!0);let $=w(f.length);for(let q of $){if(m)break;k.emit(q)}},D=()=>{x("close"),!(r.onceOnly&&h)&&u.emit(!1)},M=gt(R,{audit:p,freeze:!1,onSuccess:($,q,F)=>({action:"approve",count:$[0]??1,t_ns:F.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,q,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),N=gt(S,{audit:p,freeze:!1,onSuccess:($,q,F)=>({action:"reject",count:$[0]??1,t_ns:F.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,q,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),P=gt(_,{audit:p,freeze:!1,onSuccess:($,q,F)=>({action:"modify",count:$[1]??1,t_ns:F.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,q,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),j=gt(O,{audit:p,freeze:!1,onSuccess:($,q,F)=>({action:"open",t_ns:F.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,q,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})}),G=gt(D,{audit:p,freeze:!1,onSuccess:($,q,F)=>({action:"close",t_ns:F.t_ns,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}}),onFailure:($,q,F)=>({action:"drop",t_ns:F.t_ns,errorType:F.errorType,...r.handlerVersion!=null?{handlerVersion:r.handlerVersion}:{}})});return this.addDisposer(c.subscribe(()=>{})),{output:k,pending:d,count:c,isOpen:u,droppedCount:l,decisions:p,audit:p,approve:M,reject:N,modify:P,open:j,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=Q([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([[H]]);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:Go("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 Nr(t,e){let n=new Fo(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("pipelineGraph",He(s)),n}async function dm(t,e,n,r){let o="",s=0;for await(let i of t.stream(e,n))r.publish({...i,seq:s++,ts:ie()}),i.type==="token"&&(o+=i.delta);return o}function um(t,e){if(e==="json")try{return JSON.parse(Ut(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 cm(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 sb(t,e,n,r){let o=r?.name??"llm",s=r?.format??"text",i=Ai(`${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=ke(a,l=>{let p=l;if(!p||p.length===0)return C(null);let f=new AbortController;async function*m(){try{let h=await dm(t,p,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,systemPrompt:r?.systemPrompt,signal:f.signal},i);yield um(h,s)}finally{f.abort()}}return X(m())},{meta:Te("streamingPromptNode")}),u=cm(i,`${o}::accumulatedText`),c=ne(d);return{output:d,deltaTopic:i,accumulatedText:u,dispose:()=>{c(),i.destroy()}}}function ib(t,e,n,r,o,s){let i=C(0,{name:`${e}/cancel`}),a=0,d=[...r,i],u=s?.name??e,c=s?.format??"text",l=Ai(`${u}/stream`,{...s?.retainedLimit!=null?{retainedLimit:s.retainedLimit}:{}}),p=A(d,x=>{let R=x.slice(0,-1);if(R.some(_=>_==null))return[];let S=typeof o=="string"?o:o(...R);return S?[{role:"user",content:S}]:[]},{name:`${u}::messages`,meta:ve("prompt_node::messages"),initial:[]}),f=ke(p,x=>{let R=x;if(!R||R.length===0)return C(null);let S=new AbortController;async function*_(){try{let O=await dm(n,R,{model:s?.model,temperature:s?.temperature,maxTokens:s?.maxTokens,systemPrompt:s?.systemPrompt,signal:S.signal},l);yield um(O,c)}finally{S.abort()}}return X(_())},{meta:Te("gatedStream")}),m=cm(l,`${u}::accumulatedText`),h=xt(f,x=>x!=null);t.add(h,{name:`${e}/raw`});let g=Nr(`${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=ne(f),v=ne(y.output),T=ne(m);t.addDisposer(b),t.addDisposer(v),t.addDisposer(T);let w=y.reject.bind(y),k={...y,reject(x=1){Z(()=>{w(x),i.emit(++a)})}};return{output:y.output,deltaTopic:l,accumulatedText:m,gate:k,dispose:()=>{b(),v(),T(),l.destroy()}}}re();pe();function ab(t,e){let n=e?.separator??`
|
|
38
38
|
|
|
39
|
-
`,r=t.map(i=>typeof i=="string"?A(i):Q(i)),o=O(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 rb=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function ob(t,e){let n=e?.charsPerToken??4,r={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return O([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=_t(i.usage)+Ht(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:rb})}ne();var sb=(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 ib(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 O([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:sb})}ne();function ab(t,e,n){return O([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 db=(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 ub(t,e){return O([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:db})}ne();function cb(t,e,n,r){let o=n*(r?.hardMultiplier??1.5),s=typeof e!="function",i=[t];return s&&i.push(e),O(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 lb(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 O([t],([i])=>s(i??""),{name:r?.name??"redactor",initial:""})}ne();ce();Fe();var Ai=class extends Y{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=We([],{name:"messages",maxSize:n.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=O([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=O([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 tu(t,e){return new Ai(t,e)}Ze();ne();ze();ce();function pb(t,e,n){let r=Q(t),o=n?.condition!=null?Q(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:Te("handoff")});let i=O([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:Te("handoff")})}ne();ze();on();function nu(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=>fb(d,n,r,o));return O(a,d=>d,{name:"toolExecution::batch",equals:s})})}function fb(t,e,n,r){let o=xt(()=>e.executeReactive(t.name,t.arguments),{count:n}),s=O([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)})}))}se();ne();ce();Fe();var Ci=class extends Y{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Xe({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=O([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 H(o=>{let s=new AbortController,i;try{let d=r.handler(n,{signal:s.signal});i=mb(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 ru(t,e){return new Ci(t,e)}function mb(t,e){return Yd(t)?t:t!=null&&typeof t.then=="function"?fr(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?io(t,{signal:e}):fr(Promise.resolve(t),{signal:e})}Ze();ne();ce();function gb(t,e,n){let r=Q(t),o=e.map(i=>Q(i)),s=[r,...o];return O(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"),...Te("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 sm(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 hb(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=sm({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}Oe();Re();ne();ce();var Pi={};Ee(Pi,{collection:()=>ou,cosineSimilarity:()=>Ii,knowledgeGraph:()=>iu,vectorIndex:()=>su});Re();Me();ne();ut();ce();Fe();var yb=1e9;function yt(t,e){return we("memory",t,e)}function Do(t,e){return t instanceof Ae?t:A(t,e?{name:e}:void 0)}function im(t,e){return(t-e)/yb}function Ii(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 bb(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 vb(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 ou(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 Ae?a:void 0,u=()=>d?d.cache??i:a,c=new Y(t),p=Xe({name:"items",...n!==void 0?{retention:{score:(M,C)=>r?It(C.baseScore,im(W(),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=st(M,{period:M});f=O([C],()=>W(),{name:"refresh_tick_ns",describeKind:"derived",initial:W(),meta:yt("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=O(M,C=>{let $=C[0],V;if(f){let K=C[1];V=typeof K=="number"?K:W()}else V=W();if(!$||$.size===0)return[];let G=[];for(let K of $.values())G.push({...K,score:It(K.baseScore,im(V,K.lastAccessNs),o,s)});return G.sort((K,F)=>F.score-K.score||F.lastAccessNs-K.lastAccessNs),G},{name:"ranked",describeKind:"derived",equals:vb,meta:yt("ranked")}),c.add(m,{name:"ranked"})}else m=A([],{name:"ranked",describeKind:"state",meta:yt("ranked_disabled")}),c.add(m,{name:"ranked"});let h=O([p.entries],([M])=>(M??new Map).size,{name:"size",describeKind:"derived",initial:0,meta:yt("size")});c.add(h,{name:"size"}),c.addDisposer(te(h));let g=at({name:"events",retainedLimit:1024,graph:c}),y=ht(c,"seq",0),b=(M,C,$)=>{let V=W(),G=p.get(M),K=$?.score??u()(C);p.set(M,{id:M,value:C,baseScore:K,createdAtNs:G?.createdAtNs??V,lastAccessNs:V})},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 V of C.values())$.push([V.id,{...V,baseScore:M(V.value)}]);p.setMany($)},k=Ce(b,{audit:g,seq:y,onSuccess:([M],C,$)=>({action:"upsert",id:M,t_ns:$.t_ns,seq:$.seq})}),R=Ce(v,{audit:g,seq:y,onSuccess:([M],C,$)=>({action:"remove",id:M,t_ns:$.t_ns,seq:$.seq})}),S=Ce(T,{audit:g,seq:y,onSuccess:(M,C,$)=>({action:"clear",t_ns:$.t_ns,seq:$.seq})}),x=Ce(w,{audit:g,seq:y,onSuccess:(M,C,$)=>({action:"rescore",t_ns:$.t_ns,seq:$.seq})});function N(M){let C=Do(M,"id");return O([p.entries,C],([$,V])=>$?.get(V),{describeKind:"derived",meta:yt("collection_item")})}function E(M){let C=Do(M,"id");return O([p.entries,C],([$,V])=>$?.has(V)??!1,{describeKind:"derived",meta:yt("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 su(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 Y(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=at({name:"events",retainedLimit:1024,graph:a}),f=ht(a,"seq",0),m=Xe({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:ie(),seq:Bt(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 P=(()=>{if(E!==void 0)return E===null||typeof E!="object"?E:Array.isArray(E)?[...E]:{...E}})(),M={id:x,vector:[...N],...P!==void 0?{meta:P}:{},upsertedAtNs:W()};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=Ce(h,{audit:p,freeze:!1,seq:f,onSuccess:([x],N,E)=>({action:"upsert",id:x,t_ns:E.t_ns,seq:E.seq})}),T=Ce(g,{audit:p,seq:f,onSuccess:([x],N,E)=>({action:"remove",id:x,t_ns:E.t_ns,seq:E.seq})}),w=Ce(y,{audit:p,seq:f,onSuccess:(x,N,E)=>({action:"clear",t_ns:E.t_ns,seq:E.seq})}),k=Ce(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=Do(N,"k");return O([m.entries,x,E],P=>{let M=P[0],C=P[1],$=P[2],V=Number.isFinite($)?Math.max(0,Math.floor($)):0;if(!M||M.size===0||V<=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,V)]:[...M.values()].map(F=>({id:F.id,score:Ii(C,F.vector),...F.meta!==void 0?{meta:F.meta}:{}})).sort((F,q)=>q.score-F.score).slice(0,V)},{describeKind:"derived",equals:(P,M)=>bb(P,M),meta:yt("vector_search")})}return Object.assign(a,{backend:e,events:p,entries:m.entries,upsert:v,remove:T,clear:w,reindex:k,searchNode:R})}var am="\0";function Li(t,e,n){return`${t}${am}${e}${am}${n}`}function dm(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 um(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 iu(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 Y(t),o=Xe({name:"entities",...e.entitiesMaxSize!==void 0?{maxSize:e.entitiesMaxSize}:{}}),s=Xe({name:"edges",...e.edgesMaxSize!==void 0?{maxSize:e.edgesMaxSize}:{}});r.add(o.entries,{name:"entities"}),r.add(s.entries,{name:"edges"});let i=O([s.entries],([S])=>dm(S,"from"),{name:"adjacencyOut",describeKind:"derived",initial:new Map,equals:um,meta:yt("adjacency_out")}),a=O([s.entries],([S])=>dm(S,"to"),{name:"adjacencyIn",describeKind:"derived",initial:new Map,equals:um,meta:yt("adjacency_in")});r.add(i,{name:"adjacencyOut"}),r.add(a,{name:"adjacencyIn"}),r.addDisposer(te(i)),r.addDisposer(te(a));let d=O([o.entries],([S])=>(S??new Map).size,{name:"entityCount",describeKind:"derived",initial:0,meta:yt("entity_count")}),u=O([s.entries],([S])=>(S??new Map).size,{name:"edgeCount",describeKind:"derived",initial:0,meta:yt("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=ht(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:ie(),seq:Bt(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[P,M]of x)(M.from===S||M.to===S)&&(E.push(P),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(Li(S,x,N),{from:S,to:x,relation:N,weight:E})},y=(S,x,N)=>{if(N!==void 0)s.delete(Li(S,x,N));else{let E=s.entries.cache;if(!E)return;let P=[];for(let[M,C]of E)C.from===S&&C.to===x&&P.push(M);P.length>0&&s.deleteMany(P)}f([S,x])},b=Ce(m,{audit:c,seq:l,onSuccess:([S],x,N)=>({action:"upsertEntity",id:S,t_ns:N.t_ns,seq:N.seq})}),v=Ce(h,{audit:c,seq:l,onSuccess:([S],x,N)=>({action:"removeEntity",id:S,t_ns:N.t_ns,seq:N.seq})}),T=Ce(g,{audit:c,seq:l,onSuccess:([S,x,N,E],P,M)=>({action:"link",from:S,to:x,relation:N,weight:E??1,t_ns:M.t_ns,seq:M.seq})}),w=Ce(y,{audit:c,seq:l,onSuccess:([S,x,N],E,P)=>({action:"unlink",from:S,to:x,...N!==void 0?{relation:N}:{},t_ns:P.t_ns,seq:P.seq})});function k(S,x){let N=Do(S,"id"),E=x!==void 0?Do(x,"relation"):void 0;return O(E?[i,a,N,E]:[i,a,N],M=>{let C=M[0],$=M[1],V=M[2],G=E?M[3]:void 0,K=C.get(V)??[],F=$.get(V)??[],q=new Set,D=[];for(let B of K){let re=Li(B.from,B.to,B.relation);q.has(re)||G!==void 0&&B.relation!==G||(q.add(re),D.push(B))}for(let B of F){let re=Li(B.from,B.to,B.relation);q.has(re)||G!==void 0&&B.relation!==G||(q.add(re),D.push(B))}return D},{describeKind:"derived",equals:(M,C)=>{let $=M,V=C;if($===V)return!0;if($==null||V==null||$.length!==V.length)return!1;for(let G=0;G<$.length;G+=1){let K=$[G],F=V[G];if(K.from!==F.from||K.to!==F.to||K.relation!==F.relation||K.weight!==F.weight)return!1}return!0},meta:yt("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 au(t,e,n){let r=su({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=he([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 du(t,e,n,r){let o=r.mountPath??n,s=iu(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let i=r.entityFn,d=he([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 uu(t,e,n){let r=n.decayRate??li,o=n.maxActive??1e3,s=n.archiveThreshold??.1,i=n.permanentFilter??(()=>!1),a=ou("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?Q(n.context):A(null),h=he([p,f],([b,v])=>{let T=b??new Map,w=W(),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),P=l.get(x)??w,M=Number(w-P)/1e9;It(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,P])=>({key:E,score:n.score(P,v)})).sort((E,P)=>E.score-P.score),N=S-o;for(let E=0;E<N&&E<x.length;E++){let P=x[E].key;k.includes(P)||k.push(P)}}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 Tb(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 cu(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?Q(o.context):A(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:Ii(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,P=[...b.entityIds??[],...v.keys()],M=new Set,C=P;for(let $=0;$<i;$++){let V=[];for(let G of C){if(M.has(G))continue;M.add(G);let K=N?.get(G)??[],F=E?.get(G)??[];for(let q of K){let D=q.to;if(!M.has(D)){V.push(D);let B=g.get(D);if(B){let re=v.get(D);re?re.sources.add("graph"):v.set(D,{value:B,sources:new Set(["graph"])}),w.push(D)}}}for(let q of F){let D=q.from;if(!M.has(D)){V.push(D);let B=g.get(D);if(B){let re=v.get(D);re?re.sources.add("graph"):v.set(D,{value:B,sources:new Set(["graph"])}),w.push(D)}}}}C=V}}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:P}]of v){let M=o.contextOf?o.contextOf(E):void 0,C=o.score(E,y);if(d>0&&k>0){let V=Tb(b.context,M);V>0&&(C=C*(1+d*V/k))}let $=M?{key:N,value:E,score:C,sources:[...P],context:M}:{key:N,value:E,score:C,sources:[...P]};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=A([],{name:"retrieval",describeKind:"state",meta:ve("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=A(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=Q(g),b=O([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=he([b],([w])=>{let k=w;Z(()=>{p.emit(k.packed),k.trace&&f.emit(k.trace)})}).subscribe(()=>{});return t.addDisposer(T),O([b],([w])=>w.packed,{name:"retrievalReactive",describeKind:"derived",meta:ve("retrieval_reactive"),initial:[],equals:l})}}}Oe();se();Ze();Me();ne();ze();ce();Fe();var Di=class extends Y{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=tu(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=ru(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let D of n.tools)this.tools.register(D);this.status=A("idle",{name:"status",describeKind:"state",meta:ve("agent_status")}),this.add(this.status,{name:"status"}),this.turn=A(0,{name:"turn",describeKind:"state",meta:ve("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=A(!1,{name:"aborted",describeKind:"state",meta:ve("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(D=>{for(let B of D)B[0]===_&&(r=B[1])}),s=!1,i=this.aborted.subscribe(D=>{for(let B of D)B[0]===_&&(s=B[1])}),a=this.chat.messages.cache??[],d=this.chat.messages.subscribe(D=>{for(let B of D)B[0]===_&&(a=B[1])}),u=this.tools.schemas.cache??[],c=this.tools.schemas.subscribe(D=>{for(let B of D)B[0]===_&&(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,k=this.aborted,R=J([T],(D,B,re)=>{if(Go(D,re.prevData,0,"idle")!=="thinking"||s||r>=g){B.down([[z]]);return}if(a.length===0){B.down([[z]]);return}B.emit({messages:a,tools:u})},{name:"promptInput",describeKind:"derived",meta:ve("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),S=ke(R,D=>{let B=new AbortController;return this._currentAbortController=B,s&&B.abort(new Error("agentLoop: aborted")),Q(l.invoke(D.messages,{tools:D.tools.length>0?D.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:B.signal}),{signal:B.signal})},{equals:()=>!1}),x=A(null,{name:"lastResponse",describeKind:"state",meta:ve("agent_last_response")});this.lastResponse=x;let N=J([x,T],(D,B,re)=>{let ye=Go(D,re.prevData,0,null);if(Go(D,re.prevData,1,"idle")!=="acting"){B.down([[z]]);return}let me=ye?.toolCalls;if(me==null||me.length===0){B.down([[z]]);return}B.emit(me)},{name:"toolCallsRaw",describeKind:"derived",meta:ve("agent_tool_calls_raw")}),E=n.interceptToolCalls?n.interceptToolCalls(N):N;this.toolCalls=E;let P=nu({toolCalls:E,tools:v,retryCount:1});this.toolResults=P;let M=he([S],([D])=>{if(s)return;let B=D,re=r+1,ye=B.toolCalls!=null&&B.toolCalls.length>0,ee=B.finishReason==="end_turn"&&(!B.toolCalls||B.toolCalls.length===0),me=y?.(B)===!0,Le=re>=g,rt=me||ee||!ye||Le?"done":"acting";Z(()=>{x.emit(B),T.emit(rt),w.emit(re),b.append("assistant",B.content,{toolCalls:B.toolCalls})})}),C=he([P],([D])=>{if(s)return;let B=D;if(B.length===0)return;let re=r>=g?"done":"thinking";Z(()=>{T.emit(re);for(let ye of B)b.appendToolResult(ye.id,ye.content)})}),$=T.cache??"idle",V=T.subscribe(D=>{for(let B of D)B[0]===_&&($=B[1])}),G=he([k],([D])=>{D===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),$!=="done"&&T.emit("done"))}),K=te(M),F=te(C),q=te(G);this._terminalResult=J([T,x],(D,B,re)=>{let ye=Go(D,re.prevData,0,"idle"),ee=Go(D,re.prevData,1,null);if(ye==="done"){if(ee!=null){B.emit(ee);return}let me=new Error("agentLoop: aborted");me.name="AbortError",B.down([[L,me]]);return}if(ye==="error"){B.down([[L,new Error("agentLoop: errored")]]);return}B.down([[z]])},{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(P,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(i),this.addDisposer(V),this.addDisposer(d),this.addDisposer(c),this.addDisposer(K),this.addDisposer(F),this.addDisposer(q),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=Ds(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 Go(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 wb(t,e){let n=new Di(t,e);return n.tagFactory("agentLoop",He(e)),n}se();Ze();ne();ze();ce();Fe();function kb(t,e,n){let r=new Y(t,n.graph);r.tagFactory("agentMemory",He(n));let o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=Zd(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),ke(b,k=>k==null?{upsert:[]}:o(k,T))},i=e;if(n.admissionFilter){let b=Q(e),v=n.admissionFilter;i=O([b],([T])=>{if(v(T))return T},{name:"admissionFilter",describeKind:"derived"})}let a;n.consolidateFn?a=n.consolidateFn:n.adapter&&n.consolidatePrompt&&(a=eu(n.consolidatePrompt,{adapter:n.adapter}));let d=n.consolidateTrigger;if(!d&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;d=st(b,{period:b})}let u={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:d},c=ri(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=au(r,c,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let p=null;n.enableKnowledgeGraph&&(p=du(r,c,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let f=null;n.tiers&&(f=uu(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=cu(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 xb(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)}se();
|
|
39
|
+
`,r=t.map(i=>typeof i=="string"?C(i):X(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=ne(o);return Object.assign(o,{dispose:s})}re();var db=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function ub(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=Ot(i.usage)+Wt(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:db})}re();var cb=(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 lb(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:cb})}re();function pb(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}:{}})}re();var fb=(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 mb(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:fb})}re();function gb(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"})}re();function hb(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:""})}re();pe();Fe();var Pi=class extends Y{_log;messages;latest;messageCount;constructor(e,n={}){super(e,n.graph),this._log=Ue([],{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(ne(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(ne(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 du(t,e){return new Pi(t,e)}Ze();re();We();pe();function yb(t,e,n){let r=X(t),o=n?.condition!=null?X(n.condition):null,s=C(null,{name:n?.name?`${n.name}::null`:"handoff::null"});if(o==null)return ke(r,a=>{if(a==null)return s;let d=C(a);return e(d)},{meta:Te("handoff")});let i=A([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 C(a);let u=C(a);return e(u)},{meta:Te("handoff")})}re();We();sn();function uu(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=>bb(d,n,r,o));return A(a,d=>d,{name:"toolExecution::batch",equals:s})})}function bb(t,e,n,r){let o=Rt(()=>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:so(s,i=>({id:t.id,content:JSON.stringify({error:String(i)})}))}se();re();pe();Fe();var Di=class extends Y{definitions;schemas;_bundle;constructor(e,n={}){super(e,n.graph),this._bundle=Ke({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(ne(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=vb(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 cu(t,e){return new Di(t,e)}function vb(t,e){return ru(t)?t:t!=null&&typeof t.then=="function"?mr(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?co(t,{signal:e}):mr(Promise.resolve(t),{signal:e})}Ze();re();pe();function Tb(t,e,n){let r=X(t),o=e.map(i=>X(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"),...Te("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 lm(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 wb(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},n=lm({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}Oe();Re();se();re();pe();var $i={};Ee($i,{collection:()=>lu,cosineSimilarity:()=>Fi,knowledgeGraph:()=>fu,vectorIndex:()=>pu});Re();Me();re();ut();pe();Fe();var kb=1e9;function Tt(t,e){return we("memory",t,e)}function $o(t,e){return t instanceof Ae?t:C(t,e?{name:e}:void 0)}function pm(t,e){return(t-e)/kb}function Fi(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 xb(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 Rb(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 lu(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 Ae?a:void 0,u=()=>d?d.cache??i:a,c=new Y(t),p=Ke({name:"items",...n!==void 0?{retention:{score:(M,N)=>r?Pt(N.baseScore,pm(W(),N.lastAccessNs),o,s):N.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)),N=st(M,{period:M});f=A([N],()=>W(),{name:"refresh_tick_ns",describeKind:"derived",initial:W(),meta:Tt("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,N=>{let P=N[0],j;if(f){let V=N[1];j=typeof V=="number"?V:W()}else j=W();if(!P||P.size===0)return[];let G=[];for(let V of P.values())G.push({...V,score:Pt(V.baseScore,pm(j,V.lastAccessNs),o,s)});return G.sort((V,$)=>$.score-V.score||$.lastAccessNs-V.lastAccessNs),G},{name:"ranked",describeKind:"derived",equals:Rb,meta:Tt("ranked")}),c.add(m,{name:"ranked"})}else m=C([],{name:"ranked",describeKind:"state",meta:Tt("ranked_disabled")}),c.add(m,{name:"ranked"});let h=A([p.entries],([M])=>(M??new Map).size,{name:"size",describeKind:"derived",initial:0,meta:Tt("size")});c.add(h,{name:"size"}),c.addDisposer(ne(h));let g=at({name:"events",retainedLimit:1024,graph:c}),y=vt(c,"seq",0),b=(M,N,P)=>{let j=W(),G=p.get(M),V=P?.score??u()(N);p.set(M,{id:M,value:N,baseScore:V,createdAtNs:G?.createdAtNs??j,lastAccessNs:j})},v=M=>{p.has(M)&&p.delete(M)},T=()=>{p.size!==0&&p.clear()},w=()=>{if(!r)return;let M=u(),N=p.entries.cache;if(!N||N.size===0)return;let P=[];for(let j of N.values())P.push([j.id,{...j,baseScore:M(j.value)}]);p.setMany(P)},k=Le(b,{audit:g,seq:y,onSuccess:([M],N,P)=>({action:"upsert",id:M,t_ns:P.t_ns,seq:P.seq})}),x=Le(v,{audit:g,seq:y,onSuccess:([M],N,P)=>({action:"remove",id:M,t_ns:P.t_ns,seq:P.seq})}),R=Le(T,{audit:g,seq:y,onSuccess:(M,N,P)=>({action:"clear",t_ns:P.t_ns,seq:P.seq})}),S=Le(w,{audit:g,seq:y,onSuccess:(M,N,P)=>({action:"rescore",t_ns:P.t_ns,seq:P.seq})});function _(M){let N=$o(M,"id");return A([p.entries,N],([P,j])=>P?.get(j),{describeKind:"derived",meta:Tt("collection_item")})}function O(M){let N=$o(M,"id");return A([p.entries,N],([P,j])=>P?.has(j)??!1,{describeKind:"derived",meta:Tt("collection_has")})}return Object.assign(c,{events:g,items:p.entries,ranked:m,size:h,upsert:k,remove:x,clear:R,rescore:S,itemNode:_,hasNode:O})}function pu(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 Y(t.name??"vector_index"),d;function u(S){if(n!==void 0){if(S.length!==n)throw new RangeError(`vector dimension mismatch: expected ${n}, got ${S.length}`);return}if(r){if(d===void 0){d=S.length;return}if(S.length!==d)throw new RangeError(`vector dimension mismatch: inferred ${d} from first upsert, got ${S.length}. Pass \`strictDimension: false\` to opt into zero-pad behavior, or set an explicit \`dimension\`.`)}}let c=s??(S=>S.upsertedAtNs),l=!1,p=at({name:"events",retainedLimit:1024,graph:a}),f=vt(a,"seq",0),m=Ke({name:"entries",...o!==void 0?{retention:{score:(S,_)=>c(_),maxSize:o,onArchive:S=>{l||(e==="hnsw"&&i.remove(S),p.append({action:"evict",id:S,t_ns:ie(),seq:Kt(f)}))}}}:{}});if(a.add(m.entries,{name:"entries"}),a.addDisposer(ne(m.entries)),i?.dispose){let S=i.dispose.bind(i);a.addDisposer(()=>S())}let h=(S,_,O)=>{u(_),e==="hnsw"&&i.upsert(S,_,O);let D=(()=>{if(O!==void 0)return O===null||typeof O!="object"?O:Array.isArray(O)?[...O]:{...O}})(),M={id:S,vector:[..._],...D!==void 0?{meta:D}:{},upsertedAtNs:W()};m.set(S,M)},g=S=>{m.has(S)&&(e==="hnsw"&&i.remove(S),m.delete(S))},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 S=m.entries.cache;if(S){i.clear();for(let _ of S.values())i.upsert(_.id,_.vector,_.meta)}},v=Le(h,{audit:p,freeze:!1,seq:f,onSuccess:([S],_,O)=>({action:"upsert",id:S,t_ns:O.t_ns,seq:O.seq})}),T=Le(g,{audit:p,seq:f,onSuccess:([S],_,O)=>({action:"remove",id:S,t_ns:O.t_ns,seq:O.seq})}),w=Le(y,{audit:p,seq:f,onSuccess:(S,_,O)=>({action:"clear",t_ns:O.t_ns,seq:O.seq})}),k=Le(b,{audit:p,seq:f,onSuccess:(S,_,O)=>({action:"reindex",t_ns:O.t_ns,seq:O.seq})});function x(S,_=5){let O=$o(_,"k");return A([m.entries,S,O],D=>{let M=D[0],N=D[1],P=D[2],j=Number.isFinite(P)?Math.max(0,Math.floor(P)):0;if(!M||M.size===0||j<=0)return[];if(N==null||N.length===0)return[];let G=n??(r?d:void 0);return G!==void 0&&N.length!==G?[]:e==="hnsw"?[...i.search(N,j)]:[...M.values()].map($=>({id:$.id,score:Fi(N,$.vector),...$.meta!==void 0?{meta:$.meta}:{}})).sort(($,q)=>q.score-$.score).slice(0,j)},{describeKind:"derived",equals:(D,M)=>xb(D,M),meta:Tt("vector_search")})}return Object.assign(a,{backend:e,events:p,entries:m.entries,upsert:v,remove:T,clear:w,reindex:k,searchNode:x})}var fm="\0";function Gi(t,e,n){return`${t}${fm}${e}${fm}${n}`}function mm(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 gm(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 fu(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 Y(t),o=Ke({name:"entities",...e.entitiesMaxSize!==void 0?{maxSize:e.entitiesMaxSize}:{}}),s=Ke({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],([R])=>mm(R,"from"),{name:"adjacencyOut",describeKind:"derived",initial:new Map,equals:gm,meta:Tt("adjacency_out")}),a=A([s.entries],([R])=>mm(R,"to"),{name:"adjacencyIn",describeKind:"derived",initial:new Map,equals:gm,meta:Tt("adjacency_in")});r.add(i,{name:"adjacencyOut"}),r.add(a,{name:"adjacencyIn"}),r.addDisposer(ne(i)),r.addDisposer(ne(a));let d=A([o.entries],([R])=>(R??new Map).size,{name:"entityCount",describeKind:"derived",initial:0,meta:Tt("entity_count")}),u=A([s.entries],([R])=>(R??new Map).size,{name:"edgeCount",describeKind:"derived",initial:0,meta:Tt("edge_count")});r.add(d,{name:"entityCount"}),r.add(u,{name:"edgeCount"}),r.addDisposer(ne(d)),r.addDisposer(ne(u));let c=at({name:"events",retainedLimit:1024,graph:r}),l=vt(r,"seq",0);function p(R){let S=i.cache,_=a.cache;return(S?.get(R)?.length??0)>0||(_?.get(R)?.length??0)>0}function f(R){if(n==="remove")for(let S of R)o.has(S)&&(p(S)||(o.delete(S),c.append({action:"orphanRemove",id:S,t_ns:ie(),seq:Kt(l)})))}let m=(R,S)=>{o.set(R,S)},h=R=>{let S=s.entries.cache,_=new Set;if(S){let O=[];for(let[D,M]of S)(M.from===R||M.to===R)&&(O.push(D),M.from!==R&&_.add(M.from),M.to!==R&&_.add(M.to));O.length>0&&s.deleteMany(O)}o.has(R)&&o.delete(R),f([..._])},g=(R,S,_,O=1)=>{s.set(Gi(R,S,_),{from:R,to:S,relation:_,weight:O})},y=(R,S,_)=>{if(_!==void 0)s.delete(Gi(R,S,_));else{let O=s.entries.cache;if(!O)return;let D=[];for(let[M,N]of O)N.from===R&&N.to===S&&D.push(M);D.length>0&&s.deleteMany(D)}f([R,S])},b=Le(m,{audit:c,seq:l,onSuccess:([R],S,_)=>({action:"upsertEntity",id:R,t_ns:_.t_ns,seq:_.seq})}),v=Le(h,{audit:c,seq:l,onSuccess:([R],S,_)=>({action:"removeEntity",id:R,t_ns:_.t_ns,seq:_.seq})}),T=Le(g,{audit:c,seq:l,onSuccess:([R,S,_,O],D,M)=>({action:"link",from:R,to:S,relation:_,weight:O??1,t_ns:M.t_ns,seq:M.seq})}),w=Le(y,{audit:c,seq:l,onSuccess:([R,S,_],O,D)=>({action:"unlink",from:R,to:S,..._!==void 0?{relation:_}:{},t_ns:D.t_ns,seq:D.seq})});function k(R,S){let _=$o(R,"id"),O=S!==void 0?$o(S,"relation"):void 0;return A(O?[i,a,_,O]:[i,a,_],M=>{let N=M[0],P=M[1],j=M[2],G=O?M[3]:void 0,V=N.get(j)??[],$=P.get(j)??[],q=new Set,F=[];for(let B of V){let te=Gi(B.from,B.to,B.relation);q.has(te)||G!==void 0&&B.relation!==G||(q.add(te),F.push(B))}for(let B of $){let te=Gi(B.from,B.to,B.relation);q.has(te)||G!==void 0&&B.relation!==G||(q.add(te),F.push(B))}return F},{describeKind:"derived",equals:(M,N)=>{let P=M,j=N;if(P===j)return!0;if(P==null||j==null||P.length!==j.length)return!1;for(let G=0;G<P.length;G+=1){let V=P[G],$=j[G];if(V.from!==$.from||V.to!==$.to||V.relation!==$.relation||V.weight!==$.weight)return!1}return!0},meta:Tt("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 mu(t,e,n){let r=pu({dimension:n.dimension});t.add(r.entries,{name:"vectorIndex"});let s=he([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 gu(t,e,n,r){let o=r.mountPath??n,s=fu(`${n}-kg`);if(t.mount(o,s),!r.entityFn)return{kg:s,dispose:()=>{}};let i=r.entityFn,d=he([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 hu(t,e,n,r){let o=r.decayRate??gi,s=r.maxActive??1e3,i=r.archiveThreshold??.1,a=r.permanentFilter??(()=>!1),d=lu("permanent",{ranked:!1});t.mount("permanent",d);let u=Ke({name:"permanentKeys"});t.add(u.entries,{name:"permanentKeys"});let c=Ke({name:"entryCreatedAtNs"});t.add(c.entries,{name:"entryCreatedAtNs"});let l=r.context?X(r.context):C(null),p=l.cache,f=l.subscribe(x=>{for(let R of x)R[0]===E&&(p=R[1])}),m={score:(x,R)=>{if(a(x,R)||u.has(x))return Number.POSITIVE_INFINITY;let S=W(),_=c.get(x);_===void 0&&(_=S,c.set(x,S));let O=Number(S-_)/1e9;return Pt(r.score(R,p),O,o)},archiveThreshold:i,maxSize:s},h=Tr(e,n,{score:r.score,cost:r.cost,...r.budget!==void 0?{budget:r.budget}:{},...r.evict!==void 0?{evict:r.evict}:{},...r.consolidate!==void 0?{consolidate:r.consolidate}:{},...r.consolidateTrigger!==void 0?{consolidateTrigger:r.consolidateTrigger}:{},...r.context!==void 0?{context:r.context}:{},mapOptions:{retention:m}}),g=x=>u.has(x)?"permanent":(h.store.entries.cache??new Map).has(x)?"active":"archived",y=(x,R)=>{u.set(x,!0),d.upsert(x,R)},b=h.store.entries.subscribe(x=>{for(let R of x){if(R[0]!==E)continue;let S=R[1],_=c.entries.cache;if(_==null)continue;let O=[];for(let D of _.keys())S.has(D)||O.push(D);O.length>0&&Z(()=>{for(let D of O)c.delete(D)})}}),T=he([h.store.entries],([x])=>{let R=x??new Map;for(let[S,_]of R)u.has(S)||a(S,_)&&Z(()=>{y(S,_)})}).subscribe(()=>{}),w=null;r.archiveTier&&(w=t.attachSnapshotStorage([r.archiveTier],r.archiveStorageOptions??{}));let k=()=>{T(),b(),f(),w?.dispose()};return t.addDisposer(k),{store:h,tiers:{permanent:d,activeEntries:h.store.entries,archiveHandle:w,tierOf:g,markPermanent:y},dispose:k}}function Sb(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 yu(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?X(o.context):C(null),c=(g,y,b)=>{let v=new Map,T=[];if(n&&b.vector){let _=b.vector,O=n.entries.cache;if(O&&O.size>0&&s>0){T=[...O.values()].map(M=>({id:M.id,score:Fi(_,M.vector),...M.meta!==void 0?{meta:M.meta}:{}})).sort((M,N)=>N.score-M.score).slice(0,s);for(let M of T){let N=g.get(M.id);N&&v.set(M.id,{value:N,sources:new Set(["vector"])})}}}let w=[];if(r){let _=r.adjacencyOut.cache,O=r.adjacencyIn.cache,D=[...b.entityIds??[],...v.keys()],M=new Set,N=D;for(let P=0;P<i;P++){let j=[];for(let G of N){if(M.has(G))continue;M.add(G);let V=_?.get(G)??[],$=O?.get(G)??[];for(let q of V){let F=q.to;if(!M.has(F)){j.push(F);let B=g.get(F);if(B){let te=v.get(F);te?te.sources.add("graph"):v.set(F,{value:B,sources:new Set(["graph"])}),w.push(F)}}}for(let q of $){let F=q.from;if(!M.has(F)){j.push(F);let B=g.get(F);if(B){let te=v.get(F);te?te.sources.add("graph"):v.set(F,{value:B,sources:new Set(["graph"])}),w.push(F)}}}}N=j}}for(let[_,O]of g)v.has(_)||v.set(_,{value:O,sources:new Set(["store"])});let k=b.context?.length??0,x=[];for(let[_,{value:O,sources:D}]of v){let M=o.contextOf?o.contextOf(O):void 0,N=o.score(O,y);if(d>0&&k>0){let j=Sb(b.context,M);j>0&&(N=N*(1+d*j/k))}let P=M?{key:_,value:O,score:N,sources:[...D],context:M}:{key:_,value:O,score:N,sources:[...D]};x.push(P)}x.sort((_,O)=>O.score-_.score);let R=[],S=0;for(let _ of x){let O=o.cost(_.value);if(S+O>a&&R.length>0)break;R.push(_),S+=O}return{packed:R,trace:{vectorCandidates:T,graphExpanded:w,ranked:x,packed:R}}},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=C([],{name:"retrieval",describeKind:"state",meta:ve("retrieval_pipeline"),equals:l});t.add(p,{name:"retrieval"});let f=C(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=X(g),b=A([e.store.entries,u,y],([w,k,x])=>{if(x==null)return{packed:[],trace:null};let R=w??new Map,{packed:S,trace:_}=c(R,k,x);return{packed:S,trace:_}},{name:"retrievalReactive::result",describeKind:"derived",meta:ve("retrieval_reactive_result"),initial:{packed:[],trace:null}}),T=he([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})}}}Oe();se();Ze();Me();re();We();pe();Fe();var ji=class extends Y{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,n){if(super(e,n.graph),this.chat=du(`${e}-chat`,{maxMessages:n.maxMessages}),this.mount("chat",this.chat),this.tools=cu(`${e}-tools`),this.mount("tools",this.tools),n.tools)for(let F of n.tools)this.tools.register(F);this.status=C("idle",{name:"status",describeKind:"state",meta:ve("agent_status")}),this.add(this.status,{name:"status"}),this.turn=C(0,{name:"turn",describeKind:"state",meta:ve("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=C(!1,{name:"aborted",describeKind:"state",meta:ve("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let r=0,o=this.turn.subscribe(F=>{for(let B of F)B[0]===E&&(r=B[1])}),s=!1,i=this.aborted.subscribe(F=>{for(let B of F)B[0]===E&&(s=B[1])}),a=this.chat.messages.cache??[],d=this.chat.messages.subscribe(F=>{for(let B of F)B[0]===E&&(a=B[1])}),u=this.tools.schemas.cache??[],c=this.tools.schemas.subscribe(F=>{for(let B of F)B[0]===E&&(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,k=this.aborted,x=Q([T],(F,B,te)=>{if(jo(F,te.prevData,0,"idle")!=="thinking"||s||r>=g){B.down([[H]]);return}if(a.length===0){B.down([[H]]);return}B.emit({messages:a,tools:u})},{name:"promptInput",describeKind:"derived",meta:ve("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),R=ke(x,F=>{let B=new AbortController;return this._currentAbortController=B,s&&B.abort(new Error("agentLoop: aborted")),X(l.invoke(F.messages,{tools:F.tools.length>0?F.tools:void 0,systemPrompt:p,model:f,temperature:m,maxTokens:h,signal:B.signal}),{signal:B.signal})},{equals:()=>!1}),S=C(null,{name:"lastResponse",describeKind:"state",meta:ve("agent_last_response")});this.lastResponse=S;let _=Q([S,T],(F,B,te)=>{let de=jo(F,te.prevData,0,null);if(jo(F,te.prevData,1,"idle")!=="acting"){B.down([[H]]);return}let ce=de?.toolCalls;if(ce==null||ce.length===0){B.down([[H]]);return}B.emit(ce)},{name:"toolCallsRaw",describeKind:"derived",meta:ve("agent_tool_calls_raw")}),O=n.interceptToolCalls?n.interceptToolCalls(_):_;this.toolCalls=O;let D=uu({toolCalls:O,tools:v,retryCount:1});this.toolResults=D;let M=he([R],([F])=>{if(s)return;let B=F,te=r+1,de=B.toolCalls!=null&&B.toolCalls.length>0,J=B.finishReason==="end_turn"&&(!B.toolCalls||B.toolCalls.length===0),ce=y?.(B)===!0,Ce=te>=g,rt=ce||J||!de||Ce?"done":"acting";Z(()=>{S.emit(B),T.emit(rt),w.emit(te),b.append("assistant",B.content,{toolCalls:B.toolCalls})})}),N=he([D],([F])=>{if(s)return;let B=F;if(B.length===0)return;let te=r>=g?"done":"thinking";Z(()=>{T.emit(te);for(let de of B)b.appendToolResult(de.id,de.content)})}),P=T.cache??"idle",j=T.subscribe(F=>{for(let B of F)B[0]===E&&(P=B[1])}),G=he([k],([F])=>{F===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),P!=="done"&&T.emit("done"))}),V=ne(M),$=ne(N),q=ne(G);this._terminalResult=Q([T,S],(F,B,te)=>{let de=jo(F,te.prevData,0,"idle"),J=jo(F,te.prevData,1,null);if(de==="done"){if(J!=null){B.emit(J);return}let ce=new Error("agentLoop: aborted");ce.name="AbortError",B.down([[L,ce]]);return}if(de==="error"){B.down([[L,new Error("agentLoop: errored")]]);return}B.down([[H]])},{name:"terminalResult",describeKind:"derived",meta:ve("agent_terminal_result")}),this.add(x,{name:"promptInput"}),this.add(R,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===_?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(_,{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(j),this.addDisposer(d),this.addDisposer(c),this.addDisposer(V),this.addDisposer($),this.addDisposer(q),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=Bs(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 jo(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 Nb(t,e){let n=new ji(t,e);return n.tagFactory("agentLoop",He(e)),n}se();Ze();re();We();pe();Fe();function Eb(t,e,n){let r=new Y(t,n.graph);r.tagFactory("agentMemory",He(n));let o;if(n.extractFn)o=n.extractFn;else if(n.adapter&&n.extractPrompt)o=iu(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 x of k)x[0]===E&&(T=x[1])});return r.addDisposer(w),ke(b,k=>k==null?{upsert:[]}:o(k,T))},i=e;if(n.admissionFilter){let b=X(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=au(n.consolidatePrompt,{adapter:n.adapter}));let d=n.consolidateTrigger;if(!d&&a&&n.reflection?.enabled!==!1){let b=n.reflection?.interval??3e5;d=st(b,{period:b})}let u={score:n.score,cost:n.cost,budget:n.budget??2e3,context:n.context,consolidate:a,consolidateTrigger:d},c,l=null;if(n.tiers){let b=hu(r,i,s,{...n.tiers,score:n.score,cost:n.cost,...n.budget!==void 0?{budget:n.budget}:{budget:2e3},...n.context!==void 0?{context:n.context}:{},...a!==void 0?{consolidate:a}:{},...d!==void 0?{consolidateTrigger:d}:{}});c=b.store,l=b.tiers}else c=Tr(i,s,u);r.add(c.store.entries,{name:"store"}),r.add(c.compact,{name:"compact"}),r.add(c.size,{name:"size"});let p=null;n.vectorDimensions&&n.vectorDimensions>0&&n.embedFn&&(p=mu(r,c,{dimension:n.vectorDimensions,embedFn:n.embedFn}).vectors);let f=null;n.enableKnowledgeGraph&&(f=gu(r,c,t,{mountPath:"kg",entityFn:n.entityFn}).kg);let m=null,h=null,g=null,y=null;if(p||f){let b=yu(r,c,p,f,{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:p,kg:f,memoryTiers:l,retrieval:m,retrievalTrace:h,retrieve:g,retrieveReactive:y})}function _b(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)}se();re();We();pe();var qi={};Ee(qi,{compileSpec:()=>qo,decompileSpec:()=>Pb,extractFnFactory:()=>bm,extractSourceFactory:()=>vm,generateCatalogPrompt:()=>Tm,isRichFnEntry:()=>Vo,isRichSourceEntry:()=>Ki,llmCompose:()=>Gb,llmRefine:()=>xm,specDiff:()=>Db,validateSpec:()=>Er,validateSpecAgainstCatalog:()=>Ko});re();Fe();var Bi={};Ee(Bi,{feedback:()=>fn,funnel:()=>Mb,scorer:()=>Bo});Oe();se();Me();re();We();Fe();ut();pe();function bu(t,e){return we("reduction",t,e)}function Mb(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 Y(t,r),s=e.length===1?e[0]:It(...e);o.add(s,{name:"merged"});let i="merged";for(let a=0;a<n.length;a++){let d=n[a],u=new Y(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=he([c],([h])=>{p.emit(h)},{name:f});o.add(m,{name:f}),o.addDisposer(ne(m)),i=`${d.name}::output`}return o}function fn(t,e,n,r){let o=r?.maxIterations??10,s=`__feedback_${e}`,i=C(0,{meta:bu("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=Q([],(l,p)=>{let f=a.subscribe(m=>{for(let h of m){let g=h[0];if(g===E){let y=h[1];if(y==null)return;Z(()=>{Fn(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:{...bu("feedback_effect",{feedbackFrom:e,feedbackTo:n}),_internal:!0}});return t.add(c,{name:u}),t.addDisposer(ne(c)),t}function Bo(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:bu("scorer",n?.meta)})}function mn(t){let e=t.meta?.factory;return typeof e=="string"?e:void 0}function gn(t){let e=t.meta?.factoryArgs;return e!=null&&typeof e=="object"?e:{}}function hm(t){let e=gn(t);return"initial"in e?e.initial:t.value}function Vo(t){return typeof t=="object"&&t!==null&&"factory"in t}function Ki(t){return typeof t=="object"&&t!==null&&"factory"in t}function bm(t){return Vo(t)?t.factory:t}function vm(t){return Ki(t)?t.factory:t}function Tm(t){let e=[];if(t.fns){let n=new Map;for(let[r,o]of Object.entries(t.fns)){let s=Vo(o)?o.tags?.[0]??"Other":"Other";n.has(s)||n.set(s,[]),n.get(s).push(Ob(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(Ab(r,o));n.length>0&&e.push(`Sources:
|
|
43
43
|
${n.join(`
|
|
44
44
|
`)}`)}return e.join(`
|
|
45
45
|
|
|
46
|
-
`)}function
|
|
46
|
+
`)}function Ob(t,e){if(!Vo(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 Ab(t,e){if(!Ki(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 Ko(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=mn(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=Vi(d,o)??Vi(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=Vi(d,r);n.push(`Node "${s}": fn "${d}" not found in catalog`+(l?`. Did you mean "${l}"?`:""))}let c=gn(a);if(!u&&e.fns?.[d]){let l=e.fns[d];if(Vo(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(Ki(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=mn(d);if(u!=null&&!(d.type==="state"&&u==="state")&&d.type!=="producer"&&r.size>0&&!r.has(u)){let c=Vi(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 Vi(t,e){let n=null,r=1/0,o=t.toLowerCase();for(let s of e){let i=Cb(o,s.toLowerCase());i<r&&i<=Math.max(3,Math.floor(t.length/2))&&(r=i,n=s)}return n}function Cb(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 ym=new Set(["state","producer","derived","effect","operator","template"]),Lb=new Set(["state","producer","derived","effect","operator"]);function Er(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"||!Lb.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"||!ym.has(u.type)){e.push(`Node "${a}": invalid type "${String(u.type)}" (expected: ${[...ym].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 qo(t,e){let n=Er(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 v=e?.catalog?.graphFactories?.[r];if(v)return v(o)}let s=e?.catalog??{},i=e?.onMissing??"placeholder",a=new Y(t.name),d=t.templates??{},u=
|
|
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 Y(t.name),d=t.templates??{},u=Ko(t,s);if(!u.valid)throw new Error(`compileSpec: catalog validation errors:
|
|
49
49
|
${u.errors.join(`
|
|
50
|
-
`)}`);let c=[],l=(v,T,w)=>{c.push({path:v,kind:T,name:w})},p=v=>{let T=s.fns?.[v];return T?
|
|
50
|
+
`)}`);let c=[],l=(v,T,w)=>{c.push({path:v,kind:T,name:w})},p=v=>{let T=s.fns?.[v];return T?bm(T):void 0},f=v=>{let T=s.sources?.[v];return T?vm(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=mn(w),x=gn(w);if(w.type==="state"){let R=hm(w),S=C(R,{name:v,meta:m(w.meta)});a.add(S,{name:v}),h.set(v,S)}else if(w.type==="producer"){let R=k?f(k):void 0,S=k?p(k):void 0;if(R){let _=R(x);a.add(_,{name:v}),h.set(v,_)}else if(S){let _=S([],x);a.add(_,{name:v}),h.set(v,_)}else{k&&l(v,"source",k);let _=z(()=>{},{name:v,meta:{...m(w.meta),_specSource:k}});a.add(_,{name:v}),h.set(v,_)}}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(O=>h.has(O)))continue;let k=w.map(O=>h.get(O)),x=mn(T),R=gn(T),S=x?p(x):void 0,_;S?_=S(k,R):T.type==="effect"?(x&&l(v,"fn",x),_=he(k,()=>{})):(x&&l(v,"fn",x),_=A(k,O=>O[0])),a.add(_,{name:v}),h.set(v,_),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],x=new Y(v),R=new Map,S=[];for(let[M,N]of Object.entries(k.nodes)){let P=(N.deps??[]).map($=>$.startsWith("$")&&w.bind[$]?w.bind[$]:$),j={...N,deps:P},G=mn(N),V=gn(N);if(N.type==="state"){let $=hm(N),q=C($,{name:M,meta:m(N.meta)});x.add(q,{name:M}),R.set(M,q)}else if(N.type==="producer"){let $=G?f(G):void 0,q=G?p(G):void 0;if($){let F=$(V);x.add(F,{name:M}),R.set(M,F)}else if(q){let F=q([],V);x.add(F,{name:M}),R.set(M,F)}else{G&&l(`${v}.${M}`,"source",G);let F=z(()=>{},{name:M,meta:{...m(N.meta),_specSource:G}});x.add(F,{name:M}),R.set(M,F)}}else S.push([M,j])}let _=!0,O=new Map(S);for(;O.size>0&&_;){_=!1;for(let[M,N]of[...O.entries()]){let P=N.deps??[];if(!P.every(B=>R.has(B)||h.has(B)))continue;let G=P.map(B=>R.get(B)??h.get(B)),V=mn(N),$=gn(N),q=V?p(V):void 0,F;q?F=q(G,$):N.type==="effect"?(V&&l(`${v}.${M}`,"fn",V),F=he(G,()=>{})):(V&&l(`${v}.${M}`,"fn",V),F=A(G,B=>B[0])),x.add(F,{name:M}),R.set(M,F),O.delete(M),_=!0}}if(O.size>0){let M=[...O.keys()].sort().join(", ");throw new Error(`compileSpec: template "${w.template}" has unresolvable deps: ${M}`)}a.mount(v,x);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??[])fn(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
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
|
|
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 Ib=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function Pb(t){let e=t.describe({detail:"spec"}),n=`::${ot}::`,r=/^__feedback_(?!effect_)(.+)$/,o=[],s=new Set;for(let[u,c]of Object.entries(e.nodes))c.meta?.factory!=null&&!u.includes("::")&&s.add(u);let i=new Set(Object.keys(e.nodes));for(let u of i){let c=u.indexOf("::");if(c<=0)continue;let l=u.slice(0,c);if(!u.includes(n)&&!(u.startsWith("__feedback_effect_")||u.startsWith("__bridge_"))&&!s.has(l)&&i.has(l))throw new Error(`decompileSpec: untagged compound factory at "${l}" (child: "${u}"). Compound factories that ship \`parent::child\` topology MUST set \`meta.factory\` on the parent so \`compileSpec\` can reconstruct the internals via the catalog. Either tag the parent (\`{ meta: factoryTag('myFactory', args) }\`) OR rename the child to use \`/\` instead of \`::\` if it's not a compound-factory internal (see COMPOSITION-GUIDE \xA738).`)}let a={};for(let[u,c]of Object.entries(e.nodes)){if(u.includes(n))continue;let l=u.indexOf("::");if(l>0&&s.has(u.slice(0,l)))continue;if(r.exec(u)){let g=c.meta;g?.feedbackFrom&&g?.feedbackTo&&o.push({from:g.feedbackFrom,to:g.feedbackTo,...g.maxIterations?{maxIterations:g.maxIterations}:{}});continue}if(c.meta?._internal||u.startsWith("__feedback_effect_")||u.startsWith("__bridge_"))continue;let f=c.meta,m=f;if(f&&Object.keys(f).length>0){let g={};for(let[y,b]of Object.entries(f))Ib.has(y)||(g[y]=b);g.factory==="withStatus"?(delete g.status,delete g.error):g.factory==="withBreaker"?delete g.breakerState:g.factory==="verifiable"&&delete g.sourceVersion,m=Object.keys(g).length>0?g:void 0}let h={...c};m===void 0?delete h.meta:h.meta=m,a[u]=h}let d={...e,nodes:a};return delete d.expand,o.length>0&&(d.feedback=o),d}function Db(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:mn(v),x=T.type==="template"?void 0:mn(T);k!==x&&w.push(`fn: ${k} \u2192 ${x}`);let R=v.type==="template"?void 0:gn(v),S=T.type==="template"?void 0:gn(T);JSON.stringify(R)!==JSON.stringify(S)&&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 wm=`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
|
|
|
@@ -95,20 +95,20 @@ Rules:
|
|
|
95
95
|
- Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
|
|
96
96
|
- Use "feedback" for bounded cycles where a derived value writes back to a state node.
|
|
97
97
|
- meta.description is required for every node.
|
|
98
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;function
|
|
98
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;function km(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}async function Gb(t,e,n){let r=wm,o=n?.catalogDescription??(n?.catalog?Tm(n.catalog):void 0);o&&(r+=`
|
|
99
99
|
|
|
100
100
|
Available catalog (use ONLY these names):
|
|
101
101
|
${o}`),n?.systemPromptExtra&&(r+=`
|
|
102
102
|
|
|
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=
|
|
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=km(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=Er(u);if(!c.valid)throw new Error(`llmCompose: invalid GraphSpec:
|
|
104
104
|
${c.errors.join(`
|
|
105
|
-
`)}`);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=Ko(l,n.catalog);if(m.valid)break;if(f===p)throw new Error(`llmCompose: catalog validation failed after ${p} refine attempts:
|
|
106
106
|
${m.errors.join(`
|
|
107
|
-
`)}`);l=await
|
|
107
|
+
`)}`);l=await xm(l,`Fix these catalog errors:
|
|
108
108
|
${m.errors.join(`
|
|
109
109
|
`)}
|
|
110
110
|
|
|
111
|
-
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 xm(t,e,n,r){let o=wm;r?.catalogDescription&&(o+=`
|
|
112
112
|
|
|
113
113
|
Available catalog:
|
|
114
114
|
${r.catalogDescription}`),r?.systemPromptExtra&&(o+=`
|
|
@@ -118,9 +118,9 @@ ${JSON.stringify(t,null,2)}
|
|
|
118
118
|
|
|
119
119
|
Modification request: ${e}
|
|
120
120
|
|
|
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=
|
|
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=km(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=Er(u);if(!c.valid)throw new Error(`llmRefine: invalid GraphSpec:
|
|
122
122
|
${c.errors.join(`
|
|
123
|
-
`)}`);return u}var
|
|
123
|
+
`)}`);return u}var Rm=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
124
124
|
|
|
125
125
|
Given a natural-language description, produce a JSON graph specification with this structure:
|
|
126
126
|
|
|
@@ -153,9 +153,9 @@ Rules:
|
|
|
153
153
|
- "operator" nodes are parameterized transformations with deps.
|
|
154
154
|
- Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
|
|
155
155
|
- meta.description is required for every node.
|
|
156
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function
|
|
156
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Sm(t,e,n){let o=[{role:"system",content:n?.systemPromptExtra?`${Rm}
|
|
157
157
|
|
|
158
|
-
${n.systemPromptExtra}`:
|
|
158
|
+
${n.systemPromptExtra}`:Rm},{role:"user",content:t}],s=e.invoke(o,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),a=(await Lo(s)).content.trim();a.startsWith("```")&&(a=Ut(a));let d;try{d=JSON.parse(a)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${a.slice(0,200)}`)}return qo(d,{catalog:n?.catalog})}function Fb(t,e,n){let r=X(t);return ke(r,o=>!o||typeof o!="string"||o.trim().length===0?C(null):z(s=>{let i=new AbortController,a=!1;return Sm(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 $b(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 jb(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=$b(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}}se();re();We();pe();var Bb=`You are a reactive graph optimizer for GraphReFly.
|
|
159
159
|
|
|
160
160
|
Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
|
|
161
161
|
|
|
@@ -176,8 +176,8 @@ Return ONLY valid JSON with this structure:
|
|
|
176
176
|
Rules:
|
|
177
177
|
- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
|
|
178
178
|
- Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
|
|
179
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function
|
|
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 Ut(t,e,n,r,o){let s=Bb(t);if(s.length===0)return[];let i=Vb(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&&(jb.has(b)||km.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($b(b)){let k="";for(let R of a.segment(b)){let S=R.segment;if(k.length>0&&km.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 Hn(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 P=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(N.text)].map(M=>M.segment);S+=P.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),P=d===w?u:0;S+=E.slice(P,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 pu(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var fu=null;function Kb(){return fu===null&&(fu=new Intl.Segmenter(void 0,{granularity:"grapheme"})),fu}function xm(t,e,n){if(e===0&&n<0)return t.text;let r=[...Kb().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function gn(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+=xm(d,n,-1):i+=d.text)}if(o>0&&r<t.length){let a=t[r];i+=xm(a,e===r?n:0,o)}return s&&(i+="-"),i}function qb(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 mu(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=qb(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:gn(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:gn(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:gn(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,pu(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(pu(w.kind)){c=o+1,l=0;let x=w.kind==="soft-hyphen",N=w.kind==="space"?u:u+(x?i:0);return{text:gn(t,a,d,c,l,x),width:N,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}return f>=0?{text:gn(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:gn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}:{text:gn(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,pu(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:gn(t,a,d,c,l,v),width:u+(v?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}function gu(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 Vi(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 Hb(t){let{adapter:e,name:n="reactive-layout"}=t,r=new Y(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=J([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=W(),k={hits:0,misses:0},R=Ut(b,T,e,o,k),S=W()-w,x=k.hits+k.misses,N=x===0?1:k.hits/x,E=c.meta;E&&(Mt(E["cache-hit-rate"],N),Mt(E["segment-count"],R.length),Mt(E["layout-time-ns"],S)),h.emit(R);let P=()=>{o.clear(),e.clearCache?.()};return{deactivate:P,invalidate:P}},{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=O([c,d,i],([m,h,g])=>Hn(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=O([l,a],([m,h])=>m.lineCount*h,{name:"height"}),f=O([l,c,a],([m,h,g])=>Vi(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 Ko(t){return Math.max(0,Math.min(1,t))}function zb(t){let e=Ko(t?.mainRatio??.65),n=Ko(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 Y("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=O([u,p,l],([G,K,F])=>{let q=G,D=K,B=F;return B==="main"?D:B==="graph"||B==="code"?0:Math.round(D*q)},{name:"pane/main-width"}),m=O([f,p,l],([G,K,F])=>{let q=F,D=K;return q==="main"?0:q==="graph"||q==="code"?D:D-G},{name:"pane/side-width"}),h=O([c,l],([G,K])=>{let F=K;return F==="graph"?1:F==="code"||F==="main"?0:Ko(G)},{name:"pane/graph-height-ratio"}),g=O([h,l],([G,K])=>{let F=K;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=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=O([y,b],([G,K])=>{let F=G;return F?tn(F.describe()):""},{name:"graph/mermaid"}),T=O([y,b],([G,K])=>{let F=G;if(!F)return null;let{expand:q,...D}=F.describe({detail:"standard"});return D},{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 k=O([w],([G])=>{let K=G;if(!K)return null;let F=o.get(K.id);return F?F.codeLine:null},{name:"highlight/code-scroll"}),R=O([w],([G])=>{let K=G;if(!K)return null;let F=o.get(K.id);return F?F.visualSelector:null},{name:"highlight/visual"}),S=O([w],([G])=>{let K=G;return K?K.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,K=he([k],([F])=>{G(F)});d.add(K,{name:"highlight/apply-code-scroll"})}if(a?.visual){let G=a.visual,K=he([R],([F])=>{G(F)});d.add(K,{name:"highlight/apply-visual"})}if(a?.graph){let G=a.graph,K=he([S],([F])=>{G(F)});d.add(K,{name:"highlight/apply-graph"})}let x=A(null,{name:"inspect/selected-node"});d.add(x,{name:"inspect/selected-node"});let N=Xt("standard"),E=O([x,y,b],([G,K,F])=>{let q=K,D=G;if(!q||!D)return null;try{let B=q.resolve(D),re=Jr(B,N);return{path:D,...re,value:B.cache}}catch{return null}},{name:"inspect/node-detail"}),P=O([y,b],([G,K])=>{let F=G;return F?F.trace():[]},{name:"inspect/trace-log"});d.add(E,{name:"inspect/node-detail"}),d.add(P,{name:"inspect/trace-log"});let M=A(!1,{name:"meta/debug"});d.add(M,{name:"meta/debug"});let C=O([M,b],([G,K])=>G?tn(d.describe()):"",{name:"meta/shell-mermaid"});d.add(C,{name:"meta/shell-mermaid"});let $=A("",{name:"layout/code-text"});if(d.add($,{name:"layout/code-text"}),s){let G=new Map,K=O([T],([D])=>{let B=D;if(!B)return new Map;let re=new Map;for(let[ye]of Object.entries(B.nodes)){let ee=Ut(ye,i,s,G),me=Hn(ee,1/0,s,i,G),Le=me.lines.reduce((Qe,U)=>Math.max(Qe,U.width),0),rt=me.lineCount*20;re.set(ye,{width:Le,height:rt})}return re},{name:"layout/graph-labels",equals:(D,B)=>{if(D===B)return!0;let re=D,ye=B;if(re.size!==ye.size)return!1;for(let[ee,me]of re){let Le=ye.get(ee);if(!Le||Le.width!==me.width||Le.height!==me.height)return!1}return!0}}),F=O([$,m],([D,B])=>{let re=D;if(!re)return{lineCount:0,lines:[]};let ye=Ut(re,i,s,G),ee=B-40;return Hn(ye,Math.max(100,ee),s,i,G)},{name:"layout/code-lines"}),q=O([K],([D])=>{let B=D;if(B.size===0)return 200;let re=0;for(let{width:ye}of B.values())ye>re&&(re=ye);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(q,{name:"layout/side-width-hint"})}let V=0;return{graph:d,setMainRatio(G){d.set("pane/main-ratio",Ko(G))},setSideSplit(G){d.set("pane/side-split",Ko(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",++V)},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 qi={};Ee(qi,{contentModerationGraph:()=>Jb,dataQualityGraph:()=>Yb,issueTrackerGraph:()=>Ub,observabilityGraph:()=>Wb});Oe();ne();Fe();ut();ce();function Pe(t,e){return we("domain_template",t,e)}function Wb(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>hu(T,"error")},{name:"traces",classify:T=>hu(T,"trace")},{name:"metrics",classify:T=>hu(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=No("stratify",e.source,s);n.mount("stratify",i);let a=o.map(T=>{try{let w=n.resolve(`stratify::branch/${T.name}`);return O([w],([k])=>k,{initial:null})}catch{return A(null)}}),d=e.correlate??(T=>T),u=O(a,T=>d(T),{meta:Pe("observability",{stage:"correlate"})});n.add(u,{name:"correlate"});let c=e.sloCheck??(()=>({pass:!0})),l=O([u],T=>T[0],{meta:Pe("observability",{stage:"slo_value"})}),p=O([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=>O([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=Fo(m,h);n.add(g,{name:"alerts"});let y=O([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=O([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"}),pn(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function Ub(t,e){let n=new Y(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=O([e.source],T=>s(T[0]),{meta:Pe("issue_tracker",{stage:"extract"})});n.add(i,{name:"extract"});let a=e.verify??(()=>({valid:!0})),d=O([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=O([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=O([i],T=>T[0]?.severity??0),f=O([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=Fo([p,f],[m,h]);n.add(g,{name:"priority"});let y=O([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=O([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"}),pn(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function Jb(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=v=>({label:"review",confidence:.5,original:v}),o=e.classify??r,s=O([e.source],v=>o(v[0]),{meta:Pe("content_moderation",{stage:"classify"})});n.add(s,{name:"classify"});let i=No("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=We([],{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=he([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=O([s],v=>v[0]?.confidence??0),f=O([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=Fo([p,f],[m,h]);n.add(g,{name:"priority"});let y=O([s,g],v=>({classification:v[0],priority:v[1]}),{meta:Pe("content_moderation",{stage:"output"})});n.add(y,{name:"output"});let b=O([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"}),pn(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function Yb(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=e.validate??(g=>({valid:!0,errors:[],record:g})),o=O([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=O([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=he([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=O([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=O([o,i],g=>l({validation:g[0],anomaly:g[1]}),{meta:Pe("data_quality",{stage:"remediate"})});n.add(p,{name:"remediate"});let f=O([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=O([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"}),pn(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function hu(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var Zi={};Ee(Zi,{DEFAULT_DECAY_RATE:()=>Er,DEFAULT_EXECUTE_PROMPT:()=>bu,DEFAULT_QUEUE_CONFIGS:()=>Hi,DEFAULT_SEVERITY_WEIGHTS:()=>Nr,DEFAULT_TRIAGE_PROMPT:()=>yu,DEFAULT_VERIFY_PROMPT:()=>vu,HarnessGraph:()=>Xi,QUEUE_NAMES:()=>pt,actuatorExecutor:()=>Rm,affectedTaskFilter:()=>av,autoSolidify:()=>nv,beforeAfterCompare:()=>iv,blindVariation:()=>fv,codeChangeBridge:()=>dv,createIntakeBridge:()=>rv,defaultErrorClassifier:()=>zi,defaultLlmExecutor:()=>Am,defaultLlmVerifier:()=>Cm,dispatchActuator:()=>tv,effectivenessTracker:()=>lv,errorCritique:()=>hv,evalIntakeBridge:()=>ov,evalSource:()=>sv,evalVerifier:()=>Nm,harnessEvalPair:()=>wv,harnessLoop:()=>Ev,harnessProfile:()=>Mv,harnessTrace:()=>Av,notifyEffect:()=>uv,priorityScore:()=>Sv,refineExecutor:()=>ku,refineLoop:()=>wu,resolvePromptFn:()=>qo,strategyKey:()=>_r,strategyModel:()=>Su});se();ne();ce();function Qb(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${ev(e.summary)}`,artifact:t}}function Xb(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function Zb(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function ev(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function Rm(t){let e=t.name??"actuator-executor",n=t.toOutput??Qb,r=t.onError??Xb,o=t.skipDetail??Zb;return s=>{let i=s.payload.item;return t.shouldApply&&!t.shouldApply(i)?{...s.payload,execution:{item:i,outcome:"failure",detail:o(i)}}:H(a=>{let d=new AbortController,u=!1,c=null,l=f=>{u||(u=!0,a.down([[_,{...s.payload,execution:{item:i,...f}}],[I]]),c?.(),c=null)},p;try{let f=t.apply(i,{signal:d.signal});p=Q(f,{signal:d.signal})}catch(f){return l(r(f,i)),()=>{d.abort()}}return c=p.subscribe(f=>{for(let m of f){if(u)return;if(m[0]===_){l(n(m[1],i));return}if(m[0]===L){l(r(m[1],i));return}if(m[0]===I){l(r(new Error("actuator inner completed without emitting DATA"),i));return}}}),u&&c&&(c(),c=null),()=>{d.abort(),c?.(),c=null}},{name:`${e}/inner`})}}function tv(t){let e=t.name??"dispatch-actuator",n=t.default??null,r=n!=null;return Rm({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})}se();ne();function nv(t){let e=t.name??"auto-solidify",n=t.extract??(o=>o.execution.artifact??null),r=t.predicate??(()=>!0);return H(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();ze();ce();function rv(t,e,n,r){return he([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function ov(t,e,n){let r=n?.defaultSeverity??"medium";return he([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 sv(t,e){return ke(t,()=>Q(e()))}function iv(t,e){return O([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 av(t,e){let n=e==null?null:Array.isArray(e)?A(e):e,r=[t];return n&&r.push(n),O(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 dv(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 he([t],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:r?.name??"code-change-bridge"})}function uv(t,e,n){return he([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var pt=["auto-fix","needs-decision","investigation","backlog"],Hi={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},Nr={critical:100,high:70,medium:40,low:10},Er=Math.LN2/(168*3600);function _r(t,e){return`${t}\u2192${e}`}var cv=/\b(parse|json|config|validation|syntax)\b/i,zi=t=>cv.test(t.detail)?"self-correctable":"structural",yu=`You are a triage classifier for a reactive collaboration harness.
|
|
179
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Nm(t,e,n,r){let{expand:o,...s}=t.describe({actor:r?.actor,detail:"standard"}),i=[{role:"system",content:Bb},{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 Lo(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 Vb(t,e,n,r){let o=X(e),s=On(o,t);return ke(s,i=>{if(i==null)return C(null);let[a,d]=i;return!d||!a||typeof a!="string"||a.trim().length===0?C(null):d.destroyed?C(null):z(u=>{let c=new AbortController,l=!1;return Nm(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 Em=new Set(["state","derived","producer","operator","effect"]);function Kb(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"||!Em.has(i.type))&&e.push(`Node "${o}": invalid type "${String(i.type)}" (expected: ${[...Em].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 Wi={};Ee(Wi,{demoShell:()=>Qb});Oe();Ze();re();ed();Fe();Re();Me();re();Fe();Oe();se();Me();function At(t,e){t!=null&&$t(n=>t.down(n),[[E,e]],je.tierOf)}function zo(t){return t.relatedTo?.[0]??t.summary}function qb(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 _m=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),zb=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function Hb(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function Wb(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 Yt(t,e,n,r,o){let s=Hb(t);if(s.length===0)return[];let i=Wb(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&&(zb.has(b)||_m.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(qb(b)){let k="";for(let x of a.segment(b)){let R=x.segment;if(k.length>0&&_m.has(R)){k+=R;continue}if(k.length>0){let S=h(k);g.push({text:k,width:S,kind:"text",graphemeWidths:null})}k=R}if(k.length>0){let x=h(k);g.push({text:k,width:x,kind:"text",graphemeWidths:null})}continue}let T=h(b),w=null;if(f[y]&&b.length>1){let k=[];for(let x of a.segment(b))k.push(h(x.segment));k.length>1&&(w=k)}g.push({text:b,width:T,kind:"text",graphemeWidths:w})}return g}function Hn(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,x=i){let R="";for(let S=d;S<w;S++){let _=t[S];if(!(_.kind==="soft-hyphen"||_.kind==="hard-break"))if(S===d&&u>0&&_.graphemeWidths){let D=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(_.text)].map(M=>M.segment);R+=D.slice(u).join("")}else R+=_.text}if(k>0&&w<t.length){let S=t[w],O=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(S.text)].map(M=>M.segment),D=d===w?u:0;R+=O.slice(D,k).join("")}w>0&&t[w-1]?.kind==="soft-hyphen"&&!(d===w&&u>0)&&(R+="-"),s.push({text:R,width:x,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,x){a=!0,d=w,u=k,c=w+1,l=0,i=x}function v(w,k,x){a=!0,d=w,u=k,c=w,l=k+1,i=x}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 x=k.width;if(!a){x>e&&k.graphemeWidths?T(w,0,k.graphemeWidths):b(w,0,x),y(k.kind)&&(p=w+1,f=k.kind==="space"?i-x:i);continue}let R=i+x;if(R>e+.005){if(y(k.kind)){i+=x,c=w+1,l=0,g(w+1,0,k.kind==="space"?i-x:i);continue}if(p>=0){g(p,0,f),w--;continue}if(x>e&&k.graphemeWidths){g(),T(w,0,k.graphemeWidths);continue}g(),w--;continue}i=R,c=w+1,l=0,y(k.kind)&&(p=w+1,f=k.kind==="space"?i-x:i)}return a&&g(),{lines:s,lineCount:s.length};function T(w,k,x){for(let R=k;R<x.length;R++){let S=x[R];if(!a){v(w,R,S);continue}i+S>e+.005?(g(),v(w,R,S)):(i+=S,c=w,l=R+1)}a&&c===w&&l===x.length&&(c=w+1,l=0)}}function vu(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var Tu=null;function Ub(){return Tu===null&&(Tu=new Intl.Segmenter(void 0,{granularity:"grapheme"})),Tu}function Mm(t,e,n){if(e===0&&n<0)return t.text;let r=[...Ub().segment(t.text)].map(s=>s.segment),o=n<0?r.length:n;return r.slice(e,o).join("")}function hn(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+=Mm(d,n,-1):i+=d.text)}if(o>0&&r<t.length){let a=t[r];i+=Mm(a,e===r?n:0,o)}return s&&(i+="-"),i}function Jb(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 wu(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=Jb(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,x,R)=>{f=w,m=k,h=x,g=R==="soft-hyphen"},b=(w,k,x)=>{for(let R=k;R<x.length;R++){let S=x[R];if(!p){u=S,c=w,l=R+1,p=!0;continue}if(u+S>n+.005)return!0;u+=S,c=w,l=R+1}return c===w&&l===x.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:hn(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 R=c>0&&t[c-1]?.kind==="soft-hyphen";return{text:hn(t,a,d,c,l,R),width:u+(R?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:hn(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,vu(w.kind)&&y(o+1,0,w.kind==="space"?u-k:u,w.kind),o+=1;continue}let x=u+k;if(x>n+.005){if(vu(w.kind)){c=o+1,l=0;let S=w.kind==="soft-hyphen",_=w.kind==="space"?u:u+(S?i:0);return{text:hn(t,a,d,c,l,S),width:_,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}return f>=0?{text:hn(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:hn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}:{text:hn(t,a,d,c,l,!1),width:u,start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}u=x,c=o+1,l=0,vu(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:hn(t,a,d,c,l,v),width:u+(v?i:0),start:{segmentIndex:a,graphemeIndex:d},end:{segmentIndex:c,graphemeIndex:l}}}function ku(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 Hi(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 Yb(t){let{adapter:e,name:n="reactive-layout"}=t,r=new Y(n),o=new Map,s=C(t.text??"",{name:"text"}),i=C(t.font??"16px sans-serif",{name:"font"}),a=C(t.lineHeight??20,{name:"line-height"}),d=C(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=Q([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=W(),k={hits:0,misses:0},x=Yt(b,T,e,o,k),R=W()-w,S=k.hits+k.misses,_=S===0?1:k.hits/S,O=c.meta;O&&(At(O["cache-hit-rate"],_),At(O["segment-count"],x.length),At(O["layout-time-ns"],R)),h.emit(x);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])=>Hn(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])=>Hi(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 Ho(t){return Math.max(0,Math.min(1,t))}function Qb(t){let e=Ho(t?.mainRatio??.65),n=Ho(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 Y("demo-shell"),u=C(e,{name:"pane/main-ratio"}),c=C(n,{name:"pane/side-split"}),l=C(null,{name:"pane/fullscreen"}),p=C(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,$])=>{let q=G,F=V,B=$;return B==="main"?F:B==="graph"||B==="code"?0:Math.round(F*q)},{name:"pane/main-width"}),m=A([f,p,l],([G,V,$])=>{let q=$,F=V;return q==="main"?0:q==="graph"||q==="code"?F:F-G},{name:"pane/side-width"}),h=A([c,l],([G,V])=>{let $=V;return $==="graph"?1:$==="code"||$==="main"?0:Ho(G)},{name:"pane/graph-height-ratio"}),g=A([h,l],([G,V])=>{let $=V;return $==="code"?1:$==="graph"||$==="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=C(null,{name:"demo/graph-ref"}),b=C(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 $=G;return $?rn($.describe()):""},{name:"graph/mermaid"}),T=A([y,b],([G,V])=>{let $=G;if(!$)return null;let{expand:q,...F}=$.describe({detail:"standard"});return F},{name:"graph/describe"});d.add(v,{name:"graph/mermaid"}),d.add(T,{name:"graph/describe"});let w=C(null,{name:"hover/target"});d.add(w,{name:"hover/target"});let k=A([w],([G])=>{let V=G;if(!V)return null;let $=o.get(V.id);return $?$.codeLine:null},{name:"highlight/code-scroll"}),x=A([w],([G])=>{let V=G;if(!V)return null;let $=o.get(V.id);return $?$.visualSelector:null},{name:"highlight/visual"}),R=A([w],([G])=>{let V=G;return V?V.id:null},{name:"highlight/graph"});if(d.add(k,{name:"highlight/code-scroll"}),d.add(x,{name:"highlight/visual"}),d.add(R,{name:"highlight/graph"}),a?.codeScroll){let G=a.codeScroll,V=he([k],([$])=>{G($)});d.add(V,{name:"highlight/apply-code-scroll"})}if(a?.visual){let G=a.visual,V=he([x],([$])=>{G($)});d.add(V,{name:"highlight/apply-visual"})}if(a?.graph){let G=a.graph,V=he([R],([$])=>{G($)});d.add(V,{name:"highlight/apply-graph"})}let S=C(null,{name:"inspect/selected-node"});d.add(S,{name:"inspect/selected-node"});let _=en("standard"),O=A([S,y,b],([G,V,$])=>{let q=V,F=G;if(!q||!F)return null;try{let B=q.resolve(F),te=Qr(B,_);return{path:F,...te,value:B.cache}}catch{return null}},{name:"inspect/node-detail"}),D=A([y,b],([G,V])=>{let $=G;return $?$.trace():[]},{name:"inspect/trace-log"});d.add(O,{name:"inspect/node-detail"}),d.add(D,{name:"inspect/trace-log"});let M=C(!1,{name:"meta/debug"});d.add(M,{name:"meta/debug"});let N=A([M,b],([G,V])=>G?rn(d.describe()):"",{name:"meta/shell-mermaid"});d.add(N,{name:"meta/shell-mermaid"});let P=C("",{name:"layout/code-text"});if(d.add(P,{name:"layout/code-text"}),s){let G=new Map,V=A([T],([F])=>{let B=F;if(!B)return new Map;let te=new Map;for(let[de]of Object.entries(B.nodes)){let J=Yt(de,i,s,G),ce=Hn(J,1/0,s,i,G),Ce=ce.lines.reduce((Xe,U)=>Math.max(Xe,U.width),0),rt=ce.lineCount*20;te.set(de,{width:Ce,height:rt})}return te},{name:"layout/graph-labels",equals:(F,B)=>{if(F===B)return!0;let te=F,de=B;if(te.size!==de.size)return!1;for(let[J,ce]of te){let Ce=de.get(J);if(!Ce||Ce.width!==ce.width||Ce.height!==ce.height)return!1}return!0}}),$=A([P,m],([F,B])=>{let te=F;if(!te)return{lineCount:0,lines:[]};let de=Yt(te,i,s,G),J=B-40;return Hn(de,Math.max(100,J),s,i,G)},{name:"layout/code-lines"}),q=A([V],([F])=>{let B=F;if(B.size===0)return 200;let te=0;for(let{width:de}of B.values())de>te&&(te=de);return Math.max(200,Math.round(te+80))},{name:"layout/side-width-hint"});d.add(V,{name:"layout/graph-labels"}),d.add($,{name:"layout/code-lines"}),d.add(q,{name:"layout/side-width-hint"})}let j=0;return{graph:d,setMainRatio(G){d.set("pane/main-ratio",Ho(G))},setSideSplit(G){d.set("pane/side-split",Ho(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",++j)},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 Ui={};Ee(Ui,{contentModerationGraph:()=>ev,dataQualityGraph:()=>tv,issueTrackerGraph:()=>Zb,observabilityGraph:()=>Xb});Oe();re();Fe();ut();pe();function Pe(t,e){return we("domain_template",t,e)}function Xb(t,e){let n=new Y(t,e);n.add(e.source,{name:"source"});let r=[{name:"errors",classify:T=>xu(T,"error")},{name:"traces",classify:T=>xu(T,"trace")},{name:"metrics",classify:T=>xu(T,"metric")}],o=e.branches??r,s=o.map(T=>({name:T.name,classify:T.classify})),i=Mo("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 C(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=>C(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=Bo(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=C(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"}),fn(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??5}),n}function Zb(t,e){let n=new Y(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=C([],{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=C(1),h=C(1.5);n.add(m,{name:"__severity_weight"}),n.add(h,{name:"__regression_weight"});let g=Bo([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=C(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"}),fn(n,"feedback_condition","feedback_reentry",{maxIterations:e.maxFeedbackIterations??3}),n}function ev(t,e){let n=new Y(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=Mo("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=Ue([],{name:"review_queue",maxSize:e.maxQueueSize});n.add(a.entries,{name:"review_queue"});let d;try{d=n.resolve("stratify::branch/review")}catch{d=C(null),n.add(d,{name:"__review_fallback"})}let u=he([d],v=>{let T=v[0];T&&a.append(T)});n.add(u,{name:"__review_accumulator"}),n.addDisposer(ne(u));let c=C({},{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=C(1),h=C(1);n.add(m,{name:"__w_confidence"}),n.add(h,{name:"__w_severity"});let g=Bo([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"}),fn(n,"feedback_condition","policy",{maxIterations:e.maxFeedbackIterations??5}),n}function tv(t,e){let n=new Y(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=C(null,{meta:Pe("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(a,{name:"baseline"});let d=he([o],g=>{let y=g[0];y?.valid&&Z(()=>{a.emit(y.record)})});n.add(d,{name:"__baseline_updater"}),ne(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=C([],{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"}),fn(n,"feedback_condition","validation_rules",{maxIterations:e.maxFeedbackIterations??3}),n}function xu(t,e){if(t==null||typeof t!="object")return!1;let n=t;return n.type===e||n.kind===e}var oa={};Ee(oa,{DEFAULT_DECAY_RATE:()=>Mr,DEFAULT_EXECUTE_PROMPT:()=>Su,DEFAULT_QUEUE_CONFIGS:()=>Ji,DEFAULT_SEVERITY_WEIGHTS:()=>_r,DEFAULT_TRIAGE_PROMPT:()=>Ru,DEFAULT_VERIFY_PROMPT:()=>Nu,HarnessGraph:()=>ra,QUEUE_NAMES:()=>ft,actuatorExecutor:()=>Om,affectedTaskFilter:()=>pv,autoSolidify:()=>av,beforeAfterCompare:()=>lv,blindVariation:()=>bv,codeChangeBridge:()=>fv,createIntakeBridge:()=>dv,defaultErrorClassifier:()=>Yi,defaultLlmExecutor:()=>Gm,defaultLlmVerifier:()=>Fm,dispatchActuator:()=>iv,effectivenessTracker:()=>hv,errorCritique:()=>wv,evalIntakeBridge:()=>uv,evalSource:()=>cv,evalVerifier:()=>Cm,harnessEvalPair:()=>Nv,harnessLoop:()=>Cv,harnessProfile:()=>Iv,harnessTrace:()=>Dv,notifyEffect:()=>mv,priorityScore:()=>Ov,refineExecutor:()=>Mu,refineLoop:()=>_u,resolvePromptFn:()=>Wo,strategyKey:()=>Or,strategyModel:()=>Au});se();re();pe();function nv(t,e){return{outcome:"success",detail:`actuator applied ${e.intervention} for ${sv(e.summary)}`,artifact:t}}function rv(t,e){let n=t instanceof Error?t.message:String(t);return{outcome:"failure",detail:`actuator threw on ${e.intervention}: ${n}`}}function ov(t){return`actuator skipped ${t.intervention} (shouldApply returned false)`}function sv(t,e=80){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function Om(t){let e=t.name??"actuator-executor",n=t.toOutput??nv,r=t.onError??rv,o=t.skipDetail??ov;return(s,i)=>{let a=s.payload.item;return t.shouldApply&&!t.shouldApply(a)?{...s.payload,execution:{item:a,outcome:"failure",detail:o(a)}}:z(d=>{let u=new AbortController,c=i?.signal,l=()=>{};if(c)if(c.aborted)u.abort();else{let g=()=>u.abort();c.addEventListener("abort",g,{once:!0}),l=()=>c.removeEventListener("abort",g)}let p=!1,f=null,m=g=>{p||(p=!0,d.down([[E,{...s.payload,execution:{item:a,...g}}],[I]]),f?.(),f=null)},h;try{let g=t.apply(a,{signal:u.signal});h=X(g,{signal:u.signal})}catch(g){return m(r(g,a)),()=>{l(),u.abort()}}return f=h.subscribe(g=>{for(let y of g){if(p)return;if(y[0]===E){m(n(y[1],a));return}if(y[0]===L){m(r(y[1],a));return}if(y[0]===I){m(r(new Error("actuator inner completed without emitting DATA"),a));return}}}),p&&f&&(f(),f=null),()=>{l(),u.abort(),f?.(),f=null}},{name:`${e}/inner`})}}function iv(t){let e=t.name??"dispatch-actuator",n=t.default??null,r=n!=null;return Om({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})}se();re();function av(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]!==E){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([[E,f]])}}}),i&&s&&(s(),s=null),()=>{a()}},{name:e})}re();We();pe();function dv(t,e,n,r){return he([t],([o])=>{if(o==null)return;let s=n(o);for(let i of s)e.publish(i)},{name:r?.name??"intake-bridge"})}function uv(t,e,n){let r=n?.defaultSeverity??"medium";return he([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 cv(t,e){return ke(t,()=>X(e()))}function lv(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 pv(t,e){let n=e==null?null:Array.isArray(e)?C(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 fv(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 he([t],([a])=>{if(a!=null)for(let d of i(a))e.publish(d)},{name:r?.name??"code-change-bridge"})}function mv(t,e,n){return he([t.latest],([r])=>{r!=null&&e(r)},{name:n?.name??"notify-effect"})}var ft=["auto-fix","needs-decision","investigation","backlog"],Ji={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},_r={critical:100,high:70,medium:40,low:10},Mr=Math.LN2/(168*3600);function Or(t,e){return`${t}\u2192${e}`}var gv=/\b(parse|json|config|validation|syntax)\b/i,Yi=t=>gv.test(t.detail)?"self-correctable":"structural",Ru=`You are a triage classifier for a reactive collaboration harness.
|
|
181
181
|
|
|
182
182
|
Given an intake item, classify it and output JSON:
|
|
183
183
|
{
|
|
@@ -192,7 +192,7 @@ Strategy model (past effectiveness):
|
|
|
192
192
|
{{strategy}}
|
|
193
193
|
|
|
194
194
|
Intake item:
|
|
195
|
-
{{item}}`,
|
|
195
|
+
{{item}}`,Su=`You are an implementation agent.
|
|
196
196
|
|
|
197
197
|
Given a triaged issue with root cause and intervention type, produce a fix.
|
|
198
198
|
|
|
@@ -203,7 +203,7 @@ Output JSON:
|
|
|
203
203
|
{
|
|
204
204
|
"outcome": "success" | "failure" | "partial",
|
|
205
205
|
"detail": "<description of what was done or what failed>"
|
|
206
|
-
}`,
|
|
206
|
+
}`,Nu=`You are a QA reviewer.
|
|
207
207
|
|
|
208
208
|
Given an execution result, verify whether the fix is correct.
|
|
209
209
|
|
|
@@ -218,11 +218,11 @@ Output JSON:
|
|
|
218
218
|
"verified": true/false,
|
|
219
219
|
"findings": ["<finding1>", ...],
|
|
220
220
|
"errorClass": "self-correctable" | "structural" // only if verified=false
|
|
221
|
-
}`;function
|
|
221
|
+
}`;function Wo(t,e,n){if(typeof t=="function")return t;let r=t??e;return o=>n(r,o)}re();pe();function hv(t){let e=Ke({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=ne(n);return{node:n,record:r,lookup:o,dispose:()=>{s(),e.dispose()}}}Oe();re();We();re();We();Oe();Re();se();Me();re();We();Fe();function yv(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 Am(t,e){if(t.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(t.length===1){let s=Eu(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 Eu(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 _u(t,e,n,r){let o=r.name??"refine-loop",s=new Y(o,r.graph),i=yv(r.dataset)?r.dataset:C(r.dataset,{name:"dataset"});s.add(i,{name:"dataset"});let a=C(0,{name:"iteration"});s.add(a,{name:"iteration"});let d=C(n,{name:"strategy",equals:()=>!1});s.add(d,{name:"strategy"});let u=C(null,{name:"lastFeedback"});s.add(u,{name:"lastFeedback"});let c=C([],{name:"prevCandidates"});s.add(c,{name:"prevCandidates"});let l=C(!1,{name:"paused"});s.add(l,{name:"paused"});let p=C("running",{name:"status"});s.add(p,{name:"status"});let f=C([],{name:"history",equals:()=>!1});s.add(f,{name:"history"});let m=C(null,{name:"best"});s.add(m,{name:"best"});let h=C(Number.NEGATIVE_INFINITY,{name:"score"});s.add(h,{name:"score"});let g=C(0,{name:"budget-used"});s.add(g,{name:"budget-used"});let y=Do("stages");s.mount("stages",y);let b=y.topic("generate"),v=y.topic("evaluate"),T=y.topic("analyze"),w=y.topic("decide"),k=n,x=null,R=[];s.addDisposer(d.subscribe(U=>{for(let ue of U)ue[0]===E&&(k=ue[1])})),s.addDisposer(u.subscribe(U=>{for(let ue of U)ue[0]===E&&(x=ue[1])})),s.addDisposer(c.subscribe(U=>{for(let ue of U)ue[0]===E&&(R=ue[1])}));let S=ke(a,U=>{let ue=k,De=U===0||x==null;return Q([],($e,Ve)=>{let Se=!1;try{let ee=De?ue.seed(t):ue.generate(x,R);if(ee instanceof Promise)return ee.then(K=>{Se||Ve.emit(K)},K=>{Se||Ve.down([[L,K]])}),()=>{Se=!0};Ve.emit(ee)}catch(ee){Se=!0,Ve.down([[L,ee]])}},{describeKind:"producer"})},{name:"candidates"});s.add(S,{name:"candidates"});let _=he([S],(U,ue,De)=>{let $e=De.terminalDeps[0];$e!==void 0&&$e!==!0&&p.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});s.add(_,{name:"error-watcher"}),s.addDisposer(_.subscribe(()=>{}));let O=A([S,a],([U,ue])=>({iteration:ue,candidates:U,timestamp_ns:W()}),{name:"generate-event"});s.add(O,{name:"generate-event"}),s.addDisposer(O.subscribe(()=>{}));let D=he([O],([U])=>{b.publish(U)},{name:"generate-publish"});s.add(D,{name:"generate-publish"}),s.addDisposer(D.subscribe(()=>{}));let M=he([S],([U])=>{c.emit(U)},{name:"generate-mirror"});s.add(M,{name:"generate-mirror"}),s.addDisposer(M.subscribe(()=>{}));let N=e(S,i);s.add(N,{name:"scores"});let P=A([N,S,a],([U,ue,De])=>({iteration:De,candidates:ue,scores:U,timestamp_ns:W()}),{name:"evaluate-event"});s.add(P,{name:"evaluate-event"}),s.addDisposer(P.subscribe(()=>{}));let j=he([P],([U])=>{v.publish(U)},{name:"evaluate-publish"});s.add(j,{name:"evaluate-publish"}),s.addDisposer(j.subscribe(()=>{}));let G=A([N,S],([U,ue])=>k.analyze(U,ue),{name:"feedback"});s.add(G,{name:"feedback"});let V=A([G,S,a],([U,ue,De])=>({iteration:De,candidates:ue,feedback:U,timestamp_ns:W()}),{name:"analyze-event"});s.add(V,{name:"analyze-event"}),s.addDisposer(V.subscribe(()=>{}));let $=he([V],([U])=>{T.publish(U)},{name:"analyze-publish"});s.add($,{name:"analyze-publish"}),s.addDisposer($.subscribe(()=>{}));let q=A([f],([U])=>{let ue=U;if(r.patience==null||ue.length<=r.patience)return!1;let De=ue.slice(-(r.patience+1)),$e=De[0].bestScore;return De.slice(1).every(Ve=>Ve.bestScore<=$e)},{name:"patience-check"});s.add(q,{name:"patience-check"});let F=A([h],([U])=>r.minScore!=null&&U>=r.minScore,{name:"min-score-check"});s.add(F,{name:"min-score-check"});let B=A([f],([U])=>{let ue=U;if(r.minDelta==null||ue.length<2)return!1;let De=ue[ue.length-2].bestScore,$e=ue[ue.length-1].bestScore;return Math.abs($e-De)<r.minDelta},{name:"min-delta-check"});s.add(B,{name:"min-delta-check"});let te=A([g],([U])=>r.maxEvaluations!=null&&U>=r.maxEvaluations,{name:"max-evaluations-check"});s.add(te,{name:"max-evaluations-check"});let de=A([a],([U])=>r.maxIterations!=null&&U>=r.maxIterations,{name:"max-iterations-check"});s.add(de,{name:"max-iterations-check"});let J=A([g],([U])=>r.budget!=null&&U>=r.budget,{name:"budget-exhausted-check"});s.add(J,{name:"budget-exhausted-check"}),s.addDisposer(q.subscribe(()=>{})),s.addDisposer(F.subscribe(()=>{})),s.addDisposer(B.subscribe(()=>{})),s.addDisposer(te.subscribe(()=>{})),s.addDisposer(de.subscribe(()=>{})),s.addDisposer(J.subscribe(()=>{}));let ce=A([q,F,B,te,de],([U,ue,De,$e,Ve])=>U?{converged:!0,reason:"patience"}:ue?{converged:!0,reason:"min-score"}:De?{converged:!0,reason:"min-delta"}:$e?{converged:!0,reason:"max-evaluations"}:Ve?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});s.add(ce,{name:"converged"}),s.addDisposer(ce.subscribe(()=>{}));let Ce=-1,rt=he([G,N,S],([U,ue,De])=>{let $e=a.cache,Ve=U,Se=De,ee=ue;if($e<=Ce)return;Ce=$e;let{best:K,bestScore:ae}=Am(Se,ee),fe=f.cache,Ne={n:$e,candidates:Se,scores:ee,feedback:Ve,best:K,bestScore:ae,timestamp_ns:W()},xe=[...fe,Ne],qe=g.cache+Se.length,me="continue",le,Wn=r.budget!=null&&qe>=r.budget,yn=l.cache;if(Wn)me="budget",le="budget";else if(r.minScore!=null&&Ve.score>=r.minScore)me="converged",le="min-score";else if(r.maxIterations!=null&&$e>=r.maxIterations)me="converged",le="max-iterations";else if(r.maxEvaluations!=null&&qe>=r.maxEvaluations)me="converged",le="max-evaluations";else if(r.minDelta!=null&&xe.length>=2){let Qo=xe[xe.length-2].bestScore,wa=xe[xe.length-1].bestScore;Math.abs(wa-Qo)<r.minDelta&&(me="converged",le="min-delta")}else if(r.patience!=null&&xe.length>r.patience){let Qo=xe.slice(-(r.patience+1)),wa=Qo[0].bestScore;Qo.slice(1).every(Zm=>Zm.bestScore<=wa)&&(me="converged",le="patience")}me==="continue"&&yn&&(me="paused"),Z(()=>{m.emit(K),h.emit(Ve.score),f.emit(xe),g.emit(qe),u.emit(Ve),w.publish({iteration:$e,decision:me,reason:le,timestamp_ns:W()}),me==="continue"?a.emit($e+1):p.emit(me==="converged"?"converged":me==="budget"?"budget":"paused")})},{name:"decide-bridge"});return s.add(rt,{name:"decide-bridge"}),s.addDisposer(rt.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(U){d.emit(U)},pause(){l.emit(!0)},resume(){p.cache==="paused"&&Z(()=>{l.emit(!1),p.emit("running"),a.emit(a.cache+1)})}})}function bv(t){let e=t.width??4;return{name:t.name??"blindVariation",seed(r){return[r]},analyze(r,o){let s=Eu(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 vv(t){return typeof t=="object"&&t!==null&&t.kind==="errorCritique"}function Tv(t,e){return t.length===0?`No task scored below the batch mean (${e.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
|
|
222
222
|
${t.map(r=>{let o=r.error!=null?` | error: ${r.error}`:"";return`- ${r.taskId} (score=${r.score.toFixed(3)})${o}`}).join(`
|
|
223
|
-
`)}`}function hv(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??gv;return{name:n,seed(s){return[s]},analyze(s,i){let a=Tu(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}=Sm(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=mv(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 yv(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 ku(t){let e=t.name??"refine-executor",n=t.toOutput??yv;return r=>{let o=r.payload.item,s=wu(t.seedFrom(o),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(o),name:`${e}/inner`}),i=O([s.status,s.best,s.score],([a,d,u])=>{let c=a;if(c!=="converged"&&c!=="budget"&&c!=="errored")return null;let l=n({best:d,score:u,status:c});return{...r.payload,execution:{item:o,...l}}},{name:`${e}/output`});return kt(i,a=>a!=null,{name:`${e}/gate-out`})}}function bv(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 vv(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 Tv(t){return t.artifact??null}function Nm(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??vv,o=t.extractArtifact??Tv;return s=>{let{item:i,execution:a}=s.payload;if(a==null)return{...s.payload,verify:{verified:!1,findings:["evalVerifier: prior execute stage produced no execution"],errorClass:"structural"}};let d=o(a,i);if(d==null)return{...s.payload,verify:r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0})};let u=A([d],{name:`${e}/candidates`}),c=A(t.datasetFor(i),{name:`${e}/dataset`}),l;Z(()=>{l=t.evaluator(u,c)});let p=O([l],([f])=>{let m=f;if(m==null)return null;let h=bv(m),g=m.filter(y=>y.score>=n).length;return{...s.payload,verify:r({scores:m,meanScore:h,passCount:g,total:m.length,threshold:n})}},{name:`${e}/output`});return kt(p,f=>f!=null,{name:`${e}/gate-out`})}}function wv(t){let e=t.name??"harness-pair",n=ku({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=Nm({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}Re();Ze();ne();ze();Fe();var Qi={};Ee(Qi,{JobFlowGraph:()=>Ji,JobQueueGraph:()=>Ui,jobEventKeyOf:()=>Rv,jobFlow:()=>Ru,jobQueue:()=>Yi});Re();Me();ut();ce();Tt();var kv=256,xv=1024;function xu(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Wi(t,e){return we("job_queue",t,e)}var Rv=t=>t.action,Ui=class extends Y{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;_enqueueImpl;_ackImpl;_nackImpl;_removeByIdImpl;constructor(e,n={}){super(e,n.graph),this._pending=ii([],{name:"pending"}),this._jobs=Xe({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=O([this.pending],([r])=>r.length,{name:"depth",describeKind:"derived",meta:Wi("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=ht(this,"seq",0),this._enqueueImpl=Ce((r,o)=>{let s=this._seqCursor.cache,i=o.id??`${this.name}-${s}`;if(this._jobs.get(i)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${i}"`);let a={id:i,payload:r,attempts:0,metadata:Object.freeze({...o.metadata??{}}),state:"queued"};return this._jobs.set(i,a),this._pending.append(i),i},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([r],o,{t_ns:s,seq:i})=>({action:"enqueue",id:o,payload:r,t_ns:s,seq:i??0})}),this._ackImpl=Ce((r,o)=>{this._jobs.delete(r)},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([r,o],s,{t_ns:i,seq:a})=>({action:"ack",id:r,attempts:o.attempts,t_ns:i,seq:a??0})}),this._nackImpl=Ce((r,o,s)=>{s?(this._jobs.set(r,{...o,state:"queued"}),this._pending.append(r)):this._jobs.delete(r)},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([r,o],s,{t_ns:i,seq:a})=>({action:"nack",id:r,attempts:o.attempts,t_ns:i,seq:a??0})}),this._removeByIdImpl=Ce((r,o)=>{if(o.state==="queued"){let i=this.pending.cache.indexOf(r);i>=0&&this._pending.pop(i)}this._jobs.delete(r)},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([r,o],s,{t_ns:i,seq:a})=>({action:"remove",id:r,attempts:o.attempts,t_ns:i,seq:a??0})})}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,n={}){return this._enqueueImpl(e,n)}claim(e=1){let n=xu(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:ie(),seq:Bt(this._seqCursor)})}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._ackImpl(e,n),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:(this._nackImpl(e,r,n.requeue??!0),!0)}removeById(e){let n=this._jobs.get(e);return n?(this._removeByIdImpl(e,n),!0):!1}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)}})}},Ji=class extends Y{_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,i=new Map;for(let u of r){let c=typeof u=="string"?u.trim():u.name.trim();typeof u!="string"&&u.work&&s.set(c,u.work),typeof u!="string"&&u.maxPerPump!=null&&i.set(c,Math.max(1,xu(u.maxPerPump,`job flow stage "${c}" maxPerPump`))),o.push(c)}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 u of this._stageNames){let c=Yi(`${e}-${u}`);this._queues.set(u,c),this.mount(u,c)}this._completed=We([],{name:"completed",maxSize:xv}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=O([this.completed],([u])=>u.length,{name:"completedCount",describeKind:"derived",meta:Wi("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(te(this.completedCount));let d=Math.max(1,xu(n.maxPerPump??kv,"job flow maxPerPump"));for(let u=0;u<this._stageNames.length;u+=1){let c=this._stageNames[u],l=this.queue(c),p=u+1<this._stageNames.length?this.queue(this._stageNames[u+1]):null,f=this._stageWorkFns.get(c),m=i.get(c)??d,h=p===null;if(f){let g=J([l.pending],()=>{let y=0;for(;y<m;){let b=l.claim(1);if(b.length===0)break;let v=b[0];if(!v)break;let w=[...v.metadata.job_flow_path??[],c],k;try{k=f(v)}catch{l.nack(v.id,{requeue:!1}),y+=1;continue}let R=Q(k),S=!1,x;x=R.subscribe(N=>{if(!S){for(let E of N)if(E[0]===_){S=!0,x?x():Promise.resolve().then(()=>x?.());let P=E[1],M={...v.metadata,job_flow_path:w};if(h){let C={...v,payload:P,metadata:Object.freeze(M)};Z(()=>{l.ack(v.id),this._completed.append(C)})}else Z(()=>{l.ack(v.id),p.enqueue(P,{metadata:M})});return}else if(E[0]===L){S=!0,x?x():Promise.resolve().then(()=>x?.()),l.nack(v.id,{requeue:!1});return}}}),y+=1}},{name:`pump_${c}`,describeKind:"effect",meta:Wi("job_flow_pump",{stage:c,has_work:!0})});this.add(g,{name:`pump_${c}`}),this.addDisposer(te(g))}else{let g=J([l.pending],()=>{let y=0;for(;y<m;){let b=l.claim(1);if(b.length===0)break;let v=b[0];if(!v)break;let w=[...v.metadata.job_flow_path??[],c],k={...v.metadata,job_flow_path:w};if(h){let R={...v,metadata:Object.freeze(k)};Z(()=>{l.ack(v.id),this._completed.append(R)})}else Z(()=>{l.ack(v.id),p.enqueue(v.payload,{metadata:k})});y+=1}},{name:`pump_${c}`,describeKind:"effect",meta:Wi("job_flow_pump",{stage:c,has_work:!1})});this.add(g,{name:`pump_${c}`}),this.addDisposer(te(g))}}}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 Yi(t,e){return new Ui(t,e)}function Ru(t,e){let n=new Ji(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("jobFlow",He(s)),n}Re();ne();function Su(){let t=Xe({name:"strategy-entries"}),e=O([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=_r(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(_r(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function Sv(t,e,n,r,o){let s={...Nr,...o?.severityWeights},i=o?.decayRate??Er,a=o?.effectivenessThreshold??.7,d=o?.effectivenessBoost??15,u=[t,e,n];return r&&u.push(r),O(u,c=>{let l=c[0],p=c[1],f=c[2],m=r?c[3]:0,h=s[l.severity??"medium"],g=(W()-f)/1e9,y=It(h,g,i,0),b=_r(l.rootCause,l.intervention),v=p.get(b);return v&&v.successRate>=a&&(y+=d),y+=m*20,y},{name:"priority-score"})}var Em="intake",Nv="triage-output",_m="retry",Mm="verify-results",Om="__unrouted";function Am(t,e){let n=qo(e,bu,(r,o)=>r.replace("{{item}}",JSON.stringify(o)));return r=>{let o=r.payload.item,s=[{role:"user",content:n(o)}],i=d=>({...r.payload,execution:{item:o,outcome:"failure",detail:d}}),a=d=>d instanceof Error?d.message:String(d);return Qd(t,s,{onSuccess:d=>{let u;try{u=JSON.parse(zt(String(d.content)))}catch(l){return i(`execute parse error: ${a(l)}`)}if(u==null||typeof u!="object"||Array.isArray(u))return i(`execute parse error: non-object response: ${JSON.stringify(u)}`);let c=u;return{...r.payload,execution:{item:o,outcome:c.outcome??"failure",detail:c.detail??"unknown",artifact:c.artifact}}},onFailure:(d,u)=>i(d==="complete"?"adapter completed without emitting DATA":`executor failed: ${a(u)}`)})}}function Cm(t,e){let n=qo(e,vu,(r,o)=>{let[s,i]=o;return r.replace("{{execution}}",JSON.stringify(s)).replace("{{item}}",JSON.stringify(i))});return r=>{let{item:o,execution:s}=r.payload;if(s==null)return{...r.payload,verify:{verified:!1,findings:["verifier: prior execute stage produced no execution"],errorClass:"structural"}};let i=[{role:"user",content:n([s,o])}],a=u=>({...r.payload,verify:{verified:!1,findings:[u],errorClass:"self-correctable"}}),d=u=>u instanceof Error?u.message:String(u);return Qd(t,i,{onSuccess:u=>{let c;try{c=JSON.parse(zt(String(u.content)))}catch(p){return a(`verify parse error: ${d(p)}`)}if(c==null||typeof c!="object"||Array.isArray(c))return a(`verify parse error: non-object response: ${JSON.stringify(c)}`);let l=c;return{...r.payload,verify:{verified:l.verified===!0,findings:l.findings??[],errorClass:l.errorClass}}},onFailure:(u,c)=>a(u==="complete"?"verifier completed without emitting DATA":`verifier failed: ${d(c)}`)})}}var Xi=class extends Y{queues;executeFlow;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(e,n,r,o,s,i,a,d,u,c){super(e),this.queues=n,this.executeFlow=r,this.queueTopics=o,this.jobs=s,this.gates=i,this.strategy=a,this.totalRetries=d,this.totalReingestions=u,this.priorityScores=c}get intake(){return this.queues.topic(Em)}get verifyResults(){return this.queues.topic(Mm)}get retry(){return this.queues.topic(_m)}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=pt.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:["executeFlow::execute::events"]},{label:"VERIFY",paths:["executeFlow::verify::events"]},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function Ev(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??zi,i=new Map;for(let X of pt)i.set(X,{...Hi[X],...e.queues?.[X]});let a=Lo(`${t}/queues`,{defaultTopicOptions:{retainedLimit:o}}),d=a.topic(Em),u=a.topic(Nv),c=a.topic(_m),l=a.topic(Mm),p=new Map;for(let X of pt)p.set(X,a.topic(X));let f=a.topic(Om),m=Su(),h=Mn(d.latest,m.node),g=qo(e.triagePrompt,yu,(X,j)=>{let[ae,le]=j;return X.replace("{{strategy}}",JSON.stringify(Array.from(le.entries()))).replace("{{item}}",JSON.stringify(ae))}),y=Ao(n,[h],X=>{let j=X;return!j||!j[0]?"":g(j)},{name:"triage",format:"json"}),b=Mn(y,h),T=he([b],([X])=>{if(X==null)return;let[j,ae]=X;if(!j?.route)return;let le=ae?.[0],Ne={...j,...le};u.publish(Ne)}).subscribe(()=>{}),w=new Set(pt);for(let X of pt)_i(`bridge/${X}`,u,p.get(X),{map:j=>j.route===X?j:void 0});_i("bridge/__unrouted",u,f,{map:X=>w.has(X.route)?void 0:X});let k=new Map,R=new Map;for(let X of pt)k.set(X,Yi(`jobs/${X}`));let S=[];for(let X of pt){let j=p.get(X),ae=k.get(X),le=new WeakSet,Ne=he([j.events],([xe])=>{let Ke=xe??[];for(let pe of Ke){if(le.has(pe))continue;le.add(pe);let ue=ae.enqueue(pe);R.set(Vo(pe),{route:X,id:ue})}},{name:`jobs/${X}-mirror`});S.push(Ne.subscribe(()=>{}))}function x(X){let j=Vo(X),ae=R.get(j);ae&&(k.get(ae.route)?.removeById(ae.id),R.delete(j))}let N=Rr("gates"),E=new Map;for(let X of pt){let j=i.get(X);if(!j.gated)continue;let ae=p.get(X),le=N.approvalGate(`${X}/gate`,ae.latest,{maxPending:j.maxPending,startOpen:j.startOpen});E.set(X,le)}let P=[];for(let X of pt)i.get(X).gated&&E.has(X)?P.push(E.get(X).node):P.push(p.get(X).latest);P.push(c.latest);let M=Ct(...P),C=e.executor??Am(n,e.executePrompt),$=e.verifier??Cm(n,e.verifyPrompt),V=e.executeMaxPerPump??Number.MAX_SAFE_INTEGER,G=e.verifyMaxPerPump??Number.MAX_SAFE_INTEGER,K=Ru(`${t}/executeFlow`,{stages:[{name:"execute",work:X=>C(X),maxPerPump:V},{name:"verify",work:X=>$(X),maxPerPump:G}]}),F=he([M],([X])=>{X!=null&&K.enqueue({item:X})},{name:"execute-enqueue"}),q=F.subscribe(()=>{}),D=e.maxReingestions??1,B=Math.min(e.maxTotalRetries??r*10,100),re=Math.min(e.maxTotalReingestions??D*10,100),ye=A(0),ee=A(0);function me(X,j,ae){return{item:ae,execution:X,verified:j.verified,findings:j.findings??[],errorClass:j.errorClass}}function Le(X,j){m.record(j.rootCause,j.intervention,!0),l.publish(X),x(j)}function rt(X,j){let ae=Vo(j),le=j.$retries??0,Ne={...j,$retries:le+1,summary:`[RETRY ${le+1}/${r}] ${ae} \u2014 Previous attempt failed: ${X.findings.join("; ")}`,relatedTo:[ae]};c.publish(Ne)}function Qe(X,j){m.record(j.rootCause,j.intervention,!1),l.publish(X),x(j);let ae=Vo(j),le=j.$reingestions??0;le<D&&Gn(ee,re)&&d.publish({source:j.source,summary:`Verification failed for: ${ae}`,evidence:X.findings.join(`
|
|
224
|
-
`),affectsAreas:j.affectsAreas,affectsEvalTasks:j.affectsEvalTasks,severity:j.severity??"high",relatedTo:[ae],$reingestions:le+1})}let U=0,de=he([K.completed],([X])=>{let j=X??[];U>j.length&&(U=j.length);let ae=U;U=j.length;for(let le=ae;le<j.length;le++){let Ne=j[le],{item:xe,execution:Ke,verify:pe}=Ne.payload;if(Ke==null||pe==null){x(xe);continue}let ue=me(Ke,pe,xe);if(ue.verified){Le(ue,xe);continue}let zn=ue.errorClass??s({item:xe,outcome:Ke.outcome,detail:ue.findings.join("; ")}),hn=xe.$retries??0;zn==="self-correctable"&&hn<r&&Gn(ye,B)?rt(ue,xe):Qe(ue,xe)}},{name:"verify-dispatch"}),De=de.subscribe(()=>{}),Be=O([K.completed],()=>null,{name:"reflect",equals:()=>!1}),Ve;e.priority&&(Ve=_v(p,m,e));let Se=new Xi(t,a,K,p,k,E,m,ye,ee,Ve);Se.addDisposer(T),Se.addDisposer(q),Se.addDisposer(De),Se.addDisposer(m.dispose);for(let X of S)Se.addDisposer(X);if(Se.add(h,{name:"triage-input"}),Se.add(y,{name:"triage"}),Se.add(b,{name:"router-input"}),Se.add(M,{name:"execute-input"}),Se.add(F,{name:"execute-enqueue"}),Se.add(de,{name:"verify-dispatch"}),Se.add(Be,{name:"reflect"}),Se.add(m.node,{name:"strategy"}),Se.addDisposer(Be.subscribe(()=>{})),Ve)for(let[X,j]of Ve)Se.add(j,{name:`priority/${X}`}),Se.addDisposer(j.subscribe(()=>{}));Se.mount("queues",a),Se.mount("gates",N),Se.mount("executeFlow",K);for(let[X,j]of k)Se.mount(`jobs/${X}`,j);return Se.tagFactory("harnessLoop",He(e)),Se}function _v(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={...Nr,...o.severityWeights},i=o.decayRate??Er,a=o.effectivenessThreshold??.7,d=o.effectivenessBoost??15,u=new Map;for(let[c,l]of t){let p=O([l.latest,e.node,r],f=>{let m=f[0];if(m==null)return 0;let h=s[m.severity??"medium"]??40,g=(W()-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}gs();function Mv(t,e){let n=xn(t,e),r={};for(let o of pt){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 Ov(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let o of r)e[o]=n;return e}function Av(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=W(),s=[],i=[],a=Ov(t);function d(){return(W()-o)/1e9}function u(c,l,p){let f={elapsed:d(),stage:c,type:l};r!=="summary"&&(f.summary=Cv(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 Cv(t){if(t==null)return"null";if(typeof t=="string")return Lm(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return Lm(e,120)}catch{return String(t)}}function Lm(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var oa={};Ee(oa,{AuditTrailGraph:()=>ea,GuardedExecutionGraph:()=>na,InspectGraph:()=>ra,PolicyGateGraph:()=>ta,auditTrail:()=>Eu,complianceSnapshot:()=>Mu,computeHealthReport:()=>Gm,graphLens:()=>Au,guardedExecution:()=>Fv,healthReportEqual:()=>Fm,inspect:()=>$v,policyGate:()=>_u,watchTopologyTree:()=>Nn});Oe();Re();Jt();se();Ze();Me();ne();es();ut();ce();Tt();function Dm(t,e){return we("audit",t,e)}var Lv=new Set(["data","error","complete","teardown"]),ea=class extends Y{entries;count;_log;_target;constructor(e,n){super(n.name??`${e.name}_audit`,n.graph),this._target=e,this._log=We([],{name:"entries",...n.maxSize!=null?{maxSize:n.maxSize}:{}}),this.entries=this._log.entries,this.add(this.entries,{name:"entries"}),this.count=O([this.entries],([d])=>d.length,{name:"count",describeKind:"derived",meta:Dm("count")}),this.add(this.count,{name:"count"}),this.addDisposer(te(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):Lv,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??W(),wall_clock_ns:ie(),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?Iv(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 Eu(t,e={}){return new ea(t,e)}var ta=class extends Y{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=Im(n)?n:A(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new Wt("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=O([this.violations.events],([m])=>m.length,{name:"violationCount",describeKind:"derived",meta:Dm("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(te(this.violationCount));let i=o.cache??[];this._currentGuard=Vr(i);let a=o.subscribe(m=>{for(let h of m)h[0]===_&&(i=h[1]??[],this._currentGuard=Vr(i))});this.addDisposer(a);let d=r.paths,u=Im(d)?d:void 0,c=d!=null,p=u!=null?u.cache??[]:c?[...d]:void 0,f=p??Pm(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 Ae))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=Nn(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 Y))return;let w=`${v}${y.name}::`,k=Pm(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:W(),wall_clock_ns:ie(),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 _u(t,e,n={}){let r=new ta(t,e,n);return r.tagFactory("policyGate",He(n)),r}function Mu(t,e={}){let n={format_version:1,timestamp_ns:W(),wall_clock_ns:ie(),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=Pv(n);return{...n,fingerprint:r}}function Im(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function Nu(t,e){try{return t.node(e)}catch{return}}function Iv(t,e){try{return t.annotation(e)}catch{return}}function Pm(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function Pv(t){return Yt(JSON.stringify(Dv(t)))}function Dv(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)}Re();se();ne();ut();ce();Tt();function Ou(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&"down"in t}function Gv(t){return we("guarded",t)}var na=class extends Y{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=Ou(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 Wt("lints",{retainedLimit:n.lintsLimit??64}),this.mount("lints",this.lints);let s=n.actor;s==null?this._actorNode=A(null,{name:"actor"}):Ou(s)?this._actorNode=O([s],([d])=>d??null,{name:"actor",initial:null}):this._actorNode=A(s,{name:"actor"});let i={mode:this._mode,name:"enforcer"};if(n.violationsLimit!=null&&(i.violationsLimit=n.violationsLimit),this.enforcer=_u(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=O([this._actorNode,this.enforcer.policies],([d,u])=>({actor:d??null,mode:this._mode,policiesCount:u.length}),{name:"scope",describeKind:"derived",meta:Gv("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:W()}))}scopedDescribeNode(e,n){let r=e==null?this._actorNode:Ou(e)?e:A(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 Fv(t,e){return new na(t,e)}ne();ut();ce();Tt();Tt();function Gm(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=Sn(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 Fm(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 Au(t){let e=t.describe({reactive:!0,detail:"standard",reactiveName:"graphLens.topology"}),n=e.node,r=O([n],([l])=>Gm(l),{name:"graphLens.health",describeKind:"derived",equals:Fm,meta:we("lens","health")}),o=te(r),s=new Map,i=-1,a=t.observe({reactive:!0,tiers:["data"]}),d=O([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:we("lens","flow")}),u=te(d),c=!1;return{topology:n,health:r,flow:d,dispose(){c||(c=!0,u(),o(),e.dispose())}}}Ze();Fe();var Cu=class extends Y{view;constructor(e){super("lens"),this.view=Au(e),this.add(this.view.topology,{name:"topology"}),this.add(this.view.health,{name:"health"}),this.add(this.view.flow,{name:"flow"})}},ra=class extends Y{target;lens;audit;_defaultActor;_lensSubgraph;constructor(e,n={}){super(n.name??`inspect(${e.name})`),this.target=e,this._defaultActor=n.actor,this._lensSubgraph=new Cu(e),this.lens=this._lensSubgraph.view,this.mount("lens",this._lensSubgraph),this.audit=Eu(e,n.audit??{}),this.mount("audit",this.audit),this.addDisposer(()=>this.lens.dispose())}explainTarget(e,n,r){return this.target.explain(e,n,r)}complianceSnapshot(e){let n=e?.actor??this._defaultActor;return Mu(this.target,{audit:this.audit,...n!=null?{actor:n}:{},...e?.policies!=null?{policies:e.policies}:{}})}};function $v(t,e={}){let n=new ra(t,e);return n.tagFactory("inspect",He(e)),n}var sa={};Ee(sa,{processInstanceKeyOf:()=>jv,processManager:()=>Vv});Re();se();ce();var jv=t=>t.correlationId;function $m(t){if(t==null)return Promise.resolve(void 0);let e=Q(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 Bv(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 $m(t(e,n))}catch(a){s=a}}return{outcome:"failure",error:s}}function Vv(t,e,n){let r=n.retryMax??0,o=n.backoffMs??[0],s=1024,i=new Map,a=new Set,d=new Map,u=`${e}_process_instances`,c=`${e}_process_seq`;if(t.tryResolve(u)!==void 0||t.tryResolve(c)!==void 0)throw new Error(`processManager: name "${e}" is already in use on this CQRS graph (collides on "${u}" / "${c}"). Pick a different name or destroy the previous CQRS graph before re-creating the manager.`);let l=at({name:u,retainedLimit:s,graph:t}),p=ht(t,c,0),f=Ce(()=>{},{audit:l,seq:p,freeze:!0,...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},onSuccess:([x,N,E,P],M,{t_ns:C,seq:$})=>({correlationId:x,state:N,status:E,startedAt:d.get(x)??C,updatedAt:C,t_ns:C,seq:$??0,...P!==void 0?{reason:P}:{}})}),m=`_process_${e}_started`;t.event(m),n.persistence?.eventStorage&&t.attachEventStorage(n.persistence.eventStorage);async function h(x,N,E,P){if(a.delete(x),i.delete(x),d.delete(x),n.compensate)try{await $m(n.compensate(N,E)),f(x,N,"compensated",P)}catch{f(x,N,"errored",void 0)}else f(x,N,"errored",void 0)}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(f(x,N.state,"running",void 0),n.isTerminal?.(N.state)){a.delete(x),i.delete(x),d.delete(x),f(x,N.state,"terminated",void 0);return}if(N.schedule){let{afterMs:E,eventType:P}=N.schedule,M,C=st(E),$=V=>{for(let G of V)if(G[0]===_){if(M?M():queueMicrotask(()=>M?.()),!a.has(x))return;let K=i.get(x);if(K===void 0)return;let F=n.steps[P];if(!F)return;let q={type:P,payload:null,timestampNs:ie(),seq:Number.NaN,correlationId:x,aggregateId:x};b(x,F,K,q)}};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),f(x,N.state,"terminated",void 0)}}}let y=new Map;function b(x,N,E,P){let C=(y.get(x)??Promise.resolve()).then(async()=>{let $=i.get(x);if($===void 0||!a.has(x))return;let V;try{V=await Bv(N,$,P,r,o)}catch(G){await h(x,i.get(x)??n.initial,G);return}await g(x,V)});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 V=$[1];if(V.length<=E)continue;let G=V.slice(E);E=V.length;for(let K of G){let F=K.correlationId;if(F===void 0||!a.has(F))continue;let q=n.steps[x];if(!q)continue;let D=i.get(F);D!==void 0&&b(F,q,D,K)}}});T.push(M)}function w(x,N){if(v||a.has(x))return;let E=ie();d.set(x,E),i.set(x,n.initial),a.add(x);try{t._appendEvent(m,N??null,{correlationId:x,aggregateId:x})}catch{}f(x,n.initial,"running",void 0)}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:l,audit:l,start:w,cancel:k,getState:R,dispose:S}}var ia={};Ee(ia,{CanvasMeasureAdapter:()=>Du,CliMeasureAdapter:()=>Lu,ImageSizeAdapter:()=>$u,NodeCanvasMeasureAdapter:()=>Gu,PrecomputedAdapter:()=>Pu,SvgBoundsAdapter:()=>Fu,analyzeAndMeasure:()=>Ut,carveTextLineSlots:()=>gu,circleIntervalForBand:()=>qm,computeBlockFlow:()=>Vm,computeCharPositions:()=>Vi,computeFlowLines:()=>zm,computeLineBreaks:()=>Hn,computeTotalHeight:()=>Km,layoutNextLine:()=>mu,measureBlock:()=>jm,measureBlocks:()=>Bm,reactiveBlockLayout:()=>Kv,reactiveFlowLayout:()=>Hv,reactiveLayout:()=>Hb,rectIntervalForBand:()=>Hm});bs();var Lu=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:lr(e)*this.cellPx}}},Iu=class extends Error{name="KeyError"},Pu=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 Iu(`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}}},Du=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=""}},Gu=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=""}},Fu=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")}},$u=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();Fe();function jm(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,d=t.lineHeight??s,u=Ut(t.text,a,n.text,r),c=Hn(u,e,n.text,a,r),l=Vi(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 Bm(t,e,n,r,o,s){return t.map((i,a)=>jm(i,e,n,r,o,s,a))}function Vm(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 Km(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function Kv(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new Y(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=J([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=W(),v=Bm(g,y,e,i,r,o),T=W()-b,w=c.meta;w&&(Mt(w["block-count"],v.length),Mt(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=O([c,u],([f,m])=>Vm(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=O([l],([f])=>Km(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();Fe();function qm(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 qv(t,e,n){return t.kind==="circle"?qm(t,e,n):Hm(t,e,n)}function zm(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=qv(r[S],v,T);x!==null&&w.push(x)}let k=gu({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=mu(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 Hv(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new Y(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=J([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=Ut(v,w,e,s);g.emit(k);let R=()=>{s.clear(),e.clearCache?.()};return{deactivate:R,invalidate:R}},{name:"segments",describeKind:"derived"}),m=O([f,u,c,l,d,p],([h,g,y,b,v,T])=>{let w=h,k=W(),R=T??v,{lines:S,cursor:x}=zm(w,g,y,b,v,r,{paragraphSpacing:R}),N=W()-k,E=Math.max(0,w.length-x.segmentIndex),P=m.meta;return P&&(Mt(P["line-count"],S.length),Mt(P["layout-time-ns"],N),Mt(P["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 ga={};Ee(ga,{SNAPSHOT_WIRE_VERSION:()=>Wo,SurfaceError:()=>_e,asSurfaceError:()=>aa,createGraph:()=>Mr,deleteSnapshot:()=>ma,diffSnapshots:()=>pa,listSnapshots:()=>fa,restoreSnapshot:()=>la,runReduction:()=>da,saveSnapshot:()=>ca});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=zv(this.details);n!==void 0&&(e.details=n)}return e}};function zv(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function aa(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 Mr(t,e){let n=Sr(t);if(!n.valid)throw new _e("invalid-spec",`GraphSpec validation failed:
|
|
223
|
+
`)}`}function wv(t){let e=t.width??4,n=t.name??"errorCritique",r=t.maxFailureSamples??5,o=t.formatCritique??Tv;return{name:n,seed(s){return[s]},analyze(s,i){let a=Eu(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}=Am(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=vv(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 kv(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 Mu(t){let e=t.name??"refine-executor",n=t.toOutput??kv;return r=>{let o=r.payload.item,s=_u(t.seedFrom(o),t.evaluator,t.strategy,{...t.refine,dataset:t.datasetFor(o),name:`${e}/inner`}),i=A([s.status,s.best,s.score],([a,d,u])=>{let c=a;if(c!=="converged"&&c!=="budget"&&c!=="errored")return null;let l=n({best:d,score:u,status:c});return{...r.payload,execution:{item:o,...l}}},{name:`${e}/output`});return xt(i,a=>a!=null,{name:`${e}/gate-out`})}}function xv(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 Rv(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 Sv(t){return t.artifact??null}function Cm(t){let e=t.name??"eval-verifier",n=t.threshold??.5,r=t.toOutput??Rv,o=t.extractArtifact??Sv;return s=>{let{item:i,execution:a}=s.payload;if(a==null)return{...s.payload,verify:{verified:!1,findings:["evalVerifier: prior execute stage produced no execution"],errorClass:"structural"}};let d=o(a,i);if(d==null)return{...s.payload,verify:r({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:n,missingArtifact:!0})};let u=C([d],{name:`${e}/candidates`}),c=C(t.datasetFor(i),{name:`${e}/dataset`}),l;Z(()=>{l=t.evaluator(u,c)});let p=A([l],([f])=>{let m=f;if(m==null)return null;let h=xv(m),g=m.filter(y=>y.score>=n).length;return{...s.payload,verify:r({scores:m,meanScore:h,passCount:g,total:m.length,threshold:n})}},{name:`${e}/output`});return xt(p,f=>f!=null,{name:`${e}/gate-out`})}}function Nv(t){let e=t.name??"harness-pair",n=Mu({name:`${e}-exec`,seedFrom:t.seedFrom,evaluator:t.evaluator,strategy:t.strategy,datasetFor:t.datasetFor,refine:t.refine}),r=Cm({name:`${e}-verify`,evaluator:t.evaluator,datasetFor:t.datasetFor,threshold:t.threshold});return{executor:n,verifier:r}}Re();Ze();re();We();Fe();var na={};Ee(na,{JobFlowGraph:()=>ea,JobQueueGraph:()=>Zi,jobEventKeyOf:()=>Mv,jobFlow:()=>Ou,jobQueue:()=>ta});Re();Me();ut();pe();bt();var Ev=256,_v=1024;function Qi(t,e){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new Error(`${e} must be a non-negative integer`);return t}function Xi(t,e){return we("job_queue",t,e)}var Mv=t=>t.action,Zi=class extends Y{_pending;_jobs;_seqCursor;pending;jobs;depth;events;audit;_enqueueImpl;_ackImpl;_nackImpl;_removeByIdImpl;constructor(e,n={}){super(e,n.graph),this._pending=ci([],{name:"pending"}),this._jobs=Ke({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:Xi("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(ne(this.depth)),this.events=at({name:"events",retainedLimit:1024,graph:this}),this.audit=this.events,this._seqCursor=vt(this,"seq",0),this._enqueueImpl=Le((r,o)=>{let s=this._seqCursor.cache,i=o.id??`${this.name}-${s}`;if(this._jobs.get(i)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${i}"`);let a={id:i,payload:r,attempts:0,metadata:Object.freeze({...o.metadata??{}}),state:"queued"};return this._jobs.set(i,a),this._pending.append(i),i},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([r],o,{t_ns:s,seq:i})=>({action:"enqueue",id:o,payload:r,t_ns:s,seq:i??0})}),this._ackImpl=Le((r,o)=>{this._jobs.delete(r)},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([r,o],s,{t_ns:i,seq:a})=>({action:"ack",id:r,attempts:o.attempts,t_ns:i,seq:a??0})}),this._nackImpl=Le((r,o,s)=>{s?(this._jobs.set(r,{...o,state:"queued"}),this._pending.append(r)):this._jobs.delete(r)},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([r,o],s,{t_ns:i,seq:a})=>({action:"nack",id:r,attempts:o.attempts,t_ns:i,seq:a??0})}),this._removeByIdImpl=Le((r,o)=>{if(o.state==="queued"){let i=this.pending.cache.indexOf(r);i>=0&&this._pending.pop(i)}this._jobs.delete(r)},{audit:this.events,seq:this._seqCursor,freeze:!1,onSuccess:([r,o],s,{t_ns:i,seq:a})=>({action:"remove",id:r,attempts:o.attempts,t_ns:i,seq:a??0})})}attachEventStorage(e){return this.events.attachStorage(e)}enqueue(e,n={}){return this._enqueueImpl(e,n)}claim(e=1){let n=Qi(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:ie(),seq:Kt(this._seqCursor)})}return r}ack(e){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:(this._ackImpl(e,n),!0)}nack(e,n={}){let r=this._jobs.get(e);return!r||r.state!=="inflight"?!1:(this._nackImpl(e,r,n.requeue??!0),!0)}removeById(e){let n=this._jobs.get(e);return n?(this._removeByIdImpl(e,n),!0):!1}consumeFrom(e,n){return e.subscribe(r=>{for(let o of r){if(o[0]!==E)continue;let s=o[1];this.enqueue(s,n?{metadata:n.metadata}:void 0)}})}},ea=class extends Y{_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,i=new Map,a=new Map;for(let c of r){let l=typeof c=="string"?c.trim():c.name.trim();typeof c!="string"&&c.work&&s.set(l,c.work),typeof c!="string"&&c.maxPerPump!=null&&i.set(l,Math.max(1,Qi(c.maxPerPump,`job flow stage "${l}" maxPerPump`))),typeof c!="string"&&c.maxInflight!=null&&a.set(l,Math.max(1,Qi(c.maxInflight,`job flow stage "${l}" maxInflight`))),o.push(l)}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 c of this._stageNames){let l=ta(`${e}-${c}`);this._queues.set(c,l),this.mount(c,l)}this._completed=Ue([],{name:"completed",maxSize:_v}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=A([this.completed],([c])=>c.length,{name:"completedCount",describeKind:"derived",meta:Xi("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(ne(this.completedCount));let u=Math.max(1,Qi(n.maxPerPump??Ev,"job flow maxPerPump"));for(let c=0;c<this._stageNames.length;c+=1){let l=this._stageNames[c],p=this.queue(l),f=c+1<this._stageNames.length?this.queue(this._stageNames[c+1]):null,m=this._stageWorkFns.get(l),h=i.get(l)??u,g=a.get(l),y=g!==void 0?C(0,{name:`__inflight__/${l}`}):null;y&&this.add(y,{name:`__inflight__/${l}`});let b=f===null;if(m){let v=y!=null?[p.pending,y]:[p.pending],T=Q(v,(w,k,x)=>{"inflight"in x.store||(x.store.inflight={entries:new Set,terminated:!1});let R=x.store.inflight,S=R.entries,_=0;for(;_<h&&!(g!==void 0&&S.size>=g);){let O=p.claim(1);if(O.length===0)break;let D=O[0];if(!D)break;let N=[...D.metadata.job_flow_path??[],l],P=new AbortController,j={unsub:()=>{},ac:P};S.add(j),y?.emit(S.size);let G;try{G=m(D,{signal:P.signal})}catch{S.delete(j),y?.emit(S.size),p.nack(D.id,{requeue:!1}),_+=1;continue}let V=X(G),$=!1,q,F=()=>{q?q():Promise.resolve().then(()=>q?.()),S.delete(j),R.terminated||y?.emit(S.size)};q=V.subscribe(B=>{if(!$){for(let te of B)if(te[0]===E){$=!0,F();let de=te[1],J={...D.metadata,job_flow_path:N};if(b){let ce={...D,payload:de,metadata:Object.freeze(J)};Z(()=>{p.ack(D.id),this._completed.append(ce)})}else Z(()=>{p.ack(D.id),f.enqueue(de,{metadata:J})});return}else if(te[0]===L){$=!0,F(),p.nack(D.id,{requeue:!1});return}}}),j.unsub=()=>q?.(),_+=1}return{deactivate:()=>{R.terminated=!0;for(let O of S){try{O.ac.abort()}catch{}try{O.unsub()}catch{}}S.clear()}}},{name:`pump_${l}`,describeKind:"effect",meta:Xi("job_flow_pump",{stage:l,has_work:!0})});this.add(T,{name:`pump_${l}`}),this.addDisposer(ne(T))}else{let v=Q([p.pending],()=>{let T=0;for(;T<h;){let w=p.claim(1);if(w.length===0)break;let k=w[0];if(!k)break;let R=[...k.metadata.job_flow_path??[],l],S={...k.metadata,job_flow_path:R};if(b){let _={...k,metadata:Object.freeze(S)};Z(()=>{p.ack(k.id),this._completed.append(_)})}else Z(()=>{p.ack(k.id),f.enqueue(k.payload,{metadata:S})});T+=1}},{name:`pump_${l}`,describeKind:"effect",meta:Xi("job_flow_pump",{stage:l,has_work:!1})});this.add(v,{name:`pump_${l}`}),this.addDisposer(ne(v))}}}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 ta(t,e){return new Zi(t,e)}function Ou(t,e){let n=new ea(t,e),{factory:r,factoryArgs:o,...s}=e??{};return n.tagFactory("jobFlow",He(s)),n}Re();re();function Au(){let t=Ke({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=Or(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(Or(i,a))}let o=e.subscribe(()=>{});function s(){o()}return{node:e,record:n,lookup:r,dispose:s}}function Ov(t,e,n,r,o){let s={..._r,...o?.severityWeights},i=o?.decayRate??Mr,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=(W()-f)/1e9,y=Pt(h,g,i,0),b=Or(l.rootCause,l.intervention),v=p.get(b);return v&&v.successRate>=a&&(y+=d),y+=m*20,y},{name:"priority-score"})}var Lm="intake",Av="triage-output",Im="retry",Pm="verify-results",Dm="__unrouted";function Gm(t,e){let n=Wo(e,Su,(r,o)=>r.replace("{{item}}",JSON.stringify(o)));return(r,o)=>{let s=r.payload.item,i=[{role:"user",content:n(s)}],a=u=>({...r.payload,execution:{item:s,outcome:"failure",detail:u}}),d=u=>u instanceof Error?u.message:String(u);return ou(t,i,{parentSignal:o?.signal,onSuccess:u=>{let c;try{c=JSON.parse(Ut(String(u.content)))}catch(p){return a(`execute parse error: ${d(p)}`)}if(c==null||typeof c!="object"||Array.isArray(c))return a(`execute parse error: non-object response: ${JSON.stringify(c)}`);let l=c;return{...r.payload,execution:{item:s,outcome:l.outcome??"failure",detail:l.detail??"unknown",artifact:l.artifact}}},onFailure:(u,c)=>a(u==="complete"?"adapter completed without emitting DATA":`executor failed: ${d(c)}`)})}}function Fm(t,e){let n=Wo(e,Nu,(r,o)=>{let[s,i]=o;return r.replace("{{execution}}",JSON.stringify(s)).replace("{{item}}",JSON.stringify(i))});return(r,o)=>{let{item:s,execution:i}=r.payload;if(i==null)return{...r.payload,verify:{verified:!1,findings:["verifier: prior execute stage produced no execution"],errorClass:"structural"}};let a=[{role:"user",content:n([i,s])}],d=c=>({...r.payload,verify:{verified:!1,findings:[c],errorClass:"self-correctable"}}),u=c=>c instanceof Error?c.message:String(c);return ou(t,a,{parentSignal:o?.signal,onSuccess:c=>{let l;try{l=JSON.parse(Ut(String(c.content)))}catch(f){return d(`verify parse error: ${u(f)}`)}if(l==null||typeof l!="object"||Array.isArray(l))return d(`verify parse error: non-object response: ${JSON.stringify(l)}`);let p=l;return{...r.payload,verify:{verified:p.verified===!0,findings:p.findings??[],errorClass:p.errorClass}}},onFailure:(c,l)=>d(c==="complete"?"verifier completed without emitting DATA":`verifier failed: ${u(l)}`)})}}var ra=class extends Y{queues;executeFlow;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;reflect;constructor(e,n,r,o,s,i,a,d,u,c,l){super(e),this.queues=n,this.executeFlow=r,this.queueTopics=o,this.jobs=s,this.gates=i,this.strategy=a,this.totalRetries=d,this.totalReingestions=u,this.reflect=c,this.priorityScores=l}get intake(){return this.queues.topic(Lm)}get verifyResults(){return this.queues.topic(Pm)}get retry(){return this.queues.topic(Im)}get unrouted(){return this.queues.topic(Dm)}stageNodes(){let e=this.queues,n=i=>e.has(i)?`queues::${i}::latest`:null,r=i=>i==null?[]:[i],o=ft.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:["executeFlow::execute::events"]},{label:"VERIFY",paths:["executeFlow::verify::events"]},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function Cv(t,e){let n=e.adapter,r=e.maxRetries??2,o=e.retainedLimit??1e3,s=e.errorClassifier??Yi,i=new Map;for(let ee of ft)i.set(ee,{...Ji[ee],...e.queues?.[ee]});let a=Do(`${t}/queues`,{defaultTopicOptions:{retainedLimit:o}}),d=a.topic(Lm),u=a.topic(Av),c=a.topic(Im),l=a.topic(Pm),p=new Map;for(let ee of ft)p.set(ee,a.topic(ee));let f=a.topic(Dm),m=Au(),h=On(d.latest,m.node),g=Wo(e.triagePrompt,Ru,(ee,K)=>{let[ae,fe]=K;return ee.replace("{{strategy}}",JSON.stringify(Array.from(fe.entries()))).replace("{{item}}",JSON.stringify(ae))}),y=Io(n,[h],ee=>{let K=ee;return!K||!K[0]?"":g(K)},{name:"triage",format:"json"}),b=On(y,h),T=he([b],([ee])=>{if(ee==null)return;let[K,ae]=ee;if(!K?.route)return;let fe=ae?.[0],Ne={...K,...fe};u.publish(Ne)}).subscribe(()=>{}),w=new Set(ft);for(let ee of ft)Ci(`bridge/${ee}`,u,p.get(ee),{map:K=>K.route===ee?K:void 0});Ci("bridge/__unrouted",u,f,{map:ee=>w.has(ee.route)?void 0:ee});let k=new Map,x=new Map;for(let ee of ft)k.set(ee,ta(`jobs/${ee}`));let R=[];for(let ee of ft){let K=p.get(ee),ae=k.get(ee),fe=new WeakSet,Ne=he([K.events],([xe])=>{let qe=xe??[];for(let me of qe){if(fe.has(me))continue;fe.add(me);let le=ae.enqueue(me);x.set(zo(me),{route:ee,id:le})}},{name:`jobs/${ee}-mirror`});R.push(Ne.subscribe(()=>{}))}function S(ee){let K=zo(ee),ae=x.get(K);ae&&(k.get(ae.route)?.removeById(ae.id),x.delete(K))}let _=Nr("gates"),O=new Map;for(let ee of ft){let K=i.get(ee);if(!K.gated)continue;let ae=p.get(ee),fe=_.approvalGate(`${ee}/gate`,ae.latest,{maxPending:K.maxPending,startOpen:K.startOpen});O.set(ee,fe)}let D=[];for(let ee of ft)i.get(ee).gated&&O.has(ee)?D.push(O.get(ee).output):D.push(p.get(ee).latest);D.push(c.latest);let M=It(...D),N=e.executor??Gm(n,e.executePrompt),P=e.verifier??Fm(n,e.verifyPrompt),j=e.executeMaxPerPump??Number.MAX_SAFE_INTEGER,G=e.verifyMaxPerPump??Number.MAX_SAFE_INTEGER,V=Ou(`${t}/executeFlow`,{stages:[{name:"execute",work:ee=>N(ee),maxPerPump:j},{name:"verify",work:ee=>P(ee),maxPerPump:G}]}),$=he([M],([ee])=>{ee!=null&&V.enqueue({item:ee})},{name:"execute-enqueue"}),q=$.subscribe(()=>{}),F=e.maxReingestions??1,B=Math.min(e.maxTotalRetries??r*10,100),te=Math.min(e.maxTotalReingestions??F*10,100),de=C(0),J=C(0);function ce(ee,K,ae){return{item:ae,execution:ee,verified:K.verified,findings:K.findings??[],errorClass:K.errorClass}}function Ce(ee,K){m.record(K.rootCause,K.intervention,!0),l.publish(ee),S(K)}function rt(ee,K){let ae=zo(K),fe=K.$retries??0,Ne={...K,$retries:fe+1,summary:`[RETRY ${fe+1}/${r}] ${ae} \u2014 Previous attempt failed: ${ee.findings.join("; ")}`,relatedTo:[ae]};c.publish(Ne)}function Xe(ee,K){m.record(K.rootCause,K.intervention,!1),l.publish(ee),S(K);let ae=zo(K),fe=K.$reingestions??0;fe<F&&Fn(J,te)&&d.publish({source:K.source,summary:`Verification failed for: ${ae}`,evidence:ee.findings.join(`
|
|
224
|
+
`),affectsAreas:K.affectsAreas,affectsEvalTasks:K.affectsEvalTasks,severity:K.severity??"high",relatedTo:[ae],$reingestions:fe+1})}let U=0,ue=he([V.completed],([ee])=>{let K=ee??[];U>K.length&&(U=K.length);let ae=U;U=K.length;for(let fe=ae;fe<K.length;fe++){let Ne=K[fe],{item:xe,execution:qe,verify:me}=Ne.payload;if(qe==null||me==null){S(xe);continue}let le=ce(qe,me,xe);if(le.verified){Ce(le,xe);continue}let Wn=le.errorClass??s({item:xe,outcome:qe.outcome,detail:le.findings.join("; ")}),yn=xe.$retries??0;Wn==="self-correctable"&&yn<r&&Fn(de,B)?rt(le,xe):Xe(le,xe)}},{name:"verify-dispatch"}),De=ue.subscribe(()=>{}),$e=A([V.completed],()=>null,{name:"reflect",equals:()=>!1}),Ve;e.priority&&(Ve=Lv(p,m,e));let Se=new ra(t,a,V,p,k,O,m,de,J,$e,Ve);Se.addDisposer(T),Se.addDisposer(q),Se.addDisposer(De),Se.addDisposer(m.dispose);for(let ee of R)Se.addDisposer(ee);if(Se.add(h,{name:"triage-input"}),Se.add(y,{name:"triage"}),Se.add(b,{name:"router-input"}),Se.add(M,{name:"execute-input"}),Se.add($,{name:"execute-enqueue"}),Se.add(ue,{name:"verify-dispatch"}),Se.add($e,{name:"reflect"}),Se.add(m.node,{name:"strategy"}),Se.addDisposer($e.subscribe(()=>{})),Ve)for(let[ee,K]of Ve)Se.add(K,{name:`priority/${ee}`}),Se.addDisposer(K.subscribe(()=>{}));Se.mount("queues",a),Se.mount("gates",_),Se.mount("executeFlow",V);for(let[ee,K]of k)Se.mount(`jobs/${ee}`,K);return Se.tagFactory("harnessLoop",He(e)),Se}function Lv(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={..._r,...o.severityWeights},i=o.decayRate??Mr,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=(W()-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}bs();function Iv(t,e){let n=Rn(t,e),r={};for(let o of ft){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 Pv(t){let e={};for(let{label:n,paths:r}of t.stageNodes())for(let o of r)e[o]=n;return e}function Dv(t,e){let n=e?.logger===null?null:e?.logger??console.log,r=e?.detail??"summary",o=W(),s=[],i=[],a=Pv(t);function d(){return(W()-o)/1e9}function u(c,l,p){let f={elapsed:d(),stage:c,type:l};r!=="summary"&&(f.summary=Gv(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 Gv(t){if(t==null)return"null";if(typeof t=="string")return $m(t,80);if(typeof t=="number"||typeof t=="boolean"||typeof t=="bigint")return String(t);try{let e=JSON.stringify(t);return $m(e,120)}catch{return String(t)}}function $m(t,e){return t.length>e?`${t.slice(0,e-1)}\u2026`:t}var ua={};Ee(ua,{AuditTrailGraph:()=>sa,GuardedExecutionGraph:()=>aa,InspectGraph:()=>da,PolicyGateGraph:()=>ia,auditTrail:()=>Lu,complianceSnapshot:()=>Pu,computeHealthReport:()=>Km,graphLens:()=>Gu,guardedExecution:()=>Kv,healthReportEqual:()=>qm,inspect:()=>qv,policyGate:()=>Iu,watchTopologyTree:()=>En});Oe();Re();Qt();se();Ze();Me();re();rs();ut();pe();bt();function Vm(t,e){return we("audit",t,e)}var Fv=new Set(["data","error","complete","teardown"]),sa=class extends Y{entries;count;includeTypes;_log;_target;constructor(e,n){super(n.name??`${e.name}_audit`,n.graph),this._target=e,this._log=Ue([],{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:Vm("count")}),this.add(this.count,{name:"count"}),this.addDisposer(ne(this.count));let r=n.includeTypes!=null?new Set(n.includeTypes):new Set(Fv);this.includeTypes=r;let 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??W(),wall_clock_ns:ie(),path:c,type:u},f=(c?Cu(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?$v(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 Lu(t,e={}){return new sa(t,e)}var ia=class extends Y{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=jm(n)?n:C(n,{name:"policies"});this.policies=o,this.add(this.policies,{name:"policies"}),this.violations=new Jt("violations",{retainedLimit:r.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=A([this.violations.events],([m])=>m.length,{name:"violationCount",describeKind:"derived",meta:Vm("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(ne(this.violationCount));let i=o.cache??[];this._currentGuard=qr(i);let a=o.subscribe(m=>{for(let h of m)h[0]===E&&(i=h[1]??[],this._currentGuard=qr(i))});this.addDisposer(a);let d=r.paths,u=jm(d)?d:void 0,c=d!=null,p=u!=null?u.cache??[]:c?[...d]:void 0,f=p??Bm(e);if(this._mode!=="enforce"&&u!=null){let m=u.subscribe(h=>{for(let g of h)g[0]===E&&(p=g[1]??[])});this.addDisposer(m)}if(this._mode==="enforce"){let m=new Map,h=g=>{if(m.has(g))return;let y=Cu(e,g);if(!(y instanceof Ae))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]!==E)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 x=m.get(k);x!=null&&(x(),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]!==E)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=En(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 Y))return;let w=`${v}${y.name}::`,k=Bm(T);for(let x of k)h(x===""?`${v}${y.name}`:`${w}${x}`)}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,x]of m)(k===T||k.startsWith(w))&&(x(),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??Cu(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:W(),wall_clock_ns:ie(),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 Iu(t,e,n={}){let r=new ia(t,e,n);return r.tagFactory("policyGate",He(n)),r}function Pu(t,e={}){let n={format_version:1,timestamp_ns:W(),wall_clock_ns:ie(),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=jv(n);return{...n,fingerprint:r}}function jm(t){return typeof t=="object"&&t!==null&&"subscribe"in t}function Cu(t,e){try{return t.node(e)}catch{return}}function $v(t,e){try{return t.annotation(e)}catch{return}}function Bm(t){let e=t.describe({detail:"minimal"});return Object.keys(e.nodes)}function jv(t){return Xt(JSON.stringify(Bv(t)))}function Bv(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)}Re();se();re();ut();pe();bt();function Du(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&"down"in t}function Vv(t){return we("guarded",t)}var aa=class extends Y{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=Du(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 Jt("lints",{retainedLimit:n.lintsLimit??64}),this.mount("lints",this.lints);let s=n.actor;s==null?this._actorNode=C(null,{name:"actor"}):Du(s)?this._actorNode=A([s],([d])=>d??null,{name:"actor",initial:null}):this._actorNode=C(s,{name:"actor"});let i={mode:this._mode,name:"enforcer"};if(n.violationsLimit!=null&&(i.violationsLimit=n.violationsLimit),this.enforcer=Iu(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]!==E)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:Vv("scope")}),this.add(this.scope,{name:"scope"}),this.addDisposer(ne(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:W()}))}scopedDescribeNode(e,n){let r=e==null?this._actorNode:Du(e)?e:C(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 Kv(t,e){return new aa(t,e)}re();ut();pe();bt();bt();function Km(t){let e=[];for(let[n,r]of Object.entries(t.nodes)){if(r.status!=="errored")continue;let o={path:n,status:"errored"},s=Nn(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 qm(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 Gu(t){let e=t.describe({reactive:!0,detail:"standard",reactiveName:"graphLens.topology"}),n=e.node,r=A([n],([l])=>Km(l),{name:"graphLens.health",describeKind:"derived",equals:qm,meta:we("lens","health")}),o=ne(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:we("lens","flow")}),u=ne(d),c=!1;return{topology:n,health:r,flow:d,dispose(){c||(c=!0,u(),o(),e.dispose())}}}Ze();Fe();var Fu=class extends Y{view;constructor(e){super("lens"),this.view=Gu(e),this.add(this.view.topology,{name:"topology"}),this.add(this.view.health,{name:"health"}),this.add(this.view.flow,{name:"flow"})}},da=class extends Y{target;lens;audit;_defaultActor;_lensSubgraph;constructor(e,n={}){super(n.name??`inspect(${e.name})`),this.target=e,this._defaultActor=n.actor,this._lensSubgraph=new Fu(e),this.lens=this._lensSubgraph.view,this.mount("lens",this._lensSubgraph),this.audit=Lu(e,n.audit??{}),this.mount("audit",this.audit),this.addDisposer(()=>this.lens.dispose())}explainTarget(e,n,r){return this.target.explain(e,n,r)}complianceSnapshot(e){let n=e?.actor??this._defaultActor;return Pu(this.target,{audit:this.audit,...n!=null?{actor:n}:{},...e?.policies!=null?{policies:e.policies}:{}})}};function qv(t,e={}){let n=new da(t,e);return n.tagFactory("inspect",He(e)),n}var ca={};Ee(ca,{processInstanceKeyOf:()=>zv,processManager:()=>Uv,processStateKeyOf:()=>Hv});Re();se();pe();bt();var zv=t=>t.correlationId,Hv=t=>t.correlationId;function zm(t){if(t==null)return Promise.resolve(void 0);let e=X(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]===E){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 Wv(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 zm(t(e,n))}catch(a){s=a}}return{outcome:"failure",error:s}}function Uv(t,e,n){let r=n.retryMax??0,o=n.backoffMs??[0],s=1024,i=new Map,a=new Set,d=new Map,u=`__processManagers__/${e}`,c=new Y(e);try{t.mount(u,c)}catch(N){let P=N instanceof Error?N.message:String(N);throw new Error(`processManager: name "${e}" is already in use on this CQRS graph (mount path "${u}" collides). Call .dispose() on the prior manager OR pick a different name before re-creating. (${P})`)}let l=at({name:"instances",retainedLimit:s,graph:c}),p=vt(c,"seq",0),f=gt(()=>{},{audit:l,seq:p,freeze:!0,...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},onSuccess:([N,P,j,G],V,{t_ns:$,seq:q})=>({correlationId:N,state:P,status:j,startedAt:d.get(N)??$,updatedAt:$,t_ns:$,seq:q??0,...G!==void 0?{reason:G}:{}})}),m=n.persistence?.stateStorage??[],h=(N,P)=>{if(m.length===0)return;let j=i.get(N);if(j===void 0)return;let G={correlationId:N,state:j,status:P,startedAt:d.get(N)??ie(),updatedAt:ie(),...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{}};for(let V of m)try{let $=V.save(N,G);$!=null&&typeof $.then=="function"&&$.catch(()=>{})}catch{}},g=N=>{if(m.length!==0){for(let P of m)if(P.delete)try{let j=P.delete(N);j!=null&&typeof j.then=="function"&&j.catch(()=>{})}catch{}}},y=`_process_${e}_started`;t.event(y),n.persistence?.eventStorage&&t.attachEventStorage(n.persistence.eventStorage);async function b(N,P,j,G){if(a.delete(N),i.delete(N),d.delete(N),n.compensate)try{await zm(n.compensate(P,j)),f(N,P,"compensated",G),g(N)}catch{f(N,P,"errored",void 0),g(N)}else f(N,P,"errored",void 0),g(N)}async function v(N,P){if(a.has(N)){if(P.outcome==="failure"){let j=i.get(N)??n.initial;await b(N,j,P.error);return}if(P.outcome==="success"){if(i.set(N,P.state),P.emit)for(let j of P.emit)try{t._appendEvent(j.type,j.payload,{correlationId:N,aggregateId:N})}catch{}if(f(N,P.state,"running",void 0),h(N,"running"),n.isTerminal?.(P.state)){a.delete(N),i.delete(N),d.delete(N),f(N,P.state,"terminated",void 0),g(N);return}if(P.schedule){let{afterMs:j,eventType:G}=P.schedule,V,$=st(j),q=F=>{for(let B of F)if(B[0]===E){if(V?V():queueMicrotask(()=>V?.()),!a.has(N))return;let te=i.get(N);if(te===void 0)return;let de=n.steps[G];if(!de)return;let J={type:G,payload:null,timestampNs:ie(),seq:Number.NaN,correlationId:N,aggregateId:N};w(N,de,te,J)}};V=$.subscribe(q)}return}if(P.outcome==="terminate"){if(i.set(N,P.state),P.emit)for(let j of P.emit)try{t._appendEvent(j.type,j.payload,{correlationId:N,aggregateId:N})}catch{}a.delete(N),i.delete(N),d.delete(N),f(N,P.state,"terminated",void 0),g(N)}}}let T=new Map;function w(N,P,j,G){let $=(T.get(N)??Promise.resolve()).then(async()=>{let q=i.get(N);if(q===void 0||!a.has(N))return;let F;try{F=await Wv(P,q,G,r,o)}catch(B){await b(N,i.get(N)??n.initial,B);return}await v(N,F)});T.set(N,$),$.finally(()=>{T.get(N)===$&&T.delete(N)})}let k=!1,x=[];for(let N of n.watching){let P=t.event(N),j=0;j=(P.cache??[]).length;let V=P.subscribe($=>{for(let q of $){if(q[0]!==E)continue;let F=q[1];if(F.length<=j)continue;let B=F.slice(j);j=F.length;for(let te of B){let de=te.correlationId;if(de===void 0||!a.has(de))continue;let J=n.steps[N];if(!J)continue;let ce=i.get(de);ce!==void 0&&w(de,J,ce,te)}}});x.push(V)}let R=gt((N,P)=>{t._appendEvent(y,P??null,{correlationId:N,aggregateId:N}),d.set(N,ie()),i.set(N,n.initial),a.add(N)},{audit:l,seq:p,freeze:!0,...n.handlerVersion!==void 0?{handlerVersion:n.handlerVersion}:{},onSuccess:([N],P,{t_ns:j,seq:G})=>({correlationId:N,state:n.initial,status:"running",startedAt:d.get(N)??j,updatedAt:j,t_ns:j,seq:G??0})});function S(N,P){k||a.has(N)||(R(N,P),h(N,"running"))}function _(N,P){if(k||!a.has(N))return;let j=i.get(N)??n.initial;b(N,j,new Error(`cancelled: ${P??"no reason given"}`),P)}function O(N){return i.get(N)}async function D(){if(k)return 0;let N=m[0];if(N==null||N.list==null||N.load==null)return 0;let P=await N.list(),j=0;for(let G of P){let V=await N.load(G);V!=null&&V.status==="running"&&(i.set(V.correlationId,V.state),a.add(V.correlationId),d.set(V.correlationId,V.startedAt),j+=1)}return j}function M(){if(!k){k=!0;for(let N of x)try{N()}catch{}x.length=0;try{t.remove(u)}catch{}}}return{instances:l,audit:l,start:S,cancel:_,getState:O,restore:D,dispose:M}}var la={};Ee(la,{CanvasMeasureAdapter:()=>Vu,CliMeasureAdapter:()=>$u,ImageSizeAdapter:()=>zu,NodeCanvasMeasureAdapter:()=>Ku,PrecomputedAdapter:()=>Bu,SvgBoundsAdapter:()=>qu,analyzeAndMeasure:()=>Yt,carveTextLineSlots:()=>ku,circleIntervalForBand:()=>Ym,computeBlockFlow:()=>Um,computeCharPositions:()=>Hi,computeFlowLines:()=>Xm,computeLineBreaks:()=>Hn,computeTotalHeight:()=>Jm,layoutNextLine:()=>wu,measureBlock:()=>Hm,measureBlocks:()=>Wm,reactiveBlockLayout:()=>Jv,reactiveFlowLayout:()=>Qv,reactiveLayout:()=>Yb,rectIntervalForBand:()=>Qm});ks();var $u=class{cellPx;constructor(e){this.cellPx=e?.cellPx??8}measureSegment(e,n){return{width:pr(e)*this.cellPx}}},ju=class extends Error{name="KeyError"},Bu=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 ju(`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}}},Vu=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=""}},Ku=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=""}},qu=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")}},zu=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();re();Fe();function Hm(t,e,n,r,o,s,i){switch(t.type){case"text":{let a=t.font??o,d=t.lineHeight??s,u=Yt(t.text,a,n.text,r),c=Hn(u,e,n.text,a,r),l=Hi(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 Wm(t,e,n,r,o,s){return t.map((i,a)=>Hm(i,e,n,r,o,s,a))}function Um(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 Jm(t){if(t.length===0)return 0;let e=t[t.length-1];return e.y+e.height}function Jv(t){let{adapters:e,name:n="reactive-block-layout",defaultFont:r="16px sans-serif",defaultLineHeight:o=20}=t,s=new Y(n),i=new Map,a=C(t.blocks??[],{name:"blocks"}),d=C(Math.max(0,t.maxWidth??800),{name:"max-width"}),u=C(t.gap??0,{name:"gap"}),c=Q([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=W(),v=Wm(g,y,e,i,r,o),T=W()-b,w=c.meta;w&&(At(w["block-count"],v.length),At(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])=>Um(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])=>Jm(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();re();Fe();function Ym(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 Qm(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 Yv(t,e,n){return t.kind==="circle"?Ym(t,e,n):Qm(t,e,n)}function Xm(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 R=0;R<r.length;R++){let S=Yv(r[R],v,T);S!==null&&w.push(S)}let k=ku({left:y,right:b},w,s);if(k.length===0){v+=o;continue}let x=!1;for(let R=0;R<k.length;R++){let S=k[R],_=S.right-S.left,O=wu(t,u,_);if(O===null)return{lines:d,cursor:u};if(O.text.length===0&&O.width===0){u=O.end,x=!0;break}d.push({x:S.left,y:v,width:O.width,slotWidth:_,text:O.text,columnIndex:g,flushToRight:S.right<b-.5}),u=O.end}if(x){v+=a;continue}if(v+=o,u.segmentIndex>=t.length)break e}if(u.segmentIndex>=t.length)break}return{lines:d,cursor:u}}function Qv(t){let{adapter:e,name:n="reactive-flow-layout",minSlotWidth:r=20}=t,o=new Y(n),s=new Map,i=C(t.text??"",{name:"text"}),a=C(t.font??"16px sans-serif",{name:"font"}),d=C(t.lineHeight??20,{name:"line-height"}),u=C(t.container??{width:800,height:600,paddingX:0,paddingY:0},{name:"container"}),c=C(t.columns??{count:1,gap:0},{name:"columns"}),l=C(t.obstacles??[],{name:"obstacles"}),p=C(t.paragraphSpacing??null,{name:"paragraph-spacing"}),f=Q([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=Yt(v,w,e,s);g.emit(k);let x=()=>{s.clear(),e.clearCache?.()};return{deactivate:x,invalidate:x}},{name:"segments",describeKind:"derived"}),m=A([f,u,c,l,d,p],([h,g,y,b,v,T])=>{let w=h,k=W(),x=T??v,{lines:R,cursor:S}=Xm(w,g,y,b,v,r,{paragraphSpacing:x}),_=W()-k,O=Math.max(0,w.length-S.segmentIndex),D=m.meta;return D&&(At(D["line-count"],R.length),At(D["layout-time-ns"],_),At(D["overflow-segments"],O)),R},{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 Ta={};Ee(Ta,{SNAPSHOT_WIRE_VERSION:()=>Yo,SurfaceError:()=>_e,asSurfaceError:()=>pa,createGraph:()=>Ar,deleteSnapshot:()=>va,diffSnapshots:()=>ya,listSnapshots:()=>ba,restoreSnapshot:()=>ha,runReduction:()=>fa,saveSnapshot:()=>ga});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=Xv(this.details);n!==void 0&&(e.details=n)}return e}};function Xv(t){try{return JSON.parse(JSON.stringify(t))}catch{return}}function pa(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 Ar(t,e){let n=Er(t);if(!n.valid)throw new _e("invalid-spec",`GraphSpec validation failed:
|
|
225
225
|
${n.errors.join(`
|
|
226
|
-
`)}`,{errors:n.errors});let r=e?.catalog??{},o=
|
|
226
|
+
`)}`,{errors:n.errors});let r=e?.catalog??{},o=Ko(t,r);if(!o.valid)throw new _e("catalog-error",`Catalog validation failed:
|
|
227
227
|
${o.errors.join(`
|
|
228
|
-
`)}`,{errors:o.errors});try{return
|
|
228
|
+
`)}`,{errors:o.errors});try{return qo(t,e)}catch(s){let i=s instanceof Error?s.message:String(s);throw new _e("catalog-error",i)}}se();var Zv=3e4;async function fa(t,e,n){let r=n?.inputPath??"input",o=n?.outputPath??"output",s=n?.timeoutMs??Zv,i=Ar(t,{catalog:n?.catalog}),a;try{a=i.resolve(o)}catch{throw i.destroy(),new _e("node-not-found",`reduce: output path "${o}" is not registered`,{path:o})}try{i.resolve(r)}catch{throw i.destroy(),new _e("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]===E){h(()=>d(y[1]));return}if(y[0]===H){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 _e("internal-error",`reduce: output emitted ERROR: ${v}`,T!=null?{cause:T}:void 0)));return}if(y[0]===I){h(()=>u(new _e("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 _e("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 _e("reduce-timeout",`reduce: no output emitted within ${s}ms`,{timeoutMs:s,outputPath:o})))},s),p.unref?.())})}finally{i.destroy()}}Re();Fe();var Yo=kt,Uo="snapshot:";function Jo(t){if(t.startsWith(Uo))throw new _e("snapshot-failed",`snapshot id must not start with "${Uo}" (reserved); got "${t}"`,{snapshotId:t})}function ma(t){return`${Uo}${t}`}function eT(t){return t.startsWith(Uo)?t.slice(Uo.length):void 0}function Hu(t,e){if(t==null||typeof t!="object")throw new _e("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 _e("restore-failed",`snapshot "${e}" is a diff record; restore the baseline and replay WAL instead`,{snapshotId:e,mode:"diff"}):new _e("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 _e("restore-failed",`snapshot "${e}" payload is not a GraphCheckpointRecord or GraphPersistSnapshot`,{snapshotId:e})}async function ga(t,e,n){Jo(e);let r;try{r=t.snapshot()}catch(s){let i=s instanceof Error?s.message:String(s);throw new _e("snapshot-failed",`snapshot "${e}" serialization failed: ${i}`,{snapshotId:e})}let o={name:t.name,mode:"full",seq:0,timestamp_ns:ie(),format_version:Yo,snapshot:r};try{await n.save(ma(e),o)}catch(s){let i=s instanceof Error?s.message:String(s);throw new _e("snapshot-failed",`snapshot "${e}" save failed: ${i}`,{snapshotId:e})}return{snapshotId:e,timestamp_ns:o.timestamp_ns}}async function ha(t,e,n){Jo(t);let r=ma(t),o=await e.load(r);o===void 0&&(o=await e.load(t));let s=Hu(o,t);try{return Y.fromSnapshot(s,n?.factories?{factories:n.factories}:void 0)}catch(i){let a=i instanceof Error?i.message:String(i);throw new _e("restore-failed",`snapshot "${t}" restore failed: ${a}`,{snapshotId:t})}}async function ya(t,e,n){Jo(t),Jo(e);let r=async d=>{let u=ma(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=Hu(o,t),a=Hu(s,e);return Y.diff(i,a)}async function ba(t,e){if(typeof t.list!="function")throw new _e("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=eT(s);i!==void 0?r.push(i):o&&r.push(s)}return r}async function va(t,e){if(Jo(t),typeof e.delete!="function")throw new _e("snapshot-failed",`KvStorageTier is append-only (no delete()); cannot delete "${t}"`,{snapshotId:t});try{await e.delete(ma(t))}catch(n){let r=n instanceof Error?n.message:String(n);throw new _e("snapshot-failed",`snapshot "${t}" delete failed: ${r}`,{snapshotId:t})}}var tT="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,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,derivedT,deserializeError,dictKv,dictSnapshot,diffForWAL,diffSnapshots,distill,distinctUntilChanged,domainMeta,domainTemplates,downWithBatch,dynamicNode,effect,effectT,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,harness,inspect,interval,isBatching,isV1,jobQueue,jotai,jsonCodec,jsonCodecFor,keepalive,kvStorage,last,layout,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,registerBuiltinCodecs,registerBuiltins,registerCursor,registerCursorMap,repeat,replay,replayWAL,rescue,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,validateNoIslands,valve,verifiable,version,vue,wallClockNs,watchTopologyTree,window,windowCount,windowTime,withBreaker,withLatestFrom,withMaxAttempts,withStatus,workerBridge,workerSelf,wrapMutation,zip,zustand});
|