@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/chunk-7VKFXLZQ.js
DELETED
|
@@ -1,84 +0,0 @@
|
|
|
1
|
-
import{b as X}from"./chunk-G5VBJ5K6.js";import{h as Q,j as U}from"./chunk-ACMJ2ZPS.js";import{E as z,F as W,G as Y,H as V}from"./chunk-LYCLF26R.js";import{b as ie}from"./chunk-QYADASLV.js";var he={};ie(he,{compileSpec:()=>ue,decompileSpec:()=>me,extractFnFactory:()=>te,extractSourceFactory:()=>ne,generateCatalogPrompt:()=>oe,isRichFnEntry:()=>T,isRichSourceEntry:()=>I,llmCompose:()=>ye,llmRefine:()=>ae,specDiff:()=>ge,validateSpec:()=>q,validateSpecAgainstCatalog:()=>K});function M(n){let e=n.meta?.factory;return typeof e=="string"?e:void 0}function C(n){let e=n.meta?.factoryArgs;return e!=null&&typeof e=="object"?e:{}}function Z(n){let e=C(n);return"initial"in e?e.initial:n.value}function T(n){return typeof n=="object"&&n!==null&&"factory"in n}function I(n){return typeof n=="object"&&n!==null&&"factory"in n}function te(n){return T(n)?n.factory:n}function ne(n){return I(n)?n.factory:n}function oe(n){let e=[];if(n.fns){let o=new Map;for(let[s,f]of Object.entries(n.fns)){let p=T(f)?f.tags?.[0]??"Other":"Other";o.has(p)||o.set(p,[]),o.get(p).push(ce(s,f))}for(let[s,f]of o)e.push(`${s}:
|
|
2
|
-
${f.join(`
|
|
3
|
-
`)}`)}if(n.sources){let o=[];for(let[s,f]of Object.entries(n.sources))o.push(pe(s,f));o.length>0&&e.push(`Sources:
|
|
4
|
-
${o.join(`
|
|
5
|
-
`)}`)}return e.join(`
|
|
6
|
-
|
|
7
|
-
`)}function ce(n,e){if(!T(e))return`- ${n}`;let o=`- ${n}: ${e.description}`;if(e.configSchema){let s=Object.entries(e.configSchema).map(([f,p])=>{let u=`${f}: ${p.type}`;return p.enum&&(u+=` (${p.enum.join("|")})`),p.required===!1&&(u+="?"),u});o+=`. Config: { ${s.join(", ")} }`}return o}function pe(n,e){if(!I(e))return`- ${n}`;let o=`- ${n}: ${e.description}`;if(e.configSchema){let s=Object.entries(e.configSchema).map(([f,p])=>{let u=`${f}: ${p.type}`;return p.required===!1&&(u+="?"),u});o+=`. Config: { ${s.join(", ")} }`}return o}function K(n,e){let o=[],s=new Set(Object.keys(e.fns??{})),f=new Set(Object.keys(e.sources??{}));for(let[p,u]of Object.entries(n.nodes)){if(u.type==="template")continue;let i=u,r=M(i);if(r==null)continue;let t=i.type==="producer";if(i.type==="state"&&r==="state")continue;if(t){let h=f.has(r),l=s.has(r);if(!h&&!l&&(f.size>0||s.size>0)){let b=J(r,f)??J(r,s);o.push(`Node "${p}": source "${r}" not found in catalog`+(b?`. Did you mean "${b}"?`:""))}}else if(s.size>0&&!s.has(r))if(f.has(r))o.push(`Node "${p}": fn "${r}" is a source, not a function. Use it as a producer source instead, or use a function from: ${[...s].join(", ")}`);else{let h=J(r,s);o.push(`Node "${p}": fn "${r}" not found in catalog`+(h?`. Did you mean "${h}"?`:""))}let m=C(i);if(!t&&e.fns?.[r]){let h=e.fns[r];if(T(h)&&h.configSchema){for(let[l,b]of Object.entries(h.configSchema))if(b.required!==!1&&!(l in m)&&o.push(`Node "${p}": config missing required field "${l}"`),l in m&&b.enum){let S=m[l];b.enum.includes(S)||o.push(`Node "${p}": config.${l} = ${JSON.stringify(S)}, expected one of: ${b.enum.join(", ")}`)}}}if(t&&e.sources?.[r]){let h=e.sources[r];if(I(h)&&h.configSchema){for(let[l,b]of Object.entries(h.configSchema))if(b.required!==!1&&!(l in m)&&o.push(`Node "${p}": config missing required field "${l}"`),l in m&&b.enum){let S=m[l];b.enum.includes(S)||o.push(`Node "${p}": config.${l} = ${JSON.stringify(S)}, expected one of: ${b.enum.join(", ")}`)}}}}if(n.templates)for(let[p,u]of Object.entries(n.templates))for(let[i,r]of Object.entries(u.nodes)){let t=M(r);if(t!=null&&!(r.type==="state"&&t==="state")&&r.type!=="producer"&&s.size>0&&!s.has(t)){let m=J(t,s);o.push(`Template "${p}" node "${i}": fn "${t}" not found in catalog`+(m?`. Did you mean "${m}"?`:""))}}return{valid:o.length===0,errors:o,warnings:[]}}function J(n,e){let o=null,s=1/0,f=n.toLowerCase();for(let p of e){let u=fe(f,p.toLowerCase());u<s&&u<=Math.max(3,Math.floor(n.length/2))&&(s=u,o=p)}return o}function fe(n,e){let o=n.length,s=e.length,f=Array.from({length:o+1},(p,u)=>Array.from({length:s+1},(i,r)=>u===0?r:r===0?u:0));for(let p=1;p<=o;p++)for(let u=1;u<=s;u++)f[p][u]=n[p-1]===e[u-1]?f[p-1][u-1]:1+Math.min(f[p-1][u],f[p][u-1],f[p-1][u-1]);return f[o][s]}var ee=new Set(["state","producer","derived","effect","operator","template"]),de=new Set(["state","producer","derived","effect","operator"]);function q(n){let e=[],o=[];if(n==null||typeof n!="object")return{valid:!1,errors:["GraphSpec must be a non-null object"],warnings:o};let s=n;if((typeof s.name!="string"||s.name.length===0)&&e.push("Missing or empty 'name' field"),s.nodes==null||typeof s.nodes!="object"||Array.isArray(s.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e,warnings:o};let f=new Set(Object.keys(s.nodes)),p=new Map,u=new Map;if(s.templates!=null&&typeof s.templates=="object"&&!Array.isArray(s.templates)){for(let[i,r]of Object.entries(s.templates))if(r!=null&&typeof r=="object"){let t=r;u.set(i,{params:Array.isArray(t.params)?t.params:[]})}}if(s.templates!=null)if(typeof s.templates!="object"||Array.isArray(s.templates))e.push("'templates' must be an object");else for(let[i,r]of Object.entries(s.templates)){if(r==null||typeof r!="object"){e.push(`Template "${i}": must be an object`);continue}let t=r;if(Array.isArray(t.params)||e.push(`Template "${i}": missing 'params' array`),t.nodes==null||typeof t.nodes!="object"||Array.isArray(t.nodes))e.push(`Template "${i}": missing or invalid 'nodes' object`);else{let m=new Set(Array.isArray(t.params)?t.params:[]),h=new Set(Object.keys(t.nodes));for(let[l,b]of Object.entries(t.nodes)){if(b==null||typeof b!="object"){e.push(`Template "${i}" node "${l}": must be an object`);continue}let S=b;if((typeof S.type!="string"||!de.has(S.type))&&e.push(`Template "${i}" node "${l}": invalid type`),Array.isArray(S.deps))for(let g of S.deps)!h.has(g)&&!m.has(g)&&e.push(`Template "${i}" node "${l}": dep "${g}" is not an inner node or param`)}typeof t.output!="string"?e.push(`Template "${i}": missing 'output' string`):t.nodes[t.output]||e.push(`Template "${i}": output "${t.output}" is not a declared node`)}}for(let[i,r]of Object.entries(s.nodes)){if(r==null||typeof r!="object"){e.push(`Node "${i}": must be an object`);continue}let t=r;if(typeof t.type!="string"||!ee.has(t.type)){e.push(`Node "${i}": invalid type "${String(t.type)}" (expected: ${[...ee].join(", ")})`);continue}if(p.set(i,t.type),t.type==="template")if(typeof t.template!="string"||!u.has(t.template))e.push(`Node "${i}": template "${String(t.template)}" not found in templates`);else if(t.bind==null||typeof t.bind!="object"||Array.isArray(t.bind))e.push(`Node "${i}": template ref requires 'bind' object`);else{let m=u.get(t.template),h=t.bind;for(let l of m.params)l in h||e.push(`Node "${i}": template param "${l}" is not bound (template "${t.template}")`);for(let[,l]of Object.entries(h))typeof l=="string"&&!f.has(l)&&e.push(`Node "${i}": bind target "${l}" does not reference an existing node`)}else{if(Array.isArray(t.deps))for(let m of t.deps)m===i?e.push(`Node "${i}": self-referencing dep`):f.has(m)||e.push(`Node "${i}": dep "${m}" does not reference an existing node`);(t.type==="derived"||t.type==="effect"||t.type==="operator")&&!Array.isArray(t.deps)&&e.push(`Node "${i}": ${t.type} node should have a 'deps' array`)}}if(s.feedback!=null)if(!Array.isArray(s.feedback))e.push("'feedback' must be an array");else for(let i=0;i<s.feedback.length;i++){let r=s.feedback[i];if(r==null||typeof r!="object"){e.push(`Feedback [${i}]: must be an object`);continue}let t=r;typeof t.from!="string"||!f.has(t.from)?e.push(`Feedback [${i}]: 'from' "${String(t.from)}" does not reference an existing node`):p.get(t.from)==="effect"&&o.push(`Feedback [${i}]: 'from' "${t.from}" is an effect node \u2014 effects emit no DATA, so the feedback edge will never fire. Did you mean a derived/state node upstream?`),typeof t.from=="string"&&t.from===t.to&&e.push(`Feedback [${i}]: 'from' and 'to' must be different nodes`),typeof t.to!="string"||!f.has(t.to)?e.push(`Feedback [${i}]: 'to' "${String(t.to)}" does not reference an existing node`):typeof t.to=="string"&&p.get(t.to)!=="state"&&e.push(`Feedback [${i}]: 'to' node "${t.to}" must be a state node (got "${p.get(t.to)??"unknown"}")`)}return{valid:e.length===0,errors:e,warnings:o}}function ue(n,e){let o=q(n);if(!o.valid)throw new Error(`compileSpec: invalid GraphSpec:
|
|
8
|
-
${o.errors.join(`
|
|
9
|
-
`)}`);let s=n.factory,f=n.factoryArgs;if(typeof s=="string"){let a=e?.catalog?.graphFactories?.[s];if(a)return a(f)}let p=e?.catalog??{},u=e?.onMissing??"placeholder",i=new U(n.name),r=n.templates??{},t=K(n,p);if(!t.valid)throw new Error(`compileSpec: catalog validation errors:
|
|
10
|
-
${t.errors.join(`
|
|
11
|
-
`)}`);let m=[],h=(a,d,y)=>{m.push({path:a,kind:d,name:y})},l=a=>{let d=p.fns?.[a];return d?te(d):void 0},b=a=>{let d=p.sources?.[a];return d?ne(d):void 0},S=a=>{if(!a)return;let d={};for(let[y,w]of Object.entries(a))y==="factory"||y==="factoryArgs"||(d[y]=w);return Object.keys(d).length>0?d:void 0},g=new Map,x=[];for(let[a,d]of Object.entries(n.nodes)){if(d.type==="template")continue;let y=d,w=M(y),k=C(y);if(y.type==="state"){let v=Z(y),R=z(v,{name:a,meta:S(y.meta)});i.add(R,{name:a}),g.set(a,R)}else if(y.type==="producer"){let v=w?b(w):void 0,R=w?l(w):void 0;if(v){let N=v(k);i.add(N,{name:a}),g.set(a,N)}else if(R){let N=R([],k);i.add(N,{name:a}),g.set(a,N)}else{w&&h(a,"source",w);let N=W(()=>{},{name:a,meta:{...S(y.meta),_specSource:w}});i.add(N,{name:a}),g.set(a,N)}}else x.push([a,y])}let L=!0,c=new Map(x);for(;c.size>0&&L;){L=!1;for(let[a,d]of[...c.entries()]){let y=d.deps??[];if(!y.every(F=>g.has(F)))continue;let w=y.map(F=>g.get(F)),k=M(d),v=C(d),R=k?l(k):void 0,N;R?N=R(w,v):d.type==="effect"?(k&&h(a,"fn",k),N=V(w,()=>{})):(k&&h(a,"fn",k),N=Y(w,F=>F[0])),i.add(N,{name:a}),g.set(a,N),c.delete(a),L=!0}}if(c.size>0){let a=[...c.keys()].sort().join(", ");throw new Error(`compileSpec: unresolvable deps for nodes: ${a}`)}for(let[a,d]of Object.entries(n.nodes)){if(d.type!=="template")continue;let y=d,w=r[y.template],k=new U(a),v=new Map,R=[];for(let[$,j]of Object.entries(w.nodes)){let P=(j.deps??[]).map(A=>A.startsWith("$")&&y.bind[A]?y.bind[A]:A),H={...j,deps:P},G=M(j),E=C(j);if(j.type==="state"){let A=Z(j),_=z(A,{name:$,meta:S(j.meta)});k.add(_,{name:$}),v.set($,_)}else if(j.type==="producer"){let A=G?b(G):void 0,_=G?l(G):void 0;if(A){let O=A(E);k.add(O,{name:$}),v.set($,O)}else if(_){let O=_([],E);k.add(O,{name:$}),v.set($,O)}else{G&&h(`${a}.${$}`,"source",G);let O=W(()=>{},{name:$,meta:{...S(j.meta),_specSource:G}});k.add(O,{name:$}),v.set($,O)}}else R.push([$,H])}let N=!0,F=new Map(R);for(;F.size>0&&N;){N=!1;for(let[$,j]of[...F.entries()]){let P=j.deps??[];if(!P.every(D=>v.has(D)||g.has(D)))continue;let G=P.map(D=>v.get(D)??g.get(D)),E=M(j),A=C(j),_=E?l(E):void 0,O;_?O=_(G,A):j.type==="effect"?(E&&h(`${a}.${$}`,"fn",E),O=V(G,()=>{})):(E&&h(`${a}.${$}`,"fn",E),O=Y(G,D=>D[0])),k.add(O,{name:$}),v.set($,O),F.delete($),N=!0}}if(F.size>0){let $=[...F.keys()].sort().join(", ");throw new Error(`compileSpec: template "${y.template}" has unresolvable deps: ${$}`)}i.mount(a,k);let B=`${a}::${w.output}`;g.set(a,i.resolve(B));try{let $=i.resolve(B);$.meta._templateName?.emit(y.template),$.meta._templateBind?.emit(y.bind)}catch{}}for(let a of n.feedback??[])X(i,a.from,a.to,{maxIterations:a.maxIterations});if(m.length>0){if(u==="error"){let a=m.map(d=>` - ${d.path}: missing ${d.kind} "${d.name}"`);throw new Error(`compileSpec: ${m.length} catalog entr${m.length===1?"y":"ies"} missing \u2014 pass them via opts.catalog or set opts.onMissing to "warn"/"placeholder":
|
|
12
|
-
${a.join(`
|
|
13
|
-
`)}`)}if(u==="warn"){let a=e?.onWarn??(d=>console.warn(d));for(let d of m)a(`compileSpec: ${d.path} references missing ${d.kind} "${d.name}" \u2014 substituted placeholder`)}}return i}var le=new Set(["reduction","reduction_type","_specFn","_specSource","_templateName","_templateBind","feedbackFrom","feedbackTo","_internal"]);function me(n){let e=n.describe({detail:"spec"}),o=`::${Q}::`,s=/^__feedback_(?!effect_)(.+)$/,f=[],p=new Set;for(let[r,t]of Object.entries(e.nodes))t.meta?.factory!=null&&!r.includes("::")&&p.add(r);let u={};for(let[r,t]of Object.entries(e.nodes)){if(r.includes(o))continue;let m=r.indexOf("::");if(m>0&&p.has(r.slice(0,m)))continue;if(s.exec(r)){let g=t.meta;g?.feedbackFrom&&g?.feedbackTo&&f.push({from:g.feedbackFrom,to:g.feedbackTo,...g.maxIterations?{maxIterations:g.maxIterations}:{}});continue}if(t.meta?._internal||r.startsWith("__feedback_effect_")||r.startsWith("__bridge_"))continue;let l=t.meta,b=l;if(l&&Object.keys(l).length>0){let g={};for(let[x,L]of Object.entries(l))le.has(x)||(g[x]=L);g.factory==="withStatus"?(delete g.status,delete g.error):g.factory==="withBreaker"?delete g.breakerState:g.factory==="verifiable"&&delete g.sourceVersion,b=Object.keys(g).length>0?g:void 0}let S={...t};b===void 0?delete S.meta:S.meta=b,u[r]=S}let i={...e,nodes:u};return delete i.expand,f.length>0&&(i.feedback=f),i}function ge(n,e){let o=[];n.name!==e.name&&o.push({type:"changed",path:"name",detail:`"${n.name}" \u2192 "${e.name}"`});let s=new Set(Object.keys(n.nodes)),f=new Set(Object.keys(e.nodes));for(let c of f)if(!s.has(c)){let a=e.nodes[c];o.push({type:"added",path:`nodes.${c}`,detail:`type: ${a.type}`})}for(let c of s)f.has(c)||o.push({type:"removed",path:`nodes.${c}`});for(let c of s){if(!f.has(c))continue;let a=n.nodes[c],d=e.nodes[c];if(JSON.stringify(a)!==JSON.stringify(d)){let y=[];a.type!==d.type&&y.push(`type: ${a.type} \u2192 ${d.type}`),JSON.stringify(a.deps)!==JSON.stringify(d.deps)&&y.push("deps changed");let w=a.type==="template"?void 0:M(a),k=d.type==="template"?void 0:M(d);w!==k&&y.push(`fn: ${w} \u2192 ${k}`);let v=a.type==="template"?void 0:C(a),R=d.type==="template"?void 0:C(d);JSON.stringify(v)!==JSON.stringify(R)&&y.push("config changed"),o.push({type:"changed",path:`nodes.${c}`,detail:y.join("; ")||"modified"})}}let p=n.templates??{},u=e.templates??{},i=new Set(Object.keys(p)),r=new Set(Object.keys(u));for(let c of r)i.has(c)||o.push({type:"added",path:`templates.${c}`});for(let c of i)r.has(c)||o.push({type:"removed",path:`templates.${c}`});for(let c of i)r.has(c)&&JSON.stringify(p[c])!==JSON.stringify(u[c])&&o.push({type:"changed",path:`templates.${c}`,detail:"template definition changed"});let t=n.feedback??[],m=e.feedback??[],h=new Set(t.map(c=>`${c.from}->${c.to}`)),l=new Set(m.map(c=>`${c.from}->${c.to}`));for(let c of m){let a=`${c.from}->${c.to}`;h.has(a)||o.push({type:"added",path:`feedback.${a}`,detail:`maxIterations: ${c.maxIterations??10}`})}for(let c of t){let a=`${c.from}->${c.to}`;l.has(a)||o.push({type:"removed",path:`feedback.${a}`})}for(let c of t){let a=`${c.from}->${c.to}`,d=m.find(y=>y.from===c.from&&y.to===c.to);d&&JSON.stringify(c)!==JSON.stringify(d)&&o.push({type:"changed",path:`feedback.${a}`,detail:`maxIterations: ${c.maxIterations??10} \u2192 ${d.maxIterations??10}`})}let b=o.filter(c=>c.type==="added").length,S=o.filter(c=>c.type==="removed").length,g=o.filter(c=>c.type==="changed").length,x=[];b&&x.push(`${b} added`),S&&x.push(`${S} removed`),g&&x.push(`${g} changed`);let L=x.length>0?x.join(", "):"no changes";return{entries:o,summary:L}}var se=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
14
|
-
|
|
15
|
-
Given a natural-language description, produce a JSON GraphSpec with this structure:
|
|
16
|
-
|
|
17
|
-
{
|
|
18
|
-
"name": "<graph_name>",
|
|
19
|
-
"nodes": {
|
|
20
|
-
"<node_name>": {
|
|
21
|
-
"type": "state" | "derived" | "producer" | "effect",
|
|
22
|
-
"deps": ["<dep_node_name>", ...],
|
|
23
|
-
"value": <initial_value>,
|
|
24
|
-
"meta": {
|
|
25
|
-
"factory": "<catalog_factory_name>",
|
|
26
|
-
"factoryArgs": { ... },
|
|
27
|
-
"description": "<purpose>"
|
|
28
|
-
}
|
|
29
|
-
},
|
|
30
|
-
"<template_instance>": {
|
|
31
|
-
"type": "template",
|
|
32
|
-
"template": "<template_name>",
|
|
33
|
-
"bind": { "$param": "node_name" }
|
|
34
|
-
}
|
|
35
|
-
},
|
|
36
|
-
"templates": {
|
|
37
|
-
"<template_name>": {
|
|
38
|
-
"params": ["$param1", "$param2"],
|
|
39
|
-
"nodes": { ... },
|
|
40
|
-
"output": "<output_node>"
|
|
41
|
-
}
|
|
42
|
-
},
|
|
43
|
-
"feedback": [
|
|
44
|
-
{ "from": "<condition_node>", "to": "<state_node>", "maxIterations": 10 }
|
|
45
|
-
]
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
Rules:
|
|
49
|
-
- "state" nodes hold user/LLM-writable values (knobs). Stamp the initial value
|
|
50
|
-
in "meta.factoryArgs.initial" (or as the top-level "value" field \u2014 both work).
|
|
51
|
-
- "derived" nodes compute from deps using a catalog function named in
|
|
52
|
-
"meta.factory"; pass any config via "meta.factoryArgs".
|
|
53
|
-
- "effect" nodes produce side effects from deps; same meta.factory shape as derived.
|
|
54
|
-
- "producer" nodes generate values from a catalog source named in "meta.factory";
|
|
55
|
-
pass any config via "meta.factoryArgs".
|
|
56
|
-
- Use "templates" when the same subgraph pattern repeats (e.g., per-source resilience).
|
|
57
|
-
- Use "feedback" for bounded cycles where a derived value writes back to a state node.
|
|
58
|
-
- meta.description is required for every node.
|
|
59
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;function re(n){let e=n.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:n}async function ye(n,e,o){let s=se,f=o?.catalogDescription??(o?.catalog?oe(o.catalog):void 0);f&&(s+=`
|
|
60
|
-
|
|
61
|
-
Available catalog (use ONLY these names):
|
|
62
|
-
${f}`),o?.systemPromptExtra&&(s+=`
|
|
63
|
-
|
|
64
|
-
${o.systemPromptExtra}`);let p=[{role:"system",content:s},{role:"user",content:n}],r=(await e.invoke(p,{model:o?.model,temperature:o?.temperature??0,maxTokens:o?.maxTokens})).content.trim();r.startsWith("```")&&(r=re(r));let t;try{t=JSON.parse(r)}catch{throw new Error(`llmCompose: LLM response is not valid JSON: ${r.slice(0,200)}`)}let m=q(t);if(!m.valid)throw new Error(`llmCompose: invalid GraphSpec:
|
|
65
|
-
${m.errors.join(`
|
|
66
|
-
`)}`);let h=t;if(o?.catalog){let l=o.maxAutoRefine??0;for(let b=0;b<=l;b++){let S=K(h,o.catalog);if(S.valid)break;if(b===l)throw new Error(`llmCompose: catalog validation failed after ${l} refine attempts:
|
|
67
|
-
${S.errors.join(`
|
|
68
|
-
`)}`);h=await ae(h,`Fix these catalog errors:
|
|
69
|
-
${S.errors.join(`
|
|
70
|
-
`)}
|
|
71
|
-
|
|
72
|
-
Use ONLY functions and sources from the catalog.`,e,{...o,catalogDescription:f})}}return h}async function ae(n,e,o,s){let f=se;s?.catalogDescription&&(f+=`
|
|
73
|
-
|
|
74
|
-
Available catalog:
|
|
75
|
-
${s.catalogDescription}`),s?.systemPromptExtra&&(f+=`
|
|
76
|
-
|
|
77
|
-
${s.systemPromptExtra}`);let p=[{role:"system",content:f},{role:"user",content:`Current GraphSpec:
|
|
78
|
-
${JSON.stringify(n,null,2)}
|
|
79
|
-
|
|
80
|
-
Modification request: ${e}
|
|
81
|
-
|
|
82
|
-
Return the complete modified GraphSpec as JSON.`}],r=(await o.invoke(p,{model:s?.model,temperature:s?.temperature??0,maxTokens:s?.maxTokens})).content.trim();r.startsWith("```")&&(r=re(r));let t;try{t=JSON.parse(r)}catch{throw new Error(`llmRefine: LLM response is not valid JSON: ${r.slice(0,200)}`)}let m=q(t);if(!m.valid)throw new Error(`llmRefine: invalid GraphSpec:
|
|
83
|
-
${m.errors.join(`
|
|
84
|
-
`)}`);return t}export{T as a,I as b,te as c,ne as d,oe as e,K as f,q as g,ue as h,me as i,ge as j,ye as k,ae as l,he as m};
|
package/dist/chunk-ACMJ2ZPS.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{a as Me}from"./chunk-ESMPEKEV.js";import{C as re}from"./chunk-2K5RXLAH.js";import{a as ye,d as we}from"./chunk-35JTVPOX.js";import{A as me,C as M,E as Z,F as be,G as ve,e as xe,f as $e,i as Q,k as Ae,l as ne,m as Te,o as L,p as Pe,s as U}from"./chunk-LYCLF26R.js";import{b as q,c as pe,d as fe,e as te,f as he,g as ge,h as B,i as H,j as W}from"./chunk-CK2E7BTU.js";var A={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},Xe=Symbol.for("sizeof");function je(o){let e=new WeakSet,t=new WeakSet,n=[o],s=0;for(;n.length>0;){let r=n.pop();s+=et(r,e,t,n)}return s}function et(o,e,t,n){if(o==null)return 0;switch(typeof o){case"number":return A.number;case"boolean":return A.boolean;case"string":return A.string+o.length*2;case"bigint":return A.bigint+tt(o);case"symbol":return A.symbol;case"function":return e.has(o)?0:(e.add(o),A.function);case"undefined":return 0}let r=o;if(e.has(r))return 0;e.add(r);let i=r[Xe];if(typeof i=="function")try{let a=i.call(r);if(typeof a=="number"&&Number.isFinite(a))return a}catch{}if(r instanceof Date)return A.date;if(r instanceof RegExp)return A.regexp+r.source.length*2;if(r instanceof Error){let a=r.message?r.message.length*2:0,p=r.stack?r.stack.length*2:0;return A.error+a+p}if(typeof URL<"u"&&r instanceof URL)return A.url+r.href.length*2;if(typeof Promise<"u"&&r instanceof Promise)return A.promise;if(r instanceof WeakMap)return A.weakmap;if(r instanceof WeakSet)return A.weakset;if(r instanceof Map){let a=A.map;for(let[p,g]of r)a+=A.mapEntry,n.push(p),n.push(g);return a}if(r instanceof Set){let a=A.set;for(let p of r)a+=A.setEntry,n.push(p);return a}if(Array.isArray(r)){let a=A.array+r.length*8;for(let p of r)n.push(p);return a}if(r instanceof ArrayBuffer)return t.has(r)?0:(t.add(r),r.byteLength);if(ArrayBuffer.isView(r)){let a=r;return t.has(a.buffer)?48:(t.add(a.buffer),a.buffer.byteLength+48)}let c=A.object,d=Object.keys(r);for(let a of d){c+=A.string+a.length*2;try{n.push(r[a])}catch{}}return c}function tt(o){let e=o<0n?-o:o;if(e===0n)return 0;let t=e.toString(2).length;return Math.ceil(t/32)*8}function Fe(o,e,t,n={}){let s=e in o.nodes,r=t in o.nodes;if(!s)return se(e,t,"no-such-from");if(!r)return se(e,t,"no-such-to");let i=n.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(e===t){if(n.findCycle===!0){let a=nt(o,e,n);if(a!=null)return a}let d=oe(e,o.nodes[e],0,n);return ie(e,t,[d])}if(i===0)return se(e,t,"no-path");let c=Ie(o,e,t,i);return c.found?ie(e,t,ze(o,c.pathOrder,n)):se(e,t,c.truncated?"max-depth-exceeded":"no-path")}function Ie(o,e,t,n){let s=new Map,r=[{path:t,depth:0}],i=new Set([t]),c=0,d=!1;for(;c<r.length;){let g=r[c++];if(g.path===e)break;if(n!=null&&g.depth>=n){let y=o.nodes[g.path];y?.deps&&y.deps.length>0&&(d=!0);continue}let h=o.nodes[g.path];if(h==null)continue;let f=h.deps??[],u=new Map;for(let y=0;y<f.length;y++){let l=f[y];if(!l)continue;let O=u.get(l);O==null&&(O=[],u.set(l,O)),O.push(y)}for(let[y,l]of u)i.has(y)||(i.add(y),s.set(y,{from:g.path,depIndices:l}),r.push({path:y,depth:g.depth+1}))}if(!s.has(e))return{found:!1,pathOrder:[],truncated:d};let a=[{path:e}],p=e;for(;p!==t;){let g=s.get(p);if(g==null)return{found:!1,pathOrder:[],truncated:!1};a[a.length-1].depIndices=g.depIndices,a.push({path:g.from}),p=g.from}return{found:!0,pathOrder:a,truncated:!1}}function nt(o,e,t){let n=o.nodes[e];if(n==null)return null;let s=n.deps??[],r=[];for(let c=0;c<s.length;c++)s[c]===e&&r.push(c);if(r.length>0){let c=oe(e,n,0,t);c.dep_index=r[0];let d=oe(e,n,1,t);return ie(e,e,[c,d])}let i=null;for(let c=0;c<s.length;c++){let d=s[c];if(!d||d===e)continue;let a=Ie(o,d,e,t.maxDepth);a.found&&(i==null||a.pathOrder.length<i.pathOrder.length)&&(i=a,i={found:!0,pathOrder:[{path:e,depIndices:[c]},...a.pathOrder],truncated:!1})}return i==null?null:ie(e,e,ze(o,i.pathOrder,t))}function ze(o,e,t){return e.map((n,s)=>{let r=o.nodes[n.path],i=oe(n.path,r,s,t);return n.depIndices!=null&&n.depIndices.length>0&&(i.dep_index=n.depIndices[0],n.depIndices.length>1&&(i.dep_indices=[...n.depIndices])),i})}function oe(o,e,t,n){let s={path:o,type:e.type,hop:t};e.status!==void 0&&(s.status=e.status),"value"in e&&(s.value=e.value),e.v!=null&&(s.v=e.v);let r=n.annotations?.get(o)??e.annotation;r!=null&&(s.annotation=r);let i=n.lastMutations?.get(o)??e.lastMutation;return i!=null&&(s.lastMutation=i),s}function ie(o,e,t){return Be(o,e,!0,"ok",t)}function se(o,e,t){return Be(o,e,!1,t,[])}function Be(o,e,t,n,s){let r=rt(o,e,t,n,s);return{from:o,to:e,found:t,reason:n,steps:s,text:r,toJSON(){return{from:o,to:e,found:t,reason:n,steps:s}}}}function rt(o,e,t,n,s){if(!t)switch(n){case"no-such-from":return`explainPath: no node named "${o}"`;case"no-such-to":return`explainPath: no node named "${e}"`;case"max-depth-exceeded":return`explainPath: no path from "${o}" to "${e}" within maxDepth`;default:return`explainPath: no path from "${o}" to "${e}"`}let r=[`Causal path: ${o} \u2192 ${e} (${s.length} step(s))`];for(let i of s){let d=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(r.push(d),"value"in i&&r.push(` value: ${st(i.value)}`),i.annotation!=null&&r.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let a=i.lastMutation.actor;r.push(` actor: ${a.type}${a.id?`:${a.id}`:""}`)}}return r.join(`
|
|
2
|
-
`)}function st(o){if(o===void 0)return"<sentinel>";if(o===null)return"null";if(typeof o=="string")return JSON.stringify(o);if(typeof o=="number"||typeof o=="boolean"||typeof o=="bigint")return String(o);try{let e=JSON.stringify(o);return e.length>80?`${e.slice(0,77)}...`:e}catch{return String(o)}}function Oe(o,e){if(Object.is(o,e))return!0;if(o==null||e==null||typeof o!="object"||typeof e!="object")return!1;if(Array.isArray(o)){if(!Array.isArray(e)||o.length!==e.length)return!1;for(let r=0;r<o.length;r++)if(!Oe(o[r],e[r]))return!1;return!0}if(Array.isArray(e))return!1;let t=Object.keys(o),n=Object.keys(e);if(t.length!==n.length)return!1;let s=new Set(n);for(let r of t)if(!s.has(r)||!Oe(o[r],e[r]))return!1;return!0}function Le(o,e){return`${o}\0${e}`}function _e(o,e){let t=[],n=new Set(o.subgraphs),s=new Set(e.subgraphs),r=[];for(let l of s)n.has(l)||r.push(l);r.sort();for(let l of r)t.push({type:"subgraph-mounted",path:l});let i=new Set(Object.keys(o.nodes)),c=new Set(Object.keys(e.nodes)),d=[];for(let l of c)i.has(l)||d.push(l);d.sort();for(let l of d)t.push({type:"node-added",path:l,node:{...e.nodes[l]}});let a=[];for(let l of c){if(!i.has(l))continue;let O=o.nodes[l]?.meta,m=e.nodes[l]?.meta;O==null&&m==null||Oe(O??{},m??{})||a.push(l)}a.sort();for(let l of a)t.push({type:"node-meta-changed",path:l,prevMeta:o.nodes[l]?.meta??{},nextMeta:e.nodes[l]?.meta??{}});let p=new Map;for(let l of o.edges)p.set(Le(l.from,l.to),l);let g=new Map;for(let l of e.edges)g.set(Le(l.from,l.to),l);let h=[];for(let[l,O]of g)p.has(l)||h.push(O);h.sort((l,O)=>l.from<O.from?-1:l.from>O.from?1:l.to<O.to?-1:l.to>O.to?1:0);for(let l of h)t.push({type:"edge-added",from:l.from,to:l.to});let f=[];for(let[l,O]of p)g.has(l)||f.push(O);f.sort((l,O)=>l.from<O.from?-1:l.from>O.from?1:l.to<O.to?-1:l.to>O.to?1:0);for(let l of f)t.push({type:"edge-removed",from:l.from,to:l.to});let u=[];for(let l of i)c.has(l)||u.push(l);u.sort();for(let l of u)t.push({type:"node-removed",path:l});let y=[];for(let l of n)s.has(l)||y.push(l);y.sort();for(let l of y)t.push({type:"subgraph-unmounted",path:l});return{events:t,flushedAt_ns:L()}}function Ve(o,e){let t=e?.topN??10,n=o.describe({detail:"standard"}),s=[],r=o._collectObserveTargets;typeof r=="function"&&r.call(o,"",s);let i=new Map;for(let[h,f]of s)i.set(h,f);let c=[];for(let[h,f]of Object.entries(n.nodes)){let u=i.get(h),y=u instanceof M?u:null,l=y?je(y.cache):0,O=y?y._sinkCount:0,m=f.deps?.length??0,b=f.type==="effect"&&O===0,v=O===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;c.push({path:h,type:f.type,status:f.status??"unknown",valueSizeBytes:l,subscriberCount:O,depCount:m,isOrphanEffect:b,orphanKind:v})}let d=c.reduce((h,f)=>h+f.valueSizeBytes,0),a=(h,f)=>[...c].sort(f??((u,y)=>y[h]-u[h])).slice(0,t),p=c.filter(h=>h.orphanKind!=null),g=c.filter(h=>h.isOrphanEffect);return{nodeCount:c.length,edgeCount:n.edges.length,subgraphCount:n.subgraphs.length,nodes:c,totalValueSizeBytes:d,hotspots:{byValueSize:a("valueSizeBytes"),bySubscriberCount:a("subscriberCount"),byDepCount:a("depCount")},orphans:p,orphanEffects:g}}var X=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 t=(this.head+this._size)%this.capacity;this.buf[t]=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 t=e<0?this._size+e:e;if(!(t<0||t>=this._size))return this.buf[(this.head+t)%this.capacity]}toArray(){let e=new Array(this._size);for(let t=0;t<this._size;t++)e[t]=this.buf[(this.head+t)%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}};var x="::",z="__meta__",J=1;function qe(o,e){let t=Math.max(16,o.size*4),n=0;for(;o.size>0;){if(n++>=t){console.error(`[Graph "${e}".destroy] disposer drain exceeded cap (${t}); ${o.size} disposer(s) discarded`),o.clear();return}let s=o.values().next();if(s.done)return;let r=s.value;o.delete(r);try{r()}catch(i){console.error(`[Graph "${e}".destroy] disposer threw:`,i)}}}function Ye(o){return o!=null&&typeof o=="object"&&"cache"in o&&typeof o.subscribe=="function"&&typeof o.down=="function"}function ot(o){if(o!=null)return Ye(o)?o.cache:o}function K(o){return o!=null&&typeof o=="object"&&"cache"in o&&typeof o.subscribe=="function"&&typeof o.down=="function"}function V(o){return K(o)?o.cache??"":o}function Ke(o){return K(o)?o.cache??0:o}function He(o){return K(o)?o.cache??!1:o}function it(o){let e=[];for(let t of Object.keys(o).sort()){let n=o[t].v;n!=null&&e.push(`${t} ${n.id} ${n.version}`)}return e.join(`
|
|
3
|
-
`)}function We(o){if(o.version!==J)throw new Error(`unsupported snapshot version ${String(o.version)} (expected ${J})`);for(let e of["name","nodes","edges","subgraphs"])if(!(e in o))throw new Error(`snapshot missing required key "${e}"`);if(typeof o.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof o.nodes!="object"||o.nodes===null||Array.isArray(o.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(o.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(o.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function at(o,e){let t=new WeakMap,n=(s,r)=>{if(Object.is(s,r))return!0;if(s==null||r==null||typeof s!="object"||typeof r!="object")return!1;let i=t.get(s);if(i==null&&(i=new WeakSet,t.set(s,i)),i.has(r))return!0;i.add(r);let c=s.constructor,d=r.constructor;if(c!==d)return!1;if(s instanceof Date)return s.getTime()===r.getTime();if(s instanceof RegExp)return s.source===r.source&&s.flags===r.flags;if(Array.isArray(s)){let h=r;if(s.length!==h.length)return!1;for(let f=0;f<s.length;f++)if(!n(s[f],h[f]))return!1;return!0}if(s instanceof Map){let h=r;if(s.size!==h.size)return!1;for(let[f,u]of s)if(!h.has(f)||!n(u,h.get(f)))return!1;return!0}if(s instanceof Set){let h=r;if(s.size!==h.size)return!1;for(let f of s){let u=!1;for(let y of h)if(n(f,y)){u=!0;break}if(!u)return!1}return!0}if(ArrayBuffer.isView(s)){let h=s,f=r;if(h.length!==f.length)return!1;for(let u=0;u<h.length;u++)if(h[u]!==f[u])return!1;return!0}let a=Object.keys(s),p=Object.keys(r);if(a.length!==p.length)return!1;let g=new Set(p);for(let h of a)if(!g.has(h)||!n(s[h],r[h]))return!1;return!0};return n(o,e)}function ut(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ae(o){let e="^";for(let t=0;t<o.length;t+=1){let n=o[t];if(n==="*"){e+=".*";continue}if(n==="?"){e+=".";continue}if(n==="["){let s=o.indexOf("]",t+1);if(s<=t+1){e+="\\[";continue}let r=o.slice(t+1,s);r.startsWith("!")&&(r=`^${r.slice(1)}`),r=r.replace(/\\/g,"\\\\"),e+=`[${r}]`,t=s;continue}e+=ut(n)}return e+="$",new RegExp(e)}var ct={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"},dt={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function Ee(o){if(typeof o=="string")return JSON.stringify(o);if(typeof o=="number"||typeof o=="boolean"||o==null)return String(o);try{return JSON.stringify(o)}catch{return"[unserializable]"}}function lt(o){return o==="none"?dt:o==="ansi"||o==null?ct:{data:o.data??"",dirty:o.dirty??"",resolved:o.resolved??"",invalidate:o.invalidate??"",pause:o.pause??"",resume:o.resume??"",complete:o.complete??"",error:o.error??"",teardown:o.teardown??"",derived:o.derived??"",path:o.path??"",reset:o.reset??""}}function Ue(o){if(o==null)return{};let e=o.detail;return e==="full"?{...o,structured:o.structured??!0,timeline:o.timeline??!0,causal:o.causal??!0,derived:o.derived??!0}:e==="minimal"?{...o,structured:o.structured??!0}:o.format==="stage-log"?{...o,structured:o.structured??!0,timeline:o.timeline??!0}:o}function pt(o,e,t){for(let n=0;n<o.length;n++){let s=o.charCodeAt(n);if(s<32||s===127)throw new Error(`Graph "${e}": ${t} "${o}" must not contain control character (U+${s.toString(16).padStart(4,"0").toUpperCase()} at index ${n})`)}}function ke(o,e,t){if(o==="")throw new Error(`Graph "${e}": ${t} name must be non-empty`);if(o.includes(x))throw new Error(`Graph "${e}": ${t} "${o}" must not contain '${x}' (path separator)`);if(o===z)throw new Error(`Graph "${e}": ${t} name "${z}" is reserved for meta companion paths`);pt(o,e,t)}function ft(o,e){if(o==="")throw new Error(`Graph "${e}": resolve path must be non-empty`);let t=o.split(x);for(let n of t)if(n==="")throw new Error(`Graph "${e}": resolve path has empty segment`);return t}function ht(o,e){let t=!1;for(let s of o)if(!e.isMetaPassthrough(s[0])){t=!0;break}return t?o.filter(s=>e.isMetaPassthrough(s[0])):o}function Qe(o){for(let e of o._mounts.values())Qe(e);for(let e of o._nodes.values())try{e.down([[B]],{internal:!0})}catch{}}var Se=class o{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,t){if(e==="")throw new Error("Graph name must be non-empty");if(e.includes(x))throw new Error(`Graph name must not contain '${x}' (got "${e}")`);if(e===z)throw new Error(`Graph name "${z}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...t??{}}),this.config=t?.config??me,this._traceRing=new X(t?.traceCapacity??1e3),t?.versioning!=null&&this.setVersioning(t.versioning),typeof t?.factory=="string"&&(this._factory=t.factory,t.factoryArgs!==void 0&&(this._factoryArgs=t.factoryArgs))}tagFactory(e,t){return this._factory=e,this._factoryArgs=t,this}ancestors(e=!0){let t=[],n=e?this:this._parent;for(;n!=null;)t.push(n),n=n._parent;return t}get topology(){return this._topology==null&&(this._topology=be(e=>{let t=n=>{e.emit(n)};return this._topologyEmitters.add(t),()=>{this._topologyEmitters.delete(t)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(e){if(!(this._topology==null||this._topologyEmitters.size===0))for(let t of this._topologyEmitters)t(e)}nameOf(e){return this._nodeToName.get(e)}add(e,t){let n=e.name,s=t?.name??n;if(s==null||s==="")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 r=s,i=t?.annotation;if(ke(r,this.name,"add"),this._mounts.has(r))throw new Error(`Graph "${this.name}": name "${r}" is already a mount point`);if(this._nodes.has(r))throw new Error(`Graph "${this.name}": node "${r}" already exists`);let c=this._nodeToName.get(e);if(c!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${c}"`);return this._nodes.set(r,e),this._nodeToName.set(e,r),this._emitTopology({kind:"added",name:r,nodeKind:"node"}),i!=null&&(this._annotations.set(r,i),this.config.inspectorEnabled&&this._traceRing.push({path:r,annotation:i,timestamp_ns:L()})),e}setVersioning(e){if(e!=null)for(let t of this._nodes.values())t instanceof M&&t._applyVersioning(e)}remove(e){ke(e,this.name,"remove");let t=this._mounts.get(e);if(t){let r={kind:"mount",nodes:[],mounts:[]},i=[];t._collectObserveTargets("",i);for(let[c,d]of i)c.includes(`${x}${z}${x}`)||r.nodes.push(c);return r.nodes.sort(),r.mounts.push(e),r.mounts.push(...t._collectSubgraphs(`${e}${x}`)),this._mounts.delete(e),t._parent=void 0,Qe(t),this._emitTopology({kind:"removed",name:e,nodeKind:"mount",audit:r}),r}let n=this._nodes.get(e);if(!n)throw new Error(`Graph "${this.name}": unknown node or mount "${e}"`);this._nodes.delete(e),this._nodeToName.delete(n),n.down([[B]],{internal:!0});let s={kind:"node",nodes:[e],mounts:[]};return this._emitTopology({kind:"removed",name:e,nodeKind:"node",audit:s}),s}removeAll(e){let t=typeof e=="function"?e:(()=>{let r=ae(e);return i=>r.test(i)})(),n={kind:"mount",nodes:[],mounts:[]},s=[...this._nodes.keys(),...this._mounts.keys()].filter(r=>t(r));for(let r of s){let i=this.remove(r);n.nodes.push(...i.nodes),n.mounts.push(...i.mounts)}return n.nodes.sort(),n.mounts.sort(),n}[Symbol.iterator](){let e=[...this._nodes.keys()].sort(),t=this._nodes,n=0;return{[Symbol.iterator](){return this},next(){if(n>=e.length)return{value:void 0,done:!0};let s=e[n++];return{value:[s,t.get(s)],done:!1}}}}node(e){if(e==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(e.includes(x))return this.resolve(e);let t=this._nodes.get(e);if(!t)throw new Error(`Graph "${this.name}": unknown node "${e}"`);return t}get(e){return this.node(e).cache}set(e,t,n){let s=n?.internal===!0;this.node(e).down([[q,t]],{actor:n?.actor,internal:s,delivery:"write"})}setAll(e,t){let n=Symbol.iterator in e?e:Object.entries(e);Te(()=>{for(let[s,r]of n)this.set(s,r,t)})}invalidate(e,t){let n=t?.internal===!0;this.node(e).down([[te]],{actor:t?.actor,internal:n,delivery:"write"})}error(e,t,n){let s=n?.internal===!0;this.node(e).down([[W,t]],{actor:n?.actor,internal:s,delivery:"write"})}complete(e,t){let n=t?.internal===!0;this.node(e).down([[H]],{actor:t?.actor,internal:n,delivery:"write"})}edges(e){let t=e?.recursive===!0,n=new Map;if(!t){for(let[d,a]of this._nodes)n.set(a,d);let c=[];for(let[d,a]of this._nodes)if(a instanceof M)for(let p of a._deps){let g=n.get(p.node);g!=null&&c.push([g,d])}return c.sort((d,a)=>d[0]<a[0]?-1:d[0]>a[0]?1:d[1]<a[1]?-1:d[1]>a[1]?1:0),c}let s=[];this._collectObserveTargets("",s);let r=new Map;for(let[c,d]of s)r.set(d,c);let i=[];for(let[c,d]of s)if(d instanceof M)for(let a of d._deps){let p=r.get(a.node);p!=null&&i.push([p,c])}return i.sort((c,d)=>c[0]<d[0]?-1:c[0]>d[0]?1:c[1]<d[1]?-1:c[1]>d[1]?1:0),i}mount(e,t){if(t===void 0){let s=new o(e);return this.mount(e,s)}if(typeof t=="function"){let s=new o(e);return t(s),this.mount(e,s)}let n=t;if(ke(e,this.name,"mount"),this._nodes.has(e))throw new Error(`Graph "${this.name}": cannot mount at "${e}" \u2014 node with that name exists`);if(this._mounts.has(e))throw new Error(`Graph "${this.name}": mount "${e}" already exists`);if(n===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(n._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${n._parent.name}"`);for(let s=this;s!=null;s=s._parent)if(s===n)throw new Error(`Graph "${this.name}": mount("${e}", \u2026) would create a mount cycle`);return this._mounts.set(e,n),n._parent=this,this._emitTopology({kind:"added",name:e,nodeKind:"mount"}),n}resolve(e){let t=ft(e,this.name);return this._resolveFromSegments(t)}tryResolve(e){try{return this.resolve(e)}catch{return}}_resolveFromSegments(e){let t=e;if(t[0]===this.name&&(t=t.slice(1),t.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let n=t[0],s=t.slice(1);if(s.length===0){let c=this._nodes.get(n);if(c)return c;throw this._mounts.has(n)?new Error(`Graph "${this.name}": path ends at subgraph "${n}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${n}"`)}let r=this._nodes.get(n);if(r&&s.length>0&&s[0]===z)return this._resolveMetaChainFromNode(r,s,t.join(x));let i=this._mounts.get(n);if(!i)throw this._nodes.has(n)?new Error(`Graph "${this.name}": "${n}" is a node; trailing path "${s.join(x)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return i.resolve(s.join(x))}_resolveMetaChainFromNode(e,t,n){let s=e,r=0,i=[...t];for(;r<i.length;){if(i[r]!==z)throw new Error(`Graph "${this.name}": expected ${z} segment in meta path "${n}"`);if(r+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${z} in "${n}"`);let c=i[r+1],d=s.meta[c];if(!d)throw new Error(`Graph "${this.name}": unknown meta "${c}" in path "${n}"`);s=d,r+=2}return s}signal(e,t){if(t?.internal!==!0){for(let s of e)if(this.config.messageTier(s[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 n=[];if(this._signalDeliver(e,t??{},new Set,n),n.length>0)throw n[0]}_signalDeliver(e,t,n,s){for(let d of this._mounts.values())d._signalDeliver(e,t,n,s);let i=t.internal===!0?{internal:!0}:{actor:t.actor,delivery:"signal"},c=ht(e,this.config);for(let d of[...this._nodes.keys()].sort()){let a=this._nodes.get(d);if(!n.has(a)){n.add(a);try{a.down(e,i)}catch(p){if(p instanceof U)throw p;s.push(p)}c.length!==0&&this._signalMetaSubtree(a,c,n,i,s)}}}_signalMetaSubtree(e,t,n,s,r){for(let i of Object.keys(e.meta).sort()){let c=e.meta[i];if(!n.has(c)){n.add(c);try{c.down(t,s)}catch(d){if(d instanceof U)throw d;r.push(d)}this._signalMetaSubtree(c,t,n,s,r)}}}describe(e){if(e?.reactive==="diff")return this._describeReactiveDiff(e);if(e?.reactive===!0)return this._describeReactive(e);let t=ot(e?.actor),n=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 s=ye(e?.detail,e?.fields),r=e?.detail==="spec",i=s,c=[];this._collectObserveTargets("",c);let d=new Map;for(let[v,w]of c)d.set(w,v);let a=[];{let v=c.map(([,S])=>S),w=new Set(d.values()),E=0;for(;v.length>0;){let S=v.shift();if(S instanceof M)for(let R of S._deps){let G=R.node;if(d.has(G))continue;let D=G.name??"",k=D;if(!k||w.has(k))if(D){let I=2;for(;w.has(`${D}#${I}`);)I++;k=`${D}#${I}`}else for(k=`__internal__/${E++}`;w.has(k);)k=`__internal__/${E++}`;d.set(G,k),w.add(k),a.push([k,G]),v.push(G)}}}let p=[...c,...a],g={};for(let[v,w]of p){if(t!=null&&!w.allowsObserve(t))continue;let E=we(w,i,r),S=w instanceof M?w._deps.map(k=>d.get(k.node)??k.node.name??""):[],{name:R,...G}=E,D={...G,deps:S};if(!r){let k=this._annotations.get(v);k!=null&&(D.annotation=k)}if(n!=null)if(typeof n=="function"){let k=n;if(!(k.length>=2?k(v,D):k(D)))continue}else{let k=!0;for(let[I,T]of Object.entries(n)){let $=I==="deps_includes"?"depsIncludes":I==="meta_has"?"metaHas":I;if($==="depsIncludes"){if(!D.deps.includes(String(T))){k=!1;break}continue}if($==="metaHas"){if(!Object.hasOwn(D.meta??{},String(T))){k=!1;break}continue}if(D[$]!==T){k=!1;break}}if(!k)continue}g[v]=D}let h=new Set(Object.keys(g)),f=[];for(let[v,w]of p)if(w instanceof M)for(let E of w._deps){let S=d.get(E.node);S!=null&&f.push([S,v])}f.sort((v,w)=>v[0]<w[0]?-1:v[0]>w[0]?1:v[1]<w[1]?-1:v[1]>w[1]?1:0);let u=f.map(([v,w])=>({from:v,to:w}));(t!=null||n!=null)&&(u=u.filter(v=>h.has(v.from)&&h.has(v.to)));let y=this._collectSubgraphs(""),l=t!=null||n!=null?y.filter(v=>{let w=`${v}${x}`;return[...h].some(E=>E===v||E.startsWith(w))}):y,O=this,m=e;return{name:this.name,nodes:g,edges:u,subgraphs:l,...this._factory!==void 0?{factory:this._factory}:{},...this._factoryArgs!==void 0?{factoryArgs:this._factoryArgs}:{},expand(v){let w={...m};return Array.isArray(v)?(w.fields=v,w.detail=void 0):(w.detail=v,w.fields=void 0),O.describe(w)}}}_collectSubgraphs(e){let t=[];for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${n}`;t.push(s),t.push(...this._mounts.get(n)._collectSubgraphs(`${s}${x}`))}return t}resourceProfile(e){return Ve(this,e)}reachable(e,t,n={}){return n.withDetail===!0?Je(this.describe(),e,t,{...n,withDetail:!0}):Je(this.describe(),e,t,n)}explain(e,t,n){return n?.reactive===!0?this._explainReactive(e,t,n):this._explainStatic(V(e),V(t),{...n?.maxDepth!==void 0?{maxDepth:Ke(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:He(n.findCycle)}:{}})}_explainStatic(e,t,n){let s=this.describe({detail:"full"}),r=new Map(this._annotations),i=new Map;for(let[c,d]of Object.entries(s.nodes))d.lastMutation!=null&&i.set(c,d.lastMutation);return Fe(s,e,t,{...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{},annotations:r,lastMutations:i})}_describeReactive(e){let t={...e,reactive:!1},n=e.reactiveName??"describe",s=0,r=Z(s,{name:`${n}_version`}),i=this.observe({timeline:!0,structured:!0}),c=!1,d=!1,a=()=>{c||d||(c=!0,ne(()=>{c=!1,!d&&(s+=1,r.emit(s))}))},p=i.onEvent(m=>{let b=m.type;b!=="data"&&b!=="error"&&b!=="complete"&&b!=="teardown"||a()}),g=[],h=new WeakSet,f=m=>{if(h.has(m)||d)return;h.add(m);let b=m.topology.subscribe(v=>{for(let w of v){if(w[0]!==q)continue;let E=w[1];if(a(),E.kind==="added"&&E.nodeKind==="mount"){let S=m._mounts.get(E.name);S!=null&&f(S)}}});g.push(b);for(let v of m._mounts.keys()){let w=m._mounts.get(v);w!=null&&f(w)}};f(this);let u,y=e.actor;Ye(y)&&(u=y.subscribe(m=>{let b=!1,v=!1;for(let w of m){let E=w[0];E===q?b=!0:(E===H||E===W||E===B)&&(v=!0)}b&&a(),v&&(u?.(),u=void 0,a())}));let l;try{l=ve([r],()=>this.describe(t),{name:n,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(m,b)=>m===b})}catch(m){p(),u?.();for(let b of g)b();throw i.dispose(),m}let O=re(l);return{node:l,dispose(){d=!0,p(),u?.();for(let m of g)m();g.length=0,i.dispose(),O()}}}_describeReactiveDiff(e){let t={...e,reactive:!1},n=e.reactiveName??"describe-diff",s={name:this.name,nodes:{},edges:[],subgraphs:[]},r=this.describe(t),i=_e(s,r),c=Z(i,{name:n,meta:{domain:"audit",kind:"describe-diff"},equals:(h,f)=>h===f}),d=this._describeReactive({...e,reactiveName:void 0}),a=!1,p=d.node.subscribe(h=>{if(!a)for(let f of h){if(f[0]!==q)continue;let u=f[1],y=_e(r,u);r=u,y.events.length!==0&&c.emit(y)}}),g=re(c);return{node:c,dispose(){a=!0,p(),d.dispose(),c.down([[B,"describe-diff disposed"]]),g()}}}_explainReactive(e,t,n){let s=0,r=Z(s,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),c=!1,d=!1,a=()=>{c||d||(c=!0,ne(()=>{c=!1,!d&&(s+=1,r.emit(s))}))},p=i.onEvent(m=>{let b=m.type;b!=="data"&&b!=="error"&&b!=="complete"&&b!=="teardown"||a()}),g=[];e!=null&&K(e)&&g.push(e),t!=null&&K(t)&&g.push(t),n?.maxDepth!=null&&K(n.maxDepth)&&g.push(n.maxDepth),n?.findCycle!=null&&K(n.findCycle)&&g.push(n.findCycle);let h=()=>{for(let m of g)if(m.cache===void 0)return!1;return!0},f=()=>{let m=V(e),b=V(t);return{from:m,to:b,found:!1,reason:"pending",steps:[],text:"(awaiting reactive args)",toJSON:()=>({from:m,to:b,found:!1,reason:"pending",steps:[]})}},u;try{u=ve([r],()=>{if(!h())return f();let m=V(e),b=V(t),v={...n?.maxDepth!==void 0?{maxDepth:Ke(n.maxDepth)}:{},...n?.findCycle!==void 0?{findCycle:He(n.findCycle)}:{}};return this._explainStatic(m,b,v)},{name:n?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:V(e),to:V(t)},equals:(m,b)=>m.found===b.found&&m.reason===b.reason&&m.steps.length===b.steps.length&&mt(m.steps,b.steps)})}catch(m){throw p(),i.dispose(),m}let y=re(u),l=[],O=m=>{let b;return b=m.subscribe(v=>{let w=!1,E=!1;for(let S of v){let R=S[0];R===q?w=!0:(R===H||R===W||R===B)&&(E=!0)}(w||E)&&a(),E&&b&&(b(),b=void 0)}),()=>{b&&(b(),b=void 0)}};for(let m of g)l.push(O(m));return{node:u,dispose(){d=!0,p();for(let m of l)m?.();l.length=0,i.dispose(),y()}}}_pathsMatching(e){let t=ae(e),n=[];return this._collectObserveTargets("",n),n.map(([s])=>s).filter(s=>t.test(s))}_collectObserveTargets(e,t){for(let n of[...this._mounts.keys()].sort()){let s=e===""?n:`${e}${x}${n}`;this._mounts.get(n)._collectObserveTargets(s,t)}for(let n of[...this._nodes.keys()].sort()){let s=this._nodes.get(n),r=e===""?n:`${e}${x}${n}`;t.push([r,s]),this._appendMetaObserveTargets(r,s,t)}}_appendMetaObserveTargets(e,t,n){for(let s of Object.keys(t.meta).sort()){let r=t.meta[s],i=`${e}${x}${z}${x}${s}`;n.push([i,r]),this._appendMetaObserveTargets(i,r,n)}}observe(e,t){let n=typeof e=="string",r=Ue(n?t:e);if(r.reactive===!0)return this._observeReactive(n?e:void 0,r);let i=r.structured===!0||r.timeline===!0||r.causal===!0||r.derived===!0||r.detail==="minimal"||r.detail==="full"||r.format!=null,c=r.actor;if(n){let p=e,g=this.resolve(p);if(c!=null&&!g.allowsObserve(c))throw new U({actor:c,action:"observe",nodeName:p});return i?this._buildStructuredObserver([[p,g]],r,"one"):{subscribe(h){return g.subscribe(h)},up(h){try{g.up?.(h)}catch(f){if(f instanceof U)return;throw f}}}}let d=[];this._collectObserveTargets("",d),d.sort((p,g)=>p[0]<g[0]?-1:p[0]>g[0]?1:0);let a=c==null?d:d.filter(([,p])=>p.allowsObserve(c));return i?this._buildStructuredObserver(a,r,"all"):{subscribe:p=>{let g=a.map(([h,f])=>f.subscribe(u=>{p(h,u)}));return()=>{for(let h of g)h()}},up:(p,g)=>{try{this.resolve(p).up?.(g)}catch(h){if(h instanceof U)return;throw h}}}}_observeReactive(e,t){let n=t.tiers,s=n!=null?new Set(n):null,r=t.reactiveName??"observe";return be(i=>{let c=[],d=!1,a=!1,p=()=>{if(c.length===0||a)return;let y={events:c.slice(),flushedAt_ns:L()};c.length=0,i.emit(y)},g={...t,reactive:!1,structured:!0,timeline:!0},h=e!=null?this.observe(e,g):this.observe(g),f=y=>{a||(c.push(y),!d&&(d=!0,ne(()=>{d=!1,p()})))};for(let y of h.events)f(y);let u=h.onEvent(f);return()=>{a=!0,u(),h.dispose()}},{name:r,meta:{domain:"audit",kind:"observe-reactive"}})}_buildStructuredObserver(e,t,n){let s=n==="one"?e[0]?.[0]:void 0,r=i=>{if(n==="one"&&s!=null){let p=this.resolve(s);return this._buildStructuredObserver([[s,p]],i,"one")}let c=[];this._collectObserveTargets("",c),c.sort((p,g)=>p[0]<g[0]?-1:p[0]>g[0]?1:0);let d=i.actor,a=d==null?c:c.filter(([,p])=>p.allowsObserve(d));return this._buildStructuredObserver(a,i,"all")};return this._createObserveResult(e,t,r)}_createObserveResult(e,t,n){let s=t.timeline===!0,r=t.causal===!0,i=t.derived===!0,c=t.detail==="minimal",d=this.config.inspectorEnabled,a=(r||i)&&d,p=t.maxEvents,g=p!=null&&p>0?new X(p):null,h=[],f=new Set,u=t.tiers!=null?new Set(t.tiers):null,y={},l=new Set,O=0,m=0,b=0,v=0,w=0,E=0,S=!1,R=!1,G=0,D=new Map,k=new Map,I=new Map,T=_=>{if(!(u!=null&&!u.has(_.type))){g?g.push(_):h.push(_);for(let C of f)C(_)}},$=_=>u==null||u.has(_),Re=()=>s?{timestamp_ns:L(),in_batch:Ae(),batch_id:G}:{},Ze=(_,C)=>{if(!(!a||!(_ instanceof M)))return _._setInspectorHook(j=>{if(j.kind==="dep_message")D.set(_,j.depIndex);else if(j.kind==="run"){let Y=j.batchData.map((N,P)=>N!=null&&N.length>0?N.at(-1):j.prevData[P]);k.set(_,Y);let F=j.batchData.map(N=>N!=null?[...N]:void 0);I.set(_,F),i&&T({type:"derived",path:C,dep_values:Y,dep_batches:F,...Re()})}})},Ne=_=>{let C=D.get(_),j=k.get(_);if(!r||j==null)return{};let F=(C!=null&&C>=0&&_ instanceof M?_._deps[C]:void 0)?.node,N=F?.v,P=I.get(_);return{trigger_dep_index:C,trigger_dep_name:F?.name,...N!=null?{trigger_version:{id:N.id,version:N.version}}:{},dep_values:[...j],...P!=null?{dep_batches:P}:{}}},Ge=[],De=[];for(let[_,C]of e){let j=Ze(C,_);j&&Ge.push(j),De.push(C.subscribe(Y=>{G++;for(let F of Y){let N=F[0],P=Re();if(N===q){y[_]=F[1];let le=C instanceof M?C.lastMutation?.actor??Q:Q;T({type:"data",path:_,data:F[1],actor:le,...P,...Ne(C)})}else if(c)N===pe?$("dirty")&&O++:N===fe?$("resolved")&&m++:N===te?$("invalidate")&&b++:N===he?$("pause")&&v++:N===ge?$("resume")&&w++:N===B?$("teardown")&&E++:N===H&&!l.has(_)?$("complete")&&(S=!0):N===W&&$("error")&&(R=!0,l.add(_));else if(N===pe)$("dirty")&&O++,T({type:"dirty",path:_,...P});else if(N===fe)$("resolved")&&m++,T({type:"resolved",path:_,...P,...Ne(C)});else if(N===te)$("invalidate")&&b++,T({type:"invalidate",path:_,...P});else if(N===he)$("pause")&&v++,T({type:"pause",path:_,lockId:F[1],...P});else if(N===ge)$("resume")&&w++,T({type:"resume",path:_,lockId:F[1],...P});else if(N===H)$("complete")&&!l.has(_)&&(S=!0),T({type:"complete",path:_,...P});else if(N===W){$("error")&&(R=!0,l.add(_));let le=C instanceof M?C.lastMutation?.actor??Q:Q;T({type:"error",path:_,data:F[1],actor:le,...P})}else N===B&&($("teardown")&&E++,T({type:"teardown",path:_,...P}))}}))}let ue=!1,ce=()=>{if(!ue){ue=!0;for(let _ of De)_();for(let _ of Ge)_();for(let _ of ee)_({value:void 0,done:!0});ee.length=0}},de=[],ee=[];f.add(_=>{let C=ee.shift();C?C({value:_,done:!1}):de.push(_)});let Ce={get values(){return y},get dirtyCount(){return O},get resolvedCount(){return m},get invalidateCount(){return b},get pauseCount(){return v},get resumeCount(){return w},get teardownCount(){return E},get events(){return g?g.toArray():[...h]},get anyCompletedCleanly(){return S},get anyErrored(){return R},get completedWithoutErrors(){return S&&!R},onEvent(_){return f.add(_),()=>f.delete(_)},dispose:ce,expand(_){ce();let C={...t};return typeof _=="string"?C.detail=_:Object.assign(C,_),n(Ue(C))},[Symbol.asyncIterator](){return{next(){return de.length>0?Promise.resolve({value:de.shift(),done:!1}):ue?Promise.resolve({value:void 0,done:!0}):new Promise(_=>ee.push(_))},return(){return ce(),Promise.resolve({value:void 0,done:!0})}}}};return t.format!=null&&this._attachFormatLogger(Ce,t),Ce}_attachFormatLogger(e,t){let n=t.format;if(n==null)return;let s=t.logger??(u=>console.log(u)),r=t.includeTypes?new Set(t.includeTypes):null,i=t.excludeTypes?new Set(t.excludeTypes):null,c=r==null&&i==null?()=>!0:u=>(r==null||r.has(u))&&(i==null||!i.has(u)),d=lt(t.theme),a=n==="stage-log"?L():0,p=u=>u==null?"":t.stageLabels?.[u]??u,g=(u,y)=>u.length>y?`${u.slice(0,y-1)}\u2026`:u,h=u=>u.type==="data"||u.type==="error"?g(Ee(u.data),120):"",f=u=>{if(n==="stage-log"){let S=(L()-a)/1e9,R=p(u.path).padEnd(9);if(u.type==="data"){let G=h(u);return`[${S.toFixed(3)}s] ${R} \u2190${G?` ${G}`:""}`}if(u.type==="error"){let G=h(u);return`[${S.toFixed(3)}s] ${R} \u2717${G?` ${G}`:""}`}return u.type==="complete"?`[${S.toFixed(3)}s] ${R} \u25A0 complete`:`[${S.toFixed(3)}s] ${R} ${u.type}`}if(n==="json")try{return JSON.stringify(u)}catch{return JSON.stringify({type:u.type,path:u.path,data:"[unserializable]"})}let y=d[u.type]??"",l=u.path?`${d.path}${u.path}${d.reset} `:"",O=u.type==="data"||u.type==="error",m=u.type==="pause"||u.type==="resume",b=O?` ${Ee(u.data)}`:m?` ${Ee(u.lockId)}`:"",v=u.type==="data"||u.type==="resolved"||u.type==="derived"?u:void 0,w=v?.trigger_dep_name!=null?` <- ${v.trigger_dep_name}`:v?.trigger_dep_index!=null?` <- #${v.trigger_dep_index}`:"",E=u.in_batch?" [batch]":"";return`${l}${y}${u.type.toUpperCase()}${d.reset}${b}${w}${E}`};e.onEvent(u=>{c(u.type)&&s(f(u),u)})}addDisposer(e){return this._disposers.add(e),()=>{this._disposers.delete(e)}}destroy(){qe(this._disposers,this.name),this.signal([[B]],{internal:!0}),qe(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:t,...n}=this.describe({detail:"full"}),s={};for(let c of Object.keys(n.nodes).sort()){let{lastMutation:d,guard:a,...p}=n.nodes[c];s[c]=p}let r=[...n.subgraphs].sort(),i={...n,version:1,nodes:s,subgraphs:r};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 c=this.config.lookupCodec(e.codec);if(c==null)throw new Error(`snapshot: codec "${e.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return xe(c,c.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,t){let n=t?.config??me,{codec:s,codecVersion:r,payload:i}=$e(e,n);return s.decode(i,r)}restore(e,t){if(We(e),e.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${e.name}" does not match this graph`);let n=t?.only==null?null:(Array.isArray(t.only)?t.only:[t.only]).map(r=>ae(r)),s=t?.includeProducers===!0;for(let r of Object.keys(e.nodes).sort()){if(n!==null&&!n.some(c=>c.test(r)))continue;let i=e.nodes[r];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&t?.onError?.(r,new Error(`restore: slice.value is undefined for "${r}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!s)){if(i.v!=null){let d=this.tryResolve(r)?.v;if(d!=null&&d.id===i.v.id&&d.version===i.v.version)continue}try{this.set(r,i.value)}catch(c){t?.onError?.(r,c)}}}}}static fromSnapshot(e,t){We(e);let n=typeof t=="function"?t:t?.build,s=typeof t=="function"?void 0:t?.factories,r=new o(e.name);if(n)return n(r),r.restore(e),r;for(let f of[...e.subgraphs].sort((u,y)=>{let l=u.split(x).length,O=y.split(x).length;return l!==O?l-O:u<y?-1:u>y?1:0})){let u=f.split(x),y=r;for(let l of u)y._mounts.has(l)||y.mount(l,new o(l)),y=y._mounts.get(l)}let i=s?Object.entries(s).map(([f,u])=>({re:ae(f),factory:u})):[],c=f=>{for(let u of i)if(u.re.test(f))return u.factory},d=f=>{let u=f.split(x),y=u.pop();if(y==null||y.length===0)throw new Error(`invalid snapshot path "${f}"`);let l=r;for(let O of u){let m=l._mounts.get(O);if(!m)throw new Error(`unknown mount "${O}" in path "${f}"`);l=m}return[l,y]},a=Object.entries(e.nodes).filter(([f])=>!f.includes(`${x}${z}${x}`)).sort((f,u)=>f[0]<u[0]?-1:f[0]>u[0]?1:0),p=new Map(a),g=new Map,h=!0;for(;p.size>0&&h;){h=!1;for(let[f,u]of[...p.entries()]){let y=u?.deps??[];if(!y.every(w=>g.has(w)))continue;let[l,O]=d(f),m={...u?.meta??{}},b=c(f),v;if(u?.type==="state")v=Z(u.value,{meta:m});else{if(b==null)continue;v=b(O,{path:f,type:u.type,value:u.value,meta:m,deps:y,resolvedDeps:y.map(w=>g.get(w))})}l.add(v,{name:O}),g.set(f,v),p.delete(f),h=!0}}if(p.size>0){let f=[...p.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 r.restore(e),r}toJSON(){return this.snapshot()}attachSnapshotStorage(e,t={}){let n=e.map(a=>({tier:a,debounceMs:Math.max(0,a.debounceMs??0),compactEvery:Math.max(1,a.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));t.autoRestore===!0&&this._cascadeRestore(e,t.onError);let s=(a,p)=>{if(a.disposed)return;let g=it(p.nodes);if(a.lastSnapshot!=null&&g!==""&&g===a.lastFingerprint)return;let h=a.seq+1,f=Pe(),l=a.lastSnapshot==null||h%a.compactEvery===0?{name:this.name,mode:"full",snapshot:p,seq:h,timestamp_ns:f,format_version:J}:{name:this.name,mode:"diff",diff:gt(a.lastSnapshot,p),seq:h,timestamp_ns:f,format_version:J};if(a.tier.filter&&!a.tier.filter(l))return;let O;try{O=a.tier.save(l)}catch(m){t.onError?.(m,a.tier);return}if(O&&typeof O.then=="function"){let v=(a.savePending??Promise.resolve()).then(()=>O,()=>O).then(()=>{a.disposed||(a.seq=h,a.lastSnapshot=p,a.lastFingerprint=g)},w=>{t.onError?.(w,a.tier)});a.savePending=v.finally(()=>{a.savePending===v&&(a.savePending=void 0)})}else a.seq=h,a.lastSnapshot=p,a.lastFingerprint=g},r=(a,p)=>{try{s(a,p)}catch(g){t.onError?.(g,a.tier)}},i=(a,p)=>{if(!p.some(u=>{let y=this.config.messageTier(u[0]);return y>=3&&y<5}))return;if(t.filter){let u=this.tryResolve(a);if(u==null)return;let y=we(u,ye("standard"));if(!t.filter(a,y))return}let h,f=()=>(h==null&&(h=this.snapshot()),h);for(let u of n)u.disposed||(u.debounceMs===0?r(u,f()):(u.timer==null&&(u.timer=new Me),u.timer.start(u.debounceMs,()=>{u.disposed||r(u,this.snapshot())})))},c;if(t.paths!=null){let p=(typeof t.paths=="string"?this._pathsMatching(t.paths):t.paths).map(g=>{let h=this.tryResolve(g);return h==null?()=>{}:h.subscribe(f=>i(g,f))});c=()=>{for(let g of p)g()}}else c=this.observe().subscribe((a,p)=>i(a,p));let d=()=>{c();for(let a of n)a.disposed=!0,a.timer?.cancel();this._storageDisposers.delete(d)};return this._storageDisposers.add(d),{dispose:d}}async _cascadeRestore(e,t){for(let n of e){let s;try{s=await n.load?.()}catch(i){t?.(i,n);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let r=s;try{if(r.mode==="full"&&r.snapshot!=null)return this.restore(r.snapshot),!0;if(r.version===J&&r.nodes!=null)return this.restore(r),!0}catch(i){t?.(i,n)}}return!1}static async fromStorage(e,t,n){for(let s of t){let r;try{r=await s.load?.()}catch(d){n?.onError?.(d,s);continue}if(r==null||typeof r!="object"||Array.isArray(r))continue;let i=r,c=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===J&&i.nodes!=null?i:void 0;if(c!=null)try{return o.fromSnapshot(c,n)}catch(d){n?.onError?.(d,s)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${e}" across ${t.length} tier(s)`)}_annotations=new Map;_traceRing;trace(e,t,n){if(e!=null&&t!=null){if(this.tryResolve(e)==null)return;if(this._annotations.set(e,t),this.config.inspectorEnabled){let s={path:e,annotation:t,timestamp_ns:L(),...n?.actor!=null?{actor:n.actor}:{}};this._traceRing.push(s)}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 t=this._traceRing.toArray().filter(s=>!e(s)),n=this._traceRing.size-t.length;this._traceRing.clear();for(let s of t)this._traceRing.push(s);return n}static diff(e,t){let n=new Set(Object.keys(e.nodes)),s=new Set(Object.keys(t.nodes)),r=[...s].filter(m=>!n.has(m)).sort(),i=[...n].filter(m=>!s.has(m)).sort(),c=[],d=[];for(let m of n){if(!s.has(m))continue;let b=e.nodes[m],v=t.nodes[m],w=b.v,E=v.v;w!=null&&E!=null&&w.id===E.id&&w.version!==E.version&&d.push({path:m,id:w.id,from:w.version,to:E.version});let S=w!=null&&E!=null&&w.id===E.id&&w.version===E.version;for(let R of["type","status","sentinel"]){let G=b[R],D=v[R];G!==D&&c.push({path:m,field:R,from:G,to:D})}if(!S)for(let R of["value","meta"]){let G=b[R],D=v[R];at(G,D)||c.push({path:m,field:R,from:G,to:D})}}let a=m=>`${m.from} ${m.to}`,p=new Set(e.edges.map(a)),g=new Set(t.edges.map(a)),h=t.edges.filter(m=>!p.has(a(m))),f=e.edges.filter(m=>!g.has(a(m))),u=new Set(e.subgraphs),y=new Set(t.subgraphs),l=[...y].filter(m=>!u.has(m)).sort(),O=[...u].filter(m=>!y.has(m)).sort();return{nodesAdded:r,nodesRemoved:i,nodesChanged:c,versionChanges:d,edgesAdded:h,edgesRemoved:f,subgraphsAdded:l,subgraphsRemoved:O}}};function gt(o,e){let t=Se.diff(o,e),n={};for(let s of t.nodesAdded){let r=e.nodes[s];r!=null&&(n[s]=r)}return{...t,nodesAddedFull:n}}function Je(o,e,t,n={}){let s={paths:[],depths:new Map,truncated:!1};if(!e)return n.withDetail?s:[];if(!n.both&&t!=="upstream"&&t!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let r=n.maxDepth;if(r!=null&&(!Number.isInteger(r)||r<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(r===0)return n.withDetail?s:[];let i=new Map,c=new Map,d=new Map,a=new Map,p=new Set;for(let[b,v]of Object.entries(o.nodes)){if(!b)continue;p.add(b);let w=v.deps??[];i.set(b,w);for(let E of w)E&&(p.add(E),c.has(E)||c.set(E,new Set),c.get(E).add(b))}for(let b of o.edges){if(b==null||typeof b!="object")continue;let v=typeof b.from=="string"?b.from:"",w=typeof b.to=="string"?b.to:"";!v||!w||(p.add(v),p.add(w),a.has(v)||a.set(v,new Set),a.get(v).add(w),d.has(w)||d.set(w,new Set),d.get(w).add(v))}if(!p.has(e))return n.withDetail?s:[];let g=n.both===!0,h=b=>{if(g){let S=i.get(b)??[],R=d.get(b),G=c.get(b),D=a.get(b),k=[...S];return R&&k.push(...R),G&&k.push(...G),D&&k.push(...D),k}if(t==="upstream"){let S=i.get(b)??[],R=d.get(b);return R?[...S,...R]:S}let v=c.get(b),w=a.get(b),E=v?[...v]:[];return w&&E.push(...w),E},f=new Set([e]),u=new Map,y=[{path:e,depth:0}],l=0,O=!1;for(;l<y.length;){let b=y[l++];if(r!=null&&b.depth>=r){h(b.path).length>0&&(O=!0);continue}for(let v of h(b.path))!v||f.has(v)||(f.add(v),u.set(v,b.depth+1),y.push({path:v,depth:b.depth+1}))}let m=[...u.keys()].sort((b,v)=>b<v?-1:b>v?1:0);return n.withDetail?{paths:m,depths:u,truncated:O}:m}function mt(o,e){if(o.length!==e.length)return!1;for(let t=0;t<o.length;t++){let n=o[t],s=e[t];if(n.path!==s.path||n.type!==s.type||n.status!==s.status||n.hop!==s.hop||n.dep_index!==s.dep_index||n.annotation!==s.annotation||n.value!==s.value||n.lastMutation!==s.lastMutation)return!1;let r=n.v,i=s.v;if(r!==i&&(r==null||i==null||r.id!==i.id||r.version!==i.version))return!1}return!0}export{A as a,Xe as b,je as c,Fe as d,_e as e,X as f,Ve as g,z as h,J as i,Se as j,gt as k,Je as l};
|
package/dist/chunk-AS3TV2TV.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as N}from"./chunk-L6NSJVJZ.js";import{f as ue,j as ae}from"./chunk-ACMJ2ZPS.js";import{a as V}from"./chunk-ESMPEKEV.js";import{x as L}from"./chunk-6YFZMUMR.js";import{a as S,b as P,i as se}from"./chunk-4VVTGLXJ.js";import{m as de}from"./chunk-2K5RXLAH.js";import{b as oe,c as R}from"./chunk-35JTVPOX.js";import{D as F,F as C,m as K,o as Y}from"./chunk-LYCLF26R.js";import{b as y,c as k,d as w,f as U,g as q,h as _,i as T,j as g}from"./chunk-CK2E7BTU.js";var $=class{buf=[];head=0;get size(){return this.buf.length-this.head}push(t){this.buf.push(t)}shift(){if(this.head>=this.buf.length)return;let t=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),t}clear(){this.buf=[],this.head=0}};function W(e,t,n){if(t.length===0)throw new RangeError("budgetGate requires at least one constraint");let r=t.map(c=>c.node),i=[e,...r],l=new $,u=!1,s=!1,o=Symbol("budget-gate"),d=new Array(t.length);function f(){return t.every((c,b)=>c.check(d[b]))}function a(c){for(;l.size>0&&f();){let b=l.shift();c.emit(b)}l.size===0&&s&&(s=!1,c.down([[w]]))}return F([],(c,b)=>{for(let m=0;m<t.length;m++)d[m]=t[m].node.cache;let h=[];for(let m=0;m<i.length;m++){let O=i[m];h.push(O.subscribe(E=>{for(let M of E)p(M,m,b)}))}return()=>{for(let m of h)m()}},{...n,describeKind:"derived",meta:N("resilience","budget_gate",n?.meta)});function p(c,b,h){let m=c[0];if(b===0){if(m===y)return f()&&l.size===0?h.emit(c[1]):(l.push(c[1]),u||(u=!0,h.up([[U,o]]))),!0;if(m===k)return h.down([[k]]),!0;if(m===w)return l.size===0?h.down([[w]]):s=!0,!0;if(m===T||m===g){for(;l.size>0;)h.emit(l.shift());return s=!1,u&&(u=!1,h.up([[q,o]])),h.down([c]),!0}return!1}if(m===y&&(d[b-1]=c[1]),m===y||m===w){let O=f();return O&&l.size>0?(a(h),l.size===0&&u&&(u=!1,h.up([[q,o]]))):!O&&!u&&l.size>0&&(u=!0,h.up([[U,o]])),!0}return m===k?!0:m===g?(h.down([c]),!0):m===T}}function z(e){return typeof e=="object"&&e!==null&&"subscribe"in e&&"down"in e}function fe(e){if(e<=0)throw new RangeError("timeoutMs must be > 0");if(e>9e6)throw new RangeError("timeoutMs must be <= 9_000_000 (\u22482.5h) to stay within safe ns arithmetic")}var D=class extends ae{output;status;lastError;breakerState;droppedCount;rateLimitState;constructor(t,n={}){super(n.name??"resilient_pipeline",n.graph);let r=t,i,l,u;if(n.rateLimit!=null)if(z(n.rateLimit)){let o=r,d=n.rateLimit;r=L(d,f=>{let a={...f,maxBuffer:f.maxBuffer??1/0,meta:N("resilient","rate-limit")};return Z(o,a).node}),this.add(r,{name:"rateLimited"})}else{let o={...n.rateLimit,maxBuffer:n.rateLimit.maxBuffer??1/0,meta:N("resilient","rate-limit")},d=Z(r,o);r=d.node,i=d.droppedCount,l=d.rateLimitState,this.add(r,{name:"rateLimited"}),this.add(i,{name:"droppedCount"}),this.add(l,{name:"rateLimitState"})}if(n.budget!=null)if(z(n.budget)){let o=r,d=n.budget;r=L(d,f=>f.length>0?W(o,f,{meta:N("resilient","budget")}):o),this.add(r,{name:"budgetGated"})}else n.budget.length>0&&(r=W(r,n.budget,{meta:N("resilient","budget")}),this.add(r,{name:"budgetGated"}));if(n.breaker!=null)if(z(n.breaker)){let o=r,d=n.breaker,f=n.breakerOnOpen??"skip";r=L(d,a=>{let p=J(a);return X(p,{onOpen:f,meta:N("resilient","breaker")})(o).node}),this.add(r,{name:"breakerWrapped"})}else{let o=J(n.breaker),d=n.breakerOnOpen??"skip",f=X(o,{onOpen:d,meta:N("resilient","breaker")})(r);r=f.node,u=f.breakerState,this.add(r,{name:"breakerWrapped"}),this.add(u,{name:"breakerState"})}if(n.timeoutMs!=null)if(z(n.timeoutMs)){let o=r,d=n.timeoutMs;r=L(d,f=>(fe(f),H(o,f*1e6,{meta:N("resilient","timeout")}))),this.add(r,{name:"timeoutWrapped"})}else fe(n.timeoutMs),r=H(r,n.timeoutMs*1e6,{meta:N("resilient","timeout")}),this.add(r,{name:"timeoutWrapped"});if(n.retry!=null)if(z(n.retry)){let o=r,d=n.retry;r=L(d,f=>Q(o,{...f,meta:N("resilient","retry")})),this.add(r,{name:"retryWrapped"})}else r=Q(r,{...n.retry,meta:N("resilient","retry")}),this.add(r,{name:"retryWrapped"});n.fallback!==void 0&&(r=ce(r,n.fallback,{meta:N("resilient","fallback")}),this.add(r,{name:"fallbackWrapped"}));let s=le(r,{initialStatus:n.initialStatus??"pending",meta:N("resilient","status")});this.output=s.node,this.status=s.status,this.lastError=s.error,this.breakerState=u,this.droppedCount=i,this.rateLimitState=l,this.add(this.output,{name:"output"}),this.add(this.status,{name:"status"}),this.add(this.lastError,{name:"lastError"})}};function ye(e,t={}){let n=new D(e,t);return n.tagFactory("resilientPipeline",oe(t)),n}function v(e){return{describeKind:"derived",...e}}function we(e){return e<0?0:e}function re(e){return e[1]}function Te(e){if(typeof e!="number"||!Number.isFinite(e))throw new TypeError("backoff strategy must return a finite number");return e<0?0:e}function me(e){let t=e?.count,n=e?.backoff;if(n!==void 0&&t===void 0)throw new RangeError("retry({ backoff }) requires explicit count to prevent unbounded retries; pass { count: <n>, backoff: ... }");let r=t!==void 0?t:0;if(r<0)throw new RangeError("retry count must be >= 0");let i=n===void 0?null:typeof n=="string"?se(n):n;return{maxRetries:r,strategy:i}}function pe(e){let t={};return e?.count!==void 0&&(t.count=e.count),typeof e?.backoff=="string"&&(t.backoff=e.backoff),Object.keys(t).length>0?t:void 0}function be(e,t,n){let r=0,i=!1,l=null,u,s=new V;function o(){u?.(),u=void 0}function d(a){if(i)return;if(r>=e.maxRetries){o(),n.down([[g,a]]);return}let p=e.strategy===null?0:e.strategy(r,a,l);if(p==null){o(),n.down([[g,a]]);return}let c;try{c=Te(p)}catch{o(),n.down([[g,a]]);return}l=c,r+=1,o();let b=c>0?c/1e6:1;s.start(b,()=>{i||f()})}function f(){s.cancel(),o();let a;try{a=t()}catch(p){d(p);return}u=a.subscribe(p=>{if(!i)for(let c of p){let b=c[0];if(b===k)n.down([[k]]);else if(b===y)r=0,l=null,n.emit(c[1]);else if(b===w)n.down([[w]]);else if(b===T)o(),n.down([[T]]);else if(b===g){d(re(c));return}else n.down([c])}})}return f(),()=>{i=!0,s.cancel(),o()}}function Q(e,t){return typeof e=="function"?ge(e,t):ke(e,t)}function ke(e,t){let n=me(t);return C(r=>be(n,()=>e,r),{...v(),initial:e.cache,meta:{...t?.meta??{},...R("retry",pe(t))}})}function ge(e,t){let n=me(t);return C(r=>be(n,e,r),{...v(),initial:t?.initial,meta:{...t?.meta??{},...R("retry",pe(t))}})}var ee=class extends Error{name="CircuitOpenError";constructor(){super("Circuit breaker is open")}};function J(e){let t=Math.max(1,e?.failureThreshold??5),n=we(e?.cooldownNs??30*1e9),r=e?.cooldown??null,i=Math.max(1,e?.halfOpenMax??1),l=e?.now??Y,u="closed",s=0,o=0,d=0,f=n,a=0;function p(){if(!r)return n;let h=r(o);return h!==null?h:n}function c(){u="open",f=p(),d=l(),a=0}return{canExecute(){return u==="closed"?!0:u==="open"?l()-d>=f?(u="half-open",a=1,!0):!1:a<i?(a++,!0):!1},recordSuccess(){u==="half-open"?(u="closed",s=0,o=0):u==="closed"&&(s=0)},recordFailure(h){if(u==="half-open"){o++,c();return}u==="closed"&&(s++,s>=t&&c())},get state(){return u},get failureCount(){return s},reset(){u="closed",s=0,o=0,a=0}}}function X(e,t){let n=t?.onOpen??"skip",r=t?.meta;return i=>{let l=F([],(u,s)=>{function o(){l.meta.breakerState.down([[y,e.state]])}let d=i.subscribe(f=>{for(let a of f){let p=a[0];p===k?s.down([[k]]):p===y?e.canExecute()?(o(),s.emit(a[1])):(o(),n==="error"?s.down([[g,new ee]]):s.down([[w]])):p===w?s.down([[w]]):p===T?(e.recordSuccess(),o(),s.down([[T]])):p===g?(e.recordFailure(re(a)),o(),s.down([a])):s.down([a])}});return o(),d},{...v(),meta:{...r??{},breakerState:e.state,...R("withBreaker",{onOpen:n})},completeWhenDepsComplete:!1,initial:i.cache});return{node:l,breakerState:l.meta.breakerState}}}function Ne(e,t,n){if(e<=0)throw new RangeError("capacity must be > 0");if(t<0)throw new RangeError("refillPerSecond must be >= 0");let r=n?.clock??Y,i=e,l=r();function u(s){if(t>0){let o=s-l;i=Math.min(e,i+o/1e9*t)}l=s}return{available(){return u(r()),i},tryConsume(s=1){if(s<=0)return!0;let o=r();return u(o),i>=s?(i-=s,!0):!1},putBack(s=1){s<=0||(u(r()),i=Math.min(e,i+s))}}}var te=class extends Error{name="RateLimiterOverflowError";constructor(t){super(`rateLimiter buffer overflow (maxBuffer=${t})`)}};function Re(e,t){return e.droppedCount===t.droppedCount&&e.pendingCount===t.pendingCount&&e.paused===t.paused}var G=Object.freeze({droppedCount:0,pendingCount:0,paused:!1});function Z(e,t){let{maxEvents:n,windowNs:r}=t;if(n<=0)throw new RangeError("maxEvents must be > 0");if(r<=0)throw new RangeError("windowNs must be > 0");let i=t.maxBuffer;if(i===void 0)throw new RangeError("rateLimiter requires explicit maxBuffer (use Infinity to opt in to unbounded)");let l=i===1/0;if(!l&&(!Number.isInteger(i)||i<1))throw new RangeError("maxBuffer must be a positive integer (or Infinity for unbounded)");let u=t.onOverflow??"drop-newest",s=n*1e9/r,o=C(d=>{let f=Ne(n,s),a=l?Se():Oe(i),p=new V,c=!1,b=0,h=1e9/s,m=o.meta.droppedCount,O=o.meta.rateLimitState,E=G;function M(){m.emit(b);let A={droppedCount:b,pendingCount:a.size,paused:a.size>0};Re(E,A)||(E=A,O.emit(A))}E=G,m.emit(0),O.emit(G);function ie(){for(;a.size>0;)if(f.tryConsume(1))d.emit(a.shift()),M();else{p.start(Math.max(1,h/1e6),ie);return}}function j(){b+=1,M()}function I(){for(c=!0,p.cancel();a.size>0;)a.shift();b=0}let he=e.subscribe(A=>{for(let x of A){if(c)return;let B=x[0];if(B===k)d.down([[k]]);else if(B===y){if(!l&&a.size>=i)if(u==="drop-newest")j();else if(u==="drop-oldest")a.shift(),a.push(x[1]),j();else{j(),I(),d.down([[g,new te(i)]]);return}else a.push(x[1]),M();ie()}else if(B===w)d.down([[w]]);else if(B===T)I(),d.down([[T]]);else if(B===g)I(),d.down([x]);else if(B===_){I(),d.down([x]);return}else d.down([x])}});return()=>{c=!0,p.cancel(),he()}},{...v(),initial:e.cache,meta:{...t.meta??{},droppedCount:0,rateLimitState:G,...R("rateLimiter",t)}});return{node:o,droppedCount:o.meta.droppedCount,rateLimitState:o.meta.rateLimitState}}function Oe(e){let t=new ue(e);return{push:n=>t.push(n),shift:()=>t.shift(),get size(){return t.size}}}function Se(){let e=[];return{push:t=>{e.push(t)},shift:()=>e.shift(),get size(){return e.length}}}function le(e,t){let n=t?.initialStatus??"pending",r=t?.meta,i=F([],(l,u)=>{let s=n;return i.meta.status.down([[y,n]]),i.meta.error.down([[y,null]]),e.subscribe(d=>{for(let f of d){let a=f[0];if(a===k)u.down([[k]]);else if(a===y)s==="errored"?K(()=>{i.meta.error.down([[y,null]]),i.meta.status.down([[y,"running"]])}):i.meta.status.down([[y,"running"]]),s="running",u.emit(f[1]);else if(a===w)u.down([[w]]);else if(a===T)i.meta.status.down([[y,"completed"]]),s="completed",u.down([[T]]);else if(a===g){let p=re(f);K(()=>{i.meta.error.down([[y,p]]),i.meta.status.down([[y,"errored"]])}),s="errored",u.down([f])}else u.down([f])}})},{...v(),meta:{...r??{},status:n,error:null,...R("withStatus",{initialStatus:n})},completeWhenDepsComplete:!1,resubscribable:!0,initial:e.cache});return{node:i,status:i.meta.status,error:i.meta.error}}var ne=class extends Error{name="TimeoutError";constructor(t){super(`Timed out after ${t/1e6}ms`)}};function ve(e){return e!=null&&typeof e=="object"&&"cache"in e&&typeof e.subscribe=="function"}function xe(e){return e!=null&&typeof e.then=="function"}function Be(e){return e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function"}function ce(e,t,n){let r=n?.meta;return C(i=>{let l,u;function s(){u?.(),u=void 0,ve(t)||xe(t)||Be(t)?l=de(t).subscribe(d=>{i.down(d);for(let f of d){let a=f[0];if(a===T||a===g||a===_){l=void 0;return}}}):(i.emit(t),i.down([[T]]))}return u=e.subscribe(o=>{for(let d of o){let f=d[0];if(f===k)i.down([[k]]);else if(f===y)i.emit(d[1]);else if(f===w)i.down([[w]]);else if(f===T)i.down([[T]]);else if(f===g){s();return}else if(f===_){l?.(),i.down([d]);return}else i.down([d])}}),()=>{u?.(),l?.()}},{...v(),initial:e.cache,meta:{...r??{},...R("fallback")}})}function H(e,t,n){if(t<=0)throw new RangeError("timeoutNs must be > 0");let r=n?.meta;return C(i=>{let l=!1,u=new V;function s(){let d=t/1e6;u.start(d,()=>{l||(l=!0,o(),i.down([[g,new ne(t)]]))})}let o=e.subscribe(d=>{for(let f of d){if(l)return;let a=f[0];if(a===k)i.down([[k]]);else if(a===y)s(),i.emit(f[1]);else if(a===w)i.down([[w]]);else if(a===T){u.cancel(),l=!0,i.down([[T]]);return}else if(a===g){u.cancel(),l=!0,i.down([f]);return}else if(a===_){u.cancel(),l=!0,i.down([f]);return}else i.down([f])}});return s(),()=>{l=!0,u.cancel(),o()}},{...v(),initial:e.cache,meta:{...r??{},...R("timeout",{timeoutNs:t})}})}export{W as a,D as b,ye as c,Q as d,ee as e,J as f,X as g,Ne as h,te as i,Z as j,le as k,ne as l,ce as m,H as n};
|
package/dist/chunk-LPRWATHB.js
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import{a as kt,b as Rt,c as xt,d as wt}from"./chunk-KT5DTRBP.js";import{f as $e}from"./chunk-4QH6VJF4.js";import{c as vt}from"./chunk-AGNM6RS6.js";import{a as Ht,b as Xt,c as Zt,d as er,e as tr,f as Be,g as rr}from"./chunk-Q7QQQA3I.js";import{a as Fe,b as V,c as Le,d as de,e as ee,f as U,g as zt,h as Ge,i as Yt,j as Jt,k as Qt}from"./chunk-KCACBSJH.js";import{h as Lt}from"./chunk-7VKFXLZQ.js";import{b as Tt}from"./chunk-7B7ELAT2.js";import{a as we,b as Mt}from"./chunk-TSOYJ743.js";import{d as pt,e as Re,f as ft,h as _e}from"./chunk-AS3TV2TV.js";import{b as xe}from"./chunk-TZQPPQEQ.js";import{a as dt}from"./chunk-L6NSJVJZ.js";import{b as pe}from"./chunk-LDQ3IUIP.js";import{j as ae}from"./chunk-ACMJ2ZPS.js";import{a as Z}from"./chunk-ESMPEKEV.js";import{R as ct,b as ut,s as mt,x as $}from"./chunk-6YFZMUMR.js";import{A as bt,C as j,f as gt,k as je,l as yt,m as k,x as se,z as ht}from"./chunk-2K5RXLAH.js";import{b as ke,c as X}from"./chunk-35JTVPOX.js";import{D as le,E as w,F as Q,G as v,H as re,m as J,o as H,p as be}from"./chunk-LYCLF26R.js";import{b as G,d as ce,i as q,j as W}from"./chunk-CK2E7BTU.js";import{b as qt}from"./chunk-QYADASLV.js";var Zr={};qt(Zr,{AgentLoopGraph:()=>Pe,AllTiersExhaustedError:()=>tr,BudgetExhaustedError:()=>Ce,ChatStreamGraph:()=>Ie,CircuitOpenError:()=>Re,DEFAULT_DECAY_RATE:()=>we,FallbackMissError:()=>Jt,LLMTimeoutError:()=>ge,ReplayCacheMissError:()=>zt,ToolRegistryGraph:()=>De,admissionFilter3D:()=>Wr,admissionScored:()=>Gt,agentLoop:()=>Vr,agentMemory:()=>Ur,anthropicAdapter:()=>Ht,canonicalJson:()=>Yt,cascadingLlmAdapter:()=>Be,chatStream:()=>rt,composePricing:()=>lr,computePrice:()=>We,contentGate:()=>_r,costMeterExtractor:()=>Sr,createAdapter:()=>er,createCapabilitiesRegistry:()=>nr,createPricingRegistry:()=>sr,dryRunAdapter:()=>Fe,fallbackAdapter:()=>Qt,frozenContext:()=>xr,gatedStream:()=>Nr,gaugesAsContext:()=>qr,googleAdapter:()=>Xt,graphFromSpec:()=>$t,graphFromSpecReactive:()=>Hr,handoff:()=>Fr,keywordFlagExtractor:()=>Or,knobsAsTools:()=>Yr,llmConsolidator:()=>tt,llmExtractor:()=>et,memoryRetrieval:()=>lt,memoryWithKG:()=>st,memoryWithTiers:()=>it,memoryWithVectors:()=>at,observableAdapter:()=>or,openAICompatAdapter:()=>Zt,parseRateLimitFromError:()=>qe,pricingFor:()=>dr,promptCall:()=>Ze,promptNode:()=>Xe,redactor:()=>jr,registryPricing:()=>ir,resilientAdapter:()=>Mr,streamExtractor:()=>Ir,streamingPromptNode:()=>Lr,suggestStrategy:()=>Wt,suggestStrategyReactive:()=>Qr,systemPromptBuilder:()=>Ar,tier:()=>rr,toolCallExtractor:()=>Pr,toolExecution:()=>nt,toolRegistry:()=>ot,toolSelector:()=>$r,validateGraphDef:()=>Xr,withBreaker:()=>Ke,withBudgetGate:()=>Ue,withDryRun:()=>mr,withRateLimiter:()=>ze,withReplayCache:()=>Ge,withRetry:()=>Ye,withTimeout:()=>Je,zeroPrice:()=>Ae});function Te(t,e){return`${t}::${e}`}function nr(t){let e=xe({name:"capabilitiesRegistry"}),r=l=>{e.set(Te(l.provider,l.id),l)};if(t)for(let l of t)r(l);let n=(l,d)=>{let m=e.get(Te(l,d));if(m)return m;let p=e.entries.cache;if(!p)return;let c;for(let[,g]of p){if(g.provider!==l)continue;let y=g.id;d.startsWith(y)&&(!c||y.length>c.id.length)&&(c=g)}return c},o=128,a=new Map,s=new Map,i=(l,d,m,p)=>{for(l.has(d)&&l.delete(d),l.set(d,m);l.size>p;){let c=l.keys().next().value;if(c===void 0)break;l.delete(c)}},u=v([e.entries],([l])=>l instanceof Map?Array.from(l.values()):[],{name:"capabilitiesRegistry/entries",initial:[]});return{register:r,lookup:n,remove(l,d){let m=e.has(Te(l,d));return m&&e.delete(Te(l,d)),m},entries(){let l=e.entries.cache;return(function*(){if(l)for(let d of l.values())yield d})()},lookupNode(l,d){let m=Te(l,d),p=a.get(m);if(p)return a.delete(m),a.set(m,p),p;let c=v([e.entries],()=>n(l,d),{name:`capabilitiesRegistry/lookup/${l}::${d}`,initial:void 0});return i(a,m,c,o),c},entriesNode:u,byProvider(l){let d=s.get(l);if(d)return s.delete(l),s.set(l,d),d;let m=v([u],([p])=>p.filter(c=>c.provider===l),{name:`capabilitiesRegistry/byProvider/${l}`,initial:[]});return i(s,l,m,o),m}}}function z(t){let e=t.input,r=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return r;let n=0;for(let o of Object.values(e.extensions))n+=o;return r+n}function ne(t){let e=t.output,r=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return r;let n=0;for(let o of Object.values(e.extensions))n+=o;return r+n}function Nt(){return{input:{regular:0},output:{regular:0}}}function or(t,e){let r=e?.logMax??1e3,n=pe(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:r}),o=w(null,{name:"adapterStats/lastCall"}),a=v([n.entries],([y])=>y.length,{name:"adapterStats/totalCalls",initial:0}),s=v([n.entries],([y])=>y.reduce((f,h)=>f+z(h.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),i=v([n.entries],([y])=>y.reduce((f,h)=>f+ne(h.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[j(a),j(s),j(i)],l=y=>{n.append(y),o.emit(y)},d=()=>{n.clear(),o.emit(null)},m=V(t,{invoke(y,f){let h=H(),b=be(),N=t.model??f?.model??"",A=R=>(l(de({provider:t.provider,model:t.model??f?.model??R.model??"",tier:f?.tier??R.tier,usage:R.usage??ee(),startNs:h,startWallClockNs:b,method:"invoke"})),R),C=R=>{let D=R;l(de({provider:t.provider,model:N,tier:f?.tier,usage:ee(),startNs:h,startWallClockNs:b,method:"invoke",error:{type:D?.name??"Error",message:D?.message??String(R)}}))};return Le(t.invoke(y,f),{onResp:A,onError:C,name:"adapterStats/invokeTap"})},async*stream(y,f){let h=H(),b=be(),N=t.model??f?.model??"",A;try{for await(let C of t.stream(y,f))C.type==="usage"&&(A=C.usage),yield C;l(de({provider:t.provider,model:N,tier:f?.tier,usage:A??ee(),startNs:h,startWallClockNs:b,method:"stream"}))}catch(C){let R=C;throw l(de({provider:t.provider,model:N,tier:f?.tier,usage:A??ee(),startNs:h,startWallClockNs:b,method:"stream",error:{type:R?.name??"Error",message:R?.message??String(C)}})),C}}});U(m,"observableAdapter",t);let p=!1;return{adapter:m,stats:{lastCall:o,allCalls:n,totalCalls:a,totalInputTokens:s,totalOutputTokens:i,reset:d,dispose:()=>{if(!p){p=!0;for(let y of u)y();u.length=0}}}}}function ar(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Ae(t="USD"){return{total:0,currency:t}}function We(t,e,r){let n=z(t),o=e.currency??"USD",a=r?.withBreakdown===!0,s=a?{}:null,i=0,u=(f,h,b)=>{if(!h||b==null)return;let N=ar(b,n),A=h*N/1e6;i+=A,a&&(s[f]=(s[f]??0)+A)},l=t.input,d=e.input;if(d&&(u("input.regular",l.regular,d.regular),u("input.cacheRead",l.cacheRead??0,d.cacheRead),u("input.cacheWrite5m",l.cacheWrite5m??0,d.cacheWrite5m),u("input.cacheWrite1h",l.cacheWrite1h??0,d.cacheWrite1h),u("input.cacheWriteOther",l.cacheWriteOther??0,d.cacheWriteOther),u("input.audio",l.audio??0,d.audio),u("input.image",l.image??0,d.image),u("input.video",l.video??0,d.video),u("input.toolUse",l.toolUse??0,d.toolUse),l.extensions&&d.extensions))for(let[f,h]of Object.entries(l.extensions))u(`input.ext.${f}`,h,d.extensions[f]);let m=t.output,p=e.output;if(p&&(u("output.regular",m.regular,p.regular),u("output.reasoning",m.reasoning??0,p.reasoning),u("output.audio",m.audio??0,p.audio),u("output.predictionAccepted",m.predictionAccepted??0,p.predictionAccepted),u("output.predictionRejected",m.predictionRejected??0,p.predictionRejected),m.extensions&&p.extensions))for(let[f,h]of Object.entries(m.extensions))u(`output.ext.${f}`,h,p.extensions[f]);let c=r?.tier;if(c&&e.tierMultipliers){let f=e.tierMultipliers[c];if(f!=null&&(i*=f,a))for(let h of Object.keys(s))s[h]*=f}let g=t.auxiliary,y=e.auxiliary;if(g&&y)for(let[f,h]of Object.entries(g)){let b=y[f];if(b==null||!h)continue;let N=h*b;i+=N,a&&(s[`auxiliary.${f}`]=N)}return a?{total:i,currency:o,breakdown:s}:{total:i,currency:o}}function Ne(t,e){return`${t}::${e}`}function sr(t){let e=new Map,r=new Map,n=(o,a,s)=>{e.set(Ne(o,a),{provider:o,model:a,pricing:s});let i=r.get(o);i||(i=new Set,r.set(o,i)),i.add(a)};if(t)for(let[o,a,s]of t)n(o,a,s);return{register:n,lookup(o,a){let s=e.get(Ne(o,a));if(s)return s.pricing;let i=r.get(o);if(!i)return;let u;for(let l of i)if(a.startsWith(l)&&(!u||l.length>u.key.length)){let d=e.get(Ne(o,l));d&&(u={key:l,pricing:d.pricing})}return u?.pricing},remove(o,a){let s=e.delete(Ne(o,a));if(s){let i=r.get(o);i?.delete(a),i&&i.size===0&&r.delete(o)}return s},entries(){let o=e.values();return(function*(){for(let{provider:a,model:s,pricing:i}of o)yield[a,s,i]})()}}}function ir(t,e="USD"){return(r,n)=>{let o=t.lookup(n.provider,n.model);return o?We(r,o,{tier:n.tier,withBreakdown:n.withBreakdown}):Ae(e)}}function lr(...t){return(e,r)=>{for(let n of t){let o=n(e,r);if(o.total!==0)return o}return t.length>0?t[0](e,r):Ae()}}function dr(t,e,r){return t?.pricing?We(e,t.pricing,r):Ae()}function Ke(t,e={}){let r=e.breaker??ft(e),n=V(t,{async invoke(o,a){if(!r.canExecute())throw new Re;try{let s=await se(k(t.invoke(o,a)));return r.recordSuccess(),s}catch(s){throw r.recordFailure(s),s}},async*stream(o,a){if(!r.canExecute())throw new Re;try{for await(let s of t.stream(o,a))yield s;r.recordSuccess()}catch(s){throw r.recordFailure(s),s}}});return U(n,"withBreaker",t),{adapter:n,breaker:r}}var Ce=class extends Error{constructor(r,n,o){super(`Budget exhausted: ${r} (limit=${n}, observed=${o})`);this.which=r;this.limit=n;this.observed=o}name="BudgetExhaustedError"},Ve=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),At=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Ue(t,e){let r=pe(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),n=w(At(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=v([n],([l])=>{let d=l;return!(e.caps.calls!=null&&d.calls>=e.caps.calls||e.caps.inputTokens!=null&&d.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&d.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&d.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(j(o),e.onExhausted!=null){let l=e.onExhausted,d=!1,m=!0;o.subscribe(p=>{for(let c of p)if(c[0]===G){let g=c[1];if(d&&m&&g===!1){let y=Ct(n.cache??Ve,e.caps);y&&l(y)}m=g,d=!0}})}let a=()=>{if(o.cache===!1){let l=n.cache??Ve,d=Ct(l,e.caps);return new Ce(d??"budget",e.caps[d??"calls"]??0,ur(l,d??"calls"))}},s=(l,d)=>{let m=t.provider,p=de({provider:m,model:d.model,tier:d.tier,usage:l,startNs:d.startNs,method:d.method,...d.error?{error:d.error}:{}});r.append(p);let c=n.cache??Ve,g=e.pricingFn?c.usd+e.pricingFn(l,{model:d.model,provider:m,tier:d.tier}).total:c.usd;n.emit({calls:c.calls+1,inputTokens:c.inputTokens+z(l),outputTokens:c.outputTokens+ne(l),usd:g})},i=()=>{r.clear(),n.emit(At())},u=V(t,{invoke(l,d){let m=a();if(m)return Promise.reject(m);let p=H(),c=t.model??d?.model??"",g=f=>(s(f.usage??ee(),{model:t.model??d?.model??f.model??"",tier:d?.tier??f.tier,startNs:p,method:"invoke"}),f),y=f=>{let h=f;s(ee(),{model:c,tier:d?.tier,startNs:p,method:"invoke",error:{type:h?.name??"Error",message:h?.message??String(f)}})};return Le(t.invoke(l,d),{onResp:g,onError:y,name:"budgetGate/invokeTap"})},async*stream(l,d){let m=a();if(m)throw m;let p=H(),c;try{for await(let g of t.stream(l,d))g.type==="usage"&&(c=g.usage),yield g;s(c??ee(),{model:t.model??d?.model??"",tier:d?.tier,startNs:p,method:"stream"})}catch(g){let y=g;throw s(c??ee(),{model:t.model??d?.model??"",tier:d?.tier,startNs:p,method:"stream",error:{type:y?.name??"Error",message:y?.message??String(g)}}),g}}});return U(u,"withBudgetGate",t),{adapter:u,budget:{totals:n,isOpen:o,log:r,reset:i}}}function Ct(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 ur(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}function mr(t,e){let r=e.mock??Fe({provider:t.provider,model:t.model}),n=typeof e.enabled=="boolean"?e.enabled:void 0,o=n===void 0?k(e.enabled):void 0,a;o&&(a=j(o));let s=()=>n!==void 0?n:!!o?.cache,i=V(t,{invoke(l,d){return s()?r.invoke(l,d):t.invoke(l,d)},stream(l,d){return s()?r.stream(l,d):t.stream(l,d)}});return U(i,"withDryRun",t),{adapter:i,dispose:()=>{a&&(a(),a=void 0)}}}function qe(t){if(t==null||typeof t!="object")return;let e=t,r=e.status,n=cr(e.headers);if(r!==429&&r!==503&&!br(e.message))return;let o={},a=n("retry-after"),s=fr(a);s!=null&&(o.retryAfterMs=s);let i=n("anthropic-ratelimit-requests-reset");if(i){let c=St(i);c!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,c))}let u=n("anthropic-ratelimit-tokens-reset");if(u){let c=St(u);c!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,c))}let l=Se(n,"x-ratelimit-limit-requests");l!=null&&(o.rpmCap=l);let d=Se(n,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let m=Se(n,"x-ratelimit-remaining-requests"),p=Se(n,"x-ratelimit-remaining-tokens");if(m!=null&&l!=null&&l>0&&(o.usageHint??={},o.usageHint.rpm=1-m/l),p!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-p/d),o.retryAfterMs==null&&e.message){let c=yr(e.message);c!=null&&(o.retryAfterMs=c)}return e.headers&&(o.metadata={headers:pr(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function cr(t){if(!t)return()=>{};if(typeof t.get=="function"){let n=t;return o=>n.get(o)??n.get(o.toLowerCase())??void 0}let e=t,r={};for(let[n,o]of Object.entries(e)){let a=Array.isArray(o)?o.join(", "):o;a!=null&&(r[n.toLowerCase()]=a)}return n=>r[n.toLowerCase()]}function pr(t){let e={};if(typeof t.forEach=="function")return t.forEach((r,n)=>{e[n]=r}),e;for(let[r,n]of Object.entries(t))n!=null&&(e[r]=Array.isArray(n)?n.join(", "):n);return e}function Se(t,e){let r=t(e);if(r==null)return;let n=Number(r);return Number.isFinite(n)?n:void 0}function fr(t){if(!t)return;let e=t.trim(),r=Number(e);if(Number.isFinite(r)&&r>=0)return r*1e3;let n=Date.parse(e);if(Number.isFinite(n)){let o=n-Date.now();if(o>0)return o}}function St(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var gr=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function yr(t){let e=gr.exec(t);if(!e)return;let r=Number(e[1]);if(!Number.isFinite(r))return;let n=(e[2]??"s").toLowerCase();if(n==="ms")return r;if(n.startsWith("s"))return r*1e3;if(n.startsWith("m"))return r*6e4}var hr=/rate\s*limit|too\s*many\s*requests|quota|429/i;function br(t){return!!t&&hr.test(t)}function He(t){let e=new Error(t);return e.name="AbortError",e}function Ot(t={}){let e=Math.max(1,t.burstMultiplier??1),r=t.clampCooldownMs??6e4,n=t.rpm!=null?k(t.rpm):w(Number.POSITIVE_INFINITY),o=t.tpm!=null?k(t.tpm):w(Number.POSITIVE_INFINITY),a=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),s=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),i=w({},{name:"adaptiveRateLimiter/lastSignal"}),u=v([n,a],([T,I])=>Math.min(Number(T??1/0),Number(I??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),l=v([o,s],([T,I])=>Math.min(Number(T??1/0),Number(I??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=fe(Number(n.cache??Number.POSITIVE_INFINITY),e),m=fe(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,c=!1,g=u.subscribe(T=>{for(let I of T)if(I[0]===G){let _=Number(I[1]);Number.isFinite(_)&&_>0?(d=fe(_,e),p=!1):_===1/0?(d=fe(1/0,e),p=!1):_<=0&&(p=!0)}}),y=l.subscribe(T=>{for(let I of T)if(I[0]===G){let _=Number(I[1]);Number.isFinite(_)&&_>0?(m=fe(_,e),c=!1):_===1/0?(m=fe(1/0,e),c=!1):_<=0&&(c=!0)}}),f=0,h=new Z,b=new Z,N;t.adaptation!=null&&(N=k(t.adaptation).subscribe(I=>{for(let _ of I)_[0]===G&&A(_[1])}));function A(T){if(i.emit(T),T.rpmCap!=null&&Number.isFinite(T.rpmCap)&&T.rpmCap>=0&&(a.emit(T.rpmCap),Number.isFinite(r)&&r>0&&h.start(r,()=>a.emit(Number.POSITIVE_INFINITY))),T.tpmCap!=null&&Number.isFinite(T.tpmCap)&&T.tpmCap>=0&&(s.emit(T.tpmCap),Number.isFinite(r)&&r>0&&b.start(r,()=>s.emit(Number.POSITIVE_INFINITY))),T.retryAfterMs!=null&&T.retryAfterMs>0){let I=H()+T.retryAfterMs*1e6;I>f&&(f=I)}}let C=w(0,{name:"adaptiveRateLimiter/pending"}),R=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),D=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),P=T=>{C.emit((C.cache??0)+T)},S=()=>{R.emit(d.available()),D.emit(m.available())};async function E(T={}){let I=T.requestCost??1,_=T.tokenCost??0,K=T.signal;P(1);try{for(;;){if(K?.aborted)throw He("AdaptiveRateLimiter.acquire aborted");let te=H();if(f>te){let M=Math.ceil((f-te)/1e6);await Ee(M,K);continue}if(I>0&&p||_>0&&c){await Ee(250,K);continue}let ie=d,ue=m;if(!ie.tryConsume(I)){await Ee(Et(ie,I),K);continue}if(!(_>0?ue.tryConsume(_):!0)){ie.putBack(I),await Ee(Et(ue,_),K);continue}S();return}}finally{P(-1)}}function O(T){T>0?m.tryConsume(T):T<0&&m.putBack(-T),S()}function F(){g(),y(),N?.(),h.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:l,lastSignal:i,pending:C,rpmAvailable:R,tpmAvailable:D,acquire:E,recordUsage:O,recordSignal:A,dispose:F}}function fe(t,e){if(!Number.isFinite(t)||t===1/0)return _e(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let r=Math.max(1,t*e),n=t/60;return _e(r,n)}function Et(t,e){let r=t.available(),n=Math.max(0,e-r);return n<=0?25:Math.min(5e3,Math.max(50,n*100))}function Ee(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(He("AdaptiveRateLimiter.acquire aborted")):new Promise((r,n)=>{let o=new Z,a,s=()=>{o.cancel(),e&&a&&e.removeEventListener("abort",a)};o.start(t,()=>{s(),r()}),e&&(a=()=>{s(),n(He("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",a,{once:!0}))})}function ze(t,e={}){let r=e.limiter??Ot({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),n=(s,i)=>e.costFn?e.costFn(s,i):0,o=s=>{let i=qe(s);i&&r.recordSignal(i)},a=V(t,{async invoke(s,i){let u=n(s,i);await r.acquire({requestCost:1,tokenCost:u,signal:i?.signal});try{let l=await se(k(t.invoke(s,i))),d=l.usage??Nt(),p=z(d)+ne(d)-u;return p>0&&r.recordUsage(p),l}catch(l){throw o(l),l}},async*stream(s,i){let u=n(s,i);await r.acquire({requestCost:1,tokenCost:u,signal:i?.signal});try{let l=0;for await(let m of t.stream(s,i))m.type==="usage"&&(l=z(m.usage)+ne(m.usage)),yield m;let d=l-u;d>0&&r.recordUsage(d)}catch(l){throw o(l),l}}});return U(a,"withRateLimiter",t),{adapter:a,limiter:r}}function Oe(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function It(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Oe()):new Promise((r,n)=>{let o=new Z,a,s=()=>{o.cancel(),e&&a&&e.removeEventListener("abort",a)};o.start(t,()=>{s(),r()}),e&&(a=()=>{s(),n(Oe())},e.addEventListener("abort",a,{once:!0}))})}function Ye(t,e={}){let r=e.attempts??3,n=e.baseDelayMs??500,o=e.maxDelayMs??1e4,a=e.strategy??"decorrelated",s=e.jitter??!0,i=e.shouldRetry??Tr,u=e.retryStreaming??!0,l=(m,p)=>{if(a==="decorrelated"){let f=Math.min(o,Math.max(n,p*3));return n+Math.random()*(f-n)}let c=a==="exp"?n*2**(m-1):n*m,g=Math.min(o,c);if(!s)return g;let y=g*(.5+Math.random());return Math.min(o,y)},d=V(t,{async invoke(m,p){if(p?.signal?.aborted)throw Oe();let c,g=n;for(let y=1;y<=r;y++)try{return await se(k(t.invoke(m,p)))}catch(f){if(c=f,y>=r||!i(f,y))throw f;let h=l(y,g);g=h,await It(h,p?.signal)}throw c},async*stream(m,p){if(p?.signal?.aborted)throw Oe();if(!u){for await(let y of t.stream(m,p))yield y;return}let c,g=n;for(let y=1;y<=r;y++){let f=!1;try{for await(let h of t.stream(m,p))f=!0,yield h;return}catch(h){if(c=h,f||y>=r||!i(h,y))throw h;let b=l(y,g);g=b,await It(b,p?.signal)}}throw c}});return U(d,"withRetry",t),d}function Tr(t,e){if(t==null)return!1;let r=t;return r.name==="LLMTimeoutError"?!0:r.name==="AbortError"||r.message==="aborted"||r.name==="DOMException"&&r.code!=null&&Number(r.code)===20||r.name==="BudgetExhaustedError"||r.name==="CircuitOpenError"?!1:r.status!=null?r.status===429||r.status>=500&&r.status<600:r.code&&typeof r.code=="string"&&/^E[A-Z]+$/.test(r.code)?!0:r.message?/network|timeout|socket|fetch|econn|eai_/i.test(r.message):!1}var ge=class extends Error{constructor(r){super(`LLM call timed out after ${r}ms`);this.ms=r}name="LLMTimeoutError"};function Je(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let r=a=>{let s=new AbortController,i=!1,u,l=new Z;return a&&(a.aborted?s.abort(a.reason):(u=()=>{l.cancel(),s.abort(a.reason)},a.addEventListener("abort",u,{once:!0}))),l.start(e,()=>{i=!0,s.abort(new ge(e))}),{signal:s.signal,cancel:()=>{l.cancel(),a&&u&&a.removeEventListener("abort",u)},timedOut:()=>i}},n=(a,s)=>{if(!s||a instanceof ge)throw a;let i=a;if(i?.name==="AbortError"||i?.name==="DOMException"&&Number(i.code)===20||a?.message==="aborted"){let l=new ge(e);throw l.cause=a,l}throw a},o=V(t,{async invoke(a,s){let{signal:i,cancel:u,timedOut:l}=r(s?.signal);try{return await se(k(t.invoke(a,{...s,signal:i})))}catch(d){return n(d,l())}finally{u()}},async*stream(a,s){let{signal:i,cancel:u,timedOut:l}=r(s?.signal);try{for await(let d of t.stream(a,{...s,signal:i}))yield d}catch(d){n(d,l())}finally{u()}}});return U(o,"withTimeout",t),o}function Mr(t,e={}){let r={adapter:t},n=t;if(e.rateLimit){let o=ze(n,e.rateLimit);n=o.adapter,r.rateLimiter=o.limiter}if(e.budget){let o=Ue(n,e.budget);n=o.adapter,r.budget=o.budget}if(e.breaker){let o=Ke(n,e.breaker);n=o.adapter,r.breaker=o.breaker}if(e.timeoutMs!=null&&(n=Je(n,e.timeoutMs)),e.retry&&(n=Ye(n,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),n=Be([{name:e.name??"primary",adapter:n},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(n=Ge(n,e.cache)),r.adapter=n,r}function L(t,e){return dt("ai",t,e)}function vr(t){return t!=null&&typeof t.then=="function"}function Qe(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function kr(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var Rr=3e4;function Dt(t,e){if(t.status==="settled"){let n=t.cache;if(n!==void 0)return Promise.resolve(n)}let r=e?.timeoutMs??Rr;return new Promise((n,o)=>{let a=new Z,s=t.subscribe(i=>{for(let u of i){if(u[0]===G){a.cancel(),s(),n(u[1]);return}if(u[0]===W){a.cancel(),s(),o(u[1]);return}if(u[0]===q){a.cancel(),s(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});a.start(r,()=>{s(),o(new Error(`firstDataFromNode: timed out after ${r}ms`))})})}async function Me(t){return vr(t)?Me(await t):Qe(t)?Dt(t):kr(t)?Dt(k(t)):t}function ye(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function co(t,e,r){return Q(n=>{let o=new AbortController,a=!1,s=null,i=d=>{a||(a=!0,n.down([[G,d],[q]]),s?.(),s=null)},u;try{u=t.invoke(e,{...r.invokeOpts,signal:o.signal})}catch(d){return i(r.onFailure("throw",d)),()=>o.abort()}return s=k(u,{signal:o.signal}).subscribe(d=>{for(let m of d){if(a)return;if(m[0]===G){try{i(r.onSuccess(m[1]))}catch(p){i(r.onFailure("onSuccess-threw",p))}return}if(m[0]===W){i(r.onFailure("error",m[1]));return}if(m[0]===q){i(r.onFailure("complete",void 0));return}}}),a&&s&&(s(),s=null),()=>{o.abort(),s?.(),s=null}})}function xr(t,e){let r=k(t),n=e?.refreshTrigger!=null?k(e.refreshTrigger):null,o=e?.name!==void 0?{name:e.name}:void 0,a=X("frozenContext",o);return n==null?le([r],(s,i,u)=>{if(u.store.emitted===!0)return;let d=s[0],m=d!=null&&d.length>0?d.at(-1):u.prevData[0];if(m!==void 0)return u.store.emitted=!0,i.emit(m),{invalidate:()=>{u.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:L("frozen_context",{...a})}):le([r,n],(s,i,u)=>{let l=s[1];if(!(l!=null&&l.length>0))return;let m=s[0],p=m!=null&&m.length>0?m.at(-1):u.prevData[0];i.emit(p)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:L("frozen_context",{...a})})}function Pt(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function wr(t,e=200){return t.length<=e?t:`${t.slice(0,e)}\u2026`}function Xe(t,e,r,n){let o=n?.format??"text",a=n?.name??"prompt_node";n?.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 s=e.length,i=n?.tools!==void 0?[...e,n.tools]:e,u=v(i,d=>{let m=d.slice(0,s),p=n?.tools!==void 0?d[s]:void 0;if(m.some(g=>g==null))return{messages:[],tools:p};let c=typeof r=="string"?r:r(...m);return c?{messages:[{role:"user",content:c}],tools:p}:{messages:[],tools:p}},{name:`${a}::messages`,meta:L("prompt_node")});return $(u,d=>{let{messages:m,tools:p}=d;return!m||m.length===0?w(null):Q(c=>{let g=!1,y=!1,f,h={model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,...p!==void 0?{tools:p}:{}};if(n?.abort){let C=bt(n.abort);h.signal=C.signal,f=C.dispose}let b;try{b=t.invoke(m,h)}catch(C){return g=!0,c.down([[W,C]]),()=>{f?.()}}let A=k(b).subscribe(C=>{if(!(y||g))for(let R of C){if(g)return;if(R[0]===G){let D=R[1];if(o==="raw")c.emit(D);else try{let P=Pt(D),S=o==="json"?JSON.parse(ye(P)):P;c.emit(S)}catch(P){let S=Pt(D),E=new Error(`promptNode: failed to parse LLM response as JSON: ${P.message}
|
|
2
|
-
Raw content (first 200 chars): ${wr(S)}`);g=!0,c.down([[W,E]]);return}}else if(R[0]===W){g=!0,c.down([[W,R[1]]]);return}else if(R[0]===q){g=!0,c.down([[q]]);return}else c.down([R])}});return()=>{y=!0,A(),f?.()}},{name:`${a}::call`,meta:L("prompt_node::call")})},{name:`${a}::output`,meta:n?.meta?{...L("prompt_node::output"),...n.meta}:L("prompt_node::output")})}function Ze(t,e,r,n){let o=r.name??n;return a=>{let s=w(a);return Xe(r.adapter,[s],i=>e(i),{name:o,format:"json",systemPrompt:t,model:r.model,temperature:r.temperature??0,maxTokens:r.maxTokens})}}function et(t,e){let r=e.maxExistingKeys??100,n=Ze(t,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,a)=>{let s=r===Number.POSITIVE_INFINITY?[...a.keys()]:[...a.keys()].slice(0,r);return n({raw:o,existingKeys:s})}}function tt(t,e){let r=Ze(t,n=>JSON.stringify({memories:n}),e,"llmConsolidator");return n=>{let o=[...n.entries()].map(([a,s])=>({key:a,value:s}));return r(o)}}async function _t(t,e,r,n){let o="",a=0;for await(let s of t.stream(e,r))n.publish({...s,seq:a++,ts:be()}),s.type==="token"&&(o+=s.delta);return o}function jt(t,e){if(e==="json")try{return JSON.parse(ye(t))}catch(r){let n=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${r.message}; content preview: ${n}`)}return t}function Ft(t,e){return v([t.latest],([r],n)=>{let o=n.store;if(r==null)return o.acc??"";let a=r;return a.seq===0&&(o.acc=""),a.type==="token"&&(o.acc=(o.acc??"")+a.delta),o.acc??""},{name:e,meta:L("accumulated_text"),initial:""})}function Lr(t,e,r,n){let o=n?.name??"llm",a=n?.format??"text",s=$e(`${o}/stream`,{...n?.retainedLimit!=null?{retainedLimit:n.retainedLimit}:{}}),i=v(e,m=>{if(m.some(c=>c==null))return[];let p=typeof r=="string"?r:r(...m);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:L("prompt_node::messages"),initial:[]}),u=$(i,m=>{let p=m;if(!p||p.length===0)return w(null);let c=new AbortController;async function*g(){try{let y=await _t(t,p,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,signal:c.signal},s);yield jt(y,a)}finally{c.abort()}}return k(g())},{meta:X("streamingPromptNode")}),l=Ft(s,`${o}::accumulatedText`),d=j(u);return{output:u,deltaTopic:s,accumulatedText:l,dispose:()=>{d(),s.destroy()}}}function Nr(t,e,r,n,o,a){let s=w(0,{name:`${e}/cancel`}),i=0,u=[...n,s],l=a?.name??e,d=a?.format??"text",m=$e(`${l}/stream`,{...a?.retainedLimit!=null?{retainedLimit:a.retainedLimit}:{}}),p=v(u,D=>{let P=D.slice(0,-1);if(P.some(E=>E==null))return[];let S=typeof o=="string"?o:o(...P);return S?[{role:"user",content:S}]:[]},{name:`${l}::messages`,meta:L("prompt_node::messages"),initial:[]}),c=$(p,D=>{let P=D;if(!P||P.length===0)return w(null);let S=new AbortController;async function*E(){try{let O=await _t(r,P,{model:a?.model,temperature:a?.temperature,maxTokens:a?.maxTokens,systemPrompt:a?.systemPrompt,signal:S.signal},m);yield jt(O,d)}finally{S.abort()}}return k(E())},{meta:X("gatedStream")}),g=Ft(m,`${l}::accumulatedText`),y=ut(c,D=>D!=null);t.add(y,{name:`${e}/raw`});let f=vt(`${e}/gate-graph`);t.mount(`${e}/gate-graph`,f),f.add(y,{name:`${e}/raw`});let h=f.approvalGate(`${e}/gate`,`${e}/raw`,a?.gate),b=j(c),N=j(h.node),A=j(g);t.addDisposer(b),t.addDisposer(N),t.addDisposer(A);let C=h.reject.bind(h),R={...h,reject(D=1){J(()=>{C(D),s.emit(++i)})}};return{output:h.node,deltaTopic:m,accumulatedText:g,gate:R,dispose:()=>{b(),N(),A(),m.destroy()}}}function Ar(t,e){let r=e?.separator??`
|
|
3
|
-
|
|
4
|
-
`,n=t.map(s=>typeof s=="string"?w(s):k(s)),o=v(n,s=>s.filter(i=>i!=null&&i!=="").join(r),{name:e?.name??"systemPrompt",describeKind:"derived",meta:L("system_prompt"),initial:""}),a=j(o);return Object.assign(o,{dispose:a})}var Cr=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function Sr(t,e){let r=e?.charsPerToken??4,n={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return v([t.latest],([o],a)=>{if(o==null)return n;let s=o;"chunkCount"in a.store||(a.store.chunkCount=0,a.store.charCount=0,a.store.usageTokens=0,a.store.sawUsage=!1);let i=a.store;s.type==="token"?(i.chunkCount+=1,i.charCount+=s.delta.length):s.type==="usage"&&(i.sawUsage=!0,i.usageTokens=z(s.usage)+ne(s.usage));let u=i.sawUsage?i.usageTokens:Math.ceil(i.charCount/r);return{chunkCount:i.chunkCount,charCount:i.charCount,estimatedTokens:u,estimated:!i.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:n,meta:L("cost_meter_extractor"),equals:Cr})}var Er=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let n=t[r],o=e[r];if(n.label!==o.label||n.pattern!==o.pattern||n.match!==o.match||n.position!==o.position)return!1}return!0};function Or(t,e){let r=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>r)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${r}); raise the option or shorten the pattern.`);let n=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return v([t],([o],a)=>{if(o==null)return[];let s=o;"flags"in a.store||(a.store.flags=[],a.store.scannedTo=0);let i=a.store.flags,u=a.store.scannedTo,l=Math.max(0,u-r),d=s.slice(l),m=!1;for(let{pattern:p,label:c,compiled:g}of n){g.lastIndex=0;for(let y of d.matchAll(g)){let f=l+(y.index??0);f+y[0].length<=u||(i.push({label:c,pattern:p,match:y[0],position:f}),m=!0)}}return a.store.scannedTo=s.length,m?[...i]:i.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:L("keyword_flag_extractor"),equals:Er})}function Ir(t,e,r){return v([t],([n])=>n==null?null:e(n),{name:r?.name??"extractor",describeKind:"derived",initial:null,meta:L("stream_extractor"),...r?.equals?{equals:r.equals}:{}})}var Dr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let n=t[r],o=e[r];if(n.startIndex!==o.startIndex||n.name!==o.name||n.raw!==o.raw)return!1}return!0};function Pr(t,e){return v([t],([r],n)=>{if(r==null)return[];let o=r;"calls"in n.store||(n.store.calls=[],n.store.scanFrom=0);let a=n.store.calls,s=n.store.scanFrom,i=!1;for(;s<o.length;){let u=o.indexOf("{",s);if(u===-1){n.store.scanFrom=o.length;break}let l=0,d=-1,m=!1;for(let c=u;c<o.length;c++){let g=o[c];if(m)g==="\\"&&c+1<o.length?c++:g==='"'&&(m=!1);else if(g==='"')m=!0;else if(g==="{")l++;else if(g==="}"&&(l--,l===0)){d=c;break}}if(d===-1){n.store.scanFrom=u;break}let p=o.slice(u,d+1);try{let c=JSON.parse(p);typeof c.name=="string"&&c.arguments!=null&&typeof c.arguments=="object"&&(a.push({name:c.name,arguments:c.arguments,raw:p,startIndex:u}),i=!0)}catch{}s=d+1,n.store.scanFrom=s}return i?[...a]:a.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:L("tool_call_extractor"),equals:Dr})}function _r(t,e,r,n){let o=r*(n?.hardMultiplier??1.5),a=typeof e!="function",s=[t];return a&&s.push(e),v(s,i=>{let u=i[0]??"";if(u.length===0)return"allow";let l=a?i[1]??0:e(u);return l>=o?"block":l>=r?"review":"allow"},{name:n?.name??"content-gate",initial:"allow"})}function jr(t,e,r,n){let o=r??(()=>"[REDACTED]");function a(s){let i=s;for(let u of e){let l=u.global?u:new RegExp(u.source,`${u.flags}g`);i=i.replace(l,d=>o(d,u))}return i}return v([t],([s])=>a(s??""),{name:n?.name??"redactor",initial:""})}var Ie=class extends ae{_log;messages;latest;messageCount;constructor(e,r={}){super(e,r.graph),this._log=pe([],{name:"messages",maxSize:r.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=v([this.messages],([n])=>{let o=n;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:L("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(j(this.latest)),this.messageCount=v([this.messages],([n])=>n.length,{name:"messageCount",describeKind:"derived",meta:L("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(j(this.messageCount))}append(e,r,n){this._log.append({role:e,content:r,...n})}appendToolResult(e,r){this._log.append({role:"tool",content:r,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function rt(t,e){return new Ie(t,e)}function Fr(t,e,r){let n=k(t),o=r?.condition!=null?k(r.condition):null,a=w(null,{name:r?.name?`${r.name}::null`:"handoff::null"});if(o==null)return $(n,i=>{if(i==null)return a;let u=w(i);return e(u)},{meta:X("handoff")});let s=v([n,o],([i,u])=>({v:i,open:u===!0}),{name:r?.name?`${r.name}::router`:"handoff::router",describeKind:"derived"});return $(s,({v:i,open:u})=>{if(i==null)return a;if(!u)return w(i);let l=w(i);return e(l)},{meta:X("handoff")})}function nt(t){let{toolCalls:e,tools:r}=t,n=t.retryCount??1,o=t.onError??"rescue",a=(s,i)=>{if(s===i)return!0;if(s.length!==i.length)return!1;for(let u=0;u<s.length;u++){let l=s[u],d=i[u];if(l?.id!==d?.id||l?.content!==d?.content)return!1}return!0};return $(e,s=>{if(s==null||s.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 i=s.map(u=>Gr(u,r,n,o));return v(i,u=>u,{name:"toolExecution::batch",equals:a})})}function Gr(t,e,r,n){let o=pt(()=>e.executeReactive(t.name,t.arguments),{count:r}),a=v([o],([s])=>({id:t.id,content:typeof s=="string"?s:JSON.stringify(s)}));return n==="propagate"?a:ct(a,s=>({id:t.id,content:JSON.stringify({error:String(s)})}))}var De=class extends ae{definitions;schemas;_bundle;constructor(e,r={}){super(e,r.graph),this._bundle=xe({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=v([this.definitions],([n])=>[...(n??new Map).values()],{name:"schemas",describeKind:"derived",meta:L("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(j(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}executeReactive(e,r){let n=this._bundle.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);return Q(o=>{let a=new AbortController,s;try{let u=n.handler(r,{signal:a.signal});s=Br(u,a.signal)}catch(u){return o.down([[W,u]]),()=>{a.abort()}}let i=s.subscribe(u=>{o.down(u)});return()=>{a.abort(),i()}},{name:`executeReactive::${e}`,meta:L("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function ot(t,e){return new De(t,e)}function Br(t,e){return Qe(t)?t:t!=null&&typeof t.then=="function"?je(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?yt(t,{signal:e}):je(Promise.resolve(t),{signal:e})}function $r(t,e,r){let n=k(t),o=e.map(s=>k(s)),a=[n,...o];return v(a,s=>{let i=s[0]??[],u=s.slice(1);return i.filter(l=>{for(let d of u)if(d!=null&&!d(l))return!1;return!0})},{name:r?.name??"tool-selector",describeKind:"derived",meta:{...L("tool_selector"),...X("toolSelector")},equals:(s,i)=>{let u=s,l=i;if(u.length!==l.length)return!1;for(let d=0;d<u.length;d++)if(u[d]!==l[d])return!1;return!0}})}function Gt(t){let e=t.thresholds??{};return r=>{let n=t.scoreFn(r);for(let o of Object.keys(e)){let a=e[o];if(a===void 0)continue;let s=n[o];if((Number.isFinite(s)?s:Number.NEGATIVE_INFINITY)<a)return!1}return!0}}function Wr(t){let e={persistence:t.persistenceThreshold??.3,personalValue:t.personalValueThreshold??.3},r=Gt({scoreFn:t.scoreFn,thresholds:e});return t.requireStructured?n=>{if(!r(n))return!1;let o=t.scoreFn(n).structure;return Number.isFinite(o)&&o>0}:r}function at(t,e,r){let n=xt({dimension:r.dimension});t.add(n.entries,{name:"vectorIndex"});let a=re([e.store.entries],([s])=>{let i=s??new Map;for(let[u,l]of i){let d=r.embedFn(l);d&&n.upsert(u,d,l)}}).subscribe(()=>{});return t.addDisposer(a),{vectors:n,dispose:()=>a()}}function st(t,e,r,n){let o=n.mountPath??r,a=wt(`${r}-kg`);if(t.mount(o,a),!n.entityFn)return{kg:a,dispose:()=>{}};let s=n.entityFn,u=re([e.store.entries],([l])=>{let d=l??new Map;for(let[m,p]of d){let c=s(m,p);if(c){for(let g of c.entities??[])a.upsertEntity(g.id,g.value);for(let g of c.relations??[])a.link(g.from,g.to,g.relation,g.weight)}}}).subscribe(()=>{});return t.addDisposer(u),{kg:a,dispose:()=>u()}}function it(t,e,r){let n=r.decayRate??we,o=r.maxActive??1e3,a=r.archiveThreshold??.1,s=r.permanentFilter??(()=>!1),i=Rt("permanent",{ranked:!1});t.mount("permanent",i);let u=new Set,l=b=>u.has(b)?"permanent":(e.store.entries.cache??new Map).has(b)?"active":"archived",d=(b,N)=>{u.add(b),i.upsert(b,N)},m=new Map,p=e.store.entries,c=r.context?k(r.context):w(null),y=re([p,c],([b,N])=>{let A=b??new Map,C=H(),R=[],D=[];for(let[S,E]of A){if(m.has(S)||m.set(S,C),s(S,E)){D.push({key:S,value:E});continue}let O=r.score(E,N),F=m.get(S)??C,T=Number(C-F)/1e9;Mt(O,T,n)<a&&R.push(S)}for(let S of m.keys())A.has(S)||m.delete(S);for(let{key:S,value:E}of D)u.has(S)||d(S,E);let P=A.size-u.size;if(P>o){let S=[...A.entries()].filter(([O])=>!u.has(O)).map(([O,F])=>({key:O,score:r.score(F,N)})).sort((O,F)=>O.score-F.score),E=P-o;for(let O=0;O<E&&O<S.length;O++){let F=S[O].key;R.includes(F)||R.push(F)}}R.length>0&&J(()=>{for(let S of R)e.store.delete(S)})}).subscribe(()=>{}),f=null;r.archiveTier&&(f=t.attachSnapshotStorage([r.archiveTier],r.archiveStorageOptions??{}));let h=()=>{y(),f?.dispose()};return t.addDisposer(h),{tiers:{permanent:i,activeEntries:p,archiveHandle:f,tierOf:l,markPermanent:d},dispose:h}}function Kr(t,e){if(!t||!e)return 0;let r=Math.min(t.length,e.length),n=0;for(;n<r&&t[n]===e[n];)n++;return n}function lt(t,e,r,n,o){let a=o.topK??20,s=o.graphDepth??1,i=o.budget??2e3,u=o.contextWeight??0,l=o.context?k(o.context):w(null),d=(f,h,b)=>{let N=new Map,A=[];if(r&&b.vector){let E=b.vector,O=r.entries.cache;if(O&&O.size>0&&a>0){A=[...O.values()].map(T=>({id:T.id,score:kt(E,T.vector),...T.meta!==void 0?{meta:T.meta}:{}})).sort((T,I)=>I.score-T.score).slice(0,a);for(let T of A){let I=f.get(T.id);I&&N.set(T.id,{value:I,sources:new Set(["vector"])})}}}let C=[];if(n){let E=n.adjacencyOut.cache,O=n.adjacencyIn.cache,F=[...b.entityIds??[],...N.keys()],T=new Set,I=F;for(let _=0;_<s;_++){let K=[];for(let te of I){if(T.has(te))continue;T.add(te);let ie=E?.get(te)??[],ue=O?.get(te)??[];for(let me of ie){let x=me.to;if(!T.has(x)){K.push(x);let M=f.get(x);if(M){let B=N.get(x);B?B.sources.add("graph"):N.set(x,{value:M,sources:new Set(["graph"])}),C.push(x)}}}for(let me of ue){let x=me.from;if(!T.has(x)){K.push(x);let M=f.get(x);if(M){let B=N.get(x);B?B.sources.add("graph"):N.set(x,{value:M,sources:new Set(["graph"])}),C.push(x)}}}}I=K}}for(let[E,O]of f)N.has(E)||N.set(E,{value:O,sources:new Set(["store"])});let R=b.context?.length??0,D=[];for(let[E,{value:O,sources:F}]of N){let T=o.contextOf?o.contextOf(O):void 0,I=o.score(O,h);if(u>0&&R>0){let K=Kr(b.context,T);K>0&&(I=I*(1+u*K/R))}let _=T?{key:E,value:O,score:I,sources:[...F],context:T}:{key:E,value:O,score:I,sources:[...F]};D.push(_)}D.sort((E,O)=>O.score-E.score);let P=[],S=0;for(let E of D){let O=o.cost(E.value);if(S+O>i&&P.length>0)break;P.push(E),S+=O}return{packed:P,trace:{vectorCandidates:A,graphExpanded:C,ranked:D,packed:P}}},m=(f,h)=>{if(f===h)return!0;if(f.length!==h.length)return!1;for(let b=0;b<f.length;b++)if(f[b]!==h[b])return!1;return!0},p=w([],{name:"retrieval",describeKind:"state",meta:L("retrieval_pipeline"),equals:m});t.add(p,{name:"retrieval"});let c=w(null,{name:"retrievalTrace",describeKind:"state",meta:L("retrieval_trace")});return t.add(c,{name:"retrievalTrace"}),{retrieval:p,retrievalTrace:c,retrieve:f=>{let h=e.store.entries.cache??new Map,{packed:b,trace:N}=d(h,l.cache,f);return J(()=>{p.emit(b),c.emit(N)}),b},retrieveReactive:f=>{let h=k(f),b=v([e.store.entries,l,h],([C,R,D])=>{if(D==null)return{packed:[],trace:null};let P=C??new Map,{packed:S,trace:E}=d(P,R,D);return{packed:S,trace:E}},{name:"retrievalReactive::result",describeKind:"derived",meta:L("retrieval_reactive_result"),initial:{packed:[],trace:null}}),A=re([b],([C])=>{let R=C;J(()=>{p.emit(R.packed),R.trace&&c.emit(R.trace)})}).subscribe(()=>{});return t.addDisposer(A),v([b],([C])=>C.packed,{name:"retrievalReactive",describeKind:"derived",meta:L("retrieval_reactive"),initial:[],equals:m})}}}var Pe=class extends ae{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_running=!1;_currentAbortController=null;constructor(e,r){if(super(e,r.graph),this.chat=rt(`${e}-chat`,{maxMessages:r.maxMessages}),this.mount("chat",this.chat),this.tools=ot(`${e}-tools`),this.mount("tools",this.tools),r.tools)for(let x of r.tools)this.tools.register(x);this.status=w("idle",{name:"status",describeKind:"state",meta:L("agent_status")}),this.add(this.status,{name:"status"}),this.turn=w(0,{name:"turn",describeKind:"state",meta:L("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=w(!1,{name:"aborted",describeKind:"state",meta:L("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let n=0,o=this.turn.subscribe(x=>{for(let M of x)M[0]===G&&(n=M[1])}),a=!1,s=this.aborted.subscribe(x=>{for(let M of x)M[0]===G&&(a=M[1])}),i=this.chat.messages.cache??[],u=this.chat.messages.subscribe(x=>{for(let M of x)M[0]===G&&(i=M[1])}),l=this.tools.schemas.cache??[],d=this.tools.schemas.subscribe(x=>{for(let M of x)M[0]===G&&(l=M[1])}),m=r.adapter,p=r.systemPrompt,c=r.model,g=r.temperature,y=r.maxTokens,f=r.maxTurns??10,h=r.stopWhen,b=this.chat,N=this.tools,A=this.status,C=this.turn,R=this.aborted,D=le([A],(x,M,B)=>{if(ve(x,B.prevData,0,"idle")!=="thinking"||a||n>=f){M.down([[ce]]);return}if(i.length===0){M.down([[ce]]);return}M.emit({messages:i,tools:l})},{name:"promptInput",describeKind:"derived",meta:L("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),P=$(D,x=>{let M=new AbortController;return this._currentAbortController=M,a&&M.abort(new Error("agentLoop: aborted")),k(m.invoke(x.messages,{tools:x.tools.length>0?x.tools:void 0,systemPrompt:p,model:c,temperature:g,maxTokens:y,signal:M.signal}),{signal:M.signal})},{equals:()=>!1}),S=w(null,{name:"lastResponse",describeKind:"state",meta:L("agent_last_response")});this.lastResponse=S;let E=le([S,A],(x,M,B)=>{let Y=ve(x,B.prevData,0,null);if(ve(x,B.prevData,1,"idle")!=="acting"){M.down([[ce]]);return}let oe=Y?.toolCalls;if(oe==null||oe.length===0){M.down([[ce]]);return}M.emit(oe)},{name:"toolCallsRaw",describeKind:"derived",meta:L("agent_tool_calls_raw")}),O=r.interceptToolCalls?r.interceptToolCalls(E):E;this.toolCalls=O;let F=nt({toolCalls:O,tools:N,retryCount:1});this.toolResults=F;let T=re([P],([x])=>{if(a)return;let M=x,B=n+1,Y=M.toolCalls!=null&&M.toolCalls.length>0,he=M.finishReason==="end_turn"&&(!M.toolCalls||M.toolCalls.length===0),oe=h?.(M)===!0,Vt=B>=f,Ut=oe||he||!Y||Vt?"done":"acting";J(()=>{S.emit(M),A.emit(Ut),C.emit(B),b.append("assistant",M.content,{toolCalls:M.toolCalls})})}),I=re([F],([x])=>{if(a)return;let M=x;if(M.length===0)return;let B=n>=f?"done":"thinking";J(()=>{A.emit(B);for(let Y of M)b.appendToolResult(Y.id,Y.content)})}),_=A.cache??"idle",K=A.subscribe(x=>{for(let M of x)M[0]===G&&(_=M[1])}),te=re([R],([x])=>{x===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),_!=="done"&&A.emit("done"))}),ie=j(T),ue=j(I),me=j(te);this._terminalResult=le([A,S],(x,M,B)=>{let Y=ve(x,B.prevData,0,"idle"),he=ve(x,B.prevData,1,null);if(Y==="done"){if(he!=null){M.emit(he);return}let oe=new Error("agentLoop: aborted");oe.name="AbortError",M.down([[W,oe]]);return}if(Y==="error"){M.down([[W,new Error("agentLoop: errored")]]);return}M.down([[ce]])},{name:"terminalResult",describeKind:"derived",meta:L("agent_terminal_result")}),this.add(D,{name:"promptInput"}),this.add(P,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===E?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(E,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(F,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(s),this.addDisposer(K),this.addDisposer(u),this.addDisposer(d),this.addDisposer(ie),this.addDisposer(ue),this.addDisposer(me),this._disposeRunWiring=()=>{}}async run(e,r){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let n;try{J(()=>{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=ht(this._terminalResult,{skipCurrent:!0});if(r!=null)if(r.aborted)this.aborted.emit(!0);else{let a=()=>this.aborted.emit(!0);r.addEventListener("abort",a,{once:!0}),n=()=>r.removeEventListener("abort",a)}return r?.aborted!==!0&&this.status.emit("thinking"),await o}finally{n?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function ve(t,e,r,n){let o=t[r];if(o!=null&&o.length>0)return o[o.length-1];let a=e[r];return a!==void 0?a:n}function Vr(t,e){let r=new Pe(t,e);return r.tagFactory("agentLoop",ke(e)),r}function Ur(t,e,r){let n=new ae(t,r.graph);n.tagFactory("agentMemory",ke(r));let o;if(r.extractFn)o=r.extractFn;else if(r.adapter&&r.extractPrompt)o=et(r.extractPrompt,{adapter:r.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let a=(b,N)=>{let A=N.cache??new Map,C=N.subscribe(R=>{for(let D of R)D[0]===G&&(A=D[1])});return n.addDisposer(C),$(b,R=>R==null?{upsert:[]}:o(R,A))},s=e;if(r.admissionFilter){let b=k(e),N=r.admissionFilter;s=v([b],([A])=>{if(N(A))return A},{name:"admissionFilter",describeKind:"derived"})}let i;r.consolidateFn?i=r.consolidateFn:r.adapter&&r.consolidatePrompt&&(i=tt(r.consolidatePrompt,{adapter:r.adapter}));let u=r.consolidateTrigger;if(!u&&i&&r.reflection?.enabled!==!1){let b=r.reflection?.interval??3e5;u=gt(b,{period:b})}let l={score:r.score,cost:r.cost,budget:r.budget??2e3,context:r.context,consolidate:i,consolidateTrigger:u},d=Tt(s,a,l);n.add(d.store.entries,{name:"store"}),n.add(d.compact,{name:"compact"}),n.add(d.size,{name:"size"});let m=null;r.vectorDimensions&&r.vectorDimensions>0&&r.embedFn&&(m=at(n,d,{dimension:r.vectorDimensions,embedFn:r.embedFn}).vectors);let p=null;r.enableKnowledgeGraph&&(p=st(n,d,t,{mountPath:"kg",entityFn:r.entityFn}).kg);let c=null;r.tiers&&(c=it(n,d,{...r.tiers,score:r.score,context:r.context}).tiers);let g=null,y=null,f=null,h=null;if(m||p){let b=lt(n,d,m,p,{score:r.score,cost:r.cost,budget:r.budget,topK:r.retrieval?.topK,graphDepth:r.retrieval?.graphDepth,contextOf:r.contextOf,contextWeight:r.contextWeight,context:r.context});g=b.retrieval,y=b.retrievalTrace,f=b.retrieve,h=b.retrieveReactive}return Object.assign(n,{distillBundle:d,compact:d.compact,size:d.size,vectors:m,kg:p,memoryTiers:c,retrieval:g,retrievalTrace:y,retrieve:f,retrieveReactive:h})}function qr(t,e,r){let n=t.describe({actor:e,detail:"full"}),o=r?.groupByTags??!0,a=r?.separator??`
|
|
5
|
-
`,s=[],i=r?.sinceVersion;for(let[u,l]of Object.entries(n.nodes)){let d=l.meta??{},m=d.description,p=d.format;if(!m&&!p)continue;if(i!=null&&l.v!=null){let h=i.get(u);if(h!=null&&h.id===l.v.id&&l.v.version<=h.version)continue}let c=m??u,g=l.value,y=d.unit,f;p==="currency"&&typeof g=="number"?f=`$${g.toFixed(2)}`:p==="percentage"&&typeof g=="number"?f=`${(g*100).toFixed(1)}%`:g==null?f="(no value)":f=String(g),y&&p!=="currency"&&p!=="percentage"&&(f=`${f} ${y}`),s.push({path:u,description:c,formatted:f})}if(s.length===0)return"";if(o){let u=new Map,l=[];for(let m of s){let c=n.nodes[m.path].meta?.tags;if(c&&c.length>0){let g=c[0],y=u.get(g);y||(y=[],u.set(g,y)),y.push(m)}else l.push(m)}if(u.size===0)return s.map(m=>`- ${m.description}: ${m.formatted}`).join(a);let d=[];for(let[m,p]of[...u.entries()].sort((c,g)=>c[0].localeCompare(g[0])))d.push(`[${m}]${a}${p.map(c=>`- ${c.description}: ${c.formatted}`).join(a)}`);return l.length>0&&d.push(l.map(m=>`- ${m.description}: ${m.formatted}`).join(a)),d.join(a+a)}return s.map(u=>`- ${u.description}: ${u.formatted}`).join(a)}var Bt=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
6
|
-
|
|
7
|
-
Given a natural-language description, produce a JSON graph specification with this structure:
|
|
8
|
-
|
|
9
|
-
{
|
|
10
|
-
"name": "<graph_name>",
|
|
11
|
-
"nodes": {
|
|
12
|
-
"<node_name>": {
|
|
13
|
-
"type": "state" | "derived" | "producer" | "effect" | "operator",
|
|
14
|
-
"initial": <initial_value_for_state_nodes>,
|
|
15
|
-
"deps": ["<dep_node_name>", ...],
|
|
16
|
-
"meta": {
|
|
17
|
-
"description": "<human-readable purpose>",
|
|
18
|
-
"type": "string" | "number" | "boolean" | "integer" | "enum",
|
|
19
|
-
"range": [min, max],
|
|
20
|
-
"values": ["a", "b"],
|
|
21
|
-
"format": "currency" | "percentage" | "status",
|
|
22
|
-
"access": "human" | "llm" | "both" | "system",
|
|
23
|
-
"unit": "<unit>",
|
|
24
|
-
"tags": ["<tag>"]
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
Rules:
|
|
31
|
-
- "state" nodes have no deps and hold user/LLM-writable values (knobs). Use "initial" for the starting value.
|
|
32
|
-
- "derived" nodes have deps and compute from them (pure, no side effects).
|
|
33
|
-
- "effect" nodes have deps but produce side effects (no return value).
|
|
34
|
-
- "producer" nodes have no deps but generate values asynchronously.
|
|
35
|
-
- "operator" nodes are parameterized transformations with deps.
|
|
36
|
-
- Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
|
|
37
|
-
- meta.description is required for every node.
|
|
38
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function $t(t,e,r){let o=[{role:"system",content:r?.systemPromptExtra?`${Bt}
|
|
39
|
-
|
|
40
|
-
${r.systemPromptExtra}`:Bt},{role:"user",content:t}],a=e.invoke(o,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens,signal:r?.signal}),i=(await Me(a)).content.trim();i.startsWith("```")&&(i=ye(i));let u;try{u=JSON.parse(i)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${i.slice(0,200)}`)}return Lt(u,{catalog:r?.catalog})}function Hr(t,e,r){let n=k(t);return $(n,o=>!o||typeof o!="string"||o.trim().length===0?w(null):Q(a=>{let s=new AbortController,i=!1;return $t(o,e,{...r,signal:s.signal}).then(u=>{if(i){u.destroy();return}a.emit(u),a.down([[q]])}).catch(u=>{i||a.down([[W,u]])}),()=>{i=!0,s.abort()}},{name:"graphFromSpec::call"}))}function zr(t){let e={},r=t.type;return r==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):r==="integer"?e.type="integer":r==="number"?e.type="number":r==="boolean"?e.type="boolean":r==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function Yr(t,e){let r=t.describe({actor:e,detail:"full"}),n=[],o=[],a=[];for(let[s,i]of Object.entries(r.nodes)){if(i.type!=="state"||s.includes("::__meta__::")||i.status==="completed"||i.status==="errored")continue;let u=i.meta??{},l=u.access;if(l==="human"||l==="system")continue;let d=u.description??`Set the value of ${s}`,m=zr(u),p={type:"object",required:["value"],properties:{value:m},additionalProperties:!1},c=s.replace(/::/g,"__");n.push({type:"function",function:{name:c,description:d,parameters:p}}),o.push({name:s,description:d,inputSchema:p});let g=t,y=e,f=i.v;a.push({name:s,description:d,parameters:p,handler(h){return g.set(s,h.value,y?{actor:y}:void 0),h.value},...f!=null?{version:{id:f.id,version:f.version}}:{}})}return{openai:n,mcp:o,definitions:a}}var Jr=`You are a reactive graph optimizer for GraphReFly.
|
|
41
|
-
|
|
42
|
-
Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
|
|
43
|
-
|
|
44
|
-
Return ONLY valid JSON with this structure:
|
|
45
|
-
{
|
|
46
|
-
"summary": "<one-line summary of the strategy>",
|
|
47
|
-
"reasoning": "<explanation of why these changes help>",
|
|
48
|
-
"operations": [
|
|
49
|
-
{ "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
|
|
50
|
-
{ "type": "remove_node", "name": "<name>" },
|
|
51
|
-
{ "type": "connect", "from": "<source>", "to": "<target>" },
|
|
52
|
-
{ "type": "disconnect", "from": "<source>", "to": "<target>" },
|
|
53
|
-
{ "type": "set_value", "name": "<name>", "value": <new_value> },
|
|
54
|
-
{ "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
|
|
55
|
-
]
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
Rules:
|
|
59
|
-
- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
|
|
60
|
-
- Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
|
|
61
|
-
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Wt(t,e,r,n){let{expand:o,...a}=t.describe({actor:n?.actor,detail:"standard"}),s=[{role:"system",content:Jr},{role:"user",content:JSON.stringify({graph:a,problem:e})}],i=r.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),l=(await Me(i)).content.trim();l.startsWith("```")&&(l=l.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(l)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${l.slice(0,200)}`)}let m=d;if(typeof m.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof m.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(m.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:m.summary,reasoning:m.reasoning,operations:m.operations}}function Qr(t,e,r,n){let o=k(e),a=mt(o,t);return $(a,s=>{if(s==null)return w(null);let[i,u]=s;return!u||!i||typeof i!="string"||i.trim().length===0?w(null):u.destroyed?w(null):Q(l=>{let d=new AbortController,m=!1;return Wt(u,i,r,{...n,signal:d.signal}).then(p=>{m||(l.emit(p),l.down([[q]]))}).catch(p=>{m||l.down([[W,p]])}),()=>{m=!0,d.abort()}},{name:"suggestStrategy::call"})})}var Kt=new Set(["state","derived","producer","operator","effect"]);function Xr(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let n=new Set(Object.keys(r.nodes));for(let[o,a]of Object.entries(r.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${o}": must be an object`);continue}let s=a;if((typeof s.type!="string"||!Kt.has(s.type))&&e.push(`Node "${o}": invalid type "${String(s.type)}" (expected: ${[...Kt].join(", ")})`),Array.isArray(s.deps))for(let i of s.deps)typeof i=="string"&&!n.has(i)&&e.push(`Node "${o}": dep "${i}" does not reference an existing node`)}if(!Array.isArray(r.edges))r.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let a=0;a<r.edges.length;a++){let s=r.edges[a];if(s==null||typeof s!="object"){e.push(`Edge [${a}]: must be an object`);continue}let i=s;(typeof i.from!="string"||!n.has(i.from))&&e.push(`Edge [${a}]: 'from' "${String(i.from)}" does not reference an existing node`),(typeof i.to!="string"||!n.has(i.to))&&e.push(`Edge [${a}]: 'to' "${String(i.to)}" does not reference an existing node`);let u=`${i.from}->${i.to}`;o.has(u)&&e.push(`Edge [${a}]: duplicate edge ${u}`),o.add(u)}}return{valid:e.length===0,errors:e}}export{nr as a,or as b,Ae as c,We as d,sr as e,ir as f,lr as g,dr as h,Ke as i,Ce as j,Ue as k,mr as l,qe as m,ze as n,Ye as o,ge as p,Je as q,Mr as r,ye as s,co as t,xr as u,Xe as v,Ze as w,et as x,tt as y,Lr as z,Nr as A,Ar as B,Sr as C,Or as D,Ir as E,Pr as F,_r as G,jr as H,Ie as I,rt as J,Fr as K,nt as L,De as M,ot as N,$r as O,Gt as P,Wr as Q,at as R,st as S,it as T,lt as U,Pe as V,Vr as W,Ur as X,qr as Y,$t as Z,Hr as _,Yr as $,Wt as aa,Qr as ba,Xr as ca,Zr as da};
|
package/dist/chunk-LYCLF26R.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as Y,b,c as M,d as S,e as R,f as N,g as L,h as k,i as C,j as _,k as P,l as he,n as se,q as ie,r as fe,s as pe,t as _e,u as re}from"./chunk-CK2E7BTU.js";var Ce={name:"json",version:1,contentType:"application/json",encode(n){let e=JSON.stringify(n);return new TextEncoder().encode(e)},decode(n,e){let t=new TextDecoder().decode(n);return JSON.parse(t)}};function $e(n){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>n.encode(e),decode:(e,t)=>n.decode(e)}}function je(n,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:t=>e.compressSync(n.encode(t)),decode:(t,s)=>n.decode(e.decompressSync(t))}}var oe=1,ge=4;function ze(n,e){let t=new TextEncoder().encode(n.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${n.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let s=n.version;if(!Number.isInteger(s)||s<0||s>65535)throw new Error(`encodeEnvelope: codec.version ${s} out of u16 range (expected integer 0\u201365535)`);let i=2+t.length+2+e.length;if(i>4294967295)throw new Error(`encodeEnvelope: total envelope size ${i} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let r=new Uint8Array(i),a=0;return r[a++]=oe,r[a++]=t.length,r.set(t,a),a+=t.length,r[a++]=s>>>8&255,r[a++]=s&255,r.set(e,a),r}function qe(n,e){if(n.length<ge)throw new Error(`decodeEnvelope: bytes too short (${n.length} < ${ge})`);let t=0,s=n[t++];if(s!==oe)throw new Error(`decodeEnvelope: unsupported envelope version ${s} (expected ${oe})`);let i=n[t++];if(i===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+i+2>n.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+i+2} bytes, have ${n.length})`);let r=new TextDecoder().decode(n.subarray(t,t+i));t+=i;let a=(n[t]<<8|n[t+1])>>>0;t+=2;let o=n.subarray(t),d=e.lookupCodec(r);if(d==null)throw new Error(`decodeEnvelope: codec "${r}" not registered (envelope codec_v=${a})`);return{codec:d,codecVersion:a,payload:o}}function ye(n){n.registerCodec(Ce)}function Ke(n){if(n.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=n[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let t=JSON.parse(JSON.stringify(e.snapshot)),s=e.seq;for(let i=1;i<n.length;i++){let r=n[i];if(r.seq<=s)throw new Error(`WAL chain broken at index ${i}: seq=${r.seq} must exceed prev seq=${s}`);if(r.mode==="full"){t=JSON.parse(JSON.stringify(r.snapshot)),s=r.seq;continue}let a=r.diff;for(let d of a.nodesRemoved)delete t.nodes[d];let o=a.nodesAddedFull;if(o!=null)for(let[d,l]of Object.entries(o))t.nodes[d]=JSON.parse(JSON.stringify(l));for(let d of a.nodesChanged){let l=t.nodes[d.path];l!=null&&(l[d.field]=d.to)}s=r.seq}return t}var De={type:"system",id:""};function J(n){if(n==null)return De;let{type:e,id:t,...s}=n;return{type:e??"system",id:t??"",...s}}var D=0,U=!1,A=[],E=[],O=[],W=[];function me(){return D>0||U}function be(){return D>0}function ve(n){D>0?W.push(n):n()}function Xe(n){D+=1;let e=!1;try{n()}catch(t){throw e=!0,t}finally{if(D-=1,D===0)if(e){if(!U){let t=W.splice(0);for(let s of t)try{s()}catch{}A.length=0,E.length=0,O.length=0}}else Oe()}}function Oe(){let n=!U;n&&(U=!0);let e=[],t=0;try{for(;A.length>0||E.length>0||O.length>0||n&&W.length>0;){if(n&&W.length>0){let r=W.splice(0);for(let a of r)try{a()}catch(o){e.push(o)}continue}if(t+=1,t>1e3)throw A.length=0,E.length=0,O.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let i=(A.length>0?A:E.length>0?E:O).splice(0);for(let r of i)try{r()}catch(a){e.push(a)}}}finally{n&&(U=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function X(n,e,t){if(e.length===0)return;if(e.length===1){let l=t(e[0][0]);if(l<3||!me()){n(e);return}(l>=5?O:l===4?E:A).push(()=>n(e));return}let s=e.length,i=s,r=s,a=s,o=0;for(;o<s&&t(e[o][0])<3;)o++;for(i=o;o<s&&t(e[o][0])===3;)o++;for(r=o;o<s&&t(e[o][0])===4;)o++;a=o;let d=me();if(i>0){let l=e.slice(0,i);n(l)}if(r>i){let l=e.slice(i,r);d?A.push(()=>n(l)):n(l)}if(a>r){let l=e.slice(r,a);d?E.push(()=>n(l)):n(l)}if(s>a){let l=e.slice(a,s);d?O.push(()=>n(l)):n(l)}}function Qe(){return Math.trunc(performance.now()*1e6)}function we(){return Date.now()*1e6}var Z=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_rigorRecorder;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let s=this._messageTypes.get(t);return s!=null?s.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}get rigorRecorder(){return this._rigorRecorder}set rigorRecorder(e){this._rigorRecorder=e}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}};function xe(n){n.registerMessageType(Y,{tier:0,wireCrossing:!1}),n.registerMessageType(M,{tier:1,wireCrossing:!1}),n.registerMessageType(R,{tier:1,wireCrossing:!1,metaPassthrough:!1}),n.registerMessageType(N,{tier:2,wireCrossing:!1}),n.registerMessageType(L,{tier:2,wireCrossing:!1}),n.registerMessageType(b,{tier:3,wireCrossing:!0}),n.registerMessageType(S,{tier:3,wireCrossing:!0}),n.registerMessageType(C,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(_,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(k,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var F=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};function Te(n){return Array.isArray(n)?[...n]:[n]}function Fe(n,e){return n.has(e)||n.has("*")}function Ge(n){let e=[];return n((i,r)=>{e.push({kind:"allow",actions:new Set(Te(i)),where:r?.where??(()=>!0)})},(i,r)=>{e.push({kind:"deny",actions:new Set(Te(i)),where:r?.where??(()=>!0)})}),(i,r)=>{let a=!1,o=!1;for(let d of e)Fe(d.actions,r)&&d.where(i)&&(d.kind==="deny"?a=!0:o=!0);return a?!1:o}}function st(n){return Ge((e,t)=>{for(let s of n){let i=s.actorType==null?null:new Set(Array.isArray(s.actorType)?s.actorType:[s.actorType]),r=s.actorId==null?null:new Set(Array.isArray(s.actorId)?s.actorId:[s.actorId]),a=Object.entries(s.claims??{}),o=d=>{if(i!==null&&!i.has(String(d.type))||r!==null&&!r.has(String(d.id??"")))return!1;for(let[l,c]of a)if(d[l]!==c)return!1;return!0};s.effect==="deny"?t(s.action,{where:o}):e(s.action,{where:o})}})}var Ie=["human","llm","wallet","system"];function it(n){let e=Ie.filter(t=>n({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}function ae(n){if(n===void 0)return null;if(typeof n=="number"){if(!Number.isFinite(n))throw new TypeError(`Cannot hash non-finite number: ${n}`);if(Number.isInteger(n)&&!Number.isSafeInteger(n))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${n}. Cross-language cid parity is not guaranteed for unsafe integers.`);return n}if(typeof n=="string"||typeof n=="boolean"||n===null)return n;if(Array.isArray(n))return n.map(ae);if(typeof n=="object"&&n!==null){let e={};for(let t of Object.keys(n).sort())e[t]=ae(n[t]);return e}return null}var He=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ve=new TextEncoder;function Le(n){let e=Ve.encode(n),t=e.length,s=t*8,i=t+9+63&-64,r=new Uint8Array(i);r.set(e),r[t]=128;let a=new DataView(r.buffer);a.setUint32(i-4,s>>>0,!1),a.setUint32(i-8,Math.floor(s/4294967296)>>>0,!1);let o=1779033703,d=3144134277,l=1013904242,c=2773480762,h=1359893119,p=2600822924,u=528734635,g=1541459225,T=new Uint32Array(64),m=(w,y)=>w>>>y|w<<32-y;for(let w=0;w<i;w+=64){for(let f=0;f<16;f++)T[f]=a.getUint32(w+f*4,!1);for(let f=16;f<64;f++){let H=T[f-15],V=T[f-2],K=m(H,7)^m(H,18)^H>>>3,ne=m(V,17)^m(V,19)^V>>>10;T[f]=T[f-16]+K+T[f-7]+ne>>>0}let y=o,G=d,I=l,ee=c,x=h,z=p,q=u,te=g;for(let f=0;f<64;f++){let H=m(x,6)^m(x,11)^m(x,25),V=x&z^~x&q,K=te+H+V+He[f]+T[f]>>>0,ne=m(y,2)^m(y,13)^m(y,22),Se=y&G^y&I^G&I,Re=ne+Se>>>0;te=q,q=z,z=x,x=ee+K>>>0,ee=I,I=G,G=y,y=K+Re>>>0}o=o+y>>>0,d=d+G>>>0,l=l+I>>>0,c=c+ee>>>0,h=h+x>>>0,p=p+z>>>0,u=u+q>>>0,g=g+te>>>0}let v=w=>w.toString(16).padStart(8,"0");return v(o)+v(d)+v(l)+v(c)+v(h)+v(p)+v(u)+v(g)}function de(n){let e=ae(n??null),t=JSON.stringify(e);return Le(t).slice(0,16)}function Pe(){let n=globalThis.crypto;if(n?.randomUUID)return n.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function le(n,e,t){let s=t?.id??Pe();if(n===0)return{id:s,version:0};let r=(t?.hash??de)(e);return{id:s,version:0,cid:r,prev:null}}function Ne(n,e,t){n.version+=1,"cid"in n&&(n.prev=n.cid,n.cid=t(e))}function ot(n){return"cid"in n}var ke=()=>{},Ae=100;function Ee(n){return{node:n,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function ce(n){n.prevData=void 0,n.dirty=!1,n.involvedThisWave=!1,n.dataBatch.length=0,n.terminal=void 0}function Q(n){return n.length===0?n:typeof n[0]=="symbol"?[n]:n}var Ue=(n,e,t,s)=>{t.direction==="down-in"&&n._onDepMessage(t.depIndex,e)},We=(n,e,t,s)=>{let i=n;if(i._status==="completed"||i._status==="errored")return;let r=i._cached,a=r===void 0?[se]:[se,[b,r]];i._status==="dirty"&&a.push(P),X(e,a,i._config.tierOf)},B=new Z({onMessage:Ue,onSubscribe:We});xe(B);ye(B);function gt(n){if(B._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");n(B)}var $=class n{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,t,s){this._config=s.config??B,this._config.onMessage,this._optsName=s.name,this._describeKind=s.describeKind,this._equals=s.equals??Object.is,this._resubscribable=s.resubscribable??!1,this._resetOnTeardown=s.resetOnTeardown??!1,this._autoComplete=s.completeWhenDepsComplete??!0,this._autoError=s.errorWhenDepsError??!0,this._pausable=s.pausable??!0,this._guard=s.guard,this._fn=t,this._partial=s.partial??!1,this._cached=s.initial!==void 0?s.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=s.versioningHash??this._config.defaultHashFn??de;let i=s.versioning??this._config.defaultVersioning;this._versioningLevel=i,this._versioning=i!=null?le(i,this._cached===void 0?void 0:this._cached,{id:s.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Ee);let r={};for(let[o,d]of Object.entries(s.meta??{})){let l={initial:d,name:`${s.name??"node"}:meta:${o}`,describeKind:"state",config:this._config};s.guard!=null&&(l.guard=s.guard),r[o]=new n([],void 0,l)}Object.freeze(r),this.meta=r,this._hasMeta=Object.keys(r).length>0;let a=this;this._actions={emit(o){a._emit([[b,o]])},down(o){a._emit(Q(o))},up(o){a._emitUp(Q(o))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,t){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let s=this._versioningLevel;if(s!=null&&e<=s)return;let i=t?.hash??this._hashFn;i!==this._hashFn&&(this._hashFn=i);let r=this._cached===void 0?void 0:this._cached,a=this._versioning,o=a?.id??t?.id,d=a?.version??0,l=le(e,r,{id:o,hash:i});l.version=d,this._versioning=l,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let t=J(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let s of this._extraGuards)if(!s(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,s=e?.actor!=null;if(!t&&!s)return;let i=J(e?.actor),r=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(i,r))throw new F({actor:i,action:r,nodeName:this.name});if(this._extraGuards!=null){for(let a of this._extraGuards)if(!a(i,r))throw new F({actor:i,action:r,nodeName:this.name})}this._lastMutation={actor:i,timestamp_ns:we()}}down(e,t){let s=Q(e);s.length!==0&&(this._checkGuard(t),this._emit(s))}emit(e,t){this._checkGuard(t),this._emit([[b,e]])}up(e,t){if(this._deps.length===0)return;let s=Q(e);if(s.length===0)return;this._checkGuard(t);let i=t??{internal:!0};this._validateUpTiers(s);for(let r of this._deps)r.node.up?.(s,i)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let s of e){let i=t(s[0]);if(i===3||i===4)throw new Error(`Node "${this.name}": tier-${i} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,t){if(t!=null&&this._guard!=null){let d=J(t);if(!this._guard(d,"observe"))throw new F({actor:d,action:"observe",nodeName:this.name})}let i=this._isTerminal&&this._resubscribable;if(i){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)ce(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let r;try{r=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:i},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let a=this._isTerminal;if(this._sinkCount===1&&!a)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof r=="function")try{r()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let o=!1;return()=>{o||(o=!0,this._sinkCount-=1,this._removeSink(e),typeof r=="function"&&r(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[t]=this._sinks;this._sinks=t}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,t=0;try{for(let s=0;s<e;s++){let i=s,r=this._deps[s];r.unsub=ke,r.unsub=r.node.subscribe(a=>{if(r.unsub===null)return;let o=this._config.tierOf,d=!1;for(let l of a)o(l[0])>=3&&(d=!0),this._config.onMessage(this,l,{direction:"down-in",depIndex:i},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(s){this._deps[t].unsub=null;for(let i=0;i<t;i++){let r=this._deps[i];if(r.unsub!=null){let a=r.unsub;r.unsub=null;try{a()}catch{}ce(r)}}throw this._dirtyDepCount=0,s}}_addDep(e){for(let i=0;i<this._deps.length;i++)if(this._deps[i].node===e)return i;let t=this._deps.length,s=Ee(e);if(this._deps.push(s),this._sinks==null)return t;s.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ie),s.unsub=ke;try{s.unsub=e.subscribe(i=>{if(s.unsub===null)return;let r=this._config.tierOf,a=!1;for(let o of i)r(o[0])>=3&&(a=!0),this._config.onMessage(this,o,{direction:"down-in",depIndex:t},this._actions);a&&this._maybeRunFnOnSettlement()})}catch(i){throw s.unsub=null,this._deps.pop(),this._dirtyDepCount--,i}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(s){this._emit([[_,this._wrapFnError("cleanup threw",s)]])}else if(t!=null&&typeof t=="object"){let s=t.deactivate;if(typeof s=="function")try{s()}catch(i){this._emit([[_,this._wrapFnError("cleanup.deactivate threw",i)]])}}for(let s of this._deps){if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}}ce(s)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,t){let s=this._deps[e],i=t[0];if(this._inspectorHooks!=null){let r={kind:"dep_message",depIndex:e,message:t};for(let a of this._inspectorHooks)a(r)}if(i!==Y){if(i===M){this._depDirtied(s);return}if(i===R){if(this._depInvalidated(s),this._cached===void 0)return;this._emit(pe);return}if(i===N||i===L){this._emit([t]);return}if(i===k){this._emit(re);return}if(i===b)this._depSettledAsData(s,t[1]);else if(i===S)this._depSettledAsResolved(s);else if(i===C)this._depSettledAsTerminal(s,!0);else if(i===_)this._depSettledAsTerminal(s,t[1]);else{this._emit([t]);return}if(!this._fn){(i===b||i===S)&&this._emit([t]),(i===C||i===_)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ie))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(fe),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[_,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(_e)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(a){this._emit([[_,this._wrapFnError("cleanup threw",a)]]);return}}else if(e!=null&&typeof e=="object"){let a=e.beforeRun;if(typeof a=="function"){e.beforeRun=void 0;try{a()}catch(o){this._emit([[_,this._wrapFnError("cleanup.beforeRun threw",o)]]);return}}}let t=this._deps.map(a=>a.involvedThisWave?a.dataBatch.length>0?[...a.dataBatch]:[]:void 0),s=this._deps.map(a=>a.prevData);for(let a=0;a<this._deps.length;a++){let o=t[a];o!=null&&o.length>0&&(this._deps[a].prevData=o[o.length-1])}let i=this._deps.map(a=>a.terminal),r={prevData:s,terminalDeps:i,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let a={kind:"run",batchData:t,prevData:s};for(let o of this._inspectorHooks)o(a)}this._isExecutingFn=!0;try{let a=this._fn(t,this._actions,r);if(typeof a=="function")this._cleanup=a;else if(a!=null&&typeof a=="object"){let o=a;(typeof o.beforeRun=="function"||typeof o.deactivate=="function"||typeof o.invalidate=="function")&&(this._cleanup=a)}}catch(a){this._emit([[_,this._wrapFnError("fn threw",a)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Ae?(this._rerunDepth=0,this._emit([[_,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Ae} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,t){let s=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${s}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[P,e[0]]:e;let s=!0,i=!1,r=!1,a=-1;for(let d of e){let l=t(d[0]);l<a&&(s=!1),l===3&&(i=!0),d[0]===M&&(r=!0),a=l}let o=e;if(!s){let d=e.map((l,c)=>({m:l,i:c,tier:t(l[0])}));d.sort((l,c)=>l.tier-c.tier||l.i-c.i),o=d.map(l=>l.m)}if(i&&!r&&this._status!=="dirty"){let d=0;for(;d<o.length&&t(o[d][0])===0;)d++;return d===0?[P,...o]:[...o.slice(0,d),P,...o.slice(d)]}return o}_emit(e){if(e.length===0)return;for(let o=0;o<e.length;o++){let d=e[o];if(d[0]===_&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let t=e;if(this._isTerminal&&!this._resubscribable){let o=e.filter(d=>d[0]===k||d[0]===R);if(o.length===0)return;t=o}t=this._frameBatch(t);let i=null;for(let o=0;o<t.length;o++){let d=t[o],l=d[0];if(l!==N&&l!==L){i?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${l===N?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let h=d[1];if(l===N)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(h),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(h))c=!1;else if(this._pauseLocks.delete(h),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?i?.push(d):i==null&&(i=t.slice(0,o))}if(i!=null){if(i.length===0)return;t=i}if(this._hasMeta&&t.some(o=>o[0]===k))for(let o of Object.keys(this.meta))try{this.meta[o]._emit(re)}catch{}let{finalMessages:r,equalsError:a}=this._updateState(t);if(r.length>0&&this._config.inspectorEnabled){let o=this._config.globalInspector;if(o!=null)try{o({kind:"emit",node:this,messages:r})}catch{}}if(r.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let o=this._config.tierOf,d=[];for(let l of r)o(l[0])===3?this._pauseBuffer.push(l):d.push(l);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(r);a!=null&&this._emit([[_,a]])}_updateState(e){let t=this._config.tierOf,s,i,r=-1,a=0;for(let c of e)t(c[0])===3&&a++;let o=a<=1,d=-1;if(this._versioning!=null&&a>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===b){d=c;break}}for(let c=0;c<e.length;c++){let h=e[c],p=h[0];if(p===b){if(h.length>=2){let u=!1;if(o&&this._cached!==void 0)try{u=this._equals(this._cached,h[1])}catch(g){i=this._wrapFnError("equals threw",g),r=c;break}if(u){s==null&&(s=e.slice(0,c)),s.push(he),this._status="resolved";continue}this._cached=h[1],this._versioning!=null&&(d<0||c===d)&&Ne(this._versioning,h[1],this._hashFn)}this._status="settled",s?.push(h)}else if(s?.push(h),p===M)this._status="dirty";else if(p===S)this._status="resolved";else if(p===C){this._status="completed";{let u=this._config.rigorRecorder;if(u!=null)try{u.onTerminalTransition(this,"completed",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===_){this._status="errored";{let u=this._config.rigorRecorder;if(u!=null)try{u.onTerminalTransition(this,"errored",this._autoComplete,this._autoError,this._deps.length>0)}catch{}}}else if(p===R){if(this._cached!==void 0){let g=this._config.rigorRecorder;if(g!=null)try{g.onNonVacuousInvalidate(this,this._cached)}catch{}}this._cached=void 0,this._status="dirty";let u=this._cleanup;if(typeof u=="function"){this._cleanup=void 0;try{u()}catch{}}else if(u!=null&&typeof u=="object"){let g=u.invalidate;if(typeof g=="function")try{g()}catch{}}}else p===k&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let l=r>=0?s??e.slice(0,r):s??e;return i!=null?{finalMessages:l,equalsError:i}:{finalMessages:l}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let s of t)s(e)};_dispatchOrAccumulate(e){if(be()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],ve(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}X(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);X(this._deliverToSinks,t,this._config.tierOf)}},Me=n=>Array.isArray(n),ue=n=>typeof n=="object"&&n!=null&&!Array.isArray(n);function j(n,e,t){let s=Me(n)?n:[],i=typeof n=="function"?n:typeof e=="function"?e:void 0,r={};return Me(n)?r=(ue(e)?e:t)??{}:ue(n)?r=n:r=(ue(e)?e:t)??{},new $(s,i,r)}function bt(n,e){return j([],{...e,initial:n})}function vt(n,e){return j((s,i,r)=>n(i,r)??void 0,{describeKind:"producer",...e})}function Be(n,e,t){return j(n,(i,r,a)=>{let o=i.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);r.emit(e(o,a))},{describeKind:"derived",...t})}function wt(n,e,t){return j(n,(i,r,a)=>{let o=i.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);return e(o,r,a)??void 0},{describeKind:"effect",...t})}function xt(n,e,t){let s=new Map;return n.forEach((i,r)=>{s.set(i,r)}),Be(n,(i,r)=>e(o=>{let d=s.get(o);if(d==null)throw new Error(`dynamicNode: untracked dep "${o.name??"<unnamed>"}"`);return i[d]},r),t)}function Tt(n,e){let t,s=new Map,i=(r,a,o)=>{let d=!1,l=c=>{let h=s.get(c);if(h!==void 0){if(h<r.length){let u=r[h];return u!=null&&u.length>0?u.at(-1):o.prevData[h]}return c.cache}d=!0;let p=t._addDep(c);return s.set(c,p),c.cache};try{let c=n(l,o);d||(a.emit(c),o.store.__autoTrackLastDiscoveryError!=null&&delete o.store.__autoTrackLastDiscoveryError)}catch(c){if(!d)throw c;o.store.__autoTrackLastDiscoveryError=c}};return t=new $([],i,{describeKind:"derived",...e}),t}function Nt(n,...e){let t=n;for(let s of e)t=s(t);return t}export{Ce as a,$e as b,je as c,oe as d,ze as e,qe as f,ye as g,Ke as h,De as i,J as j,me as k,ve as l,Xe as m,X as n,Qe as o,we as p,Z as q,xe as r,F as s,Ge as t,st as u,it as v,de as w,le as x,Ne as y,ot as z,B as A,gt as B,$ as C,j as D,bt as E,vt as F,Be as G,wt as H,xt as I,Tt as J,Nt as K};
|
package/dist/chunk-VE5SIZEM.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as T}from"./chunk-4QH6VJF4.js";import{a as k}from"./chunk-L6NSJVJZ.js";import{b as Y}from"./chunk-LDQ3IUIP.js";import{a as S}from"./chunk-XLQPNNIC.js";import{j as N,l as W}from"./chunk-ACMJ2ZPS.js";import{C as D}from"./chunk-2K5RXLAH.js";import{b as C}from"./chunk-35JTVPOX.js";import{C as Q,E,G as A,m as B,o as R,p as O,u as $,w as J}from"./chunk-LYCLF26R.js";import{b as P}from"./chunk-CK2E7BTU.js";import{b as ne}from"./chunk-QYADASLV.js";var ue={};ne(ue,{AuditTrailGraph:()=>L,GuardedExecutionGraph:()=>V,InspectGraph:()=>M,PolicyGateGraph:()=>j,auditTrail:()=>H,complianceSnapshot:()=>I,computeHealthReport:()=>te,graphLens:()=>z,guardedExecution:()=>de,healthReportEqual:()=>oe,inspect:()=>ce,policyGate:()=>K,watchTopologyTree:()=>S});function ee(o,e){return k("audit",o,e)}var ie=new Set(["data","error","complete","teardown"]),L=class extends N{entries;count;_log;_target;constructor(e,t){super(t.name??`${e.name}_audit`,t.graph),this._target=e,this._log=Y([],{name:"entries",...t.maxSize!=null?{maxSize:t.maxSize}:{}}),this.entries=this._log.entries,this.add(this.entries,{name:"entries"}),this.count=A([this.entries],([s])=>s.length,{name:"count",describeKind:"derived",meta:ee("count")}),this.add(this.count,{name:"count"}),this.addDisposer(D(this.count));let n=t.includeTypes!=null?new Set(t.includeTypes):ie,r=t.filter,i=0,u=e.observe({timeline:!0,structured:!0}),h=u.onEvent(s=>{if(s.type==="derived")return;let d=s.type;if(!n.has(d))return;let y=s.path??"",g={seq:i++,timestamp_ns:s.timestamp_ns??R(),wall_clock_ns:O(),path:y,type:d},b=(y?F(e,y):void 0)?.lastMutation;b!=null&&(g.actor=b.actor),d==="data"&&(g.value=s.data),d==="error"&&(g.error=s.data);let l=y?re(e,y):void 0;l!=null&&(g.annotation=l),!(r!=null&&!r(g))&&this._log.append(g)});this.addDisposer(()=>{h(),u.dispose()}),this.addDisposer(()=>this._log.disposeAllViews())}all(){return this.entries.cache??[]}byNode(e){return this.all().filter(t=>t.path===e)}byActor(e){return this.all().filter(t=>t.actor?.id===e)}byActorType(e){return this.all().filter(t=>t.actor?.type===e)}byTimeRange(e,t){return this.all().filter(n=>!(n.timestamp_ns<e||t!=null&&n.timestamp_ns>=t))}get target(){return this._target}};function H(o,e={}){return new L(o,e)}var j=class extends N{policies;violations;violationCount;_target;_mode;_currentGuard;constructor(e,t,n){super(n.name??`${e.name}_policy`,n.graph),this._target=e,this._mode=n.mode??"audit";let r=X(t)?t:E(t,{name:"policies"});this.policies=r,this.add(this.policies,{name:"policies"}),this.violations=new T("violations",{retainedLimit:n.violationsLimit??1e3}),this.mount("violations",this.violations),this.violationCount=A([this.violations.events],([l])=>l.length,{name:"violationCount",describeKind:"derived",meta:ee("policy_violation_count")}),this.add(this.violationCount,{name:"violationCount"}),this.addDisposer(D(this.violationCount));let u=r.cache??[];this._currentGuard=$(u);let h=r.subscribe(l=>{for(let m of l)m[0]===P&&(u=m[1]??[],this._currentGuard=$(u))});this.addDisposer(h);let s=n.paths,d=X(s)?s:void 0,y=s!=null,G=d!=null?d.cache??[]:y?[...s]:void 0,b=G??Z(e);if(this._mode!=="enforce"&&d!=null){let l=d.subscribe(m=>{for(let a of m)a[0]===P&&(G=a[1]??[])});this.addDisposer(l)}if(this._mode==="enforce"){let l=new Map,m=a=>{if(l.has(a))return;let c=F(e,a);if(!(c instanceof Q))return;let _=(p,f)=>{let w=this._currentGuard(p,f);return w||this._publishViolation(p,f,a,"blocked"),w};l.set(a,c._pushGuard(_))};for(let a of b)m(a);if(d!=null){let a=d.subscribe(c=>{for(let _ of c){if(_[0]!==P)continue;let p=_[1]??[],f=new Set(p),w=new Set(G??[]);B(()=>{for(let v of w){if(f.has(v))continue;let x=l.get(v);x!=null&&(x(),l.delete(v))}for(let v of f)w.has(v)||m(v);G=p})}});this.addDisposer(a)}if(y){let a=e.topology.subscribe(c=>{for(let _ of c){if(_[0]!==P)continue;let p=_[1];if(p.kind!=="removed"||p.nodeKind!=="node")continue;let f=l.get(p.name);f!=null&&(f(),l.delete(p.name))}});this.addDisposer(a)}else{let a=S(e,(c,_,p)=>{if(c.kind==="added")if(c.nodeKind==="node")m(`${p}${c.name}`);else{let f=_._mounts.get(c.name);if(!(f instanceof N))return;let w=`${p}${c.name}::`,v=Z(f);for(let x of v)m(x===""?`${p}${c.name}`:`${w}${x}`)}else if(c.kind==="removed")if(c.nodeKind==="node"){let f=`${p}${c.name}`,w=l.get(f);w!=null&&(w(),l.delete(f))}else{let f=`${p}${c.name}`,w=`${f}::`;for(let[v,x]of l)(v===f||v.startsWith(w))&&(x(),l.delete(v))}});this.addDisposer(a)}this.addDisposer(()=>{for(let a of l.values())a();l.clear()})}else{let l=e.observe({timeline:!0,structured:!0}),m=l.onEvent(a=>{if(a.type!=="data"&&a.type!=="error")return;let c=a.path??"";if(!c||G!=null&&!G.includes(c))return;let _=a.actor??F(e,c)?.lastMutation?.actor;if(_==null)return;let p="write";this._currentGuard(_,p)||this._publishViolation(_,p,c,"observed")});this.addDisposer(()=>{m(),l.dispose()})}}_publishViolation(e,t,n,r){this.violations.publish({timestamp_ns:R(),wall_clock_ns:O(),path:n,actor:e,action:t,mode:this._mode,result:r})}all(){return this.violations.retained()}get mode(){return this._mode}get target(){return this._target}};function K(o,e,t={}){let n=new j(o,e,t);return n.tagFactory("policyGate",C(t)),n}function I(o,e={}){let t={format_version:1,timestamp_ns:R(),wall_clock_ns:O(),graph:o.snapshot()};if(e.actor!=null&&(t.actor=e.actor),e.audit!=null){let r=[...e.audit.all()];t.audit={count:r.length,entries:r}}if(e.policies!=null){let r=e.policies.policies.cache??[];t.policies={mode:e.policies.mode,rules:r,violations:[...e.policies.all()]}}let n=ae(t);return{...t,fingerprint:n}}function X(o){return typeof o=="object"&&o!==null&&"subscribe"in o}function F(o,e){try{return o.node(e)}catch{return}}function re(o,e){try{return o.annotation(e)}catch{return}}function Z(o){let e=o.describe({detail:"minimal"});return Object.keys(e.nodes)}function ae(o){return J(JSON.stringify(se(o)))}function se(o){let e=new Set,t=n=>{if(n===void 0)return{__undefined:!0};if(n===null)return null;let r=typeof n;if(r==="bigint")return{__bigint:n.toString()};if(r!=="object")return n;let i=n;if(e.has(i))return{__circular:!0};e.add(i);try{if(Array.isArray(i))return i.map(t);if(i instanceof Date)return{__date:i.toISOString()};if(i instanceof RegExp)return{__regexp:{source:i.source,flags:i.flags}};if(i instanceof Map)return{__map:[...i.entries()].map(([s,d])=>[t(s),t(d)])};if(i instanceof Set)return{__set:[...i].map(t)};if(ArrayBuffer.isView(i)){let h=i,s=new Array(h.length);for(let d=0;d<h.length;d++)s[d]=h[d]??0;return{__typed_array:{ctor:i.constructor.name,data:s}}}let u={};for(let h of Object.keys(i).sort())u[h]=t(i[h]);return u}finally{e.delete(i)}};return t(o)}function q(o){return typeof o=="object"&&o!==null&&"subscribe"in o&&"down"in o}function le(o){return k("guarded",o)}var V=class extends N{enforcer;violations;lints;scope;scopedDescribe;_target;_actorNode;_mode;_firedLintKinds=new Set;constructor(e,t){super(t.name??`${e.name}_guarded`,t.graph),this._target=e,this._mode=t.mode??"enforce";let n=t.policies,r=q(n);if(!r&&this._mode==="enforce"&&n.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 T("lints",{retainedLimit:t.lintsLimit??64}),this.mount("lints",this.lints);let i=t.actor;i==null?this._actorNode=E(null,{name:"actor"}):q(i)?this._actorNode=A([i],([s])=>s??null,{name:"actor",initial:null}):this._actorNode=E(i,{name:"actor"});let u={mode:this._mode,name:"enforcer"};if(t.violationsLimit!=null&&(u.violationsLimit=t.violationsLimit),this.enforcer=K(e,t.policies,u),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer),r&&this._mode==="enforce"){let s=n,d=s.cache;d!=null&&d.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 y=s.subscribe(g=>{for(let G of g){if(G[0]!==P)continue;let b=G[1];(b==null||b.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(y)}if(this._mode==="audit"){let s=e.describe({detail:"full"});Object.values(s.nodes).some(y=>y.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.')}i==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],([s,d])=>({actor:s??null,mode:this._mode,policiesCount:d.length}),{name:"scope",describeKind:"derived",meta:le("scope")}),this.add(this.scope,{name:"scope"}),this.addDisposer(D(this.scope));let h=e.describe({reactive:!0,actor:this._actorNode,reactiveName:"scopedDescribe"});this.scopedDescribe=h.node,this.add(this.scopedDescribe,{name:"scopedDescribe"}),this.addDisposer(h.dispose)}_fireLint(e,t){this._firedLintKinds.has(e)||(this._firedLintKinds.add(e),this.lints.publish({kind:e,message:t,timestamp_ns:R()}))}scopedDescribeNode(e,t){let n=e==null?this._actorNode:q(e)?e:E(e,{name:"actor_override"}),r=this._target.describe({reactive:!0,actor:n,...t??{}});return this.addDisposer(r.dispose),{node:r.node,dispose:r.dispose}}get target(){return this._target}};function de(o,e){return new V(o,e)}function te(o){let e=[];for(let[t,n]of Object.entries(o.nodes)){if(n.status!=="errored")continue;let r={path:t,status:"errored"},i=W(o,t,"upstream",{});for(let u of i)if(u!==t&&o.nodes[u]?.status==="errored"){r.upstreamCause=u;break}e.push(r)}return e.sort((t,n)=>t.path<n.path?-1:t.path>n.path?1:0),{ok:e.length===0,problems:e}}function oe(o,e){if(o.ok!==e.ok||o.problems.length!==e.problems.length)return!1;for(let t=0;t<o.problems.length;t++){let n=o.problems[t],r=e.problems[t];if(n.path!==r.path||n.status!==r.status||n.upstreamCause!==r.upstreamCause)return!1}return!0}function z(o){let e=o.describe({reactive:!0,detail:"standard",reactiveName:"graphLens.topology"}),t=e.node,n=A([t],([g])=>te(g),{name:"graphLens.health",describeKind:"derived",equals:oe,meta:k("lens","health")}),r=D(n),i=new Map,u=-1,h=o.observe({reactive:!0,tiers:["data"]}),s=A([h,t],([g,G])=>{let b=g,l=G;if(b!=null&&b.flushedAt_ns>u){u=b.flushedAt_ns;for(let m of b.events){if(m.type!=="data")continue;let a=m.path;if(a==null||a==="")continue;let c=i.get(a);i.set(a,{path:a,count:(c?.count??0)+1,lastUpdate_ns:b.flushedAt_ns})}}if(l!=null&&i.size>0){let m=new Set(Object.keys(l.nodes));for(let a of[...i.keys()])m.has(a)||i.delete(a)}return new Map(i)},{name:"graphLens.flow",describeKind:"derived",meta:k("lens","flow")}),d=D(s),y=!1;return{topology:t,health:n,flow:s,dispose(){y||(y=!0,d(),r(),e.dispose())}}}var U=class extends N{view;constructor(e){super("lens"),this.view=z(e),this.add(this.view.topology,{name:"topology"}),this.add(this.view.health,{name:"health"}),this.add(this.view.flow,{name:"flow"})}},M=class extends N{target;lens;audit;_defaultActor;_lensSubgraph;constructor(e,t={}){super(t.name??`inspect(${e.name})`),this.target=e,this._defaultActor=t.actor,this._lensSubgraph=new U(e),this.lens=this._lensSubgraph.view,this.mount("lens",this._lensSubgraph),this.audit=H(e,t.audit??{}),this.mount("audit",this.audit),this.addDisposer(()=>this.lens.dispose())}explainTarget(e,t,n){return this.target.explain(e,t,n)}complianceSnapshot(e){let t=e?.actor??this._defaultActor;return I(this.target,{audit:this.audit,...t!=null?{actor:t}:{},...e?.policies!=null?{policies:e.policies}:{}})}};function ce(o,e={}){let t=new M(o,e);return t.tagFactory("inspect",C(e)),t}export{L as a,H as b,j as c,K as d,I as e,V as f,de as g,te as h,oe as i,z as j,M as k,ce as l,ue as m};
|