@graphrefly/graphrefly 0.41.0 → 0.43.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-Cxs1eztH.d.cts → cascading-CH-_VwG9.d.cts} +2 -2
- package/dist/{cascading-BNfxffgc.d.ts → cascading-OgKQZjsa.d.ts} +2 -2
- package/dist/chunk-3XDYJRYU.js +1 -0
- package/dist/{chunk-AI7QC7J6.js → chunk-4YAN45KM.js} +1 -1
- package/dist/chunk-626TESAC.js +3 -0
- package/dist/chunk-6HOSXQKF.js +1 -0
- package/dist/{chunk-G3M3IMEV.js → chunk-CUNIRONA.js} +1 -1
- package/dist/chunk-EBW4V6JN.js +1 -0
- package/dist/chunk-FDQGFWLF.js +1 -0
- package/dist/{chunk-33N4TU3X.js → chunk-FG4TKHMC.js} +1 -1
- package/dist/{chunk-YQRN4CIV.js → chunk-I7IGYPSL.js} +1 -1
- package/dist/chunk-INQD2KRQ.js +1 -0
- package/dist/{chunk-7PQLZMOG.js → chunk-JNWRYDJN.js} +1 -1
- package/dist/{chunk-TT4C7DXW.js → chunk-JQFH2DV6.js} +1 -1
- package/dist/{chunk-M3FQSXEW.js → chunk-K2Q24F5T.js} +1 -1
- package/dist/chunk-KVV66NN2.js +1 -0
- package/dist/chunk-NON4NLIC.js +45 -0
- package/dist/{chunk-CYOSWFT2.js → chunk-O2BLLH7M.js} +3 -3
- package/dist/{chunk-OV5AA6HJ.js → chunk-OCKEEPRJ.js} +1 -1
- package/dist/{chunk-X7QKTXXC.js → chunk-OFZG3TB3.js} +3 -3
- package/dist/chunk-OYJKFY7V.js +1 -0
- package/dist/{chunk-SC27WTSG.js → chunk-P6C4WHZO.js} +1 -1
- package/dist/{chunk-VV62MIG4.js → chunk-PT7W5FCD.js} +1 -1
- package/dist/{chunk-UISPDFJ3.js → chunk-Q4U3A3L5.js} +1 -1
- package/dist/chunk-QE4IGY7I.js +61 -0
- package/dist/{chunk-5VEZLQFN.js → chunk-QYVXF7GW.js} +1 -1
- package/dist/{chunk-ZAJ7J7TO.js → chunk-S3EEIPO7.js} +1 -1
- package/dist/{chunk-GI4Q7PNY.js → chunk-SUWT3ZON.js} +1 -1
- package/dist/{chunk-CGNOWGV6.js → chunk-TPKQW72B.js} +1 -1
- package/dist/{chunk-L77I47VU.js → chunk-V5A7M7RJ.js} +1 -1
- package/dist/chunk-VNC3TMVY.js +1 -0
- package/dist/{chunk-AK5RHMC5.js → chunk-VOPGGIL7.js} +1 -1
- package/dist/chunk-VQ4A6T2A.js +1 -0
- package/dist/{chunk-KNVCCBIU.js → chunk-XG62INFA.js} +1 -1
- package/dist/{chunk-F7VUYPP6.js → chunk-Y4NI3X7O.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.d.cts +2 -2
- package/dist/compat/jotai/index.d.ts +2 -2
- package/dist/compat/nanostores/index.d.cts +2 -2
- package/dist/compat/nanostores/index.d.ts +2 -2
- package/dist/compat/nestjs/index.cjs +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.d.cts +4 -4
- package/dist/core/index.d.ts +4 -4
- package/dist/{decay-C25AyNAj.d.cts → decay-2ZukgQ4o.d.cts} +2 -2
- package/dist/{decay-BnrlbxSv.d.ts → decay-CdEBmDIs.d.ts} +2 -2
- package/dist/extra/browser.d.cts +1 -1
- package/dist/extra/browser.d.ts +1 -1
- package/dist/extra/index.cjs +14 -14
- package/dist/extra/index.d.cts +10 -11
- package/dist/extra/index.d.ts +10 -11
- package/dist/extra/index.js +1 -1
- package/dist/extra/node.cjs +2 -2
- package/dist/extra/node.d.cts +1 -1
- package/dist/extra/node.d.ts +1 -1
- package/dist/extra/node.js +1 -1
- package/dist/extra/operators.cjs +1 -1
- package/dist/extra/operators.d.cts +1 -1
- package/dist/extra/operators.d.ts +1 -1
- package/dist/extra/operators.js +1 -1
- package/dist/extra/reactive.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 -1
- package/dist/extra/sources.d.cts +1 -1
- package/dist/extra/sources.d.ts +1 -1
- package/dist/extra/sources.js +1 -1
- package/dist/extra/storage-browser.d.cts +1 -1
- package/dist/extra/storage-browser.d.ts +1 -1
- package/dist/{fallback-CMZl39L5.d.ts → fallback-CqYVLL6X.d.ts} +1 -1
- package/dist/{fallback-8JYU8tlT.d.cts → fallback-Ctlj2tMY.d.cts} +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-BkIkog4h.d.ts → graph-7VguS7a4.d.ts} +3 -3
- package/dist/{graph-E6likq7w.d.cts → graph-C4SHb3Ly.d.cts} +3 -3
- package/dist/{index-DgJc8Zgc.d.cts → index-0rKFCVFp.d.cts} +90 -5
- package/dist/{index-BAQrjuZF.d.ts → index-B-i4_g3k.d.ts} +2 -2
- package/dist/{index-DpiGqtrs.d.cts → index-B5iz82A3.d.cts} +441 -381
- package/dist/{index-Bd91Nmf4.d.cts → index-BAOD98JD.d.cts} +4 -4
- package/dist/{index-2n8Eai6M.d.ts → index-BG0BN3PB.d.ts} +1 -1
- package/dist/{index-z8WFPVI8.d.cts → index-BJX94aud.d.cts} +1 -1
- package/dist/{index-DhLyOHYZ.d.ts → index-BP8a88zx.d.ts} +11 -4
- package/dist/{index-Cnr1WrlX.d.cts → index-BTQtTb_H.d.cts} +14 -3
- package/dist/{index-DOBLxOti.d.cts → index-BVpm6noz.d.cts} +1 -1
- package/dist/{index-Cczxgd2D.d.ts → index-Bc41FuHp.d.cts} +3 -3
- package/dist/{index-BiHUBEKq.d.cts → index-BdGtBX-X.d.cts} +3 -3
- package/dist/{index-da2V5vPy.d.ts → index-Bf7eqeSF.d.ts} +2 -2
- package/dist/{index-DuRsN9ae.d.cts → index-BiX1Nkgx.d.cts} +383 -18
- package/dist/{index-DGTo1yka.d.cts → index-BoLv_OfD.d.cts} +2 -2
- package/dist/{index-DVAlsmEU.d.cts → index-BojK2fwH.d.cts} +3 -3
- package/dist/{index-B72TQQHd.d.cts → index-BsT7F2et.d.ts} +3 -3
- package/dist/{index-DGD4_fj6.d.cts → index-BwLvVVsy.d.cts} +8 -5
- package/dist/{index-CQtWm7jS.d.ts → index-C59mYFKp.d.ts} +9 -9
- package/dist/{index-C6ZUaos7.d.ts → index-C7O6r5fV.d.ts} +1 -1
- package/dist/{index-CL7oilfm.d.cts → index-C9kSENB4.d.cts} +1 -1
- package/dist/{index-DVDapw2k.d.cts → index-C9pjcz3l.d.cts} +35 -36
- package/dist/{index-CG33HeBW.d.ts → index-CAC_rNzm.d.ts} +8 -5
- package/dist/{index-yLt-aPMp.d.ts → index-CCq87F7t.d.ts} +1 -1
- package/dist/{index-D4uimgee.d.cts → index-CDXc9zKM.d.cts} +1 -1
- package/dist/{index-B2RUoIUz.d.ts → index-CJK1JkYy.d.ts} +1 -1
- package/dist/{index-DktLSZOc.d.cts → index-CLon-IWF.d.cts} +4 -4
- package/dist/{index-DQQCOIt8.d.cts → index-COD1kVoS.d.cts} +10 -5
- package/dist/{index-bXXLSvor.d.ts → index-CPT7C_f1.d.ts} +4 -4
- package/dist/{index-CD2dBMet.d.ts → index-CQG3D1cp.d.ts} +10 -5
- package/dist/{index-BQ1fR4li.d.ts → index-CZQXo5tH.d.ts} +35 -36
- package/dist/{index-A3U3CSve.d.cts → index-CZjOhcBy.d.cts} +2 -2
- package/dist/{index-DYTBbF8T.d.cts → index-ChOyVLKm.d.cts} +1 -1
- package/dist/{index-BJSZxSFX.d.ts → index-CvrqGfNS.d.ts} +1 -1
- package/dist/{index-DhnsQfa3.d.ts → index-D-AEQVLo.d.ts} +441 -381
- package/dist/{index-CAP3UGsq.d.ts → index-D4Y1cMG0.d.ts} +1 -1
- package/dist/{index-40ZT4MHj.d.ts → index-DBHK8O6H.d.ts} +14 -3
- package/dist/{index-3k4Gg6-n.d.ts → index-DBevwHj_.d.ts} +3 -3
- package/dist/{index-Ctb7_2sG.d.ts → index-DIOoAZUX.d.ts} +1 -1
- package/dist/{index-WSlcjhQF.d.ts → index-DSZ3ZCHF.d.ts} +124 -13
- package/dist/{index-DH4fm2Ck.d.ts → index-Dgs8zcj7.d.ts} +2 -2
- package/dist/{index-BaA-xpSw.d.ts → index-Dh_HJ82K.d.ts} +3 -3
- package/dist/{index-CtFNGe-m.d.cts → index-Dhc7a7Xo.d.cts} +2 -2
- package/dist/{index-CoM4rzyB.d.ts → index-Dmqp7KjD.d.ts} +1 -1
- package/dist/{index-B6iTqKtJ.d.ts → index-Dn-wI9g4.d.ts} +2 -2
- package/dist/{index-C-dkXOpB.d.cts → index-Du7u1lSf.d.cts} +11 -4
- package/dist/{index-DfOK_oL5.d.ts → index-DwigL4lY.d.ts} +383 -18
- package/dist/index-DyR7eU5S.d.cts +779 -0
- package/dist/index-JZUPJIJy.d.ts +779 -0
- package/dist/{index-I1cCY3ZI.d.ts → index-K0_0eR8g.d.ts} +90 -5
- package/dist/{index-BilOa6AE.d.cts → index-O16yXPK4.d.cts} +124 -13
- package/dist/{index-CRm0YIzC.d.cts → index-O7fucFrU.d.cts} +9 -9
- package/dist/{index-MxYuWOrf.d.cts → index-RV_yDjOX.d.cts} +3 -3
- package/dist/{index-C5cQ7Gfx.d.ts → index-cm1GNcWE.d.ts} +4 -4
- package/dist/{index-CgnCFhr2.d.cts → index-f5IivDUX.d.cts} +1 -1
- package/dist/{index-PgwvGWa1.d.cts → index-hHcaFlJX.d.cts} +1 -1
- package/dist/{index-tV3AA9hI.d.cts → index-tJoTcnHh.d.cts} +2 -2
- package/dist/{index-eaQuGJnv.d.ts → index-wAzD9yVj.d.ts} +3 -3
- package/dist/{index-D3ayz3hy.d.cts → index-z96luz5O.d.cts} +1 -1
- package/dist/index.cjs +48 -48
- package/dist/index.d.cts +45 -50
- package/dist/index.d.ts +45 -50
- package/dist/index.js +1 -1
- package/dist/{meta-D8OyedKp.d.ts → meta-BgVAsg9j.d.ts} +1 -1
- package/dist/{meta-Ct9nqQS5.d.cts → meta-vE8bxW1E.d.cts} +1 -1
- package/dist/{node-BYInONRr.d.cts → node-ClS5yC-B.d.cts} +1 -1
- package/dist/{node-BYInONRr.d.ts → node-ClS5yC-B.d.ts} +1 -1
- package/dist/{observable-DO8DDEzv.d.ts → observable-BsBzUrcI.d.ts} +1 -1
- package/dist/{observable-DMIlYJV1.d.cts → observable-DLGPPtb8.d.cts} +1 -1
- 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 +17 -17
- package/dist/patterns/ai/index.d.cts +17 -17
- package/dist/patterns/ai/index.d.ts +17 -17
- package/dist/patterns/ai/index.js +1 -1
- package/dist/patterns/ai/node.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 +12 -12
- 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 +10 -8
- package/dist/patterns/harness/index.d.cts +11 -12
- package/dist/patterns/harness/index.d.ts +11 -12
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/inspect/index.cjs +3 -0
- package/dist/patterns/inspect/index.d.cts +9 -0
- package/dist/patterns/inspect/index.d.ts +9 -0
- package/dist/patterns/inspect/index.js +1 -0
- 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 +7 -7
- package/dist/patterns/orchestration/index.d.ts +7 -7
- package/dist/patterns/orchestration/index.js +1 -1
- package/dist/patterns/process/index.cjs +1 -1
- package/dist/patterns/process/index.d.cts +7 -7
- package/dist/patterns/process/index.d.ts +7 -7
- package/dist/patterns/process/index.js +1 -1
- package/dist/patterns/reactive-layout/index.cjs +4 -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 +8 -8
- 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-MWrQZXCq.d.cts → pipeline-graph-DPqKDk59.d.cts} +5 -5
- package/dist/{pipeline-graph-CB4La-UW.d.ts → pipeline-graph-loP57TBA.d.ts} +5 -5
- package/dist/{reactive-layout-BtZfUKuL.d.cts → reactive-layout-Dsvob4zD.d.cts} +2 -2
- package/dist/{reactive-layout-KJj4E2dT.d.ts → reactive-layout-v7KPvxoc.d.ts} +2 -2
- package/dist/{reactive-log-_zeEnB9H.d.cts → reactive-log-B00laMSQ.d.cts} +1 -1
- package/dist/{reactive-log-BlAsPLl2.d.ts → reactive-log-BezYsbA_.d.ts} +1 -1
- package/dist/{reactive-map-6P_k3AQM.d.cts → reactive-map-48mnZ-nu.d.cts} +1 -1
- package/dist/{reactive-map-CjXByDV-.d.ts → reactive-map-BVVPdvmi.d.ts} +1 -1
- package/dist/resilience-YIWPK4YC.js +1 -0
- package/dist/{sugar-DzePN5-g.d.cts → sugar-DLwvMr3F.d.ts} +24 -4
- package/dist/{sugar-BhfjgetH.d.ts → sugar-DyVGtczU.d.cts} +24 -4
- package/dist/{topology-tree-mF7Emqzm.d.ts → topology-tree-BNGvuG82.d.ts} +1 -1
- package/dist/{topology-tree-3LBKFsUo.d.cts → topology-tree-BSdfSwMi.d.cts} +1 -1
- package/dist/{types-1Dhoi7HM.d.cts → types-B1jDWVsM.d.cts} +1 -1
- package/dist/{types-39jk0kaV.d.ts → types-DkzUUs0H.d.ts} +1 -1
- package/package.json +11 -51
- package/dist/budget-gate-CmmVtasH.d.ts +0 -115
- package/dist/budget-gate-DiP_nK0n.d.cts +0 -115
- package/dist/chunk-2W553JJC.js +0 -1
- package/dist/chunk-4MKL6Q3K.js +0 -1
- package/dist/chunk-5B3JDG5F.js +0 -1
- package/dist/chunk-5QSXEMXG.js +0 -1
- package/dist/chunk-5TEFC2ZX.js +0 -1
- package/dist/chunk-5TOPVRN6.js +0 -1
- package/dist/chunk-EC2WNSZ7.js +0 -1
- package/dist/chunk-ELAASRBT.js +0 -3
- package/dist/chunk-H5SCWHWP.js +0 -1
- package/dist/chunk-OLIKJUKI.js +0 -1
- package/dist/chunk-POXANAJ6.js +0 -3
- package/dist/chunk-RSMEXK53.js +0 -43
- package/dist/chunk-SGS4OJGS.js +0 -1
- package/dist/chunk-URJ2VFNC.js +0 -1
- package/dist/chunk-VXPLLA4P.js +0 -1
- package/dist/chunk-WZYB3JQS.js +0 -1
- package/dist/chunk-Z6X7B6A4.js +0 -61
- package/dist/index-8s-Qm-gz.d.ts +0 -218
- package/dist/index-BgjS2b8N.d.ts +0 -366
- package/dist/index-BmSQLAZo.d.cts +0 -244
- package/dist/index-CGhMJNHb.d.cts +0 -128
- package/dist/index-CUIkE1l9.d.cts +0 -230
- package/dist/index-Ck35nA-T.d.ts +0 -244
- package/dist/index-CuPUehFa.d.cts +0 -218
- package/dist/index-D1Gc7wV5.d.ts +0 -230
- package/dist/index-N2MAxt7_.d.ts +0 -128
- package/dist/index-t6L2qpHh.d.cts +0 -366
- package/dist/patterns/audit/index.cjs +0 -3
- package/dist/patterns/audit/index.d.cts +0 -8
- package/dist/patterns/audit/index.d.ts +0 -8
- package/dist/patterns/audit/index.js +0 -1
- package/dist/patterns/guarded-execution/index.cjs +0 -3
- package/dist/patterns/guarded-execution/index.d.cts +0 -9
- package/dist/patterns/guarded-execution/index.d.ts +0 -9
- package/dist/patterns/guarded-execution/index.js +0 -1
- package/dist/patterns/lens/index.cjs +0 -3
- package/dist/patterns/lens/index.d.cts +0 -7
- package/dist/patterns/lens/index.d.ts +0 -7
- package/dist/patterns/lens/index.js +0 -1
- package/dist/patterns/refine-loop/index.cjs +0 -5
- package/dist/patterns/refine-loop/index.d.cts +0 -9
- package/dist/patterns/refine-loop/index.d.ts +0 -9
- package/dist/patterns/refine-loop/index.js +0 -1
- package/dist/patterns/resilient-pipeline/index.cjs +0 -3
- package/dist/patterns/resilient-pipeline/index.d.cts +0 -8
- package/dist/patterns/resilient-pipeline/index.d.ts +0 -8
- package/dist/patterns/resilient-pipeline/index.js +0 -1
- package/dist/resilience-JISHQD2F.js +0 -1
package/dist/chunk-H5SCWHWP.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as M,h as oe,i as ae}from"./chunk-VXPLLA4P.js";import{a as ne}from"./chunk-L6NSJVJZ.js";import{b as J}from"./chunk-TT4C7DXW.js";import{i as se}from"./chunk-POXANAJ6.js";import{C as z}from"./chunk-L77I47VU.js";import{b as re}from"./chunk-35JTVPOX.js";import{D as ee,E as te,G as j,m as Y,p as R,t as D}from"./chunk-LYCLF26R.js";import{b as X}from"./chunk-CK2E7BTU.js";import{b as ce}from"./chunk-QYADASLV.js";var me={};ce(me,{CqrsGraph:()=>G,cqrs:()=>fe,cqrsEventKeyOf:()=>pe,dispatchKeyOf:()=>he,sagaInvocationKeyOf:()=>ve});var k=class extends Error{constructor(e,n){super(e,n),this.name=this.constructor.name}},B=class extends k{constructor(n,t){super(`Duplicate ${n} registration: "${t}"`);this.kind=n;this.registrationName=t}},N=class extends k{constructor(n,t,r){super(`Command "${n}" emitted undeclared event "${t}". Declared emits: [${r.join(", ")}]`);this.commandName=n;this.eventName=t;this.declaredEmits=r}},K=class extends k{constructor(n,t,r){super(`Optimistic concurrency conflict on aggregate "${n}": expected version ${t}, got ${r}`);this.aggregateId=n;this.expected=t;this.actual=r}},H=class extends k{constructor(n){super(`Unknown command: "${n}". Register with command() first.`);this.commandName=n}},O=class extends k{constructor(n,t){super(`Command handler "${n}" threw: ${t instanceof Error?t.message:String(t)}`,{cause:t});this.commandName=n}};var P=class extends k{constructor(n,t){super(`Projection "${n}" rebuild failed: ${t instanceof Error?t.message:String(t)}`,{cause:t});this.projectionName=n}};var le=D((o,e)=>{o("write"),o("signal"),e("observe")}),ue=D((o,e)=>{o("observe"),o("signal"),e("write")}),ie=D((o,e)=>{o("observe"),o("signal"),e("write")});function $(o,e){return ne("cqrs",o,e)}function Z(o){if(o===null||typeof o!="object"||Object.isFrozen(o))return o;for(let e of Object.keys(o))Z(o[e]);return Object.freeze(o)}var pe=o=>`${o.type}::${o.aggregateId??"__default__"}`,he=o=>o.commandName,ve=o=>o.eventType,G=class extends se{_eventLogs=new Map;_eventLogsByAggregate=new Map;_aggregateVersions=new Map;_aggregateLru=new Map;_commandRegs=new Map;_projections=new Set;_sagas=new Set;_keepaliveDisposers=[];_seq=0;_retainedLimit;_freezeCommandPayload;_freezeEventPayload;_maxAggregates;_dispatchSeqCursor;dispatches;audit;aggregateEvictions;constructor(e,n={}){super(e,n.graph),this._retainedLimit=n.retainedLimit??1024,this._freezeCommandPayload=n.freezeCommandPayload??!0,this._freezeEventPayload=n.freezeEventPayload??!0,this._maxAggregates=n.maxAggregates??1e4,this.dispatches=M({name:"dispatches",retainedLimit:this._retainedLimit,graph:this}),this.audit=this.dispatches,this.aggregateEvictions=M({name:"aggregateEvictions",retainedLimit:this._retainedLimit,graph:this}),this._dispatchSeqCursor=oe(this,"dispatch_seq",0)}aggregateVersion(e,n){return this._aggregateVersions.get(`${e}::${n}`)??0}_touchAggregate(e){this._aggregateLru.delete(e),this._aggregateLru.set(e,!0)}_enforceAggregateLru(){for(;this._aggregateLru.size>this._maxAggregates;){let e=this._aggregateLru.keys().next();if(e.done)break;let n=e.value;this._aggregateLru.delete(n);let t=n.indexOf("::");if(t<0)continue;let r=n.slice(0,t),s=n.slice(t+2),a=this._aggregateVersions.get(n)??0;this._aggregateVersions.delete(n);let i=this._eventLogsByAggregate.get(r);i&&(i.delete(s),i.size===0&&this._eventLogsByAggregate.delete(r)),this.aggregateEvictions.append({aggregateId:s,type:r,lastVersion:a,t_ns:R()})}}destroy(){for(let e of this._keepaliveDisposers)e();this._keepaliveDisposers.length=0,super.destroy()}_attachedEventTiers=[];_attachedTierDisposers=new Map;attachEventStorage(e){this._attachedEventTiers.push(e);for(let[n,t]of this._eventLogs){let r=t.log.attachStorage(e),s=this._attachedTierDisposers.get(n);s||(s=[],this._attachedTierDisposers.set(n,s)),s.push(r)}for(let[n,t]of this._eventLogsByAggregate)for(let[r,s]of t){let a=`${n}::${r}`,i=s.log.attachStorage(e),c=this._attachedTierDisposers.get(a);c||(c=[],this._attachedTierDisposers.set(a,c)),c.push(i)}return()=>{let n=this._attachedEventTiers.indexOf(e);n>=0&&this._attachedEventTiers.splice(n,1)}}_autoWireStreamStorage(e,n){if(this._attachedEventTiers.length===0)return;let t=this._attachedTierDisposers.get(e);t||(t=[],this._attachedTierDisposers.set(e,t));for(let r of this._attachedEventTiers)t.push(n.attachStorage(r))}_bumpDispatchSeq(){let n=(this._dispatchSeqCursor.cache??0)+1;return this._dispatchSeqCursor.emit(n),n}event(e,n){if(n!==void 0)return this._ensureAggregateStream(e,n).node;let t=this._eventLogs.get(e);if(t)return t.node;let r=J([],{name:e,versioning:0,maxSize:this._retainedLimit});r.withLatest();let s=r.entries,a=j([s],([i])=>i,{name:e,describeKind:"state",meta:$("event",{event_name:e}),guard:ie,initial:s.cache});return this.add(a,{name:e}),this._keepaliveDisposers.push(z(a)),this._eventLogs.set(e,{log:r,node:a}),this._autoWireStreamStorage(e,r),a}_ensureAggregateStream(e,n){this._eventLogs.has(e)||this.event(e);let t=this._eventLogsByAggregate.get(e);t||(t=new Map,this._eventLogsByAggregate.set(e,t));let r=`${e}::${n}`;this._touchAggregate(r);let s=t.get(n);if(s)return s;let a=`${e}_${n.replace(/[^a-zA-Z0-9_-]/g,"_")}`,i=J([],{name:a,versioning:0,maxSize:this._retainedLimit});i.withLatest();let c=i.entries,h=j([c],([p])=>p,{name:a,describeKind:"state",meta:$("event_aggregate",{event_name:e,aggregate_id:n}),guard:ie,initial:c.cache}),l=a,m=0;for(;this.nameOf(this.resolveOptional(l)??h)===l&&(m+=1,l=`${a}_${m}`,this.resolveOptional(l)!==void 0););try{this.add(h,{name:l})}catch{}this._keepaliveDisposers.push(z(h));let u={log:i,node:h};return t.set(n,u),this._autoWireStreamStorage(`${e}::${n}`,i),this._enforceAggregateLru(),u}resolveOptional(e){try{return this.resolve(e)}catch{return}}_appendEvent(e,n,t){let r=this._eventLogs.get(e);if(r||(this.event(e),r=this._eventLogs.get(e)),r.node.status==="completed"||r.node.status==="errored")throw new Error(`Cannot dispatch to terminated event stream "${e}" (status: ${r.node.status}).`);let s,a;if(t?.aggregateId!==void 0){let l=`${e}::${t.aggregateId}`;s=(this._aggregateVersions.get(l)??0)+1,this._aggregateVersions.set(l,s),a=this._ensureAggregateStream(e,t.aggregateId)}let i=r.log.entries.v,c=this._freezeEventPayload?Z(n):n,h={type:e,payload:c,timestampNs:R(),seq:++this._seq,...t?.aggregateId!==void 0?{aggregateId:t.aggregateId}:{},...s!==void 0?{aggregateVersion:s}:{},...t?.correlationId!==void 0?{correlationId:t.correlationId}:{},...t?.causationId!==void 0?{causationId:t.causationId}:{},...t?.metadata!==void 0?{metadata:Object.freeze({...t.metadata})}:{},...t?.handlerVersion!==void 0?{handlerVersion:t.handlerVersion}:{},...i!=null?{v0:{id:i.id,version:i.version}}:{}};return r.log.append(h),a&&a.log.append(h),h}command(e,n){if(this._commandRegs.has(e))throw new B("command",e);let t=typeof n=="function"?{handler:n}:n,r=te(void 0,{name:e,describeKind:"state",meta:{...$("command",{command_name:e}),error:null},guard:le});if(this.add(r,{name:e}),this._commandRegs.set(e,{handler:t.handler,...t.emits!==void 0?{emits:t.emits}:{},...t.handlerVersion!==void 0?{handlerVersion:t.handlerVersion}:{}}),t.emits)for(let s of t.emits)this._eventLogs.has(s)||this.event(s);return r}dispatch(e,n,t){let r=this._commandRegs.get(e);if(!r)throw new H(e);if(t?.aggregateId!==void 0&&t.expectedAggregateVersion!==void 0&&r.emits!==void 0){let u=0;for(let p of r.emits){let _=this._aggregateVersions.get(`${p}::${t.aggregateId}`);_!==void 0&&_>u&&(u=_)}if(u!==t.expectedAggregateVersion)throw new K(t.aggregateId,t.expectedAggregateVersion,u)}let s=this.resolve(e),a=this._freezeCommandPayload?Z(n):n,i=[],c=R(),h=0,l,m=!1;try{Y(()=>{h=this._bumpDispatchSeq(),s.emit(a,{internal:!0});try{r.handler(a,{emit:(u,p)=>{if(r.emits!==void 0&&!r.emits.includes(u))throw new N(e,u,r.emits);i.push(u),this._appendEvent(u,p,{...t?.aggregateId!==void 0?{aggregateId:t.aggregateId}:{},...t?.correlationId!==void 0?{correlationId:t.correlationId}:{},...t?.causationId!==void 0?{causationId:t.causationId}:{},...t?.metadata!==void 0?{metadata:Object.freeze({...t.metadata})}:{},...r.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{}})}}),s.meta.error.emit(null,{internal:!0}),this.dispatches.append({commandName:e,payload:a,outcome:"success",emittedEvents:[...i],t_ns:c,seq:h,...r.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{}})}catch(u){throw l=u,m=!0,u}})}catch(u){if(m){s.meta.error.emit(l,{internal:!0});let p=l instanceof Error?l.name:typeof l,_=l instanceof O?l:new O(e,l);this.dispatches.append({commandName:e,payload:a,outcome:"failure",error:_,errorType:p,emittedEvents:[...i],t_ns:c,seq:h,...r.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{}})}throw m?l:u}}projection(e){let{name:n,events:t,reducer:r,initial:s}=e,a=e.mode??"scan",i=e.freezeInputs??!0,c=e.snapshot,h=t.map(d=>(this._eventLogs.has(d)||this.event(d),this._eventLogs.get(d).node));function l(d){d.sort((g,v)=>g.timestampNs-v.timestampNs||g.seq-v.seq||(g.aggregateId??"").localeCompare(v.aggregateId??""))}function m(d){let g=[];for(let v of d)g.push(...v);return l(g),g}let u=h.map(d=>d.cache??[]),p=m(u),_=i?Object.freeze(p):p,C=0,y=s;a==="scan"&&p.length>0&&(y=r(s,_),C=p.length);let q=a==="replay"?r(s,_):y,V=c?.saveDebounceMs??1e3,A=c?.saveEvery??1e3,E,L=0;function F(d){if(c?.save){if(L+=1,L>=A){L=0,E!==void 0&&(clearTimeout(E),E=void 0);let g=c.save(d);g instanceof Promise&&g.catch(()=>{});return}E!==void 0&&clearTimeout(E),E=setTimeout(()=>{E=void 0,L=0;let g=c.save(d);g instanceof Promise&&g.catch(()=>{})},V)}}let S=j(h,d=>{let g=m(d),v;if(a==="replay"){let w=i?Object.freeze(g):g;v=r(s,w)}else{let w=g.slice(C);C=g.length;let f=i?Object.freeze(w):w;v=r(y,f),y=v}return F(v),v},{name:n,describeKind:"derived",meta:$("projection",{projection_name:n,source_events:t}),guard:ue,initial:q});return this.add(S,{name:n}),this._keepaliveDisposers.push(z(S)),this._keepaliveDisposers.push(()=>{E!==void 0&&(clearTimeout(E),E=void 0)}),this._projections.add(n),{node:S,rebuild:async d=>{try{let g=d?.pageSize??1e3,v=d?.fromTier??this._attachedEventTiers[0]?.[0],w=m(h.map(T=>T.cache??[])).length,f=s;if(c?.load){let T=await c.load();T!==void 0&&(f=T)}if(!v||!v.loadEntries){let T=m(h.map(I=>I.cache??[])),b=i?Object.freeze(T):T;f=r(f,b)}else{let T=new Set(t),b,I=!1;for(;!I;){let U=await v.loadEntries({cursor:b,pageSize:g}),W=[...U.entries].filter(ge=>T.has(ge.type));l(W);let de=i?Object.freeze(W):W;f=r(f,de),b=U.cursor,I=!b||U.entries.length===0}}if(a==="scan"){let T=m(h.map(I=>I.cache??[])),b=T.slice(w);if(b.length>0){let I=i?Object.freeze(b):b;f=r(f,I)}y=f,C=T.length}return S.emit(f,{internal:!0}),f}catch(g){throw new P(n,g)}},reset:async()=>{try{let d=s;if(c?.load){let f=await c.load();f!==void 0&&(d=f)}let g=m(h.map(f=>f.cache??[])),v=i?Object.freeze(g):g,w=r(d,v);return a==="scan"&&(y=w,C=g.length),S.emit(w,{internal:!0}),w}catch(d){throw new P(n,d)}}}}saga(e,n,t,r={}){let s=n.map(p=>(this._eventLogs.has(p)||this.event(p),this._eventLogs.get(p).node)),a=ae(this,`${e}_cursor`,n,0),i=M({name:`${e}_invocations`,retainedLimit:this._retainedLimit,graph:this}),c=r.aggregateId,h=r.errorPolicy??"advance",l=new Map;for(let p of n){let _=a[p];l.set(p,_.cache??0);let C=_.subscribe(y=>{for(let q of y)q[0]===X&&l.set(p,q[1])});this._keepaliveDisposers.push(C)}let m={},u=ee(s,(p,_)=>{let C=m.n.meta.error;for(let y=0;y<p.length;y++){let q=p[y];if(q==null||q.length===0)continue;let V=q.at(-1);if(!V)continue;let A=n[y],E=a[A],L=l.get(A)??0;if(V.length>L){let F=V.slice(L),S=L;for(let Q of F){let x=Q;if(c!==void 0&&x.aggregateId!==c){S+=1;continue}try{t(x),C.emit(null,{internal:!0}),i.append({eventType:A,outcome:"success",aggregateId:x.aggregateId,event:x,t_ns:R(),...r.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{}}),S+=1}catch(d){if(C.emit(d,{internal:!0}),i.append({eventType:A,outcome:"failure",error:d,errorType:d instanceof Error?d.name:typeof d,aggregateId:x.aggregateId,event:x,t_ns:R(),...r.handlerVersion!==void 0?{handlerVersion:r.handlerVersion}:{}}),h==="hold")break;S+=1}}E.emit(S)}}},{name:e,describeKind:"effect",meta:{...$("saga",{saga_name:e,source_events:n}),error:null}});return m.n=u,this.add(u,{name:e}),this._keepaliveDisposers.push(z(u)),this._sagas.add(e),{node:u,invocations:i,audit:i,cursors:a}}};function fe(o,e){let n=new G(o,e),{factory:t,factoryArgs:r,...s}=e??{};return n.tagFactory("cqrs",re(s)),n}export{pe as a,he as b,ve as c,G as d,fe as e,me as f};
|
package/dist/chunk-OLIKJUKI.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{c as O}from"./chunk-VXPLLA4P.js";import{f as B,m as K}from"./chunk-L77I47VU.js";import{p as b}from"./chunk-LYCLF26R.js";import{b as M,i as A,j as L}from"./chunk-CK2E7BTU.js";import{b as H}from"./chunk-QYADASLV.js";var Y={};H(Y,{processInstanceKeyOf:()=>J,processManager:()=>X});var J=i=>i.correlationId;function V(i){if(i==null)return Promise.resolve(void 0);let y=K(i);return new Promise((s,v)=>{let u=!1,f,r=()=>{f&&f()};f=y.subscribe(a=>{if(!u)for(let o of a){if(o[0]===M){u=!0,Promise.resolve().then(r),s(o[1]);return}if(o[0]===L){u=!0,Promise.resolve().then(r),v(o[1]);return}if(o[0]===A){u=!0,Promise.resolve().then(r),s(void 0);return}}})})}async function Q(i,y,s,v,u){let f;for(let r=0;r<=v;r++){if(r>0){let a=u[Math.min(r-1,u.length-1)]??0;a>0&&await new Promise(o=>setTimeout(o,a))}try{return await V(i(y,s))}catch(a){f=a}}return{outcome:"failure",error:f}}function X(i,y,s){let v=s.retryMax??0,u=s.backoffMs??[0],f=1024,r=new Map,a=new Set,o=new Map,k=O({name:`${y}_process_instances`,retainedLimit:f,graph:i}),j=0;function $(){return++j}function S(e,t,n){C(e,t,n,void 0)}function C(e,t,n,c){let d=b(),g={correlationId:e,state:t,status:n,startedAt:o.get(e)??d,updatedAt:d,t_ns:d,seq:$(),...s.handlerVersion!==void 0?{handlerVersion:s.handlerVersion}:{},...c!==void 0?{reason:c}:{}};k.append(g)}let _=`_process_${y}_started`;i.event(_),s.persistence?.eventStorage&&i.attachEventStorage(s.persistence.eventStorage);async function x(e,t,n,c){if(a.delete(e),r.delete(e),o.delete(e),s.compensate)try{await V(s.compensate(t,n)),C(e,t,"compensated",c)}catch{S(e,t,"errored")}else S(e,t,"errored")}async function D(e,t){if(a.has(e)){if(t.outcome==="failure"){let n=r.get(e)??s.initial;await x(e,n,t.error);return}if(t.outcome==="success"){if(r.set(e,t.state),t.emit)for(let n of t.emit)try{i._appendEvent(n.type,n.payload,{correlationId:e,aggregateId:e})}catch{}if(S(e,t.state,"running"),s.isTerminal?.(t.state)){a.delete(e),r.delete(e),o.delete(e),S(e,t.state,"terminated");return}if(t.schedule){let{afterMs:n,eventType:c}=t.schedule,d,g=B(n),m=p=>{for(let T of p)if(T[0]===M){if(d?d():queueMicrotask(()=>d?.()),!a.has(e))return;let E=r.get(e);if(E===void 0)return;let l=s.steps[c];if(!l)return;let w={type:c,payload:null,timestampNs:b(),seq:Number.NaN,correlationId:e,aggregateId:e};q(e,l,E,w)}};d=g.subscribe(m)}return}if(t.outcome==="terminate"){if(r.set(e,t.state),t.emit)for(let n of t.emit)try{i._appendEvent(n.type,n.payload,{correlationId:e,aggregateId:e})}catch{}a.delete(e),r.delete(e),o.delete(e),S(e,t.state,"terminated")}}}let h=new Map;function q(e,t,n,c){let g=(h.get(e)??Promise.resolve()).then(async()=>{let m=r.get(e);if(m===void 0||!a.has(e))return;let p;try{p=await Q(t,m,c,v,u)}catch(T){await x(e,r.get(e)??s.initial,T);return}await D(e,p)});h.set(e,g),g.finally(()=>{h.get(e)===g&&h.delete(e)})}let P=!1,R=[];for(let e of s.watching){let t=i.event(e),n=0;n=(t.cache??[]).length;let d=t.subscribe(g=>{for(let m of g){if(m[0]!==M)continue;let p=m[1];if(p.length<=n)continue;let T=p.slice(n);n=p.length;for(let E of T){let l=E.correlationId;if(l===void 0||!a.has(l))continue;let w=s.steps[e];if(!w)continue;let N=r.get(l);N!==void 0&&q(l,w,N,E)}}});R.push(d)}function W(e,t){if(P||a.has(e))return;let n=b();o.set(e,n),r.set(e,s.initial),a.add(e);try{i._appendEvent(_,t??null,{correlationId:e,aggregateId:e})}catch{}S(e,s.initial,"running")}function F(e,t){if(P||!a.has(e))return;let n=r.get(e)??s.initial;x(e,n,new Error(`cancelled: ${t??"no reason given"}`),t)}function U(e){return r.get(e)}function z(){if(!P){P=!0;for(let e of R)try{e()}catch{}R.length=0}}return{instances:k,audit:k,start:W,cancel:F,getState:U,dispose:z}}export{J as a,X as b,Y as c};
|
package/dist/chunk-POXANAJ6.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{a as we}from"./chunk-SGS4OJGS.js";import{a as Me}from"./chunk-ESMPEKEV.js";import{C as ne}from"./chunk-L77I47VU.js";import{a as ve,d as ye}from"./chunk-35JTVPOX.js";import{A as ge,C as M,E as Z,F as me,G as be,e as $e,f as xe,i as Q,k as Ae,l as te,m as Te,o as z,p as Pe,s as U}from"./chunk-LYCLF26R.js";import{b as q,c as le,d as pe,e as ee,f as fe,g as he,h as L,i as H,j as W}from"./chunk-CK2E7BTU.js";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 je(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(je(l.from,l.to),l);let g=new Map;for(let l of e.edges)g.set(je(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:z()}}function Fe(o,e,t,n={}){let s=e in o.nodes,r=t in o.nodes;if(!s)return re(e,t,"no-such-from");if(!r)return re(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=Xe(o,e,n);if(a!=null)return a}let d=se(e,o.nodes[e],0,n);return oe(e,t,[d])}if(i===0)return re(e,t,"no-path");let c=Ie(o,e,t,i);return c.found?oe(e,t,Be(o,c.pathOrder,n)):re(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 Xe(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=se(e,n,0,t);c.dep_index=r[0];let d=se(e,n,1,t);return oe(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:oe(e,e,Be(o,i.pathOrder,t))}function Be(o,e,t){return e.map((n,s)=>{let r=o.nodes[n.path],i=se(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 se(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 oe(o,e,t){return Le(o,e,!0,"ok",t)}function re(o,e,t){return Le(o,e,!1,t,[])}function Le(o,e,t,n,s){let r=et(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 et(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: ${tt(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 tt(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)}}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},nt=Symbol.for("sizeof");function ze(o){let e=new WeakSet,t=new WeakSet,n=[o],s=0;for(;n.length>0;){let r=n.pop();s+=rt(r,e,t,n)}return s}function rt(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+st(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[nt];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 st(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 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?ze(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 $="::",B="__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 ie(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($))throw new Error(`Graph "${e}": ${t} "${o}" must not contain '${$}' (path separator)`);if(o===B)throw new Error(`Graph "${e}": ${t} name "${B}" 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($);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([[L]],{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($))throw new Error(`Graph name must not contain '${$}' (got "${e}")`);if(e===B)throw new Error(`Graph name "${B}" is reserved for meta companion paths`);this.name=e,this.opts=Object.freeze({...t??{}}),this.config=t?.config??ge,this._traceRing=new we(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=me(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:z()})),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(`${$}${B}${$}`)||r.nodes.push(c);return r.nodes.sort(),r.mounts.push(e),r.mounts.push(...t._collectSubgraphs(`${e}${$}`)),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([[L]],{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=ie(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($))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([[ee]],{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]===B)return this._resolveMetaChainFromNode(r,s,t.join($));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($)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return i.resolve(s.join($))}_resolveMetaChainFromNode(e,t,n){let s=e,r=0,i=[...t];for(;r<i.length;){if(i[r]!==B)throw new Error(`Graph "${this.name}": expected ${B} segment in meta path "${n}"`);if(r+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${B} 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=ve(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=ye(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 x=I==="deps_includes"?"depsIncludes":I==="meta_has"?"metaHas":I;if(x==="depsIncludes"){if(!D.deps.includes(String(T))){k=!1;break}continue}if(x==="metaHas"){if(!Object.hasOwn(D.meta??{},String(T))){k=!1;break}continue}if(D[x]!==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}${$}`;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}${$}`))}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,te(()=>{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===L)&&(v=!0)}b&&a(),v&&(u?.(),u=void 0,a())}));let l;try{l=be([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=ne(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=ne(c);return{node:c,dispose(){a=!0,p(),d.dispose(),c.down([[L,"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,te(()=>{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=be([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=ne(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===L)&&(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=ie(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}${$}${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}${$}${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}${$}${B}${$}${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 me(i=>{let c=[],d=!1,a=!1,p=()=>{if(c.length===0||a)return;let y={events:c.slice(),flushedAt_ns:z()};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,te(()=>{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 we(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(_)}},x=_=>u==null||u.has(_),Re=()=>s?{timestamp_ns:z(),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 de=C instanceof M?C.lastMutation?.actor??Q:Q;T({type:"data",path:_,data:F[1],actor:de,...P,...Ne(C)})}else if(c)N===le?x("dirty")&&O++:N===pe?x("resolved")&&m++:N===ee?x("invalidate")&&b++:N===fe?x("pause")&&v++:N===he?x("resume")&&w++:N===L?x("teardown")&&E++:N===H&&!l.has(_)?x("complete")&&(S=!0):N===W&&x("error")&&(R=!0,l.add(_));else if(N===le)x("dirty")&&O++,T({type:"dirty",path:_,...P});else if(N===pe)x("resolved")&&m++,T({type:"resolved",path:_,...P,...Ne(C)});else if(N===ee)x("invalidate")&&b++,T({type:"invalidate",path:_,...P});else if(N===fe)x("pause")&&v++,T({type:"pause",path:_,lockId:F[1],...P});else if(N===he)x("resume")&&w++,T({type:"resume",path:_,lockId:F[1],...P});else if(N===H)x("complete")&&!l.has(_)&&(S=!0),T({type:"complete",path:_,...P});else if(N===W){x("error")&&(R=!0,l.add(_));let de=C instanceof M?C.lastMutation?.actor??Q:Q;T({type:"error",path:_,data:F[1],actor:de,...P})}else N===L&&(x("teardown")&&E++,T({type:"teardown",path:_,...P}))}}))}let ae=!1,ue=()=>{if(!ae){ae=!0;for(let _ of De)_();for(let _ of Ge)_();for(let _ of X)_({value:void 0,done:!0});X.length=0}},ce=[],X=[];f.add(_=>{let C=X.shift();C?C({value:_,done:!1}):ce.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:ue,expand(_){ue();let C={...t};return typeof _=="string"?C.detail=_:Object.assign(C,_),n(Ue(C))},[Symbol.asyncIterator](){return{next(){return ce.length>0?Promise.resolve({value:ce.shift(),done:!1}):ae?Promise.resolve({value:void 0,done:!0}):new Promise(_=>X.push(_))},return(){return ue(),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"?z():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=(z()-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([[L]],{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 $e(c,c.encode(i))}throw new Error(`snapshot: unknown format "${String(e.format)}"`)}static decode(e,t){let n=t?.config??ge,{codec:s,codecVersion:r,payload:i}=xe(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=>ie(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($).length,O=y.split($).length;return l!==O?l-O:u<y?-1:u>y?1:0})){let u=f.split($),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:ie(f),factory:u})):[],c=f=>{for(let u of i)if(u.re.test(f))return u.factory},d=f=>{let u=f.split($),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(`${$}${B}${$}`)).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=ye(u,ve("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:z(),...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{_e as a,Fe as b,A as c,nt as d,ze as e,Ve as f,B as g,J as h,Se as i,gt as j,Je as k};
|
package/dist/chunk-RSMEXK53.js
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import{a as $e}from"./chunk-ELAASRBT.js";import{d as _e,e as He}from"./chunk-5B3JDG5F.js";import{s as ie,t as ue,v as Oe}from"./chunk-Z6X7B6A4.js";import{c as Me}from"./chunk-7PQLZMOG.js";import{g as Fe,i as ce}from"./chunk-URJ2VFNC.js";import{b as V}from"./chunk-D27JNOLZ.js";import{b as Pe}from"./chunk-TSOYJ743.js";import{b as Z}from"./chunk-TZQPPQEQ.js";import{a as se}from"./chunk-VXPLLA4P.js";import{f as Se,i as Ne}from"./chunk-POXANAJ6.js";import{b as X,s as ae,t as we,x as Ce}from"./chunk-AK5RHMC5.js";import{C as Ae,m as z}from"./chunk-L77I47VU.js";import{b as ke}from"./chunk-35JTVPOX.js";import{E as C,F as W,G as b,H as k,m as Ie,o as F}from"./chunk-LYCLF26R.js";import{b as $,i as _,j as K}from"./chunk-CK2E7BTU.js";import{b as ut}from"./chunk-QYADASLV.js";var Ht={};ut(Ht,{DEFAULT_DECAY_RATE:()=>L,DEFAULT_EXECUTE_PROMPT:()=>de,DEFAULT_QUEUE_CONFIGS:()=>ee,DEFAULT_SEVERITY_WEIGHTS:()=>H,DEFAULT_TRIAGE_PROMPT:()=>le,DEFAULT_VERIFY_PROMPT:()=>pe,HarnessGraph:()=>re,QUEUE_NAMES:()=>h,actuatorExecutor:()=>Le,affectedTaskFilter:()=>Et,autoSolidify:()=>mt,beforeAfterCompare:()=>Tt,codeChangeBridge:()=>bt,createIntakeBridge:()=>gt,defaultErrorClassifier:()=>te,defaultLlmExecutor:()=>Qe,defaultLlmVerifier:()=>Ue,dispatchActuator:()=>ft,effectivenessTracker:()=>xt,evalIntakeBridge:()=>yt,evalSource:()=>vt,evalVerifier:()=>De,harnessEvalPair:()=>Nt,harnessLoop:()=>Pt,harnessProfile:()=>Ft,harnessTrace:()=>$t,notifyEffect:()=>Rt,priorityScore:()=>wt,refineExecutor:()=>fe,resolvePromptFn:()=>Q,strategyKey:()=>D,strategyModel:()=>me});function ct(e,t){return{outcome:"success",detail:`actuator applied ${t.intervention} for ${pt(t.summary)}`,artifact:e}}function lt(e,t){let a=e instanceof Error?e.message:String(e);return{outcome:"failure",detail:`actuator threw on ${t.intervention}: ${a}`}}function dt(e){return`actuator skipped ${e.intervention} (shouldApply returned false)`}function pt(e,t=80){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Le(e){let t=e.name??"actuator-executor",a=e.toOutput??ct,o=e.onError??lt,n=e.skipDetail??dt;return c=>{let r=c.payload.item;return e.shouldApply&&!e.shouldApply(r)?{...c.payload,execution:{item:r,outcome:"failure",detail:n(r)}}:W(s=>{let u=new AbortController,i=!1,l=null,m=g=>{i||(i=!0,s.down([[$,{...c.payload,execution:{item:r,...g}}],[_]]),l?.(),l=null)},p;try{let g=e.apply(r,{signal:u.signal});p=z(g,{signal:u.signal})}catch(g){return m(o(g,r)),()=>{u.abort()}}return l=p.subscribe(g=>{for(let y of g){if(i)return;if(y[0]===$){m(a(y[1],r));return}if(y[0]===K){m(o(y[1],r));return}if(y[0]===_){m(o(new Error("actuator inner completed without emitting DATA"),r));return}}}),i&&l&&(l(),l=null),()=>{u.abort(),l?.(),l=null}},{name:`${t}/inner`})}}function ft(e){let t=e.name??"dispatch-actuator",a=e.default??null,o=a!=null;return Le({apply:(n,c)=>{let r=Object.hasOwn(e.routes,n.intervention)?e.routes[n.intervention]:a;if(!r)throw new Error(`dispatchActuator: no route for intervention '${n.intervention}'`);return r(n,c)},shouldApply:n=>Object.hasOwn(e.routes,n.intervention)||o,skipDetail:n=>`no route for intervention '${n.intervention}'`,name:t})}function mt(e){let t=e.name??"auto-solidify",a=e.extract??(n=>n.execution.artifact??null),o=e.predicate??(()=>!0);return W(n=>{let c=null,r=!1,s=()=>{r||(r=!0,c?.(),c=null)},u=i=>{r||(n.down([[K,i]]),s())};return c=e.verifyResults.subscribe(i=>{if(!r)for(let l of i){if(r)return;if(l[0]!==$){if(l[0]===_){n.down([[_]]),s();return}continue}let m=l[1];if(m==null||!m.verified)continue;let p;try{p=o(m)}catch(y){u(y);return}if(!p)continue;let g;try{g=a(m)}catch(y){u(y);return}if(g!=null){try{e.write(g,m)}catch(y){u(y);return}n.down([[$,g]])}}}),r&&c&&(c(),c=null),()=>{s()}},{name:t})}function gt(e,t,a,o){return k([e],([n])=>{if(n==null)return;let c=a(n);for(let r of c)t.publish(r)},{name:o?.name??"intake-bridge"})}function yt(e,t,a){let o=a?.defaultSeverity??"medium";return k([e],([n])=>{if(n==null)return;let c=Array.isArray(n)?n:[n];for(let r of c)for(let s of r.tasks)if(!(s.valid&&s.judge_scores?.every(u=>u.pass))){if(!s.valid&&(!s.judge_scores||s.judge_scores.length===0)){t.publish({source:"eval",summary:`Task ${s.task_id} invalid (model: ${r.model})`,evidence:`Run ${r.run_id}: task produced invalid output`,affectsAreas:["graphspec"],affectsEvalTasks:[s.task_id],severity:o});continue}if(s.judge_scores)for(let u of s.judge_scores)u.pass||t.publish({source:"eval",summary:`${s.task_id}: ${u.claim} (model: ${r.model})`,evidence:u.reasoning,affectsAreas:["graphspec"],affectsEvalTasks:[s.task_id],severity:o})}},{name:a?.name??"eval-intake-bridge"})}function vt(e,t){return Ce(e,()=>z(t()))}function Tt(e,t){return b([e,t],([a,o])=>{let n=a,c=o,r=new Map(n.tasks.map(p=>[p.task_id,p])),s=new Map(c.tasks.map(p=>[p.task_id,p])),u=new Set([...r.keys(),...s.keys()]),i=[],l=[],m=[];for(let p of u){let g=r.get(p),y=s.get(p),x=g?.valid??!1,I=y?.valid??!1,R=g?.judge_scores?g.judge_scores.filter(N=>N.pass).length:void 0,A=y?.judge_scores?y.judge_scores.filter(N=>N.pass).length:void 0,M=R!==void 0&&A!==void 0?A-R:void 0;i.push({taskId:p,before:x,after:I,scoreDiff:M}),x&&!I&&l.push(p),!x&&I&&m.push(p)}return{newFailures:l,resolved:m,taskDeltas:i,overallImproved:m.length>l.length}},{name:"eval-delta"})}function Et(e,t){let a=t==null?null:Array.isArray(t)?C(t):t,o=[e];return a&&o.push(a),b(o,n=>{let c=n[0],r=a?new Set(n[1]):null,s=new Set;for(let u of c)for(let i of u.affectsEvalTasks??[])(r==null||r.has(i))&&s.add(i);return[...s].sort()},{name:"affected-task-filter"})}function bt(e,t,a,o){let n=o?.defaultSeverity??"high";function c(s){let u=[];for(let i of s.lintErrors??[])u.push({source:"code-change",summary:`Lint: ${i.rule} in ${i.file}:${i.line}`,evidence:i.message,affectsAreas:[i.file],severity:n});for(let i of s.testFailures??[])u.push({source:"test",summary:`Test failure: ${i.testId}`,evidence:i.message,affectsAreas:[i.file],affectsEvalTasks:[i.testId],severity:n});return u}let r=a??c;return k([e],([s])=>{if(s!=null)for(let u of r(s))t.publish(u)},{name:o?.name??"code-change-bridge"})}function Rt(e,t,a){return k([e.latest],([o])=>{o!=null&&t(o)},{name:a?.name??"notify-effect"})}var h=["auto-fix","needs-decision","investigation","backlog"],ee={"auto-fix":{gated:!1},"needs-decision":{gated:!0},investigation:{gated:!0},backlog:{gated:!1}},H={critical:100,high:70,medium:40,low:10},L=Math.LN2/(168*3600);function D(e,t){return`${e}\u2192${t}`}var ht=/\b(parse|json|config|validation|syntax)\b/i,te=e=>ht.test(e.detail)?"self-correctable":"structural",le=`You are a triage classifier for a reactive collaboration harness.
|
|
2
|
-
|
|
3
|
-
Given an intake item, classify it and output JSON:
|
|
4
|
-
{
|
|
5
|
-
"rootCause": "composition" | "missing-fn" | "bad-docs" | "schema-gap" | "regression" | "unknown",
|
|
6
|
-
"intervention": "template" | "catalog-fn" | "docs" | "wrapper" | "schema-change" | "investigate",
|
|
7
|
-
"route": "auto-fix" | "needs-decision" | "investigation" | "backlog",
|
|
8
|
-
"priority": <number 0-100>,
|
|
9
|
-
"triageReasoning": "<one sentence>"
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
Strategy model (past effectiveness):
|
|
13
|
-
{{strategy}}
|
|
14
|
-
|
|
15
|
-
Intake item:
|
|
16
|
-
{{item}}`,de=`You are an implementation agent.
|
|
17
|
-
|
|
18
|
-
Given a triaged issue with root cause and intervention type, produce a fix.
|
|
19
|
-
|
|
20
|
-
Issue:
|
|
21
|
-
{{item}}
|
|
22
|
-
|
|
23
|
-
Output JSON:
|
|
24
|
-
{
|
|
25
|
-
"outcome": "success" | "failure" | "partial",
|
|
26
|
-
"detail": "<description of what was done or what failed>"
|
|
27
|
-
}`,pe=`You are a QA reviewer.
|
|
28
|
-
|
|
29
|
-
Given an execution result, verify whether the fix is correct.
|
|
30
|
-
|
|
31
|
-
Execution:
|
|
32
|
-
{{execution}}
|
|
33
|
-
|
|
34
|
-
Original issue:
|
|
35
|
-
{{item}}
|
|
36
|
-
|
|
37
|
-
Output JSON:
|
|
38
|
-
{
|
|
39
|
-
"verified": true/false,
|
|
40
|
-
"findings": ["<finding1>", ...],
|
|
41
|
-
"errorClass": "self-correctable" | "structural" // only if verified=false
|
|
42
|
-
}`;function Q(e,t,a){if(typeof e=="function")return e;let o=e??t;return n=>a(o,n)}function xt(e){let t=Z({name:e?.name??"effectiveness-entries"}),a=b([t.entries],([r])=>new Map(r),{name:`${e?.name??"effectiveness"}-snapshot`,equals:(r,s)=>{let u=r,i=s;if(u.size!==i.size)return!1;for(let[l,m]of u){let p=i.get(l);if(!p||m.attempts!==p.attempts||m.successes!==p.successes)return!1}return!0}});function o(r,s){let u=t.get(r),i=(u?.attempts??0)+1,l=(u?.successes??0)+(s?1:0);t.set(r,{key:r,attempts:i,successes:l,successRate:l/i})}function n(r){return t.get(r)}let c=Ae(a);return{node:a,record:o,lookup:n,dispose:()=>{c(),t.dispose()}}}function It(e){let{best:t,score:a,status:o}=e,n=Number.isFinite(a)?a.toFixed(3):String(a),c=t??void 0;return o==="converged"?{outcome:"success",detail:`refineLoop converged at score ${n}`,artifact:c}:o==="budget"?{outcome:"partial",detail:`refineLoop hit budget at score ${n}`,artifact:c}:{outcome:"failure",detail:`refineLoop errored (status=${o})`,artifact:c}}function fe(e){let t=e.name??"refine-executor",a=e.toOutput??It;return o=>{let n=o.payload.item,c=$e(e.seedFrom(n),e.evaluator,e.strategy,{...e.refine,dataset:e.datasetFor(n),name:`${t}/inner`}),r=b([c.status,c.best,c.score],([s,u,i])=>{let l=s;if(l!=="converged"&&l!=="budget"&&l!=="errored")return null;let m=a({best:u,score:i,status:l});return{...o.payload,execution:{item:n,...m}}},{name:`${t}/output`});return X(r,s=>s!=null,{name:`${t}/gate-out`})}}function kt(e){if(e.length===0)return Number.NEGATIVE_INFINITY;let t=0;for(let a of e)t+=a.score;return t/e.length}function At(e){let{passCount:t,total:a,meanScore:o,threshold:n,missingArtifact:c}=e,r=Number.isFinite(o)?o.toFixed(3):String(o),s=!c&&a>0&&o>=n,u=c?["EXECUTE stage did not emit an artifact; cannot verify reactively"]:s?[`${t}/${a} eval tasks passed; mean score ${r} \u2265 ${n}`]:a===0?["No eval tasks were selected for this item \u2014 cannot verify"]:[`${t}/${a} eval tasks passed; mean score ${r} < threshold ${n}`];return s?{verified:!0,findings:u}:{verified:!1,findings:u,errorClass:"structural"}}function St(e){return e.artifact??null}function De(e){let t=e.name??"eval-verifier",a=e.threshold??.5,o=e.toOutput??At,n=e.extractArtifact??St;return c=>{let{item:r,execution:s}=c.payload;if(s==null)return{...c.payload,verify:{verified:!1,findings:["evalVerifier: prior execute stage produced no execution"],errorClass:"structural"}};let u=n(s,r);if(u==null)return{...c.payload,verify:o({scores:[],meanScore:Number.NEGATIVE_INFINITY,passCount:0,total:0,threshold:a,missingArtifact:!0})};let i=C([u],{name:`${t}/candidates`}),l=C(e.datasetFor(r),{name:`${t}/dataset`}),m;Ie(()=>{m=e.evaluator(i,l)});let p=b([m],([g])=>{let y=g;if(y==null)return null;let x=kt(y),I=y.filter(R=>R.score>=a).length;return{...c.payload,verify:o({scores:y,meanScore:x,passCount:I,total:y.length,threshold:a})}},{name:`${t}/output`});return X(p,g=>g!=null,{name:`${t}/gate-out`})}}function Nt(e){let t=e.name??"harness-pair",a=fe({name:`${t}-exec`,seedFrom:e.seedFrom,evaluator:e.evaluator,strategy:e.strategy,datasetFor:e.datasetFor,refine:e.refine}),o=De({name:`${t}-verify`,evaluator:e.evaluator,datasetFor:e.datasetFor,threshold:e.threshold});return{executor:a,verifier:o}}function me(){let e=Z({name:"strategy-entries"}),t=b([e.entries],([r])=>{let s=r;return new Map(s)},{name:"strategy-model",equals:(r,s)=>{let u=r,i=s;if(u.size!==i.size)return!1;for(let[l,m]of u){let p=i.get(l);if(!p||m.attempts!==p.attempts||m.successes!==p.successes)return!1}return!0}});function a(r,s,u){let i=D(r,s),l=e.get(i),m=(l?.attempts??0)+1,p=(l?.successes??0)+(u?1:0);e.set(i,{rootCause:r,intervention:s,attempts:m,successes:p,successRate:p/m})}function o(r,s){return e.get(D(r,s))}let n=t.subscribe(()=>{});function c(){n()}return{node:t,record:a,lookup:o,dispose:c}}function wt(e,t,a,o,n){let c={...H,...n?.severityWeights},r=n?.decayRate??L,s=n?.effectivenessThreshold??.7,u=n?.effectivenessBoost??15,i=[e,t,a];return o&&i.push(o),b(i,l=>{let m=l[0],p=l[1],g=l[2],y=o?l[3]:0,x=c[m.severity??"medium"],I=(F()-g)/1e9,R=Pe(x,I,r,0),A=D(m.rootCause,m.intervention),M=p.get(A);return M&&M.successRate>=s&&(R+=u),R+=y*20,R},{name:"priority-score"})}var Je="intake",Ct="triage-output",je="retry",Ge="verify-results",Ve="__unrouted";function Qe(e,t){let a=Q(t,de,(o,n)=>o.replace("{{item}}",JSON.stringify(n)));return o=>{let n=o.payload.item,c=[{role:"user",content:a(n)}],r=u=>({...o.payload,execution:{item:n,outcome:"failure",detail:u}}),s=u=>u instanceof Error?u.message:String(u);return ue(e,c,{onSuccess:u=>{let i;try{i=JSON.parse(ie(String(u.content)))}catch(m){return r(`execute parse error: ${s(m)}`)}if(i==null||typeof i!="object"||Array.isArray(i))return r(`execute parse error: non-object response: ${JSON.stringify(i)}`);let l=i;return{...o.payload,execution:{item:n,outcome:l.outcome??"failure",detail:l.detail??"unknown",artifact:l.artifact}}},onFailure:(u,i)=>r(u==="complete"?"adapter completed without emitting DATA":`executor failed: ${s(i)}`)})}}function Ue(e,t){let a=Q(t,pe,(o,n)=>{let[c,r]=n;return o.replace("{{execution}}",JSON.stringify(c)).replace("{{item}}",JSON.stringify(r))});return o=>{let{item:n,execution:c}=o.payload;if(c==null)return{...o.payload,verify:{verified:!1,findings:["verifier: prior execute stage produced no execution"],errorClass:"structural"}};let r=[{role:"user",content:a([c,n])}],s=i=>({...o.payload,verify:{verified:!1,findings:[i],errorClass:"self-correctable"}}),u=i=>i instanceof Error?i.message:String(i);return ue(e,r,{onSuccess:i=>{let l;try{l=JSON.parse(ie(String(i.content)))}catch(p){return s(`verify parse error: ${u(p)}`)}if(l==null||typeof l!="object"||Array.isArray(l))return s(`verify parse error: non-object response: ${JSON.stringify(l)}`);let m=l;return{...o.payload,verify:{verified:m.verified===!0,findings:m.findings??[],errorClass:m.errorClass}}},onFailure:(i,l)=>s(i==="complete"?"verifier completed without emitting DATA":`verifier failed: ${u(l)}`)})}}var re=class extends Ne{queues;executeFlow;jobs;gates;queueTopics;strategy;totalRetries;totalReingestions;priorityScores;constructor(t,a,o,n,c,r,s,u,i,l){super(t),this.queues=a,this.executeFlow=o,this.queueTopics=n,this.jobs=c,this.gates=r,this.strategy=s,this.totalRetries=u,this.totalReingestions=i,this.priorityScores=l}get intake(){return this.queues.topic(Je)}get verifyResults(){return this.queues.topic(Ge)}get retry(){return this.queues.topic(je)}get unrouted(){return this.queues.topic(Ve)}stageNodes(){let t=this.queues,a=r=>t.has(r)?`queues::${r}::latest`:null,o=r=>r==null?[]:[r],n=h.flatMap(r=>o(a(r))),c=[];for(let[r]of this.gates)c.push(`gates::${r}/gate`);return[{label:"INTAKE",paths:o(a("intake"))},{label:"TRIAGE",paths:["triage"]},{label:"QUEUE",paths:n},{label:"GATE",paths:c},{label:"EXECUTE",paths:["executeFlow::execute::events"]},{label:"VERIFY",paths:["executeFlow::verify::events"]},{label:"REFLECT",paths:["reflect"]},{label:"STRATEGY",paths:["strategy"]}]}};function Pt(e,t){let a=t.adapter,o=t.maxRetries??2,n=t.retainedLimit??1e3,c=t.errorClassifier??te,r=new Map;for(let d of h)r.set(d,{...ee[d],...t.queues?.[d]});let s=Fe(`${e}/queues`,{defaultTopicOptions:{retainedLimit:n}}),u=s.topic(Je),i=s.topic(Ct),l=s.topic(je),m=s.topic(Ge),p=new Map;for(let d of h)p.set(d,s.topic(d));let g=s.topic(Ve),y=me(),x=ae(u.latest,y.node),I=Q(t.triagePrompt,le,(d,f)=>{let[T,E]=f;return d.replace("{{strategy}}",JSON.stringify(Array.from(E.entries()))).replace("{{item}}",JSON.stringify(T))}),R=Oe(a,[x],d=>{let f=d;return!f||!f[0]?"":I(f)},{name:"triage",format:"json"}),A=ae(R,x),N=k([A],([d])=>{if(d==null)return;let[f,T]=d;if(!f?.route)return;let E=T?.[0],P={...f,...E};i.publish(P)}).subscribe(()=>{}),Be=new Set(h);for(let d of h)ce(`bridge/${d}`,i,p.get(d),{map:f=>f.route===d?f:void 0});ce("bridge/__unrouted",i,g,{map:d=>Be.has(d.route)?void 0:d});let J=new Map,ne=new Map;for(let d of h)J.set(d,_e(`jobs/${d}`));let ge=[];for(let d of h){let f=p.get(d),T=J.get(d),E=new WeakSet,P=k([f.events],([S])=>{let G=S??[];for(let O of G){if(E.has(O))continue;E.add(O);let w=T.enqueue(O);ne.set(V(O),{route:d,id:w})}},{name:`jobs/${d}-mirror`});ge.push(P.subscribe(()=>{}))}function oe(d){let f=V(d),T=ne.get(f);T&&(J.get(T.route)?.removeById(T.id),ne.delete(f))}let ye=Me("gates"),U=new Map;for(let d of h){let f=r.get(d);if(!f.gated)continue;let T=p.get(d),E=ye.approvalGate(`${d}/gate`,T.latest,{maxPending:f.maxPending,startOpen:f.startOpen});U.set(d,E)}let q=[];for(let d of h)r.get(d).gated&&U.has(d)?q.push(U.get(d).node):q.push(p.get(d).latest);q.push(l.latest);let ve=we(...q),Ye=t.executor??Qe(a,t.executePrompt),Ke=t.verifier??Ue(a,t.verifyPrompt),We=t.executeMaxPerPump??Number.MAX_SAFE_INTEGER,ze=t.verifyMaxPerPump??Number.MAX_SAFE_INTEGER,j=He(`${e}/executeFlow`,{stages:[{name:"execute",work:d=>Ye(d),maxPerPump:We},{name:"verify",work:d=>Ke(d),maxPerPump:ze}]}),Te=k([ve],([d])=>{d!=null&&j.enqueue({item:d})},{name:"execute-enqueue"}),Xe=Te.subscribe(()=>{}),Ee=t.maxReingestions??1,Ze=Math.min(t.maxTotalRetries??o*10,100),et=Math.min(t.maxTotalReingestions??Ee*10,100),be=C(0),Re=C(0);function tt(d,f,T){return{item:T,execution:d,verified:f.verified,findings:f.findings??[],errorClass:f.errorClass}}function rt(d,f){y.record(f.rootCause,f.intervention,!0),m.publish(d),oe(f)}function nt(d,f){let T=V(f),E=f.$retries??0,P={...f,$retries:E+1,summary:`[RETRY ${E+1}/${o}] ${T} \u2014 Previous attempt failed: ${d.findings.join("; ")}`,relatedTo:[T]};l.publish(P)}function ot(d,f){y.record(f.rootCause,f.intervention,!1),m.publish(d),oe(f);let T=V(f),E=f.$reingestions??0;E<Ee&&se(Re,et)&&u.publish({source:f.source,summary:`Verification failed for: ${T}`,evidence:d.findings.join(`
|
|
43
|
-
`),affectsAreas:f.affectsAreas,affectsEvalTasks:f.affectsEvalTasks,severity:f.severity??"high",relatedTo:[T],$reingestions:E+1})}let B=0,he=k([j.completed],([d])=>{let f=d??[];B>f.length&&(B=f.length);let T=B;B=f.length;for(let E=T;E<f.length;E++){let P=f[E],{item:S,execution:G,verify:O}=P.payload;if(G==null||O==null){oe(S);continue}let w=tt(G,O,S);if(w.verified){rt(w,S);continue}let at=w.errorClass??c({item:S,outcome:G.outcome,detail:w.findings.join("; ")}),it=S.$retries??0;at==="self-correctable"&&it<o&&se(be,Ze)?nt(w,S):ot(w,S)}},{name:"verify-dispatch"}),st=he.subscribe(()=>{}),xe=b([j.completed],()=>null,{name:"reflect",equals:()=>!1}),Y;t.priority&&(Y=Ot(p,y,t));let v=new re(e,s,j,p,J,U,y,be,Re,Y);v.addDisposer(N),v.addDisposer(Xe),v.addDisposer(st),v.addDisposer(y.dispose);for(let d of ge)v.addDisposer(d);if(v.add(x,{name:"triage-input"}),v.add(R,{name:"triage"}),v.add(A,{name:"router-input"}),v.add(ve,{name:"execute-input"}),v.add(Te,{name:"execute-enqueue"}),v.add(he,{name:"verify-dispatch"}),v.add(xe,{name:"reflect"}),v.add(y.node,{name:"strategy"}),v.addDisposer(xe.subscribe(()=>{})),Y)for(let[d,f]of Y)v.add(f,{name:`priority/${d}`}),v.addDisposer(f.subscribe(()=>{}));v.mount("queues",s),v.mount("gates",ye),v.mount("executeFlow",j);for(let[d,f]of J)v.mount(`jobs/${d}`,f);return v.tagFactory("harnessLoop",ke(t)),v}function Ot(e,t,a){if(!a.lastInteractionNs)throw new Error("harnessLoop: `opts.priority` requires `opts.lastInteractionNs` \u2014 pass a Node<number> (e.g. `fromTimer(60_000)` or a `state(monotonicNs())` you bump on human interaction). Priority scores only decay when this node settles; an internal default would freeze age at construction time.");let o=a.lastInteractionNs,n=a.priority??{},c={...H,...n.severityWeights},r=n.decayRate??L,s=n.effectivenessThreshold??.7,u=n.effectivenessBoost??15,i=new Map;for(let[l,m]of e){let p=b([m.latest,t.node,o],g=>{let y=g[0];if(y==null)return 0;let x=c[y.severity??"medium"]??40,I=(F()-g[2])/1e9,R=x*Math.exp(-r*Math.max(0,I)),A=`${y.rootCause}\u2192${y.intervention}`,N=g[1]?.get(A);return N&&N.successRate>=s&&(R+=u),R},{name:`priority/${l}`});i.set(l,p)}return i}function Ft(e,t){let a=Se(e,t),o={};for(let n of h){let c=e.queues.has(n)?e.queues.topic(n):null;o[n]=c?.retained().length??0}return{...a,queueDepths:o,strategyEntries:e.strategy.node.cache?.size??0,totalRetries:e.totalRetries.cache??0,totalReingestions:e.totalReingestions.cache??0}}function Mt(e){let t={};for(let{label:a,paths:o}of e.stageNodes())for(let n of o)t[n]=a;return t}function $t(e,t){let a=t?.logger===null?null:t?.logger??console.log,o=t?.detail??"summary",n=F(),c=[],r=[],s=Mt(e);function u(){return(F()-n)/1e9}function i(l,m,p){let g={elapsed:u(),stage:l,type:m};o!=="summary"&&(g.summary=_t(p)),o==="full"&&(g.data=p),r.push(g)}for(let[l,m]of Object.entries(s))try{let p=e.observe(l,{format:"stage-log",stageLabels:s,logger:a?g=>a(g):()=>{},includeTypes:["data","error","complete"]});p.onEvent(g=>{g.type==="data"?i(m,"data",g.data):g.type==="error"?i(m,"error",g.data):g.type==="complete"&&i(m,"complete",void 0)}),c.push(p)}catch(p){let g=p instanceof Error?p.message:String(p);i(m,"error",`observe-unavailable: ${l} \u2014 ${g}`),a&&a(`[${u().toFixed(3)}s] ${m.padEnd(9)} \u2717 observe-unavailable: ${g}`)}return{get events(){return r},dispose(){for(let l of c)l.dispose();c.length=0}}}function _t(e){if(e==null)return"null";if(typeof e=="string")return qe(e,80);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{let t=JSON.stringify(e);return qe(t,120)}catch{return String(e)}}function qe(e,t){return e.length>t?`${e.slice(0,t-1)}\u2026`:e}export{Le as a,ft as b,mt as c,gt as d,yt as e,vt as f,Tt as g,Et as h,bt as i,Rt as j,h as k,ee as l,H as m,L as n,D as o,te as p,le as q,de as r,pe as s,Q as t,xt as u,fe as v,De as w,Nt as x,me as y,wt as z,Qe as A,Ue as B,re as C,Pt as D,Ft as E,$t as F,Ht as G};
|
package/dist/chunk-SGS4OJGS.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var t=class{constructor(i){this.capacity=i;if(!Number.isInteger(i)||i<=0)throw new Error(`RingBuffer capacity must be a positive integer (got ${i})`);this.buf=new Array(i)}buf;head=0;_size=0;get size(){return this._size}get maxSize(){return this.capacity}push(i){let e=(this.head+this._size)%this.capacity;this.buf[e]=i,this._size<this.capacity?this._size++:this.head=(this.head+1)%this.capacity}shift(){if(this._size===0)return;let i=this.buf[this.head];return this.buf[this.head]=void 0,this.head=(this.head+1)%this.capacity,this._size--,i}at(i){if(this._size===0)return;let e=i<0?this._size+i:i;if(!(e<0||e>=this._size))return this.buf[(this.head+e)%this.capacity]}toArray(){let i=new Array(this._size);for(let e=0;e<this._size;e++)i[e]=this.buf[(this.head+e)%this.capacity];return i}clear(){for(let i=0;i<this._size;i++)this.buf[(this.head+i)%this.capacity]=void 0;this.head=0,this._size=0}};export{t as a};
|
package/dist/chunk-URJ2VFNC.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as M}from"./chunk-L6NSJVJZ.js";import{b as S}from"./chunk-TT4C7DXW.js";import{i as l}from"./chunk-POXANAJ6.js";import{C as o}from"./chunk-L77I47VU.js";import{D as P,E as v,G as _,m as N}from"./chunk-LYCLF26R.js";import{b as L,i as I}from"./chunk-CK2E7BTU.js";import{b as C}from"./chunk-QYADASLV.js";var U={};C(U,{MessagingHubGraph:()=>w,SubscriptionGraph:()=>T,TopicBridgeGraph:()=>y,TopicGraph:()=>m,TopicRegistry:()=>O,messagingHub:()=>H,subscription:()=>D,topic:()=>z,topicBridge:()=>F});var R=256;function c(i,e){if(!Number.isFinite(i)||!Number.isInteger(i)||i<0)throw new Error(`${e} must be a non-negative integer`);return i}function a(i,e){return M("messaging",i,e)}var B=1024,m=class extends l{_log;events;latest;hasLatest;constructor(e,s={}){super(e,s.graph),this._log=S([],{name:"events",maxSize:s.retainedLimit??B}),this._log.withLatest(),this.events=this._log.entries,this.add(this.events,{name:"events"}),this.latest=_([this.events],([t])=>{let n=t;return n.length===0?null:n[n.length-1]},{name:"latest",describeKind:"derived",meta:a("topic_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(o(this.latest)),this.hasLatest=_([this.events],([t])=>t.length>0,{name:"hasLatest",describeKind:"derived",meta:a("topic_has_latest")}),this.add(this.hasLatest,{name:"hasLatest"}),this.addDisposer(o(this.hasLatest)),this.addDisposer(()=>{this.events.down([[I]])}),this.addDisposer(()=>this._log.disposeAllViews())}publish(e){if(e===void 0)throw new TypeError(`TopicGraph "${this.name}": publish(undefined) is not allowed (spec \xA75.12 SENTINEL).`);this._log.append(e)}attachEventStorage(e){return this._log.attachStorage(e)}retained(){return this.events.cache}get _logBundle(){return this._log}},T=class extends l{cursor;available;topic;_disposed=!1;constructor(e,s,t={}){super(e,t.graph),this.topic=s;let n;if(t.from!==void 0?t.from==="retained"?n=0:t.from==="now"?n=s.events.cache.length:n=c(t.from,"subscription from"):n=c(t.cursor??0,"subscription cursor"),this.cursor=v(n,{name:"cursor",describeKind:"state",meta:a("subscription_cursor")}),this.add(this.cursor,{name:"cursor"}),this.available=s._logBundle.view({kind:"fromCursor",cursor:this.cursor}),this.add(this.available,{name:"available"}),this.addDisposer(o(this.available)),t.advanceOn!==void 0){let r=t.advanceOn,b=!1,d=P([r],()=>{if(!b){b=!0;return}if(this._disposed)return;let p=this.available.cache;if(p.length===0)return;let g=this.cursor.cache+p.length;this.cursor.emit(g)},{name:"advancePump",describeKind:"effect",meta:a("subscription_advance_pump")});this.add(d,{name:"advancePump"}),this.addDisposer(o(d))}}ack(e){if(this._disposed)return this.cursor.cache;let s=this.available.cache,t=e===void 0?s.length:c(e,"subscription ack count"),n=Math.min(t,s.length);if(n<=0)return this.cursor.cache;let r=this.cursor.cache+n;return this.cursor.emit(r),r}pull(e){if(this._disposed)return[];let s=this.available.cache,t=e===void 0?s.length:c(e,"subscription pull limit");return s.slice(0,t)}pullAndAck(e){if(this._disposed)return{items:[],cursor:this.cursor.cache};let s=this.available.cache,t=e===void 0?s.length:c(e,"subscription pullAndAck limit"),n=s.slice(0,t);if(n.length===0)return{items:n,cursor:this.cursor.cache};let r=this.cursor.cache+n.length;return this.cursor.emit(r),{items:n,cursor:r}}dispose(){this._disposed||(this._disposed=!0,this.cursor.down([[I]]),this.destroy())}},y=class extends l{_sourceSub;bridgedCount;output;constructor(e,s,t,n={}){super(e,n.graph),this._sourceSub=D(`${e}-subscription`,s,{cursor:n.cursor}),this.mount("subscription",this._sourceSub);let r=Math.max(1,c(n.maxPerPump??R,"topic bridge maxPerPump")),b=n.map??(u=>u);this.output=_([this._sourceSub.available],([u])=>{let f=u,h=[],k=Math.min(f.length,r);for(let x=0;x<k;x++){let A=b(f[x]);A!==void 0&&h.push(A)}return h},{name:"output",describeKind:"derived",meta:a("topic_bridge_output",{targetRef:t.name}),initial:[]}),this.add(this.output,{name:"output"}),this.addDisposer(o(this.output)),this.bridgedCount=v(0,{name:"bridgedCount",describeKind:"state",meta:a("topic_bridge_count")}),this.add(this.bridgedCount,{name:"bridgedCount"}),this.addDisposer(o(this.bridgedCount));let d=this.output,p=this._sourceSub,g=this.bridgedCount,G=P([d],()=>{let u=d.cache;if(u.length===0)return;let f=p.available.cache.length,h=Math.min(f,r);if(h>0){p.ack(h);let k=g.cache??0;g.emit(k+u.length)}},{name:"ackPump",describeKind:"effect",meta:a("topic_bridge_ack_pump")});this.add(G,{name:"ackPump"}),this.addDisposer(o(G));let E=K(this.output,t);this.addDisposer(E)}};function K(i,e){return i.subscribe(s=>{for(let t of s){if(t[0]!==L)continue;let n=t[1];n.length!==0&&N(()=>{for(let r of n)e.publish(r)})}})}var O=class{_map=new Map;version;constructor(e){this.version=e}get size(){return this._map.size}has(e){return this._map.has(e)}get(e){return this._map.get(e)}set(e,s){this._map.set(e,s)}delete(e){return this._map.delete(e)}keys(){return this._map.keys()}},w=class extends l{_registry;version;_defaultTopicOptions;constructor(e,s={}){super(e,s.graph);let t=v(0,{name:"version",describeKind:"state",meta:a("hub_version")});this.add(t,{name:"version"}),this.version=t,this._registry=new O(t),this._defaultTopicOptions={...s.defaultTopicOptions??{}}}get size(){return this._registry.size}has(e){return this._registry.has(e)}topicNames(){return this._registry.keys()}topic(e,s){let t=this._registry.get(e);if(t===void 0){let n={...this._defaultTopicOptions,...s??{}};t=new m(e,n),this._registry.set(e,t),this.mount(e,t);let r=this.version.cache??0;this.version.emit(r+1)}return t}publish(e,s){this.topic(e).publish(s)}publishMany(e){N(()=>{for(let[s,t]of e)this.topic(s).publish(t)})}subscribe(e,s,t){let n=this.topic(s);return new T(e,n,t)}removeTopic(e){if(!this._registry.has(e))return!1;try{this.remove(e)}finally{this._registry.delete(e);let s=this.version.cache??0;this.version.emit(s+1)}return!0}};function z(i,e){return new m(i,e)}function H(i,e){return new w(i,e)}function D(i,e,s){return new T(i,e,s)}function F(i,e,s,t){return new y(i,e,s,t)}export{m as a,T as b,y as c,O as d,w as e,z as f,H as g,D as h,F as i,U as j};
|
package/dist/chunk-VXPLLA4P.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as y}from"./chunk-TT4C7DXW.js";import{i as x}from"./chunk-POXANAJ6.js";import{E as T,m as A,p as f,t as b}from"./chunk-LYCLF26R.js";import{b as m,c as R}from"./chunk-CK2E7BTU.js";function N(r,e){let t=r.cache??0;return t>=e?!1:(r.down([[R],[m,t+1]]),!0)}var M=b((r,e)=>{r("observe"),r("signal"),e("write")});function q(r){let e=y([],{name:r.name,maxSize:r.retainedLimit??1024,guard:r.guard??M,...r.versioning!=null?{versioning:r.versioning}:{}});return e.withLatest(),r.graph&&r.graph.add(e.entries,{name:r.name}),e}function p(r){if(r===null||typeof r!="object"||Object.isFrozen(r))return r;for(let e of Object.keys(r))p(r[e]);return Object.freeze(r)}function w(r){let e=r.cache,u=(typeof e=="number"&&Number.isFinite(e)?e:0)+1;return r.down([[R],[m,u]]),u}function g(r,e,t,u,i,s){let o=e(t,u,i);if(o===void 0)return;let a=s!=null?{...o,handlerVersion:s}:o;r.append(a)}function z(r,e){let t=e.freeze??!0;return function(...i){let s=t?i.map(p):i,o=f(),a=e.seq?w(e.seq):void 0;try{let n=r(...s);return e.onSuccess&&g(e.audit,e.onSuccess,s,n,{t_ns:o,seq:a},e.handlerVersion),n}catch(n){if(e.onFailure){let d=n instanceof Error?n.name:typeof n;g(e.audit,e.onFailure,s,n,{t_ns:o,seq:a,errorType:d},e.handlerVersion)}throw n}}}function G(r,e){let t=e.freeze??!0;return function(...i){let s=t?i.map(p):i,o=f(),a,n,d=!1,l;try{A(()=>{e.seq&&(l=w(e.seq));try{a=r(...s),e.onSuccess&&g(e.audit,e.onSuccess,s,a,{t_ns:o,seq:l},e.handlerVersion)}catch(c){throw n=c,d=!0,c}})}catch(c){if(d&&e.onFailure){let h=n instanceof Error?n.name:typeof n;g(e.audit,e.onFailure,s,n,{t_ns:o,seq:l,errorType:h},e.handlerVersion)}throw d?n:c}return a}}function V(r,e,t=0){let u=T(t,{name:e,describeKind:"state"});return r.add(u,{name:e}),u}function _(r,e,t,u=0){let i={},s=new x(e);for(let o of t){let a=T(u,{name:o,describeKind:"state"});s.add(a,{name:o}),i[o]=a}return r.mount(e,s),i}export{N as a,M as b,q as c,w as d,g as e,z as f,G as g,V as h,_ as i};
|
package/dist/chunk-WZYB3JQS.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as E}from"./chunk-TZQPPQEQ.js";import{t as I,x as w}from"./chunk-AK5RHMC5.js";import{m as d,s as g}from"./chunk-L77I47VU.js";import{c as O}from"./chunk-35JTVPOX.js";import{E as R,G as V,m as h}from"./chunk-LYCLF26R.js";import{b}from"./chunk-CK2E7BTU.js";function C(o){return typeof o=="object"&&o!==null&&"cache"in o&&typeof o.subscribe=="function"}function H(o,a,e){let r=d(o),t=r.v!=null,p=R(e?.initialVerified??null,{meta:{...O("verifiable"),...t?{sourceVersion:null}:{}}}),x=e?.trigger!==void 0&&e.trigger!==null,s=null;if(x&&e?.autoVerify?s=I(d(e.trigger),r):x?s=d(e.trigger):e?.autoVerify&&(s=r),s!==null){let y;if(s===r)y=w(r,c=>a(c));else{let c=r.cache;r.subscribe(f=>{for(let M of f)M[0]===b&&(c=M[1])}),y=w(s,()=>a(c))}g(y,c=>{h(()=>{if(p.down([[b,c]]),t){let f=r.v;f!=null&&p.meta.sourceVersion.down([[b,{id:f.id,version:f.version}]])}})})}return{node:r,verified:p,trigger:s}}function B(o){o.subscribe(()=>{})}function v(o){return o instanceof Map?o:new Map}function S(o,a){if(!Array.isArray(a.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");h(()=>{for(let{key:e,value:r}of a.upsert)o.set(e,r);for(let e of a.remove??[])o.delete(e)})}function J(o,a,e){let r=d(o),t=E(e.mapOptions??{}),p=e.budget??2e3,s=e.context!==void 0&&e.context!==null?d(e.context):R(null),y=v(t.entries.cache);t.entries.subscribe(i=>{for(let u of i)u[0]===b&&(y=v(u[1]))});let c=d(a(r,t.entries));if(g(c,i=>{S(t,i)}),e.evict){let i=new Map,u=V([t.entries],([l])=>{let m=[],N=v(l);for(let n of i.keys())N.has(n)||(i.get(n)(),i.delete(n));for(let[n,T]of N){let k=e.evict(n,T);if(C(k)){if(!i.has(n)){let D=g(k,z=>{z===!0&&t.has(n)&&t.delete(n)});i.set(n,D)}continue}if(typeof k=="boolean"){k&&m.push(n);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return m});g(u,l=>{for(let m of l)t.delete(m)})}let f=e.consolidateTrigger!==void 0&&e.consolidateTrigger!==null;if(e.consolidate&&f){let i=d(e.consolidateTrigger),u=w(i,()=>e.consolidate(y));g(u,l=>{S(t,l)})}let M=V([t.entries,s],([i,u])=>{let l=[...v(i).entries()].map(([n,T])=>({key:n,value:T,score:e.score(T,u),cost:e.cost(T)}));l.sort((n,T)=>T.score-n.score);let m=[],N=p;for(let n of l)n.cost<=N&&(m.push({key:n.key,value:n.value,score:n.score}),N-=n.cost);return m},{meta:{...O("distill",{budget:p})}}),A=V([t.entries],([i])=>v(i).size);return B(M),B(A),{store:t,compact:M,size:A}}export{H as a,J as b};
|
package/dist/chunk-Z6X7B6A4.js
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import{h as Lt}from"./chunk-F7VUYPP6.js";import{a as kt,b as Rt,c as xt,d as wt}from"./chunk-GI4Q7PNY.js";import{c as vt}from"./chunk-7PQLZMOG.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-VV62MIG4.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-UISPDFJ3.js";import{f as $e}from"./chunk-URJ2VFNC.js";import{b as Tt}from"./chunk-WZYB3JQS.js";import{a as we,b as Mt}from"./chunk-TSOYJ743.js";import{b as ut,c as Re,d as mt,f as je}from"./chunk-4MKL6Q3K.js";import{b as xe}from"./chunk-TZQPPQEQ.js";import{a as dt}from"./chunk-L6NSJVJZ.js";import{b as pe}from"./chunk-TT4C7DXW.js";import{i as se}from"./chunk-POXANAJ6.js";import{a as Z}from"./chunk-ESMPEKEV.js";import{R as bt,b as yt,s as ht,x as $}from"./chunk-AK5RHMC5.js";import{A as gt,C as j,f as ct,k as _e,l as pt,m as x,x as ae,z as ft}from"./chunk-L77I47VU.js";import{b as ke,c as X}from"./chunk-35JTVPOX.js";import{D as le,E as L,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:()=>Kr,admissionScored:()=>Gt,agentLoop:()=>Br,agentMemory:()=>Ur,anthropicAdapter:()=>Ht,canonicalJson:()=>Yt,cascadingLlmAdapter:()=>Be,chatStream:()=>rt,composePricing:()=>lr,computePrice:()=>We,contentGate:()=>jr,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:()=>$r,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:()=>_r,registryPricing:()=>ir,resilientAdapter:()=>Mr,streamExtractor:()=>Ir,streamingPromptNode:()=>Lr,suggestStrategy:()=>Wt,suggestStrategyReactive:()=>Qr,systemPromptBuilder:()=>Ar,tier:()=>rr,toolCallExtractor:()=>Pr,toolExecution:()=>nt,toolRegistry:()=>ot,toolSelector:()=>Wr,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=i=>{e.set(Te(i.provider,i.id),i)};if(t)for(let i of t)r(i);let n=(i,d)=>{let m=e.get(Te(i,d));if(m)return m;let c=e.entries.cache;if(!c)return;let p;for(let[,g]of c){if(g.provider!==i)continue;let y=g.id;d.startsWith(y)&&(!p||y.length>p.id.length)&&(p=g)}return p},o=128,a=new Map,s=new Map,l=(i,d,m,c)=>{for(i.has(d)&&i.delete(d),i.set(d,m);i.size>c;){let p=i.keys().next().value;if(p===void 0)break;i.delete(p)}},u=v([e.entries],([i])=>Array.from(i.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:r,lookup:n,remove(i,d){let m=e.has(Te(i,d));return m&&e.delete(Te(i,d)),m},entries(){let i=e.entries.cache;return(function*(){if(i)for(let d of i.values())yield d})()},lookupNode(i,d){let m=Te(i,d),c=a.get(m);if(c)return a.delete(m),a.set(m,c),c;let p=v([e.entries],()=>n(i,d),{name:`capabilitiesRegistry/lookup/${i}::${d}`,initial:void 0});return l(a,m,p,o),p},entriesNode:u,byProvider(i){let d=s.get(i);if(d)return s.delete(i),s.set(i,d),d;let m=v([u],([c])=>c.filter(p=>p.provider===i),{name:`capabilitiesRegistry/byProvider/${i}`,initial:[]});return l(s,i,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=L(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}),l=v([n.entries],([y])=>y.reduce((f,h)=>f+ne(h.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[j(a),j(s),j(l)],i=y=>{n.append(y),o.emit(y)},d=()=>{n.clear(),o.emit(null)},m=V(t,{invoke(y,f){let h=H(),b=be(),k=t.model??f?.model??"",R=A=>(i(de({provider:t.provider,model:t.model??f?.model??A.model??"",tier:f?.tier??A.tier,usage:A.usage??ee(),startNs:h,startWallClockNs:b,method:"invoke"})),A),C=A=>{let D=A;i(de({provider:t.provider,model:k,tier:f?.tier,usage:ee(),startNs:h,startWallClockNs:b,method:"invoke",error:{type:D?.name??"Error",message:D?.message??String(A)}}))};return Le(t.invoke(y,f),{onResp:R,onError:C,name:"adapterStats/invokeTap"})},async*stream(y,f){let h=H(),b=be(),k=t.model??f?.model??"",R;try{for await(let C of t.stream(y,f))C.type==="usage"&&(R=C.usage),yield C;i(de({provider:t.provider,model:k,tier:f?.tier,usage:R??ee(),startNs:h,startWallClockNs:b,method:"stream"}))}catch(C){let A=C;throw i(de({provider:t.provider,model:k,tier:f?.tier,usage:R??ee(),startNs:h,startWallClockNs:b,method:"stream",error:{type:A?.name??"Error",message:A?.message??String(C)}})),C}}});U(m,"observableAdapter",t);let c=!1;return{adapter:m,stats:{lastCall:o,allCalls:n,totalCalls:a,totalInputTokens:s,totalOutputTokens:l,reset:d,dispose:()=>{if(!c){c=!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,l=0,u=(f,h,b)=>{if(!h||b==null)return;let k=ar(b,n),R=h*k/1e6;l+=R,a&&(s[f]=(s[f]??0)+R)},i=t.input,d=e.input;if(d&&(u("input.regular",i.regular,d.regular),u("input.cacheRead",i.cacheRead??0,d.cacheRead),u("input.cacheWrite5m",i.cacheWrite5m??0,d.cacheWrite5m),u("input.cacheWrite1h",i.cacheWrite1h??0,d.cacheWrite1h),u("input.cacheWriteOther",i.cacheWriteOther??0,d.cacheWriteOther),u("input.audio",i.audio??0,d.audio),u("input.image",i.image??0,d.image),u("input.video",i.video??0,d.video),u("input.toolUse",i.toolUse??0,d.toolUse),i.extensions&&d.extensions))for(let[f,h]of Object.entries(i.extensions))u(`input.ext.${f}`,h,d.extensions[f]);let m=t.output,c=e.output;if(c&&(u("output.regular",m.regular,c.regular),u("output.reasoning",m.reasoning??0,c.reasoning),u("output.audio",m.audio??0,c.audio),u("output.predictionAccepted",m.predictionAccepted??0,c.predictionAccepted),u("output.predictionRejected",m.predictionRejected??0,c.predictionRejected),m.extensions&&c.extensions))for(let[f,h]of Object.entries(m.extensions))u(`output.ext.${f}`,h,c.extensions[f]);let p=r?.tier;if(p&&e.tierMultipliers){let f=e.tierMultipliers[p];if(f!=null&&(l*=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 k=h*b;l+=k,a&&(s[`auxiliary.${f}`]=k)}return a?{total:l,currency:o,breakdown:s}:{total:l,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 l=r.get(o);l||(l=new Set,r.set(o,l)),l.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 l=r.get(o);if(!l)return;let u;for(let i of l)if(a.startsWith(i)&&(!u||i.length>u.key.length)){let d=e.get(Ne(o,i));d&&(u={key:i,pricing:d.pricing})}return u?.pricing},remove(o,a){let s=e.delete(Ne(o,a));if(s){let l=r.get(o);l?.delete(a),l&&l.size===0&&r.delete(o)}return s},entries(){let o=e.values();return(function*(){for(let{provider:a,model:s,pricing:l}of o)yield[a,s,l]})()}}}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??mt(e),n=V(t,{async invoke(o,a){if(!r.canExecute())throw new Re;try{let s=await ae(x(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=L(At(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=v([n],([i])=>{let d=i;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 i=e.onExhausted,d=!1,m=!0;o.subscribe(c=>{for(let p of c)if(p[0]===G){let g=p[1];if(d&&m&&g===!1){let y=Ct(n.cache??Ve,e.caps);y&&i(y)}m=g,d=!0}})}let a=()=>{if(o.cache===!1){let i=n.cache??Ve,d=Ct(i,e.caps);return new Ce(d??"budget",e.caps[d??"calls"]??0,ur(i,d??"calls"))}},s=(i,d)=>{let m=t.provider,c=de({provider:m,model:d.model,tier:d.tier,usage:i,startNs:d.startNs,method:d.method,...d.error?{error:d.error}:{}});r.append(c);let p=n.cache??Ve,g=e.pricingFn?p.usd+e.pricingFn(i,{model:d.model,provider:m,tier:d.tier}).total:p.usd;n.emit({calls:p.calls+1,inputTokens:p.inputTokens+z(i),outputTokens:p.outputTokens+ne(i),usd:g})},l=()=>{r.clear(),n.emit(At())},u=V(t,{invoke(i,d){let m=a();if(m)return Promise.reject(m);let c=H(),p=t.model??d?.model??"",g=f=>(s(f.usage??ee(),{model:t.model??d?.model??f.model??"",tier:d?.tier??f.tier,startNs:c,method:"invoke"}),f),y=f=>{let h=f;s(ee(),{model:p,tier:d?.tier,startNs:c,method:"invoke",error:{type:h?.name??"Error",message:h?.message??String(f)}})};return Le(t.invoke(i,d),{onResp:g,onError:y,name:"budgetGate/invokeTap"})},async*stream(i,d){let m=a();if(m)throw m;let c=H(),p;try{for await(let g of t.stream(i,d))g.type==="usage"&&(p=g.usage),yield g;s(p??ee(),{model:t.model??d?.model??"",tier:d?.tier,startNs:c,method:"stream"})}catch(g){let y=g;throw s(p??ee(),{model:t.model??d?.model??"",tier:d?.tier,startNs:c,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:l}}}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?x(e.enabled):void 0,a;o&&(a=j(o));let s=()=>n!==void 0?n:!!o?.cache,l=V(t,{invoke(i,d){return s()?r.invoke(i,d):t.invoke(i,d)},stream(i,d){return s()?r.stream(i,d):t.stream(i,d)}});return U(l,"withDryRun",t),{adapter:l,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 l=n("anthropic-ratelimit-requests-reset");if(l){let p=St(l);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let u=n("anthropic-ratelimit-tokens-reset");if(u){let p=St(u);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let i=Se(n,"x-ratelimit-limit-requests");i!=null&&(o.rpmCap=i);let d=Se(n,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let m=Se(n,"x-ratelimit-remaining-requests"),c=Se(n,"x-ratelimit-remaining-tokens");if(m!=null&&i!=null&&i>0&&(o.usageHint??={},o.usageHint.rpm=1-m/i),c!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-c/d),o.retryAfterMs==null&&e.message){let p=yr(e.message);p!=null&&(o.retryAfterMs=p)}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?x(t.rpm):L(Number.POSITIVE_INFINITY),o=t.tpm!=null?x(t.tpm):L(Number.POSITIVE_INFINITY),a=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),s=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),l=L({},{name:"adaptiveRateLimiter/lastSignal"}),u=v([n,a],([T,I])=>Math.min(Number(T??1/0),Number(I??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),i=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),c=!1,p=!1,g=u.subscribe(T=>{for(let I of T)if(I[0]===G){let P=Number(I[1]);Number.isFinite(P)&&P>0?(d=fe(P,e),c=!1):P===1/0?(d=fe(1/0,e),c=!1):P<=0&&(c=!0)}}),y=i.subscribe(T=>{for(let I of T)if(I[0]===G){let P=Number(I[1]);Number.isFinite(P)&&P>0?(m=fe(P,e),p=!1):P===1/0?(m=fe(1/0,e),p=!1):P<=0&&(p=!0)}}),f=0,h=new Z,b=new Z,k;t.adaptation!=null&&(k=x(t.adaptation).subscribe(I=>{for(let P of I)P[0]===G&&R(P[1])}));function R(T){if(l.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=L(0,{name:"adaptiveRateLimiter/pending"}),A=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),D=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),_=T=>{C.emit((C.cache??0)+T)},E=()=>{A.emit(d.available()),D.emit(m.available())};async function O(T={}){let I=T.requestCost??1,P=T.tokenCost??0,K=T.signal;_(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&&c||P>0&&p){await Ee(250,K);continue}let ie=d,ue=m;if(!ie.tryConsume(I)){await Ee(Et(ie,I),K);continue}if(!(P>0?ue.tryConsume(P):!0)){ie.putBack(I),await Ee(Et(ue,P),K);continue}E();return}}finally{_(-1)}}function S(T){T>0?m.tryConsume(T):T<0&&m.putBack(-T),E()}function F(){g(),y(),k?.(),h.cancel(),b.cancel()}return{effectiveRpm:u,effectiveTpm:i,lastSignal:l,pending:C,rpmAvailable:A,tpmAvailable:D,acquire:O,recordUsage:S,recordSignal:R,dispose:F}}function fe(t,e){if(!Number.isFinite(t)||t===1/0)return je(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let r=Math.max(1,t*e),n=t/60;return je(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,l)=>e.costFn?e.costFn(s,l):0,o=s=>{let l=qe(s);l&&r.recordSignal(l)},a=V(t,{async invoke(s,l){let u=n(s,l);await r.acquire({requestCost:1,tokenCost:u,signal:l?.signal});try{let i=await ae(x(t.invoke(s,l))),d=i.usage??Nt(),c=z(d)+ne(d)-u;return c>0&&r.recordUsage(c),i}catch(i){throw o(i),i}},async*stream(s,l){let u=n(s,l);await r.acquire({requestCost:1,tokenCost:u,signal:l?.signal});try{let i=0;for await(let m of t.stream(s,l))m.type==="usage"&&(i=z(m.usage)+ne(m.usage)),yield m;let d=i-u;d>0&&r.recordUsage(d)}catch(i){throw o(i),i}}});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,l=e.shouldRetry??Tr,u=e.retryStreaming??!0,i=(m,c)=>{if(a==="decorrelated"){let f=Math.min(o,Math.max(n,c*3));return n+Math.random()*(f-n)}let p=a==="exp"?n*2**(m-1):n*m,g=Math.min(o,p);if(!s)return g;let y=g*(.5+Math.random());return Math.min(o,y)},d=V(t,{async invoke(m,c){if(c?.signal?.aborted)throw Oe();let p,g=n;for(let y=1;y<=r;y++)try{return await ae(x(t.invoke(m,c)))}catch(f){if(p=f,y>=r||!l(f,y))throw f;let h=i(y,g);g=h,await It(h,c?.signal)}throw p},async*stream(m,c){if(c?.signal?.aborted)throw Oe();if(!u){for await(let y of t.stream(m,c))yield y;return}let p,g=n;for(let y=1;y<=r;y++){let f=!1;try{for await(let h of t.stream(m,c))f=!0,yield h;return}catch(h){if(p=h,f||y>=r||!l(h,y))throw h;let b=i(y,g);g=b,await It(b,c?.signal)}}throw p}});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,l=!1,u,i=new Z;return a&&(a.aborted?s.abort(a.reason):(u=()=>{i.cancel(),s.abort(a.reason)},a.addEventListener("abort",u,{once:!0}))),i.start(e,()=>{l=!0,s.abort(new ge(e))}),{signal:s.signal,cancel:()=>{i.cancel(),a&&u&&a.removeEventListener("abort",u)},timedOut:()=>l}},n=(a,s)=>{if(!s||a instanceof ge)throw a;let l=a;if(l?.name==="AbortError"||l?.name==="DOMException"&&Number(l.code)===20||a?.message==="aborted"){let i=new ge(e);throw i.cause=a,i}throw a},o=V(t,{async invoke(a,s){let{signal:l,cancel:u,timedOut:i}=r(s?.signal);try{return await ae(x(t.invoke(a,{...s,signal:l})))}catch(d){return n(d,i())}finally{u()}},async*stream(a,s){let{signal:l,cancel:u,timedOut:i}=r(s?.signal);try{for await(let d of t.stream(a,{...s,signal:l}))yield d}catch(d){n(d,i())}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 N(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(l=>{for(let u of l){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(x(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,l=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 l(r.onFailure("throw",d)),()=>o.abort()}return s=x(u,{signal:o.signal}).subscribe(d=>{for(let m of d){if(a)return;if(m[0]===G){try{l(r.onSuccess(m[1]))}catch(c){l(r.onFailure("onSuccess-threw",c))}return}if(m[0]===W){l(r.onFailure("error",m[1]));return}if(m[0]===q){l(r.onFailure("complete",void 0));return}}}),a&&s&&(s(),s=null),()=>{o.abort(),s?.(),s=null}})}function xr(t,e){let r=x(t),n=e?.refreshTrigger!=null?x(e.refreshTrigger):null,o=e?.name!==void 0?{name:e.name}:void 0,a=X("frozenContext",o);return n==null?le([r],(s,l,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,l.emit(m),{invalidate:()=>{u.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context",{...a})}):le([r,n],(s,l,u)=>{let i=s[1];if(!(i!=null&&i.length>0))return;let m=s[0],c=m!=null&&m.length>0?m.at(-1):u.prevData[0];l.emit(c)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("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=v(e,u=>{if(u.some(d=>d==null))return[];let i=typeof r=="string"?r:r(...u);return i?[{role:"user",content:i}]:[]},{name:`${a}::messages`,meta:N("prompt_node")});return $(s,u=>!u||u.length===0?L(null):Q(i=>{let d=!1,m=!1,c,p={model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,...n?.tools!==void 0?{tools:n.tools}:{}};if(n?.abort){let h=gt(n.abort);p.signal=h.signal,c=h.dispose}let g;try{g=t.invoke(u,p)}catch(h){return d=!0,i.down([[W,h]]),()=>{c?.()}}let f=x(g).subscribe(h=>{if(!(m||d))for(let b of h){if(d)return;if(b[0]===G){let k=b[1];if(o==="raw")i.emit(k);else try{let R=Pt(k),C=o==="json"?JSON.parse(ye(R)):R;i.emit(C)}catch(R){let C=Pt(k),A=new Error(`promptNode: failed to parse LLM response as JSON: ${R.message}
|
|
2
|
-
Raw content (first 200 chars): ${wr(C)}`);d=!0,i.down([[W,A]]);return}}else if(b[0]===W){d=!0,i.down([[W,b[1]]]);return}else if(b[0]===q){d=!0,i.down([[q]]);return}else i.down([b])}});return()=>{m=!0,f(),c?.()}},{name:`${a}::call`,meta:N("prompt_node::call")}),{name:`${a}::output`,meta:n?.meta?{...N("prompt_node::output"),...n.meta}:N("prompt_node::output")})}function Ze(t,e,r,n){let o=r.name??n;return a=>{let s=L(a);return Xe(r.adapter,[s],l=>e(l),{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 jt(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 _t(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:N("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}:{}}),l=v(e,m=>{if(m.some(p=>p==null))return[];let c=typeof r=="string"?r:r(...m);return c?[{role:"user",content:c}]:[]},{name:`${o}::messages`,meta:N("prompt_node::messages"),initial:[]}),u=$(l,m=>{let c=m;if(!c||c.length===0)return L(null);let p=new AbortController;async function*g(){try{let y=await jt(t,c,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,signal:p.signal},s);yield _t(y,a)}finally{p.abort()}}return x(g())},{meta:X("streamingPromptNode")}),i=Ft(s,`${o}::accumulatedText`),d=j(u);return{output:u,deltaTopic:s,accumulatedText:i,dispose:()=>{d(),s.destroy()}}}function Nr(t,e,r,n,o,a){let s=L(0,{name:`${e}/cancel`}),l=0,u=[...n,s],i=a?.name??e,d=a?.format??"text",m=$e(`${i}/stream`,{...a?.retainedLimit!=null?{retainedLimit:a.retainedLimit}:{}}),c=v(u,D=>{let _=D.slice(0,-1);if(_.some(O=>O==null))return[];let E=typeof o=="string"?o:o(..._);return E?[{role:"user",content:E}]:[]},{name:`${i}::messages`,meta:N("prompt_node::messages"),initial:[]}),p=$(c,D=>{let _=D;if(!_||_.length===0)return L(null);let E=new AbortController;async function*O(){try{let S=await jt(r,_,{model:a?.model,temperature:a?.temperature,maxTokens:a?.maxTokens,systemPrompt:a?.systemPrompt,signal:E.signal},m);yield _t(S,d)}finally{E.abort()}}return x(O())},{meta:X("gatedStream")}),g=Ft(m,`${i}::accumulatedText`),y=yt(p,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(p),k=j(h.node),R=j(g);t.addDisposer(b),t.addDisposer(k),t.addDisposer(R);let C=h.reject.bind(h),A={...h,reject(D=1){J(()=>{C(D),s.emit(++l)})}};return{output:h.node,deltaTopic:m,accumulatedText:g,gate:A,dispose:()=>{b(),k(),R(),m.destroy()}}}function Ar(t,e){let r=e?.separator??`
|
|
3
|
-
|
|
4
|
-
`,n=t.map(s=>typeof s=="string"?L(s):x(s)),o=v(n,s=>s.filter(l=>l!=null&&l!=="").join(r),{name:e?.name??"systemPrompt",describeKind:"derived",meta:N("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 l=a.store;s.type==="token"?(l.chunkCount+=1,l.charCount+=s.delta.length):s.type==="usage"&&(l.sawUsage=!0,l.usageTokens=z(s.usage)+ne(s.usage));let u=l.sawUsage?l.usageTokens:Math.ceil(l.charCount/r);return{chunkCount:l.chunkCount,charCount:l.charCount,estimatedTokens:u,estimated:!l.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:n,meta:N("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 l=a.store.flags,u=a.store.scannedTo,i=Math.max(0,u-r),d=s.slice(i),m=!1;for(let{pattern:c,label:p,compiled:g}of n){g.lastIndex=0;for(let y of d.matchAll(g)){let f=i+(y.index??0);f+y[0].length<=u||(l.push({label:p,pattern:c,match:y[0],position:f}),m=!0)}}return a.store.scannedTo=s.length,m?[...l]:l.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:N("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:N("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,l=!1;for(;s<o.length;){let u=o.indexOf("{",s);if(u===-1){n.store.scanFrom=o.length;break}let i=0,d=-1,m=!1;for(let p=u;p<o.length;p++){let g=o[p];if(m)g==="\\"&&p+1<o.length?p++:g==='"'&&(m=!1);else if(g==='"')m=!0;else if(g==="{")i++;else if(g==="}"&&(i--,i===0)){d=p;break}}if(d===-1){n.store.scanFrom=u;break}let c=o.slice(u,d+1);try{let p=JSON.parse(c);typeof p.name=="string"&&p.arguments!=null&&typeof p.arguments=="object"&&(a.push({name:p.name,arguments:p.arguments,raw:c,startIndex:u}),l=!0)}catch{}s=d+1,n.store.scanFrom=s}return l?[...a]:a.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:N("tool_call_extractor"),equals:Dr})}function jr(t,e,r,n){let o=r*(n?.hardMultiplier??1.5),a=typeof e!="function",s=[t];return a&&s.push(e),v(s,l=>{let u=l[0]??"";if(u.length===0)return"allow";let i=a?l[1]??0:e(u);return i>=o?"block":i>=r?"review":"allow"},{name:n?.name??"content-gate",initial:"allow"})}function _r(t,e,r,n){let o=r??(()=>"[REDACTED]");function a(s){let l=s;for(let u of e){let i=u.global?u:new RegExp(u.source,`${u.flags}g`);l=l.replace(i,d=>o(d,u))}return l}return v([t],([s])=>a(s??""),{name:n?.name??"redactor",initial:""})}var Ie=class extends se{_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:N("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:N("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 nt(t){let{toolCalls:e,tools:r}=t,n=t.retryCount??1,o=t.onError??"rescue",a=(s,l)=>{if(s===l)return!0;if(s.length!==l.length)return!1;for(let u=0;u<s.length;u++){let i=s[u],d=l[u];if(i?.id!==d?.id||i?.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 l=s.map(u=>Fr(u,r,n,o));return v(l,u=>u,{name:"toolExecution::batch",equals:a})})}function Fr(t,e,r,n){let o=ut(()=>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:bt(a,s=>({id:t.id,content:JSON.stringify({error:String(s)})}))}var De=class extends se{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:N("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=Gr(u,a.signal)}catch(u){return o.down([[W,u]]),()=>{a.abort()}}let l=s.subscribe(u=>{o.down(u)});return()=>{a.abort(),l()}},{name:`executeReactive::${e}`,meta:N("tool_execute_reactive")})}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function ot(t,e){return new De(t,e)}function Gr(t,e){return Qe(t)?t:t!=null&&typeof t.then=="function"?_e(t,{signal:e}):t!=null&&typeof t=="object"&&Symbol.asyncIterator in t?pt(t,{signal:e}):_e(Promise.resolve(t),{signal:e})}var Pe=class extends se{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 w of r.tools)this.tools.register(w);this.status=L("idle",{name:"status",describeKind:"state",meta:N("agent_status")}),this.add(this.status,{name:"status"}),this.turn=L(0,{name:"turn",describeKind:"state",meta:N("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=L(!1,{name:"aborted",describeKind:"state",meta:N("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let n=0,o=this.turn.subscribe(w=>{for(let M of w)M[0]===G&&(n=M[1])}),a=!1,s=this.aborted.subscribe(w=>{for(let M of w)M[0]===G&&(a=M[1])}),l=this.chat.messages.cache??[],u=this.chat.messages.subscribe(w=>{for(let M of w)M[0]===G&&(l=M[1])}),i=this.tools.schemas.cache??[],d=this.tools.schemas.subscribe(w=>{for(let M of w)M[0]===G&&(i=M[1])}),m=r.adapter,c=r.systemPrompt,p=r.model,g=r.temperature,y=r.maxTokens,f=r.maxTurns??10,h=r.stopWhen,b=this.chat,k=this.tools,R=this.status,C=this.turn,A=this.aborted,D=le([R],(w,M,B)=>{if(ve(w,B.prevData,0,"idle")!=="thinking"||a||n>=f){M.down([[ce]]);return}if(l.length===0){M.down([[ce]]);return}M.emit({messages:l,tools:i})},{name:"promptInput",describeKind:"derived",meta:N("agent_prompt_input",{closureReads:["aborted","turn","chat.messages","tools.schemas"]})}),_=$(D,w=>{let M=new AbortController;return this._currentAbortController=M,a&&M.abort(new Error("agentLoop: aborted")),x(m.invoke(w.messages,{tools:w.tools.length>0?w.tools:void 0,systemPrompt:c,model:p,temperature:g,maxTokens:y,signal:M.signal}),{signal:M.signal})},{equals:()=>!1}),E=L(null,{name:"lastResponse",describeKind:"state",meta:N("agent_last_response")});this.lastResponse=E;let O=le([E,R],(w,M,B)=>{let Y=ve(w,B.prevData,0,null);if(ve(w,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:N("agent_tool_calls_raw")}),S=r.interceptToolCalls?r.interceptToolCalls(O):O;this.toolCalls=S;let F=nt({toolCalls:S,tools:k,retryCount:1});this.toolResults=F;let T=re([_],([w])=>{if(a)return;let M=w,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(()=>{E.emit(M),R.emit(Ut),C.emit(B),b.append("assistant",M.content,{toolCalls:M.toolCalls})})}),I=re([F],([w])=>{if(a)return;let M=w;if(M.length===0)return;let B=n>=f?"done":"thinking";J(()=>{R.emit(B);for(let Y of M)b.appendToolResult(Y.id,Y.content)})}),P=R.cache??"idle",K=R.subscribe(w=>{for(let M of w)M[0]===G&&(P=M[1])}),te=re([A],([w])=>{w===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),P!=="done"&&R.emit("done"))}),ie=j(T),ue=j(I),me=j(te);this._terminalResult=le([R,E],(w,M,B)=>{let Y=ve(w,B.prevData,0,"idle"),he=ve(w,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:N("agent_terminal_result")}),this.add(D,{name:"promptInput"}),this.add(_,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===O?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(O,{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=ft(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 Br(t,e){let r=new Pe(t,e);return r.tagFactory("agentLoop",ke(e)),r}function $r(t,e,r){let n=x(t),o=r?.condition!=null?x(r.condition):null,a=L(null,{name:r?.name?`${r.name}::null`:"handoff::null"});if(o==null)return $(n,l=>{if(l==null)return a;let u=L(l);return e(u)},{meta:X("handoff")});let s=v([n,o],([l,u])=>({v:l,open:u===!0}),{name:r?.name?`${r.name}::router`:"handoff::router",describeKind:"derived"});return $(s,({v:l,open:u})=>{if(l==null)return a;if(!u)return L(l);let i=L(l);return e(i)},{meta:X("handoff")})}function Wr(t,e,r){let n=x(t),o=e.map(s=>x(s)),a=[n,...o];return v(a,s=>{let l=s[0]??[],u=s.slice(1);return l.filter(i=>{for(let d of u)if(d!=null&&!d(i))return!1;return!0})},{name:r?.name??"tool-selector",describeKind:"derived",meta:{...N("tool_selector"),...X("toolSelector")},equals:(s,l)=>{let u=s,i=l;if(u.length!==i.length)return!1;for(let d=0;d<u.length;d++)if(u[d]!==i[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 Kr(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 l=s??new Map;for(let[u,i]of l){let d=r.embedFn(i);d&&n.upsert(u,d,i)}}).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],([i])=>{let d=i??new Map;for(let[m,c]of d){let p=s(m,c);if(p){for(let g of p.entities??[])a.upsertEntity(g.id,g.value);for(let g of p.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),l=Rt("permanent",{ranked:!1});t.mount("permanent",l);let u=new Set,i=b=>u.has(b)?"permanent":(e.store.entries.cache??new Map).has(b)?"active":"archived",d=(b,k)=>{u.add(b),l.upsert(b,k)},m=new Map,c=e.store.entries,p=r.context?x(r.context):L(null),y=re([c,p],([b,k])=>{let R=b??new Map,C=H(),A=[],D=[];for(let[E,O]of R){if(m.has(E)||m.set(E,C),s(E,O)){D.push({key:E,value:O});continue}let S=r.score(O,k),F=m.get(E)??C,T=Number(C-F)/1e9;Mt(S,T,n)<a&&A.push(E)}for(let E of m.keys())R.has(E)||m.delete(E);for(let{key:E,value:O}of D)u.has(E)||d(E,O);let _=R.size-u.size;if(_>o){let E=[...R.entries()].filter(([S])=>!u.has(S)).map(([S,F])=>({key:S,score:r.score(F,k)})).sort((S,F)=>S.score-F.score),O=_-o;for(let S=0;S<O&&S<E.length;S++){let F=E[S].key;A.includes(F)||A.push(F)}}A.length>0&&J(()=>{for(let E of A)e.store.delete(E)})}).subscribe(()=>{}),f=null;r.archiveTier&&(f=t.attachSnapshotStorage([r.archiveTier],r.archiveStorageOptions??{}));let h=()=>{y(),f?.dispose()};return t.addDisposer(h),{tiers:{permanent:l,activeEntries:c,archiveHandle:f,tierOf:i,markPermanent:d},dispose:h}}function Vr(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,l=o.budget??2e3,u=o.contextWeight??0,i=o.context?x(o.context):L(null),d=(f,h,b)=>{let k=new Map,R=[];if(r&&b.vector){let O=b.vector,S=r.entries.cache;if(S&&S.size>0&&a>0){R=[...S.values()].map(T=>({id:T.id,score:kt(O,T.vector),...T.meta!==void 0?{meta:T.meta}:{}})).sort((T,I)=>I.score-T.score).slice(0,a);for(let T of R){let I=f.get(T.id);I&&k.set(T.id,{value:I,sources:new Set(["vector"])})}}}let C=[];if(n){let O=n.adjacencyOut.cache,S=n.adjacencyIn.cache,F=[...b.entityIds??[],...k.keys()],T=new Set,I=F;for(let P=0;P<s;P++){let K=[];for(let te of I){if(T.has(te))continue;T.add(te);let ie=O?.get(te)??[],ue=S?.get(te)??[];for(let me of ie){let w=me.to;if(!T.has(w)){K.push(w);let M=f.get(w);if(M){let B=k.get(w);B?B.sources.add("graph"):k.set(w,{value:M,sources:new Set(["graph"])}),C.push(w)}}}for(let me of ue){let w=me.from;if(!T.has(w)){K.push(w);let M=f.get(w);if(M){let B=k.get(w);B?B.sources.add("graph"):k.set(w,{value:M,sources:new Set(["graph"])}),C.push(w)}}}}I=K}}for(let[O,S]of f)k.has(O)||k.set(O,{value:S,sources:new Set(["store"])});let A=b.context?.length??0,D=[];for(let[O,{value:S,sources:F}]of k){let T=o.contextOf?o.contextOf(S):void 0,I=o.score(S,h);if(u>0&&A>0){let K=Vr(b.context,T);K>0&&(I=I*(1+u*K/A))}let P=T?{key:O,value:S,score:I,sources:[...F],context:T}:{key:O,value:S,score:I,sources:[...F]};D.push(P)}D.sort((O,S)=>S.score-O.score);let _=[],E=0;for(let O of D){let S=o.cost(O.value);if(E+S>l&&_.length>0)break;_.push(O),E+=S}return{packed:_,trace:{vectorCandidates:R,graphExpanded:C,ranked:D,packed:_}}},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},c=L([],{name:"retrieval",describeKind:"state",meta:N("retrieval_pipeline"),equals:m});t.add(c,{name:"retrieval"});let p=L(null,{name:"retrievalTrace",describeKind:"state",meta:N("retrieval_trace")});return t.add(p,{name:"retrievalTrace"}),{retrieval:c,retrievalTrace:p,retrieve:f=>{let h=e.store.entries.cache??new Map,{packed:b,trace:k}=d(h,i.cache,f);return J(()=>{c.emit(b),p.emit(k)}),b},retrieveReactive:f=>{let h=x(f),b=v([e.store.entries,i,h],([C,A,D])=>{if(D==null)return{packed:[],trace:null};let _=C??new Map,{packed:E,trace:O}=d(_,A,D);return{packed:E,trace:O}},{name:"retrievalReactive::result",describeKind:"derived",meta:N("retrieval_reactive_result"),initial:{packed:[],trace:null}}),R=re([b],([C])=>{let A=C;J(()=>{c.emit(A.packed),A.trace&&p.emit(A.trace)})}).subscribe(()=>{});return t.addDisposer(R),v([b],([C])=>C.packed,{name:"retrievalReactive",describeKind:"derived",meta:N("retrieval_reactive"),initial:[],equals:m})}}}function Ur(t,e,r){let n=new se(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,k)=>{let R=k.cache??new Map,C=k.subscribe(A=>{for(let D of A)D[0]===G&&(R=D[1])});return n.addDisposer(C),$(b,A=>A==null?{upsert:[]}:o(A,R))},s=e;if(r.admissionFilter){let b=x(e),k=r.admissionFilter;s=v([b],([R])=>{if(k(R))return R},{name:"admissionFilter",describeKind:"derived"})}let l;r.consolidateFn?l=r.consolidateFn:r.adapter&&r.consolidatePrompt&&(l=tt(r.consolidatePrompt,{adapter:r.adapter}));let u=r.consolidateTrigger;if(!u&&l&&r.reflection?.enabled!==!1){let b=r.reflection?.interval??3e5;u=ct(b,{period:b})}let i={score:r.score,cost:r.cost,budget:r.budget??2e3,context:r.context,consolidate:l,consolidateTrigger:u},d=Tt(s,a,i);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 c=null;r.enableKnowledgeGraph&&(c=st(n,d,t,{mountPath:"kg",entityFn:r.entityFn}).kg);let p=null;r.tiers&&(p=it(n,d,{...r.tiers,score:r.score,context:r.context}).tiers);let g=null,y=null,f=null,h=null;if(m||c){let b=lt(n,d,m,c,{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:c,memoryTiers:p,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=[],l=r?.sinceVersion;for(let[u,i]of Object.entries(n.nodes)){let d=i.meta??{},m=d.description,c=d.format;if(!m&&!c)continue;if(l!=null&&i.v!=null){let h=l.get(u);if(h!=null&&h.id===i.v.id&&i.v.version<=h.version)continue}let p=m??u,g=i.value,y=d.unit,f;c==="currency"&&typeof g=="number"?f=`$${g.toFixed(2)}`:c==="percentage"&&typeof g=="number"?f=`${(g*100).toFixed(1)}%`:g==null?f="(no value)":f=String(g),y&&c!=="currency"&&c!=="percentage"&&(f=`${f} ${y}`),s.push({path:u,description:p,formatted:f})}if(s.length===0)return"";if(o){let u=new Map,i=[];for(let m of s){let p=n.nodes[m.path].meta?.tags;if(p&&p.length>0){let g=p[0],y=u.get(g);y||(y=[],u.set(g,y)),y.push(m)}else i.push(m)}if(u.size===0)return s.map(m=>`- ${m.description}: ${m.formatted}`).join(a);let d=[];for(let[m,c]of[...u.entries()].sort((p,g)=>p[0].localeCompare(g[0])))d.push(`[${m}]${a}${c.map(p=>`- ${p.description}: ${p.formatted}`).join(a)}`);return i.length>0&&d.push(i.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}),l=(await Me(a)).content.trim();l.startsWith("```")&&(l=ye(l));let u;try{u=JSON.parse(l)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${l.slice(0,200)}`)}return Lt(u,{catalog:r?.catalog})}function Hr(t,e,r){let n=x(t);return $(n,o=>!o||typeof o!="string"||o.trim().length===0?L(null):Q(a=>{let s=new AbortController,l=!1;return $t(o,e,{...r,signal:s.signal}).then(u=>{if(l){u.destroy();return}a.emit(u),a.down([[q]])}).catch(u=>{l||a.down([[W,u]])}),()=>{l=!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,l]of Object.entries(r.nodes)){if(l.type!=="state"||s.includes("::__meta__::")||l.status==="completed"||l.status==="errored")continue;let u=l.meta??{},i=u.access;if(i==="human"||i==="system")continue;let d=u.description??`Set the value of ${s}`,m=zr(u),c={type:"object",required:["value"],properties:{value:m},additionalProperties:!1},p=s.replace(/::/g,"__");n.push({type:"function",function:{name:p,description:d,parameters:c}}),o.push({name:s,description:d,inputSchema:c});let g=t,y=e,f=l.v;a.push({name:s,description:d,parameters:c,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})}],l=r.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),i=(await Me(l)).content.trim();i.startsWith("```")&&(i=i.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(i)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${i.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=x(e),a=ht(o,t);return $(a,s=>{if(s==null)return L(null);let[l,u]=s;return!u||!l||typeof l!="string"||l.trim().length===0?L(null):u.destroyed?L(null):Q(i=>{let d=new AbortController,m=!1;return Wt(u,l,r,{...n,signal:d.signal}).then(c=>{m||(i.emit(c),i.down([[q]]))}).catch(c=>{m||i.down([[W,c]])}),()=>{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 l of s.deps)typeof l=="string"&&!n.has(l)&&e.push(`Node "${o}": dep "${l}" 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 l=s;(typeof l.from!="string"||!n.has(l.from))&&e.push(`Edge [${a}]: 'from' "${String(l.from)}" does not reference an existing node`),(typeof l.to!="string"||!n.has(l.to))&&e.push(`Edge [${a}]: 'to' "${String(l.to)}" does not reference an existing node`);let u=`${l.from}->${l.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,jr as G,_r as H,Ie as I,rt as J,nt as K,De as L,ot as M,Pe as N,Br as O,$r as P,Wr as Q,Gt as R,Kr as S,at as T,st as U,it as V,lt 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};
|