@graphrefly/graphrefly 0.27.0 → 0.29.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/backoff-HPZMEZNF.js +1 -0
- package/dist/cascading-Bp99ckMJ.d.ts +180 -0
- package/dist/cascading-CcAgRacD.d.cts +180 -0
- package/dist/chunk-22F4K3G7.js +1 -0
- package/dist/chunk-22SVXUPB.js +64 -0
- package/dist/chunk-2GQREQ6C.js +1 -0
- package/dist/chunk-3JXNEPCD.js +2 -0
- package/dist/chunk-4JJCCD5S.js +2 -0
- package/dist/chunk-4OFIQ66T.js +1 -0
- package/dist/chunk-4V4C7K56.js +1 -0
- package/dist/chunk-4VVTGLXJ.js +1 -0
- package/dist/chunk-567NWZ3T.js +1 -0
- package/dist/chunk-5JDE5JHE.js +1 -0
- package/dist/chunk-5QDBSZBV.js +1 -0
- package/dist/chunk-5Z4HDCO6.js +1 -0
- package/dist/chunk-63FFOHLA.js +1 -0
- package/dist/chunk-6QZNQS5B.js +1 -0
- package/dist/chunk-7JDLFI6N.js +1 -0
- package/dist/chunk-7TDOES3L.js +1 -0
- package/dist/chunk-A7IAQQ63.js +1 -0
- package/dist/chunk-AMG5VBHW.js +1 -0
- package/dist/chunk-AUY2YKCO.js +1 -0
- package/dist/chunk-AV3PIDFQ.js +1 -0
- package/dist/chunk-BA5URFYW.js +1 -0
- package/dist/chunk-BKPLTBL5.js +1 -0
- package/dist/chunk-BZP5T4X6.js +1 -0
- package/dist/chunk-CK2E7BTU.js +1 -0
- package/dist/chunk-CSJE2EKV.js +1 -0
- package/dist/chunk-E3AXATVZ.js +9 -0
- package/dist/chunk-ESMPEKEV.js +1 -0
- package/dist/chunk-GJR3P6JG.js +1 -0
- package/dist/chunk-GNCBXARM.js +1 -0
- package/dist/chunk-GPW2V3RE.js +1 -0
- package/dist/chunk-HSIEYSDY.js +1 -0
- package/dist/chunk-I6VIH3VA.js +1 -0
- package/dist/chunk-ISCENNXS.js +1 -0
- package/dist/chunk-JYOUF6UQ.js +1 -0
- package/dist/chunk-KASHOCF5.js +1 -0
- package/dist/chunk-LGSNR4LU.js +5 -0
- package/dist/chunk-LVGBLZM2.js +1 -0
- package/dist/chunk-MGKAO4EK.js +7 -0
- package/dist/chunk-NSG4C6BF.js +23 -0
- package/dist/chunk-OL33ZI6R.js +1 -0
- package/dist/chunk-PCZ35NXD.js +78 -0
- package/dist/chunk-PGMUCUHG.js +43 -0
- package/dist/chunk-QYADASLV.js +1 -0
- package/dist/chunk-RD52SNH2.js +1 -0
- package/dist/chunk-SLMYTGTU.js +1 -0
- package/dist/chunk-TWMEGG45.js +1 -0
- package/dist/chunk-UVJQ35G2.js +1 -0
- package/dist/chunk-VGTCGNRX.js +18 -0
- package/dist/chunk-VIMF6LGM.js +1 -0
- package/dist/chunk-VJLMUKOI.js +1 -0
- package/dist/chunk-VWPRPPKR.js +1 -0
- package/dist/chunk-W4TSQ6RJ.js +1 -0
- package/dist/chunk-WM7H7WTY.js +3 -0
- package/dist/chunk-Y32RJO24.js +1 -0
- package/dist/chunk-Y53B6NS4.js +1 -0
- package/dist/compat/index.cjs +15 -7656
- package/dist/compat/index.d.cts +15 -14
- package/dist/compat/index.d.ts +15 -14
- package/dist/compat/index.js +1 -50
- package/dist/compat/jotai/index.cjs +1 -2048
- package/dist/compat/jotai/index.d.cts +2 -2
- package/dist/compat/jotai/index.d.ts +2 -2
- package/dist/compat/jotai/index.js +1 -9
- package/dist/compat/nanostores/index.cjs +1 -2175
- package/dist/compat/nanostores/index.d.cts +2 -2
- package/dist/compat/nanostores/index.d.ts +2 -2
- package/dist/compat/nanostores/index.js +1 -23
- package/dist/compat/nestjs/index.cjs +15 -6782
- package/dist/compat/nestjs/index.d.cts +7 -6
- package/dist/compat/nestjs/index.d.ts +7 -6
- package/dist/compat/nestjs/index.js +1 -83
- package/dist/compat/react/index.cjs +1 -141
- package/dist/compat/react/index.d.cts +2 -2
- package/dist/compat/react/index.d.ts +2 -2
- package/dist/compat/react/index.js +1 -12
- package/dist/compat/solid/index.cjs +1 -128
- package/dist/compat/solid/index.d.cts +2 -2
- package/dist/compat/solid/index.d.ts +2 -2
- package/dist/compat/solid/index.js +1 -12
- package/dist/compat/svelte/index.cjs +1 -131
- package/dist/compat/svelte/index.d.cts +2 -2
- package/dist/compat/svelte/index.d.ts +2 -2
- package/dist/compat/svelte/index.js +1 -12
- package/dist/compat/vue/index.cjs +1 -146
- package/dist/compat/vue/index.d.cts +2 -2
- package/dist/compat/vue/index.d.ts +2 -2
- package/dist/compat/vue/index.js +1 -12
- package/dist/compat/zustand/index.cjs +7 -4931
- package/dist/compat/zustand/index.d.cts +5 -5
- package/dist/compat/zustand/index.d.ts +5 -5
- package/dist/compat/zustand/index.js +1 -12
- package/dist/composite-BL-llbnE.d.ts +69 -0
- package/dist/composite-Dze--DaA.d.cts +69 -0
- package/dist/core/index.cjs +1 -2271
- package/dist/core/index.d.cts +4 -4
- package/dist/core/index.d.ts +4 -4
- package/dist/core/index.js +1 -110
- package/dist/extra/browser.cjs +1 -0
- package/dist/extra/browser.d.cts +3 -0
- package/dist/extra/browser.d.ts +3 -0
- package/dist/extra/browser.js +1 -0
- package/dist/extra/index.cjs +24 -9971
- package/dist/extra/index.d.cts +13 -6
- package/dist/extra/index.d.ts +13 -6
- package/dist/extra/index.js +1 -381
- package/dist/extra/node.cjs +3 -0
- package/dist/extra/node.d.cts +81 -0
- package/dist/extra/node.d.ts +81 -0
- package/dist/extra/node.js +2 -0
- package/dist/extra/operators.cjs +1 -0
- package/dist/extra/operators.d.cts +910 -0
- package/dist/extra/operators.d.ts +910 -0
- package/dist/extra/operators.js +1 -0
- package/dist/extra/reactive.cjs +1 -0
- package/dist/extra/reactive.d.cts +352 -0
- package/dist/extra/reactive.d.ts +352 -0
- package/dist/extra/reactive.js +1 -0
- package/dist/extra/sources.cjs +1 -2486
- package/dist/extra/sources.d.cts +6 -2
- package/dist/extra/sources.d.ts +6 -2
- package/dist/extra/sources.js +1 -57
- package/dist/extra/storage-browser.cjs +1 -0
- package/dist/extra/storage-browser.d.cts +71 -0
- package/dist/extra/storage-browser.d.ts +71 -0
- package/dist/extra/storage-browser.js +1 -0
- package/dist/extra/storage-core.cjs +1 -0
- package/dist/extra/storage-core.d.cts +98 -0
- package/dist/extra/storage-core.d.ts +98 -0
- package/dist/extra/storage-core.js +1 -0
- package/dist/extra/storage-node.cjs +2 -0
- package/dist/extra/storage-node.d.cts +60 -0
- package/dist/extra/storage-node.d.ts +60 -0
- package/dist/extra/storage-node.js +1 -0
- package/dist/fallback-BaTS7vVY.d.cts +258 -0
- package/dist/fallback-eOm3LNxP.d.ts +258 -0
- package/dist/graph/index.cjs +7 -5030
- package/dist/graph/index.d.cts +6 -5
- package/dist/graph/index.d.ts +6 -5
- package/dist/graph/index.js +1 -50
- package/dist/{graph-DNCrvZSn.d.cts → graph-DgohqXK-.d.cts} +151 -32
- package/dist/{graph-CCwGKLCm.d.ts → graph-Qjg9gWHI.d.ts} +151 -32
- package/dist/{index-BwfLUNw4.d.ts → index-2BVuRCI4.d.ts} +173 -2040
- package/dist/{index-BPVt8kqc.d.ts → index-2NvguqQA.d.ts} +10 -195
- package/dist/index-A65LZhoM.d.ts +186 -0
- package/dist/{index-DlLp-2Xn.d.cts → index-B-8FCEua.d.cts} +10 -195
- package/dist/index-B-gqvYel.d.ts +135 -0
- package/dist/index-B2PRuolf.d.cts +86 -0
- package/dist/index-BJqt9EwW.d.ts +231 -0
- package/dist/{index-BHlKbUwO.d.cts → index-BKjT5DiZ.d.cts} +173 -2040
- package/dist/{index-C0svESO4.d.ts → index-BM8BU4q6.d.ts} +1 -1
- package/dist/{index-VdHQMPy1.d.ts → index-BQaEnxBf.d.ts} +1 -1
- package/dist/index-BSfwiy5B.d.ts +192 -0
- package/dist/index-BTSkeCZs.d.cts +291 -0
- package/dist/index-BUVtw1Ay.d.cts +186 -0
- package/dist/index-BUi57v_p.d.ts +163 -0
- package/dist/{messaging-Gt4LPbyA.d.cts → index-BanNUILp.d.cts} +31 -93
- package/dist/{audit-DRlSzBu9.d.ts → index-BayHDRx6.d.cts} +27 -21
- package/dist/{index-B6D3QNSA.d.ts → index-BiyjsZ0m.d.ts} +148 -20
- package/dist/index-BqZ6vB2A.d.ts +2057 -0
- package/dist/{memory-li6FL5RM.d.ts → index-BuVidq3D.d.cts} +26 -26
- package/dist/index-Byh-xTyp.d.ts +105 -0
- package/dist/index-C08QPDcV.d.cts +321 -0
- package/dist/{demo-shell-BDkOptd6.d.ts → index-C66RJiX8.d.ts} +14 -14
- package/dist/index-C8RfjffH.d.ts +291 -0
- package/dist/index-CA1Cu7Ud.d.ts +873 -0
- package/dist/{index-ByQxazQJ.d.cts → index-CABbltIu.d.cts} +1 -1
- package/dist/{index-VHqptjhu.d.cts → index-CHEBsnYv.d.cts} +1 -1
- package/dist/{index-BuEoe-Qu.d.ts → index-CI0yDnLp.d.ts} +9 -9
- package/dist/{index-B9B7_HEY.d.ts → index-CJ45TW-h.d.ts} +1 -1
- package/dist/{index-CO8uBlUh.d.cts → index-CJZKZoo4.d.cts} +148 -20
- package/dist/{index-wEn0eFe8.d.ts → index-CX2tFJL1.d.ts} +1 -1
- package/dist/{index-BaSM3aYt.d.ts → index-CcWOJ6F0.d.ts} +3 -3
- package/dist/{audit-ClmqGOCx.d.cts → index-CiaVoZGo.d.ts} +27 -21
- package/dist/{index-Dzk2hrlR.d.ts → index-Ct5CWc4E.d.ts} +1 -1
- package/dist/index-D38duMCv.d.cts +357 -0
- package/dist/{index-C8oil6M6.d.ts → index-D5XJ2tSx.d.ts} +30 -6
- package/dist/{index-DO_6JN9Z.d.cts → index-D80do5jX.d.cts} +1 -1
- package/dist/index-D9HKAH_-.d.cts +231 -0
- package/dist/index-DBe_8XW5.d.cts +143 -0
- package/dist/{memory-C6Z2tGpC.d.cts → index-DCeTyFlB.d.ts} +26 -26
- package/dist/index-DDy8eeXS.d.ts +321 -0
- package/dist/index-DJ5oNBc8.d.ts +143 -0
- package/dist/{index-CI3DprxP.d.cts → index-DP0_O3ls.d.cts} +30 -6
- package/dist/{demo-shell-Crid1WdR.d.cts → index-DX8xS-yB.d.cts} +14 -14
- package/dist/index-DiZejfCI.d.cts +2057 -0
- package/dist/index-DknyJ2Fu.d.cts +163 -0
- package/dist/index-DoWMs-Kk.d.cts +135 -0
- package/dist/{messaging-XDoYablx.d.ts → index-DuB5aO4-.d.ts} +31 -93
- package/dist/index-DwjJGKxV.d.ts +357 -0
- package/dist/{index-B6EhDnjH.d.cts → index-H_oxVec5.d.cts} +1 -1
- package/dist/{index-3lsddbbS.d.ts → index-IMAHq-ia.d.ts} +1 -1
- package/dist/{index-B1tloyhO.d.cts → index-U1nir7MX.d.cts} +1 -1
- package/dist/index-Vg7tORgk.d.ts +86 -0
- package/dist/index-dig-r2tQ.d.cts +873 -0
- package/dist/{index-CxFrXH4m.d.ts → index-gsT79Xu9.d.ts} +1 -1
- package/dist/{index-D8wS_PeY.d.cts → index-i99Ka8s7.d.cts} +9 -9
- package/dist/index-iKkyJosF.d.cts +105 -0
- package/dist/{index-Xi3u0HCQ.d.cts → index-jleeotBT.d.cts} +1 -1
- package/dist/{index-DVGiGFGT.d.cts → index-kykKWwV-.d.cts} +3 -3
- package/dist/index-vgcLF5TH.d.cts +192 -0
- package/dist/{index-DYme44FM.d.cts → index-y1RllPn4.d.cts} +1 -1
- package/dist/index.cjs +151 -24142
- package/dist/index.d.cts +69 -2099
- package/dist/index.d.ts +69 -2099
- package/dist/index.js +1 -3868
- package/dist/{meta-CbznRPYJ.d.ts → meta-CX7YsOzp.d.cts} +5 -5
- package/dist/{meta-BxCA7rcr.d.cts → meta-CckhhFRd.d.ts} +5 -5
- package/dist/{node-BmerH3kS.d.cts → node-Dd6wHSib.d.cts} +71 -11
- package/dist/{node-BmerH3kS.d.ts → node-Dd6wHSib.d.ts} +71 -11
- package/dist/{observable-BgGUwcqp.d.ts → observable-BZJgo616.d.ts} +1 -1
- package/dist/{observable-DJt_AxzQ.d.cts → observable-kwzpLvbi.d.cts} +1 -1
- package/dist/patterns/ai/browser.cjs +25 -0
- package/dist/patterns/ai/browser.d.cts +127 -0
- package/dist/patterns/ai/browser.d.ts +127 -0
- package/dist/patterns/ai/browser.js +3 -0
- package/dist/patterns/ai/index.cjs +92 -0
- package/dist/patterns/ai/index.d.cts +17 -0
- package/dist/patterns/ai/index.d.ts +17 -0
- package/dist/patterns/ai/index.js +1 -0
- package/dist/patterns/ai/node.cjs +2 -0
- package/dist/patterns/ai/node.d.cts +58 -0
- package/dist/patterns/ai/node.d.ts +58 -0
- package/dist/patterns/ai/node.js +1 -0
- package/dist/patterns/audit/index.cjs +7 -0
- package/dist/patterns/audit/index.d.cts +6 -0
- package/dist/patterns/audit/index.d.ts +6 -0
- package/dist/patterns/audit/index.js +1 -0
- package/dist/patterns/cqrs/index.cjs +7 -0
- package/dist/patterns/cqrs/index.d.cts +5 -0
- package/dist/patterns/cqrs/index.d.ts +5 -0
- package/dist/patterns/cqrs/index.js +1 -0
- package/dist/patterns/demo-shell/index.cjs +8 -0
- package/dist/patterns/demo-shell/index.d.cts +6 -0
- package/dist/patterns/demo-shell/index.d.ts +6 -0
- package/dist/patterns/demo-shell/index.js +1 -0
- package/dist/patterns/domain-templates/index.cjs +7 -0
- package/dist/patterns/domain-templates/index.d.cts +5 -0
- package/dist/patterns/domain-templates/index.d.ts +5 -0
- package/dist/patterns/domain-templates/index.js +1 -0
- package/dist/patterns/graphspec/index.cjs +84 -0
- package/dist/patterns/graphspec/index.d.cts +7 -0
- package/dist/patterns/graphspec/index.d.ts +7 -0
- package/dist/patterns/graphspec/index.js +1 -0
- package/dist/patterns/guarded-execution/index.cjs +7 -0
- package/dist/patterns/guarded-execution/index.d.cts +7 -0
- package/dist/patterns/guarded-execution/index.d.ts +7 -0
- package/dist/patterns/guarded-execution/index.js +1 -0
- package/dist/patterns/harness/index.cjs +49 -0
- package/dist/patterns/harness/index.d.cts +11 -0
- package/dist/patterns/harness/index.d.ts +11 -0
- package/dist/patterns/harness/index.js +1 -0
- package/dist/patterns/job-queue/index.cjs +7 -0
- package/dist/patterns/job-queue/index.d.cts +5 -0
- package/dist/patterns/job-queue/index.d.ts +5 -0
- package/dist/patterns/job-queue/index.js +1 -0
- package/dist/patterns/lens/index.cjs +7 -0
- package/dist/patterns/lens/index.d.cts +7 -0
- package/dist/patterns/lens/index.d.ts +7 -0
- package/dist/patterns/lens/index.js +1 -0
- package/dist/patterns/memory/index.cjs +7 -0
- package/dist/patterns/memory/index.d.cts +5 -0
- package/dist/patterns/memory/index.d.ts +5 -0
- package/dist/patterns/memory/index.js +1 -0
- package/dist/patterns/messaging/index.cjs +7 -0
- package/dist/patterns/messaging/index.d.cts +5 -0
- package/dist/patterns/messaging/index.d.ts +5 -0
- package/dist/patterns/messaging/index.js +1 -0
- package/dist/patterns/orchestration/index.cjs +7 -0
- package/dist/patterns/orchestration/index.d.cts +6 -0
- package/dist/patterns/orchestration/index.d.ts +6 -0
- package/dist/patterns/orchestration/index.js +1 -0
- package/dist/patterns/reactive-layout/index.cjs +8 -6444
- package/dist/patterns/reactive-layout/index.d.cts +6 -6
- package/dist/patterns/reactive-layout/index.d.ts +6 -6
- package/dist/patterns/reactive-layout/index.js +1 -56
- package/dist/patterns/reduction/index.cjs +7 -0
- package/dist/patterns/reduction/index.d.cts +5 -0
- package/dist/patterns/reduction/index.d.ts +5 -0
- package/dist/patterns/reduction/index.js +1 -0
- package/dist/patterns/refine-loop/index.cjs +9 -0
- package/dist/patterns/refine-loop/index.d.cts +7 -0
- package/dist/patterns/refine-loop/index.d.ts +7 -0
- package/dist/patterns/refine-loop/index.js +1 -0
- package/dist/patterns/resilient-pipeline/index.cjs +1 -0
- package/dist/patterns/resilient-pipeline/index.d.cts +7 -0
- package/dist/patterns/resilient-pipeline/index.d.ts +7 -0
- package/dist/patterns/resilient-pipeline/index.js +1 -0
- package/dist/patterns/surface/index.cjs +15 -0
- package/dist/patterns/surface/index.d.cts +8 -0
- package/dist/patterns/surface/index.d.ts +8 -0
- package/dist/patterns/surface/index.js +1 -0
- package/dist/{reactive-layout-u5Ulnqag.d.ts → reactive-layout-BkBwVvwm.d.ts} +2 -2
- package/dist/{reactive-layout-MQP--J3F.d.cts → reactive-layout-PiFwVaWS.d.cts} +2 -2
- package/dist/reactive-log-1QTyx10a.d.ts +190 -0
- package/dist/reactive-log-BiVoSxke.d.cts +190 -0
- package/dist/{composite-aUCvjZVR.d.ts → reactive-map-CwO_COHy.d.cts} +2 -67
- package/dist/{composite-C7PcQvcs.d.cts → reactive-map-FeuTVAJb.d.ts} +2 -67
- package/dist/resilience-CBfYJW5C.d.ts +493 -0
- package/dist/resilience-XRUF267O.js +1 -0
- package/dist/resilience-uBz4yvYB.d.cts +493 -0
- package/dist/{sugar-CCOxXK1e.d.ts → sugar-CY-MCfZ9.d.ts} +17 -15
- package/dist/{sugar-D02n5JjF.d.cts → sugar-DHttV0LX.d.cts} +17 -15
- package/dist/topology-tree-CVjt2gp7.d.cts +25 -0
- package/dist/topology-tree-one6oSKY.d.ts +25 -0
- package/dist/types-O3GzJY2U.d.cts +401 -0
- package/dist/types-u64Ose53.d.ts +401 -0
- package/package.json +252 -22
- package/dist/ai-CaR_912Q.d.cts +0 -1033
- package/dist/ai-WlRltJV7.d.ts +0 -1033
- package/dist/chunk-3ZWCKRHX.js +0 -117
- package/dist/chunk-3ZWCKRHX.js.map +0 -1
- package/dist/chunk-7TAQJHQV.js +0 -103
- package/dist/chunk-7TAQJHQV.js.map +0 -1
- package/dist/chunk-APFNLIRG.js +0 -62
- package/dist/chunk-APFNLIRG.js.map +0 -1
- package/dist/chunk-AT5LKYNL.js +0 -395
- package/dist/chunk-AT5LKYNL.js.map +0 -1
- package/dist/chunk-BQ6RQQFF.js +0 -5087
- package/dist/chunk-BQ6RQQFF.js.map +0 -1
- package/dist/chunk-BVZYTZ5H.js +0 -599
- package/dist/chunk-BVZYTZ5H.js.map +0 -1
- package/dist/chunk-DST5DKZS.js +0 -1371
- package/dist/chunk-DST5DKZS.js.map +0 -1
- package/dist/chunk-GTE6PWRZ.js +0 -866
- package/dist/chunk-GTE6PWRZ.js.map +0 -1
- package/dist/chunk-HXZEYDUR.js +0 -94
- package/dist/chunk-HXZEYDUR.js.map +0 -1
- package/dist/chunk-J22W6HV3.js +0 -107
- package/dist/chunk-J22W6HV3.js.map +0 -1
- package/dist/chunk-J2VBW3DZ.js +0 -302
- package/dist/chunk-J2VBW3DZ.js.map +0 -1
- package/dist/chunk-JSCT3CR4.js +0 -38
- package/dist/chunk-JSCT3CR4.js.map +0 -1
- package/dist/chunk-JWBCY4NC.js +0 -330
- package/dist/chunk-JWBCY4NC.js.map +0 -1
- package/dist/chunk-K2AUJHVP.js +0 -2251
- package/dist/chunk-K2AUJHVP.js.map +0 -1
- package/dist/chunk-MJ2NKQQL.js +0 -119
- package/dist/chunk-MJ2NKQQL.js.map +0 -1
- package/dist/chunk-N6UR7YVY.js +0 -198
- package/dist/chunk-N6UR7YVY.js.map +0 -1
- package/dist/chunk-NC6S43JJ.js +0 -456
- package/dist/chunk-NC6S43JJ.js.map +0 -1
- package/dist/chunk-OFVJBJXR.js +0 -98
- package/dist/chunk-OFVJBJXR.js.map +0 -1
- package/dist/chunk-OHISZPOJ.js +0 -97
- package/dist/chunk-OHISZPOJ.js.map +0 -1
- package/dist/chunk-OU5CQKNW.js +0 -102
- package/dist/chunk-OU5CQKNW.js.map +0 -1
- package/dist/chunk-PF7GRZMW.js +0 -2712
- package/dist/chunk-PF7GRZMW.js.map +0 -1
- package/dist/chunk-PHOUUNK7.js +0 -2291
- package/dist/chunk-PHOUUNK7.js.map +0 -1
- package/dist/chunk-RNHBMHKA.js +0 -1665
- package/dist/chunk-RNHBMHKA.js.map +0 -1
- package/dist/chunk-SX52TAR4.js +0 -110
- package/dist/chunk-SX52TAR4.js.map +0 -1
- package/dist/chunk-VYPWMZ6H.js +0 -98
- package/dist/chunk-VYPWMZ6H.js.map +0 -1
- package/dist/chunk-WBZOVTYK.js +0 -171
- package/dist/chunk-WBZOVTYK.js.map +0 -1
- package/dist/chunk-WKNUIZOY.js +0 -354
- package/dist/chunk-WKNUIZOY.js.map +0 -1
- package/dist/chunk-X3VMZYBT.js +0 -713
- package/dist/chunk-X3VMZYBT.js.map +0 -1
- package/dist/chunk-X5R3GL6H.js +0 -525
- package/dist/chunk-X5R3GL6H.js.map +0 -1
- package/dist/chunk-XGPU467M.js +0 -136
- package/dist/chunk-XGPU467M.js.map +0 -1
- package/dist/compat/index.cjs.map +0 -1
- package/dist/compat/index.js.map +0 -1
- package/dist/compat/jotai/index.cjs.map +0 -1
- package/dist/compat/jotai/index.js.map +0 -1
- package/dist/compat/nanostores/index.cjs.map +0 -1
- package/dist/compat/nanostores/index.js.map +0 -1
- package/dist/compat/nestjs/index.cjs.map +0 -1
- package/dist/compat/nestjs/index.js.map +0 -1
- package/dist/compat/react/index.cjs.map +0 -1
- package/dist/compat/react/index.js.map +0 -1
- package/dist/compat/solid/index.cjs.map +0 -1
- package/dist/compat/solid/index.js.map +0 -1
- package/dist/compat/svelte/index.cjs.map +0 -1
- package/dist/compat/svelte/index.js.map +0 -1
- package/dist/compat/vue/index.cjs.map +0 -1
- package/dist/compat/vue/index.js.map +0 -1
- package/dist/compat/zustand/index.cjs.map +0 -1
- package/dist/compat/zustand/index.js.map +0 -1
- package/dist/core/index.cjs.map +0 -1
- package/dist/core/index.js.map +0 -1
- package/dist/extra/index.cjs.map +0 -1
- package/dist/extra/index.js.map +0 -1
- package/dist/extra/sources.cjs.map +0 -1
- package/dist/extra/sources.js.map +0 -1
- package/dist/graph/index.cjs.map +0 -1
- package/dist/graph/index.js.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/patterns/ai.cjs +0 -7930
- package/dist/patterns/ai.cjs.map +0 -1
- package/dist/patterns/ai.d.cts +0 -10
- package/dist/patterns/ai.d.ts +0 -10
- package/dist/patterns/ai.js +0 -71
- package/dist/patterns/ai.js.map +0 -1
- package/dist/patterns/audit.cjs +0 -5805
- package/dist/patterns/audit.cjs.map +0 -1
- package/dist/patterns/audit.d.cts +0 -6
- package/dist/patterns/audit.d.ts +0 -6
- package/dist/patterns/audit.js +0 -29
- package/dist/patterns/audit.js.map +0 -1
- package/dist/patterns/demo-shell.cjs +0 -5604
- package/dist/patterns/demo-shell.cjs.map +0 -1
- package/dist/patterns/demo-shell.d.cts +0 -6
- package/dist/patterns/demo-shell.d.ts +0 -6
- package/dist/patterns/demo-shell.js +0 -15
- package/dist/patterns/demo-shell.js.map +0 -1
- package/dist/patterns/memory.cjs +0 -5283
- package/dist/patterns/memory.cjs.map +0 -1
- package/dist/patterns/memory.d.cts +0 -5
- package/dist/patterns/memory.d.ts +0 -5
- package/dist/patterns/memory.js +0 -20
- package/dist/patterns/memory.js.map +0 -1
- package/dist/patterns/reactive-layout/index.cjs.map +0 -1
- package/dist/patterns/reactive-layout/index.js.map +0 -1
- package/dist/storage-CMjUUuxn.d.ts +0 -190
- package/dist/storage-DdWlZo6U.d.cts +0 -190
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i}from"./chunk-4VVTGLXJ.js";import"./chunk-QYADASLV.js";export{a as NS_PER_MS,b as NS_PER_SEC,c as constant,g as decorrelatedJitter,e as exponential,f as fibonacci,d as linear,i as resolveBackoffPreset,h as withMaxAttempts};
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { L as LLMAdapter, C as ChatMessage, a as LLMInvokeOptions } from './types-u64Ose53.js';
|
|
2
|
+
import { a as CircuitBreakerOptions, e as CircuitBreaker } from './resilience-CBfYJW5C.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* OpenAICompatAdapter — default fetch-backed, optional SDK-backed.
|
|
6
|
+
*
|
|
7
|
+
* Covers any provider that speaks OpenAI chat/completions. Preset base URLs
|
|
8
|
+
* for OpenAI, OpenRouter, Groq, Ollama, DeepSeek, xAI Grok (all expose the
|
|
9
|
+
* same `/v1/chat/completions` shape).
|
|
10
|
+
*
|
|
11
|
+
* Token usage mapping:
|
|
12
|
+
* - `prompt_tokens` → `input.regular` (minus cached_tokens)
|
|
13
|
+
* - `prompt_tokens_details.cached_tokens` → `input.cacheRead`
|
|
14
|
+
* - `prompt_tokens_details.audio_tokens` → `input.audio`
|
|
15
|
+
* - `completion_tokens` → `output.regular` (minus reasoning)
|
|
16
|
+
* - `completion_tokens_details.reasoning_tokens` → `output.reasoning`
|
|
17
|
+
* - `completion_tokens_details.audio_tokens` → `output.audio`
|
|
18
|
+
* - `completion_tokens_details.accepted_prediction_tokens` → `output.predictionAccepted`
|
|
19
|
+
* - `completion_tokens_details.rejected_prediction_tokens` → `output.predictionRejected`
|
|
20
|
+
*
|
|
21
|
+
* DeepSeek compatibility: `prompt_cache_hit_tokens` / `prompt_cache_miss_tokens`
|
|
22
|
+
* are surfaced in the `raw` field of `TokenUsage`; when present we prefer
|
|
23
|
+
* them over the OpenAI-style `cached_tokens` for cache-read attribution.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
type OpenAICompatPreset = "openai" | "openrouter" | "groq" | "ollama" | "deepseek" | "xai";
|
|
27
|
+
interface OpenAICompatAdapterOptions {
|
|
28
|
+
preset?: OpenAICompatPreset;
|
|
29
|
+
/** Explicit provider label (defaults to preset's provider). */
|
|
30
|
+
provider?: string;
|
|
31
|
+
/** API key. Falls back to the preset's default env var on Node. */
|
|
32
|
+
apiKey?: string;
|
|
33
|
+
model?: string;
|
|
34
|
+
/** Override base URL (wins over `preset`). */
|
|
35
|
+
baseURL?: string;
|
|
36
|
+
/** Extra request headers. */
|
|
37
|
+
headers?: Record<string, string>;
|
|
38
|
+
/** Extra request-body fields merged on every request (OpenRouter routing etc.). */
|
|
39
|
+
bodyExtras?: Record<string, unknown>;
|
|
40
|
+
/** User-provided SDK instance (OpenAI-family shape). */
|
|
41
|
+
sdk?: OpenAISdkLike;
|
|
42
|
+
/** Custom fetch (for tests). */
|
|
43
|
+
fetchImpl?: typeof fetch;
|
|
44
|
+
}
|
|
45
|
+
interface OpenAISdkLike {
|
|
46
|
+
chat: {
|
|
47
|
+
completions: {
|
|
48
|
+
create(params: Record<string, unknown>, opts?: {
|
|
49
|
+
signal?: AbortSignal;
|
|
50
|
+
}): Promise<OpenAIChatResponse>;
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
interface OpenAIChatResponse {
|
|
55
|
+
id: string;
|
|
56
|
+
choices: ReadonlyArray<{
|
|
57
|
+
message: {
|
|
58
|
+
role: string;
|
|
59
|
+
content?: string | null;
|
|
60
|
+
tool_calls?: ReadonlyArray<{
|
|
61
|
+
id: string;
|
|
62
|
+
type: "function";
|
|
63
|
+
function: {
|
|
64
|
+
name: string;
|
|
65
|
+
arguments: string;
|
|
66
|
+
};
|
|
67
|
+
}>;
|
|
68
|
+
reasoning_content?: string;
|
|
69
|
+
};
|
|
70
|
+
finish_reason?: string;
|
|
71
|
+
}>;
|
|
72
|
+
usage?: OpenAIUsage;
|
|
73
|
+
model?: string;
|
|
74
|
+
}
|
|
75
|
+
interface OpenAIUsage {
|
|
76
|
+
prompt_tokens?: number;
|
|
77
|
+
completion_tokens?: number;
|
|
78
|
+
total_tokens?: number;
|
|
79
|
+
prompt_tokens_details?: {
|
|
80
|
+
cached_tokens?: number;
|
|
81
|
+
audio_tokens?: number;
|
|
82
|
+
};
|
|
83
|
+
completion_tokens_details?: {
|
|
84
|
+
reasoning_tokens?: number;
|
|
85
|
+
audio_tokens?: number;
|
|
86
|
+
accepted_prediction_tokens?: number;
|
|
87
|
+
rejected_prediction_tokens?: number;
|
|
88
|
+
};
|
|
89
|
+
prompt_cache_hit_tokens?: number;
|
|
90
|
+
prompt_cache_miss_tokens?: number;
|
|
91
|
+
}
|
|
92
|
+
declare function openAICompatAdapter(opts?: OpenAICompatAdapterOptions): LLMAdapter;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* `createAdapter` — provider-dispatching factory.
|
|
96
|
+
*
|
|
97
|
+
* One entry point, one config object. Picks the right concrete adapter by
|
|
98
|
+
* `provider`, forwards everything else. Users who want finer control import
|
|
99
|
+
* the concrete adapter directly (`anthropicAdapter`, `openAICompatAdapter`,
|
|
100
|
+
* `googleAdapter`, `dryRunAdapter`, `webllmAdapter`, `chromeNanoAdapter`).
|
|
101
|
+
*/
|
|
102
|
+
|
|
103
|
+
type AdapterProvider = "anthropic" | OpenAICompatPreset | "google" | "dry-run" | "fallback";
|
|
104
|
+
interface CreateAdapterOptions {
|
|
105
|
+
provider: AdapterProvider;
|
|
106
|
+
apiKey?: string;
|
|
107
|
+
model?: string;
|
|
108
|
+
baseURL?: string;
|
|
109
|
+
headers?: Record<string, string>;
|
|
110
|
+
/** OpenAI-compat bodyExtras (OpenRouter routing, etc.). */
|
|
111
|
+
bodyExtras?: Record<string, unknown>;
|
|
112
|
+
/** Provider-specific SDK instance (any of AnthropicSdkLike / OpenAISdkLike / GoogleSdkLike). */
|
|
113
|
+
sdk?: unknown;
|
|
114
|
+
/** Custom fetch (for tests). */
|
|
115
|
+
fetchImpl?: typeof fetch;
|
|
116
|
+
/** Extra per-provider options forwarded verbatim. */
|
|
117
|
+
extras?: Record<string, unknown>;
|
|
118
|
+
}
|
|
119
|
+
declare function createAdapter(opts: CreateAdapterOptions): LLMAdapter;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* `cascadingLlmAdapter` — N-tier fallback over any mix of LLM adapters.
|
|
123
|
+
*
|
|
124
|
+
* Same structural pattern as `cascadingCache` and `Graph.attachStorage`:
|
|
125
|
+
* ordered list, first-success wins, per-tier breaker optional, filter gates
|
|
126
|
+
* per request. Semantics:
|
|
127
|
+
*
|
|
128
|
+
* - `invoke()`: try tier 0 first. On error (or breaker-open), fall through
|
|
129
|
+
* to tier 1, 2, ... until one succeeds or all fail.
|
|
130
|
+
* - `stream()`: tries to start the stream on tier 0; once tokens begin, it
|
|
131
|
+
* commits — failures in mid-stream surface rather than re-starting on the
|
|
132
|
+
* next tier (would double-bill and confuse consumers). **State-machine
|
|
133
|
+
* consumers (usage accounting, UI accumulators) must handle errors in a
|
|
134
|
+
* catch block — no synthetic `{type: "finish"}` is emitted after a thrown
|
|
135
|
+
* stream error.**
|
|
136
|
+
* - `filter`: skips a tier for requests that use features it doesn't
|
|
137
|
+
* support (e.g., Chrome Nano can't do tool use).
|
|
138
|
+
* - `breaker`: per-tier circuit; when open, cascade treats the tier as
|
|
139
|
+
* unavailable and moves on immediately.
|
|
140
|
+
*
|
|
141
|
+
* On exhaustion, throws `AllTiersExhaustedError` with separate `skipped` and
|
|
142
|
+
* `failed` collections so consumers can distinguish "no tier applicable"
|
|
143
|
+
* from "all tiers failed".
|
|
144
|
+
*/
|
|
145
|
+
|
|
146
|
+
interface AdapterTier {
|
|
147
|
+
name: string;
|
|
148
|
+
adapter: LLMAdapter;
|
|
149
|
+
/** Per-tier circuit breaker. If omitted, no breaker on this tier. */
|
|
150
|
+
breaker?: CircuitBreakerOptions | CircuitBreaker;
|
|
151
|
+
/** Skip this tier when the request doesn't fit (e.g. Chrome Nano + tools). */
|
|
152
|
+
filter?: (messages: readonly ChatMessage[], opts?: LLMInvokeOptions) => boolean;
|
|
153
|
+
}
|
|
154
|
+
interface CascadeExhaustionReport {
|
|
155
|
+
/** Tiers that never ran (filter returned false, or breaker was open). */
|
|
156
|
+
readonly skipped: ReadonlyArray<{
|
|
157
|
+
name: string;
|
|
158
|
+
reason: "filter" | "breaker";
|
|
159
|
+
}>;
|
|
160
|
+
/** Tiers that ran and threw. */
|
|
161
|
+
readonly failed: ReadonlyMap<string, unknown>;
|
|
162
|
+
}
|
|
163
|
+
interface CascadingLlmAdapterOptions {
|
|
164
|
+
onFallback?: (from: string, to: string, error: unknown) => void;
|
|
165
|
+
onExhausted?: (report: CascadeExhaustionReport) => void;
|
|
166
|
+
/** Whether to attempt stream retry on subsequent tiers before first chunk. Default true. */
|
|
167
|
+
streamRetryBeforeFirstChunk?: boolean;
|
|
168
|
+
}
|
|
169
|
+
declare class AllTiersExhaustedError extends Error {
|
|
170
|
+
name: string;
|
|
171
|
+
readonly skipped: ReadonlyArray<{
|
|
172
|
+
name: string;
|
|
173
|
+
reason: "filter" | "breaker";
|
|
174
|
+
}>;
|
|
175
|
+
readonly failed: ReadonlyMap<string, unknown>;
|
|
176
|
+
constructor(report: CascadeExhaustionReport);
|
|
177
|
+
}
|
|
178
|
+
declare function cascadingLlmAdapter(tiers: readonly AdapterTier[], opts?: CascadingLlmAdapterOptions): LLMAdapter;
|
|
179
|
+
|
|
180
|
+
export { type AdapterProvider as A, type CascadingLlmAdapterOptions as C, type OpenAICompatAdapterOptions as O, type CascadeExhaustionReport as a, type AdapterTier as b, createAdapter as c, AllTiersExhaustedError as d, type CreateAdapterOptions as e, type OpenAICompatPreset as f, type OpenAISdkLike as g, cascadingLlmAdapter as h, openAICompatAdapter as o };
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { L as LLMAdapter, C as ChatMessage, a as LLMInvokeOptions } from './types-O3GzJY2U.cjs';
|
|
2
|
+
import { a as CircuitBreakerOptions, e as CircuitBreaker } from './resilience-uBz4yvYB.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* OpenAICompatAdapter — default fetch-backed, optional SDK-backed.
|
|
6
|
+
*
|
|
7
|
+
* Covers any provider that speaks OpenAI chat/completions. Preset base URLs
|
|
8
|
+
* for OpenAI, OpenRouter, Groq, Ollama, DeepSeek, xAI Grok (all expose the
|
|
9
|
+
* same `/v1/chat/completions` shape).
|
|
10
|
+
*
|
|
11
|
+
* Token usage mapping:
|
|
12
|
+
* - `prompt_tokens` → `input.regular` (minus cached_tokens)
|
|
13
|
+
* - `prompt_tokens_details.cached_tokens` → `input.cacheRead`
|
|
14
|
+
* - `prompt_tokens_details.audio_tokens` → `input.audio`
|
|
15
|
+
* - `completion_tokens` → `output.regular` (minus reasoning)
|
|
16
|
+
* - `completion_tokens_details.reasoning_tokens` → `output.reasoning`
|
|
17
|
+
* - `completion_tokens_details.audio_tokens` → `output.audio`
|
|
18
|
+
* - `completion_tokens_details.accepted_prediction_tokens` → `output.predictionAccepted`
|
|
19
|
+
* - `completion_tokens_details.rejected_prediction_tokens` → `output.predictionRejected`
|
|
20
|
+
*
|
|
21
|
+
* DeepSeek compatibility: `prompt_cache_hit_tokens` / `prompt_cache_miss_tokens`
|
|
22
|
+
* are surfaced in the `raw` field of `TokenUsage`; when present we prefer
|
|
23
|
+
* them over the OpenAI-style `cached_tokens` for cache-read attribution.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
type OpenAICompatPreset = "openai" | "openrouter" | "groq" | "ollama" | "deepseek" | "xai";
|
|
27
|
+
interface OpenAICompatAdapterOptions {
|
|
28
|
+
preset?: OpenAICompatPreset;
|
|
29
|
+
/** Explicit provider label (defaults to preset's provider). */
|
|
30
|
+
provider?: string;
|
|
31
|
+
/** API key. Falls back to the preset's default env var on Node. */
|
|
32
|
+
apiKey?: string;
|
|
33
|
+
model?: string;
|
|
34
|
+
/** Override base URL (wins over `preset`). */
|
|
35
|
+
baseURL?: string;
|
|
36
|
+
/** Extra request headers. */
|
|
37
|
+
headers?: Record<string, string>;
|
|
38
|
+
/** Extra request-body fields merged on every request (OpenRouter routing etc.). */
|
|
39
|
+
bodyExtras?: Record<string, unknown>;
|
|
40
|
+
/** User-provided SDK instance (OpenAI-family shape). */
|
|
41
|
+
sdk?: OpenAISdkLike;
|
|
42
|
+
/** Custom fetch (for tests). */
|
|
43
|
+
fetchImpl?: typeof fetch;
|
|
44
|
+
}
|
|
45
|
+
interface OpenAISdkLike {
|
|
46
|
+
chat: {
|
|
47
|
+
completions: {
|
|
48
|
+
create(params: Record<string, unknown>, opts?: {
|
|
49
|
+
signal?: AbortSignal;
|
|
50
|
+
}): Promise<OpenAIChatResponse>;
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
interface OpenAIChatResponse {
|
|
55
|
+
id: string;
|
|
56
|
+
choices: ReadonlyArray<{
|
|
57
|
+
message: {
|
|
58
|
+
role: string;
|
|
59
|
+
content?: string | null;
|
|
60
|
+
tool_calls?: ReadonlyArray<{
|
|
61
|
+
id: string;
|
|
62
|
+
type: "function";
|
|
63
|
+
function: {
|
|
64
|
+
name: string;
|
|
65
|
+
arguments: string;
|
|
66
|
+
};
|
|
67
|
+
}>;
|
|
68
|
+
reasoning_content?: string;
|
|
69
|
+
};
|
|
70
|
+
finish_reason?: string;
|
|
71
|
+
}>;
|
|
72
|
+
usage?: OpenAIUsage;
|
|
73
|
+
model?: string;
|
|
74
|
+
}
|
|
75
|
+
interface OpenAIUsage {
|
|
76
|
+
prompt_tokens?: number;
|
|
77
|
+
completion_tokens?: number;
|
|
78
|
+
total_tokens?: number;
|
|
79
|
+
prompt_tokens_details?: {
|
|
80
|
+
cached_tokens?: number;
|
|
81
|
+
audio_tokens?: number;
|
|
82
|
+
};
|
|
83
|
+
completion_tokens_details?: {
|
|
84
|
+
reasoning_tokens?: number;
|
|
85
|
+
audio_tokens?: number;
|
|
86
|
+
accepted_prediction_tokens?: number;
|
|
87
|
+
rejected_prediction_tokens?: number;
|
|
88
|
+
};
|
|
89
|
+
prompt_cache_hit_tokens?: number;
|
|
90
|
+
prompt_cache_miss_tokens?: number;
|
|
91
|
+
}
|
|
92
|
+
declare function openAICompatAdapter(opts?: OpenAICompatAdapterOptions): LLMAdapter;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* `createAdapter` — provider-dispatching factory.
|
|
96
|
+
*
|
|
97
|
+
* One entry point, one config object. Picks the right concrete adapter by
|
|
98
|
+
* `provider`, forwards everything else. Users who want finer control import
|
|
99
|
+
* the concrete adapter directly (`anthropicAdapter`, `openAICompatAdapter`,
|
|
100
|
+
* `googleAdapter`, `dryRunAdapter`, `webllmAdapter`, `chromeNanoAdapter`).
|
|
101
|
+
*/
|
|
102
|
+
|
|
103
|
+
type AdapterProvider = "anthropic" | OpenAICompatPreset | "google" | "dry-run" | "fallback";
|
|
104
|
+
interface CreateAdapterOptions {
|
|
105
|
+
provider: AdapterProvider;
|
|
106
|
+
apiKey?: string;
|
|
107
|
+
model?: string;
|
|
108
|
+
baseURL?: string;
|
|
109
|
+
headers?: Record<string, string>;
|
|
110
|
+
/** OpenAI-compat bodyExtras (OpenRouter routing, etc.). */
|
|
111
|
+
bodyExtras?: Record<string, unknown>;
|
|
112
|
+
/** Provider-specific SDK instance (any of AnthropicSdkLike / OpenAISdkLike / GoogleSdkLike). */
|
|
113
|
+
sdk?: unknown;
|
|
114
|
+
/** Custom fetch (for tests). */
|
|
115
|
+
fetchImpl?: typeof fetch;
|
|
116
|
+
/** Extra per-provider options forwarded verbatim. */
|
|
117
|
+
extras?: Record<string, unknown>;
|
|
118
|
+
}
|
|
119
|
+
declare function createAdapter(opts: CreateAdapterOptions): LLMAdapter;
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* `cascadingLlmAdapter` — N-tier fallback over any mix of LLM adapters.
|
|
123
|
+
*
|
|
124
|
+
* Same structural pattern as `cascadingCache` and `Graph.attachStorage`:
|
|
125
|
+
* ordered list, first-success wins, per-tier breaker optional, filter gates
|
|
126
|
+
* per request. Semantics:
|
|
127
|
+
*
|
|
128
|
+
* - `invoke()`: try tier 0 first. On error (or breaker-open), fall through
|
|
129
|
+
* to tier 1, 2, ... until one succeeds or all fail.
|
|
130
|
+
* - `stream()`: tries to start the stream on tier 0; once tokens begin, it
|
|
131
|
+
* commits — failures in mid-stream surface rather than re-starting on the
|
|
132
|
+
* next tier (would double-bill and confuse consumers). **State-machine
|
|
133
|
+
* consumers (usage accounting, UI accumulators) must handle errors in a
|
|
134
|
+
* catch block — no synthetic `{type: "finish"}` is emitted after a thrown
|
|
135
|
+
* stream error.**
|
|
136
|
+
* - `filter`: skips a tier for requests that use features it doesn't
|
|
137
|
+
* support (e.g., Chrome Nano can't do tool use).
|
|
138
|
+
* - `breaker`: per-tier circuit; when open, cascade treats the tier as
|
|
139
|
+
* unavailable and moves on immediately.
|
|
140
|
+
*
|
|
141
|
+
* On exhaustion, throws `AllTiersExhaustedError` with separate `skipped` and
|
|
142
|
+
* `failed` collections so consumers can distinguish "no tier applicable"
|
|
143
|
+
* from "all tiers failed".
|
|
144
|
+
*/
|
|
145
|
+
|
|
146
|
+
interface AdapterTier {
|
|
147
|
+
name: string;
|
|
148
|
+
adapter: LLMAdapter;
|
|
149
|
+
/** Per-tier circuit breaker. If omitted, no breaker on this tier. */
|
|
150
|
+
breaker?: CircuitBreakerOptions | CircuitBreaker;
|
|
151
|
+
/** Skip this tier when the request doesn't fit (e.g. Chrome Nano + tools). */
|
|
152
|
+
filter?: (messages: readonly ChatMessage[], opts?: LLMInvokeOptions) => boolean;
|
|
153
|
+
}
|
|
154
|
+
interface CascadeExhaustionReport {
|
|
155
|
+
/** Tiers that never ran (filter returned false, or breaker was open). */
|
|
156
|
+
readonly skipped: ReadonlyArray<{
|
|
157
|
+
name: string;
|
|
158
|
+
reason: "filter" | "breaker";
|
|
159
|
+
}>;
|
|
160
|
+
/** Tiers that ran and threw. */
|
|
161
|
+
readonly failed: ReadonlyMap<string, unknown>;
|
|
162
|
+
}
|
|
163
|
+
interface CascadingLlmAdapterOptions {
|
|
164
|
+
onFallback?: (from: string, to: string, error: unknown) => void;
|
|
165
|
+
onExhausted?: (report: CascadeExhaustionReport) => void;
|
|
166
|
+
/** Whether to attempt stream retry on subsequent tiers before first chunk. Default true. */
|
|
167
|
+
streamRetryBeforeFirstChunk?: boolean;
|
|
168
|
+
}
|
|
169
|
+
declare class AllTiersExhaustedError extends Error {
|
|
170
|
+
name: string;
|
|
171
|
+
readonly skipped: ReadonlyArray<{
|
|
172
|
+
name: string;
|
|
173
|
+
reason: "filter" | "breaker";
|
|
174
|
+
}>;
|
|
175
|
+
readonly failed: ReadonlyMap<string, unknown>;
|
|
176
|
+
constructor(report: CascadeExhaustionReport);
|
|
177
|
+
}
|
|
178
|
+
declare function cascadingLlmAdapter(tiers: readonly AdapterTier[], opts?: CascadingLlmAdapterOptions): LLMAdapter;
|
|
179
|
+
|
|
180
|
+
export { type AdapterProvider as A, type CascadingLlmAdapterOptions as C, type OpenAICompatAdapterOptions as O, type CascadeExhaustionReport as a, type AdapterTier as b, createAdapter as c, AllTiersExhaustedError as d, type CreateAdapterOptions as e, type OpenAICompatPreset as f, type OpenAISdkLike as g, cascadingLlmAdapter as h, openAICompatAdapter as o };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as G,d as F}from"./chunk-AMG5VBHW.js";import{c as E}from"./chunk-5Z4HDCO6.js";import{a as A}from"./chunk-GJR3P6JG.js";import{k as I}from"./chunk-MGKAO4EK.js";import{A as M}from"./chunk-KASHOCF5.js";import{b as q}from"./chunk-AUY2YKCO.js";import{E as d,G as o,H as O,m as S}from"./chunk-W4TSQ6RJ.js";import{b as V}from"./chunk-QYADASLV.js";var $={};V($,{contentModerationGraph:()=>Q,dataQualityGraph:()=>T,issueTrackerGraph:()=>B,observabilityGraph:()=>D});function s(u,a){return E("domain_template",u,a)}function D(u,a){let n=new I(u,a);n.add(a.source,{name:"source"});let h=[{name:"errors",classify:e=>C(e,"error")},{name:"traces",classify:e=>C(e,"trace")},{name:"metrics",classify:e=>C(e,"metric")}],m=a.branches??h,y=m.map(e=>({name:e.name,classify:e.classify})),c=A("stratify",a.source,y);n.mount("stratify",c);let k=m.map(e=>{try{let i=n.resolve(`stratify::branch/${e.name}`);return o([i],([x])=>x,{initial:null})}catch{return d(null)}}),l=a.correlate??(e=>e),_=o(k,e=>l(e),{meta:s("observability",{stage:"correlate"})});n.add(_,{name:"correlate"});let N=a.sloCheck??(()=>({pass:!0})),w=o([_],e=>e[0],{meta:s("observability",{stage:"slo_value"})}),f=o([w],e=>N(e[0]),{meta:s("observability",{stage:"slo_verified"})});n.add(w,{name:"slo_value"}),n.add(f,{name:"slo_verified"});let v=a.weights??m.map(()=>1),b=k.map(e=>o([e],i=>i[0]!=null?1:0)),p=v.map(e=>d(e));for(let e=0;e<b.length;e++)n.add(b[e],{name:`__signal_${e}`}),n.add(p[e],{name:`__weight_${e}`});let t=F(b,p);n.add(t,{name:"alerts"});let g=o([t,f],e=>({scored:e[0],slo:e[1]}),{meta:s("observability",{stage:"output"})});n.add(g,{name:"output"});let R=d(null,{meta:s("observability",{stage:"feedback_reentry"})});n.add(R,{name:"feedback_reentry"});let r=o([f],e=>{let i=e[0];return i&&i.pass===!1?i:null},{meta:s("observability",{stage:"feedback_condition"})});return n.add(r,{name:"feedback_condition"}),G(n,"feedback_condition","feedback_reentry",{maxIterations:a.maxFeedbackIterations??5}),n}function B(u,a){let n=new I(u,a);n.add(a.source,{name:"source"});let h=0,m=e=>({id:`issue-${++h}`,title:String(e),severity:1,source:"unknown",raw:e}),y=a.extract??m,c=o([a.source],e=>y(e[0]),{meta:s("issue_tracker",{stage:"extract"})});n.add(c,{name:"extract"});let k=a.verify??(()=>({valid:!0})),l=o([c],e=>{let i=e[0];return{issue:i,verification:k(i)}},{meta:s("issue_tracker",{stage:"verify"})});n.add(l,{name:"verify"});let _=d([],{meta:s("issue_tracker",{stage:"known_patterns"})});n.add(_,{name:"known_patterns"});let N=a.detectRegression??(()=>({regression:!1})),w=o([c,_],e=>{let i=e[0],x=e[1];return{issue:i,regression:N(i,x)}},{meta:s("issue_tracker",{stage:"regression"})});n.add(w,{name:"regression"});let f=o([c],e=>e[0]?.severity??0),v=o([w],e=>e[0]?.regression?2:0);n.add(f,{name:"__severity_signal"}),n.add(v,{name:"__regression_signal"});let b=d(1),p=d(1.5);n.add(b,{name:"__severity_weight"}),n.add(p,{name:"__regression_weight"});let t=F([f,v],[b,p]);n.add(t,{name:"priority"});let g=o([l,w,t],e=>({verified:e[0],regression:e[1],priority:e[2]}),{meta:s("issue_tracker",{stage:"output"})});n.add(g,{name:"output"});let R=d(null,{meta:s("issue_tracker",{stage:"feedback_reentry"})});n.add(R,{name:"feedback_reentry"});let r=o([l],e=>{let i=e[0];if(i){let x=i.verification;if(x&&x.valid===!1)return i}return null},{meta:s("issue_tracker",{stage:"feedback_condition"})});return n.add(r,{name:"feedback_condition"}),G(n,"feedback_condition","feedback_reentry",{maxIterations:a.maxFeedbackIterations??3}),n}function Q(u,a){let n=new I(u,a);n.add(a.source,{name:"source"});let h=r=>({label:"review",confidence:.5,original:r}),m=a.classify??h,y=o([a.source],r=>m(r[0]),{meta:s("content_moderation",{stage:"classify"})});n.add(y,{name:"classify"});let c=A("stratify",y,[{name:"safe",classify:r=>r.label==="safe"},{name:"review",classify:r=>r.label==="review"},{name:"block",classify:r=>r.label==="block"}]);n.mount("stratify",c);let k=q([],{name:"review_queue",maxSize:a.maxQueueSize});n.add(k.entries,{name:"review_queue"});let l;try{l=n.resolve("stratify::branch/review")}catch{l=d(null),n.add(l,{name:"__review_fallback"})}let _=O([l],r=>{let e=r[0];e&&k.append(e)});n.add(_,{name:"__review_accumulator"}),n.addDisposer(M(_));let N=d({},{meta:s("content_moderation",{stage:"policy",access:"both",description:"Moderation policy rules \u2014 updated via feedback"})});n.add(N,{name:"policy"});let w=a.weights??[.1,1,2],f=o([y],r=>r[0]?.confidence??0),v=o([y],r=>{let e=r[0];return e?e.label==="block"?w[2]:e.label==="review"?w[1]:w[0]:0});n.add(f,{name:"__confidence_signal"}),n.add(v,{name:"__severity_signal"});let b=d(1),p=d(1);n.add(b,{name:"__w_confidence"}),n.add(p,{name:"__w_severity"});let t=F([f,v],[b,p]);n.add(t,{name:"priority"});let g=o([y,t],r=>({classification:r[0],priority:r[1]}),{meta:s("content_moderation",{stage:"output"})});n.add(g,{name:"output"});let R=o([k.entries,N],r=>{let e=r[0];if(e&&e.length>0){let i=e[e.length-1];if(i&&i.falsePositive)return i}return null},{meta:s("content_moderation",{stage:"feedback_condition"})});return n.add(R,{name:"feedback_condition"}),G(n,"feedback_condition","policy",{maxIterations:a.maxFeedbackIterations??5}),n}function T(u,a){let n=new I(u,a);n.add(a.source,{name:"source"});let h=a.validate??(t=>({valid:!0,errors:[],record:t})),m=o([a.source],t=>t[0]!=null?h(t[0]):void 0,{meta:s("data_quality",{stage:"validate"})});n.add(m,{name:"validate"});let y=a.detectAnomaly??(t=>({anomaly:!1,score:0,record:t})),c=o([a.source],t=>t[0]!=null?y(t[0]):void 0,{meta:s("data_quality",{stage:"anomaly"})});n.add(c,{name:"anomaly"});let k=d(null,{meta:s("data_quality",{stage:"baseline",description:"Rolling baseline for drift detection"})});n.add(k,{name:"baseline"});let l=O([m],t=>{let g=t[0];g?.valid&&S(()=>{k.emit(g.record)})});n.add(l,{name:"__baseline_updater"}),M(l);let _=a.detectDrift??(()=>({drift:!1})),N=o([a.source,k],t=>_(t[0],t[1]),{meta:s("data_quality",{stage:"drift"})});n.add(N,{name:"drift"});let w=a.suggest??(()=>null),f=o([m,c],t=>w({validation:t[0],anomaly:t[1]}),{meta:s("data_quality",{stage:"remediate"})});n.add(f,{name:"remediate"});let v=o([m,c,N,f],t=>({validation:t[0],anomaly:t[1],drift:t[2],remediation:t[3]}),{meta:s("data_quality",{stage:"output"})});n.add(v,{name:"output"});let b=d([],{meta:s("data_quality",{stage:"validation_rules"})});n.add(b,{name:"validation_rules"});let p=o([c],t=>{let g=t[0];return g?.anomaly?g:null},{meta:s("data_quality",{stage:"feedback_condition"})});return n.add(p,{name:"feedback_condition"}),G(n,"feedback_condition","validation_rules",{maxIterations:a.maxFeedbackIterations??3}),n}function C(u,a){if(u==null||typeof u!="object")return!1;let n=u;return n.type===a||n.kind===a}export{D as a,B as b,Q as c,T as d,$ as e};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import{a as mt,b as ct,d as pt,e as ft}from"./chunk-4OFIQ66T.js";import{e as dt}from"./chunk-VWPRPPKR.js";import{e as De}from"./chunk-Y53B6NS4.js";import{a as Ct,b as Pt,c as jt,d as _t,e as Dt,f as _e}from"./chunk-NSG4C6BF.js";import{a as Me,b as At,c as St,d as Et,e as It,f as Ot}from"./chunk-7JDLFI6N.js";import{c as it}from"./chunk-5Z4HDCO6.js";import{b as ut}from"./chunk-LVGBLZM2.js";import{b as rt,c as Re,d as nt,f as je}from"./chunk-OL33ZI6R.js";import{k as Z}from"./chunk-MGKAO4EK.js";import{a as X}from"./chunk-ESMPEKEV.js";import{P as lt,v as J}from"./chunk-5JDE5JHE.js";import{A as K,f as ot,m as w,w as at,y as st}from"./chunk-KASHOCF5.js";import{b as ge}from"./chunk-AUY2YKCO.js";import{D as se,E as v,F as Pe,G as x,H as ie,m as ae,o as W,p as Te}from"./chunk-W4TSQ6RJ.js";import{b as q,d as fe,i as re,j as Y}from"./chunk-CK2E7BTU.js";import{b as Nt}from"./chunk-QYADASLV.js";var _r={};Nt(_r,{AgentLoopGraph:()=>Oe,AllTiersExhaustedError:()=>Dt,BudgetExhaustedError:()=>Ne,ChatStreamGraph:()=>Ee,CircuitOpenError:()=>Re,DEFAULT_DECAY_RATE:()=>Xe,FallbackMissError:()=>It,LLMTimeoutError:()=>he,ReplayCacheMissError:()=>At,ToolRegistryGraph:()=>Ie,admissionFilter3D:()=>Cr,agentLoop:()=>Rr,agentMemory:()=>Ar,anthropicAdapter:()=>Ct,canonicalJson:()=>Et,cascadingLlmAdapter:()=>_e,chatStream:()=>ze,composePricing:()=>Kt,computePrice:()=>yt,contentGate:()=>kr,costMeterExtractor:()=>gr,createAdapter:()=>_t,createCapabilitiesRegistry:()=>Ft,createPricingRegistry:()=>$t,dryRunAdapter:()=>Me,dryRunPreset:()=>rr,fallbackAdapter:()=>Ot,fromLLM:()=>nr,frozenContext:()=>lr,gatedStream:()=>cr,gaugesAsContext:()=>Sr,googleAdapter:()=>Pt,graphFromSpec:()=>Er,handoff:()=>Lr,keywordFlagExtractor:()=>hr,knobsAsTools:()=>Or,llmConsolidator:()=>Qe,llmExtractor:()=>Ye,observableAdapter:()=>Gt,openAICompatAdapter:()=>jt,parseRateLimitFromError:()=>Ke,promptNode:()=>dr,redactor:()=>vr,registryPricing:()=>Wt,resilientAdapter:()=>tr,streamExtractor:()=>br,streamingPromptNode:()=>mr,suggestStrategy:()=>jr,systemPromptBuilder:()=>pr,toolCallExtractor:()=>Mr,toolRegistry:()=>Je,toolSelector:()=>wr,validateGraphDef:()=>Ze,withBreaker:()=>Be,withBudgetGate:()=>We,withDryRun:()=>Vt,withRateLimiter:()=>Ve,withReplayCache:()=>St,withRetry:()=>He,withTimeout:()=>qe,zeroPrice:()=>Ge});function Le(t,e){return`${t}::${e}`}function Ft(t){let e=new Map,r=new Map,o=n=>{e.set(Le(n.provider,n.id),n);let a=r.get(n.provider);a||(a=new Set,r.set(n.provider,a)),a.add(n.id)};if(t)for(let n of t)o(n);return{register:o,lookup(n,a){let s=e.get(Le(n,a));if(s)return s;let i=r.get(n);if(!i)return;let l;for(let m of i)if(a.startsWith(m)&&(!l||m.length>l.key.length)){let d=e.get(Le(n,m));d&&(l={key:m,cap:d})}return l?.cap},remove(n,a){let s=e.delete(Le(n,a));if(s){let i=r.get(n);i?.delete(a),i&&i.size===0&&r.delete(n)}return s},entries(){return e.values()}}}function ne(t){let e=t.input,r=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return r;let o=0;for(let n of Object.values(e.extensions))o+=n;return r+o}function le(t){let e=t.output,r=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return r;let o=0;for(let n of Object.values(e.extensions))o+=n;return r+o}function gt(){return{input:{regular:0},output:{regular:0}}}function Gt(t,e){let r=e?.logMax??1e3,o=ge(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:r}),n=v(null,{name:"adapterStats/lastCall"}),a=v(0,{name:"adapterStats/totalCalls"}),s=v(0,{name:"adapterStats/totalInputTokens"}),i=v(0,{name:"adapterStats/totalOutputTokens"}),l=p=>{o.append(p),n.emit(p),a.emit((a.cache??0)+1),s.emit((s.cache??0)+ne(p.usage)),i.emit((i.cache??0)+le(p.usage))},m=()=>{o.clear(),n.emit(null),a.emit(0),s.emit(0),i.emit(0)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(p,c){let f=W(),y=Te(),g=t.invoke(p,c),T=b=>{let A=W();return l({timestamp:A,wallClock:y,provider:t.provider,model:t.model??c?.model??b.model??"",tier:c?.tier??b.tier,usage:b.usage??Fe(),latencyMs:Math.max(0,(A-f)/1e6),method:"invoke"}),b};if(g!=null&&typeof g.then=="function")return g.then(T);if(g!=null&&typeof g=="object"&&"content"in g)return T(g);let C=!1;return x([w(g)],([b])=>b==null||C?b:(C=!0,T(b)),{name:"adapterStats/invokeTap"})},async*stream(p,c){let f=W(),y=Te(),g;try{for await(let C of t.stream(p,c))C.type==="usage"&&(g=C.usage),yield C;let T=W();l({timestamp:T,wallClock:y,provider:t.provider,model:t.model??c?.model??"",tier:c?.tier,usage:g??Fe(),latencyMs:Math.max(0,(T-f)/1e6),method:"stream"})}catch(T){let C=W(),b=T;throw l({timestamp:C,wallClock:y,provider:t.provider,model:t.model??c?.model??"",tier:c?.tier,usage:g??Fe(),latencyMs:Math.max(0,(C-f)/1e6),method:"stream",error:{type:b?.name??"Error",message:b?.message??String(T)}}),T}}},stats:{lastCall:n,allCalls:o,totalCalls:a,totalInputTokens:s,totalOutputTokens:i,reset:m}}}function Fe(){return{input:{regular:0},output:{regular:0}}}function Bt(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Ge(t="USD"){return{total:0,currency:t}}function yt(t,e,r){let o=ne(t),n=e.currency??"USD",a=r?.withBreakdown===!0,s=a?{}:null,i=0,l=(g,T,C)=>{if(!T||C==null)return;let b=Bt(C,o),A=T*b/1e6;i+=A,a&&(s[g]=(s[g]??0)+A)},m=t.input,d=e.input;if(d&&(l("input.regular",m.regular,d.regular),l("input.cacheRead",m.cacheRead??0,d.cacheRead),l("input.cacheWrite5m",m.cacheWrite5m??0,d.cacheWrite5m),l("input.cacheWrite1h",m.cacheWrite1h??0,d.cacheWrite1h),l("input.cacheWriteOther",m.cacheWriteOther??0,d.cacheWriteOther),l("input.audio",m.audio??0,d.audio),l("input.image",m.image??0,d.image),l("input.video",m.video??0,d.video),l("input.toolUse",m.toolUse??0,d.toolUse),m.extensions&&d.extensions))for(let[g,T]of Object.entries(m.extensions))l(`input.ext.${g}`,T,d.extensions[g]);let u=t.output,p=e.output;if(p&&(l("output.regular",u.regular,p.regular),l("output.reasoning",u.reasoning??0,p.reasoning),l("output.audio",u.audio??0,p.audio),l("output.predictionAccepted",u.predictionAccepted??0,p.predictionAccepted),l("output.predictionRejected",u.predictionRejected??0,p.predictionRejected),u.extensions&&p.extensions))for(let[g,T]of Object.entries(u.extensions))l(`output.ext.${g}`,T,p.extensions[g]);let c=r?.tier;if(c&&e.tierMultipliers){let g=e.tierMultipliers[c];if(g!=null&&(i*=g,a))for(let T of Object.keys(s))s[T]*=g}let f=t.auxiliary,y=e.auxiliary;if(f&&y)for(let[g,T]of Object.entries(f)){let C=y[g];if(C==null||!T)continue;let b=T*C;i+=b,a&&(s[`auxiliary.${g}`]=b)}return a?{total:i,currency:n,breakdown:s}:{total:i,currency:n}}function we(t,e){return`${t}::${e}`}function $t(t){let e=new Map,r=new Map,o=(n,a,s)=>{e.set(we(n,a),{provider:n,model:a,pricing:s});let i=r.get(n);i||(i=new Set,r.set(n,i)),i.add(a)};if(t)for(let[n,a,s]of t)o(n,a,s);return{register:o,lookup(n,a){let s=e.get(we(n,a));if(s)return s.pricing;let i=r.get(n);if(!i)return;let l;for(let m of i)if(a.startsWith(m)&&(!l||m.length>l.key.length)){let d=e.get(we(n,m));d&&(l={key:m,pricing:d.pricing})}return l?.pricing},remove(n,a){let s=e.delete(we(n,a));if(s){let i=r.get(n);i?.delete(a),i&&i.size===0&&r.delete(n)}return s},entries(){let n=e.values();return(function*(){for(let{provider:a,model:s,pricing:i}of n)yield[a,s,i]})()}}}function Wt(t,e="USD"){return(r,o)=>{let n=t.lookup(o.provider,o.model);return n?yt(r,n,{tier:o.tier,withBreakdown:o.withBreakdown}):Ge(e)}}function Kt(...t){return(e,r)=>{for(let o of t){let n=o(e,r);if(n.total!==0)return n}return t.length>0?t[0](e,r):Ge()}}function Be(t,e={}){let r=e.breaker??nt(e);return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(n,a){if(!r.canExecute())throw new Re;try{let s=await Promise.resolve(t.invoke(n,a));return r.recordSuccess(),s}catch(s){throw r.recordFailure(s),s}},async*stream(n,a){if(!r.canExecute())throw new Re;try{for await(let s of t.stream(n,a))yield s;r.recordSuccess()}catch(s){throw r.recordFailure(s),s}}},breaker:r}}var Ne=class extends Error{constructor(r,o,n){super(`Budget exhausted: ${r} (limit=${o}, observed=${n})`);this.which=r;this.limit=o;this.observed=n}name="BudgetExhaustedError"},$e=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),ht=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function We(t,e){let r=ge(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),o=v(ht(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),n=x([o],([d])=>{let u=d;return!(e.caps.calls!=null&&u.calls>=e.caps.calls||e.caps.inputTokens!=null&&u.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&u.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&u.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(K(n),e.onExhausted!=null){let d=e.onExhausted,u=!1,p=!0;n.subscribe(c=>{for(let f of c)if(f[0]===q){let y=f[1];if(u&&p&&y===!1){let g=bt(o.cache??$e,e.caps);g&&d(g)}p=y,u=!0}})}let a=()=>{if(n.cache===!1){let d=o.cache??$e,u=bt(d,e.caps);return new Ne(u??"budget",e.caps[u??"calls"]??0,Ut(d,u??"calls"))}},s=(d,u)=>{let p=t.provider,c={timestamp:W(),wallClock:Te(),provider:p,model:u.model,tier:u.tier,usage:d,latencyMs:u.latencyMs,method:u.method,...u.error?{error:u.error}:{}};r.append(c);let f=o.cache??$e,y=e.pricingFn?f.usd+e.pricingFn(d,{model:u.model,provider:p,tier:u.tier}).total:f.usd;o.emit({calls:f.calls+1,inputTokens:f.inputTokens+ne(d),outputTokens:f.outputTokens+le(d),usd:y})},i=()=>{r.clear(),o.emit(ht())},l=()=>({input:{regular:0},output:{regular:0}});return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(d,u){let p=a();if(p)return Promise.reject(p);let c=W(),f=t.invoke(d,u),y=T=>{let C=Math.max(0,(W()-c)/1e6);return s(T.usage??l(),{model:t.model??u?.model??T.model??"",tier:u?.tier??T.tier,latencyMs:C,method:"invoke"}),T};if(f!=null&&typeof f.then=="function")return f.then(y);if(f!=null&&typeof f=="object"&&"content"in f)return y(f);let g=!1;return x([w(f)],([T])=>T==null||g?T:(g=!0,y(T)),{name:"budgetGate/invokeTap"})},async*stream(d,u){let p=a();if(p)throw p;let c=W(),f;try{for await(let y of t.stream(d,u))y.type==="usage"&&(f=y.usage),yield y;s(f??l(),{model:t.model??u?.model??"",tier:u?.tier,latencyMs:Math.max(0,(W()-c)/1e6),method:"stream"})}catch(y){let g=y;throw s(f??l(),{model:t.model??u?.model??"",tier:u?.tier,latencyMs:Math.max(0,(W()-c)/1e6),method:"stream",error:{type:g?.name??"Error",message:g?.message??String(y)}}),y}}},budget:{totals:o,isOpen:n,log:r,reset:i}}}function bt(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function Ut(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}function Vt(t,e){let r=e.mock??Me({provider:t.provider,model:t.model}),o=typeof e.enabled=="boolean"?e.enabled:void 0,n=o===void 0?w(e.enabled):void 0,a;n&&(a=K(n));let s=()=>o!==void 0?o:!!n?.cache;return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),invoke(m,d){return s()?r.invoke(m,d):t.invoke(m,d)},stream(m,d){return s()?r.stream(m,d):t.stream(m,d)}},dispose:()=>{a&&(a(),a=void 0)}}}function Ke(t){if(t==null||typeof t!="object")return;let e=t,r=e.status,o=Ht(e.headers);if(r!==429&&r!==503&&!Xt(e.message))return;let n={},a=o("retry-after"),s=zt(a);s!=null&&(n.retryAfterMs=s);let i=o("anthropic-ratelimit-requests-reset");if(i){let c=Tt(i);c!=null&&(n.retryAfterMs=Math.max(n.retryAfterMs??0,c))}let l=o("anthropic-ratelimit-tokens-reset");if(l){let c=Tt(l);c!=null&&(n.retryAfterMs=Math.max(n.retryAfterMs??0,c))}let m=Ce(o,"x-ratelimit-limit-requests");m!=null&&(n.rpmCap=m);let d=Ce(o,"x-ratelimit-limit-tokens");d!=null&&(n.tpmCap=d);let u=Ce(o,"x-ratelimit-remaining-requests"),p=Ce(o,"x-ratelimit-remaining-tokens");if(u!=null&&m!=null&&m>0&&(n.usageHint??={},n.usageHint.rpm=1-u/m),p!=null&&d!=null&&d>0&&(n.usageHint??={},n.usageHint.tpm=1-p/d),n.retryAfterMs==null&&e.message){let c=Yt(e.message);c!=null&&(n.retryAfterMs=c)}return e.headers&&(n.metadata={headers:qt(e.headers)}),n.retryAfterMs==null&&n.rpmCap==null&&n.tpmCap==null&&n.usageHint==null?n.metadata?n:void 0:n}function Ht(t){if(!t)return()=>{};if(typeof t.get=="function"){let o=t;return n=>o.get(n)??o.get(n.toLowerCase())??void 0}let e=t,r={};for(let[o,n]of Object.entries(e)){let a=Array.isArray(n)?n.join(", "):n;a!=null&&(r[o.toLowerCase()]=a)}return o=>r[o.toLowerCase()]}function qt(t){let e={};if(typeof t.forEach=="function")return t.forEach((r,o)=>{e[o]=r}),e;for(let[r,o]of Object.entries(t))o!=null&&(e[r]=Array.isArray(o)?o.join(", "):o);return e}function Ce(t,e){let r=t(e);if(r==null)return;let o=Number(r);return Number.isFinite(o)?o:void 0}function zt(t){if(!t)return;let e=t.trim(),r=Number(e);if(Number.isFinite(r)&&r>=0)return r*1e3;let o=Date.parse(e);if(Number.isFinite(o)){let n=o-Date.now();if(n>0)return n}}function Tt(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var Jt=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function Yt(t){let e=Jt.exec(t);if(!e)return;let r=Number(e[1]);if(!Number.isFinite(r))return;let o=(e[2]??"s").toLowerCase();if(o==="ms")return r;if(o.startsWith("s"))return r*1e3;if(o.startsWith("m"))return r*6e4}var Qt=/rate\s*limit|too\s*many\s*requests|quota|429/i;function Xt(t){return!!t&&Qt.test(t)}function Ue(t){let e=new Error(t);return e.name="AbortError",e}function kt(t={}){let e=Math.max(1,t.burstMultiplier??1),r=t.clampCooldownMs??6e4,o=t.rpm!=null?w(t.rpm):v(Number.POSITIVE_INFINITY),n=t.tpm!=null?w(t.tpm):v(Number.POSITIVE_INFINITY),a=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),s=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),i=v({},{name:"adaptiveRateLimiter/lastSignal"}),l=x([o,a],([L,E])=>Math.min(Number(L??1/0),Number(E??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),m=x([n,s],([L,E])=>Math.min(Number(L??1/0),Number(E??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=ye(Number(o.cache??Number.POSITIVE_INFINITY),e),u=ye(Number(n.cache??Number.POSITIVE_INFINITY),e),p=!1,c=!1,f=l.subscribe(L=>{for(let E of L)if(E[0]===q){let P=Number(E[1]);Number.isFinite(P)&&P>0?(d=ye(P,e),p=!1):P===1/0?(d=ye(1/0,e),p=!1):P<=0&&(p=!0)}}),y=m.subscribe(L=>{for(let E of L)if(E[0]===q){let P=Number(E[1]);Number.isFinite(P)&&P>0?(u=ye(P,e),c=!1):P===1/0?(u=ye(1/0,e),c=!1):P<=0&&(c=!0)}}),g=0,T=new X,C=new X,b;t.adaptation!=null&&(b=w(t.adaptation).subscribe(E=>{for(let P of E)P[0]===q&&A(P[1])}));function A(L){if(i.emit(L),L.rpmCap!=null&&Number.isFinite(L.rpmCap)&&L.rpmCap>=0&&(a.emit(L.rpmCap),Number.isFinite(r)&&r>0&&T.start(r,()=>a.emit(Number.POSITIVE_INFINITY))),L.tpmCap!=null&&Number.isFinite(L.tpmCap)&&L.tpmCap>=0&&(s.emit(L.tpmCap),Number.isFinite(r)&&r>0&&C.start(r,()=>s.emit(Number.POSITIVE_INFINITY))),L.retryAfterMs!=null&&L.retryAfterMs>0){let E=W()+L.retryAfterMs*1e6;E>g&&(g=E)}}let O=v(0,{name:"adaptiveRateLimiter/pending"}),U=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),B=v(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),V=L=>{O.emit((O.cache??0)+L)},_=()=>{U.emit(d.available()),B.emit(u.available())};async function H(L={}){let E=L.requestCost??1,P=L.tokenCost??0,M=L.signal;V(1);try{for(;;){if(M?.aborted)throw Ue("AdaptiveRateLimiter.acquire aborted");let h=W();if(g>h){let ee=Math.ceil((g-h)/1e6);await Ae(ee,M);continue}if(E>0&&p||P>0&&c){await Ae(250,M);continue}let k=d,R=u;if(!k.tryConsume(E)){await Ae(Mt(k,E),M);continue}if(!(P>0?R.tryConsume(P):!0)){k.putBack(E),await Ae(Mt(R,P),M);continue}_();return}}finally{V(-1)}}function $(L){L>0?u.tryConsume(L):L<0&&u.putBack(-L),_()}function F(){f(),y(),b?.(),T.cancel(),C.cancel()}return{effectiveRpm:l,effectiveTpm:m,lastSignal:i,pending:O,rpmAvailable:U,tpmAvailable:B,acquire:H,recordUsage:$,recordSignal:A,dispose:F}}function ye(t,e){if(!Number.isFinite(t)||t===1/0)return je(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let r=Math.max(1,t*e),o=t/60;return je(r,o)}function Mt(t,e){let r=t.available(),o=Math.max(0,e-r);return o<=0?25:Math.min(5e3,Math.max(50,o*100))}function Ae(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Ue("AdaptiveRateLimiter.acquire aborted")):new Promise((r,o)=>{let n=new X,a,s=()=>{n.cancel(),e&&a&&e.removeEventListener("abort",a)};n.start(t,()=>{s(),r()}),e&&(a=()=>{s(),o(Ue("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",a,{once:!0}))})}function Ve(t,e={}){let r=e.limiter??kt({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),o=(s,i)=>e.costFn?e.costFn(s,i):0,n=s=>{let i=Ke(s);i&&r.recordSignal(i)};return{adapter:{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(s,i){let l=o(s,i);await r.acquire({requestCost:1,tokenCost:l,signal:i?.signal});try{let m=t.invoke(s,i),d=await Zt(m),u=d.usage??gt(),c=ne(u)+le(u)-l;return c>0&&r.recordUsage(c),d}catch(m){throw n(m),m}},async*stream(s,i){let l=o(s,i);await r.acquire({requestCost:1,tokenCost:l,signal:i?.signal});try{let m=0;for await(let u of t.stream(s,i))u.type==="usage"&&(m=ne(u.usage)+le(u.usage)),yield u;let d=m-l;d>0&&r.recordUsage(d)}catch(m){throw n(m),m}}},limiter:r}}async function Zt(t){return t!=null&&typeof t.then=="function"?await t:t&&typeof t=="object"&&"content"in t?t:await at(w(t))}function Se(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function vt(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Se()):new Promise((r,o)=>{let n=new X,a,s=()=>{n.cancel(),e&&a&&e.removeEventListener("abort",a)};n.start(t,()=>{s(),r()}),e&&(a=()=>{s(),o(Se())},e.addEventListener("abort",a,{once:!0}))})}function He(t,e={}){let r=e.attempts??3,o=e.baseDelayMs??500,n=e.maxDelayMs??1e4,a=e.strategy??"decorrelated",s=e.jitter??!0,i=e.shouldRetry??er,l=e.retryStreaming??!0,m=(d,u)=>{if(a==="decorrelated"){let y=Math.min(n,Math.max(o,u*3));return o+Math.random()*(y-o)}let p=a==="exp"?o*2**(d-1):o*d,c=Math.min(n,p);if(!s)return c;let f=c*(.5+Math.random());return Math.min(n,f)};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(d,u){if(u?.signal?.aborted)throw Se();let p,c=o;for(let f=1;f<=r;f++)try{return await Promise.resolve(t.invoke(d,u))}catch(y){if(p=y,f>=r||!i(y,f))throw y;let g=m(f,c);c=g,await vt(g,u?.signal)}throw p},async*stream(d,u){if(u?.signal?.aborted)throw Se();if(!l){for await(let f of t.stream(d,u))yield f;return}let p,c=o;for(let f=1;f<=r;f++){let y=!1;try{for await(let g of t.stream(d,u))y=!0,yield g;return}catch(g){if(p=g,y||f>=r||!i(g,f))throw g;let T=m(f,c);c=T,await vt(T,u?.signal)}}throw p}}}function er(t,e){if(t==null)return!1;let r=t;return r.name==="LLMTimeoutError"?!0:r.name==="AbortError"||r.message==="aborted"||r.name==="DOMException"&&r.code!=null&&Number(r.code)===20||r.name==="BudgetExhaustedError"||r.name==="CircuitOpenError"?!1:r.status!=null?r.status===429||r.status>=500&&r.status<600:r.code&&typeof r.code=="string"&&/^E[A-Z]+$/.test(r.code)?!0:r.message?/network|timeout|socket|fetch|econn|eai_/i.test(r.message):!1}var he=class extends Error{constructor(r){super(`LLM call timed out after ${r}ms`);this.ms=r}name="LLMTimeoutError"};function qe(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let r=n=>{let a=new AbortController,s=!1,i;n&&(n.aborted?a.abort(n.reason):(i=()=>a.abort(n.reason),n.addEventListener("abort",i,{once:!0})));let l=new X;return l.start(e,()=>{s=!0,a.abort(new he(e))}),{signal:a.signal,cancel:()=>{l.cancel(),n&&i&&n.removeEventListener("abort",i)},timedOut:()=>s}},o=(n,a)=>{if(!a||n instanceof he)throw n;let s=n;if(s?.name==="AbortError"||s?.name==="DOMException"&&Number(s.code)===20||n?.message==="aborted"){let l=new he(e);throw l.cause=n,l}throw n};return{provider:t.provider,model:t.model,capabilities:t.capabilities?.bind(t),async invoke(n,a){let{signal:s,cancel:i,timedOut:l}=r(a?.signal);try{return await Promise.resolve(t.invoke(n,{...a,signal:s}))}catch(m){return o(m,l())}finally{i()}},async*stream(n,a){let{signal:s,cancel:i,timedOut:l}=r(a?.signal);try{for await(let m of t.stream(n,{...a,signal:s}))yield m}catch(m){o(m,l())}finally{i()}}}}function tr(t,e={}){let r={adapter:t},o=t;if(e.rateLimit){let n=Ve(o,e.rateLimit);o=n.adapter,r.rateLimiter=n.limiter}if(e.budget){let n=We(o,e.budget);o=n.adapter,r.budget=n.budget}if(e.breaker){let n=Be(o,e.breaker);o=n.adapter,r.breaker=n.breaker}if(e.timeoutMs!=null&&(o=qe(o,e.timeoutMs)),e.retry&&(o=He(o,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let n={};e.onFallback&&(n.onFallback=e.onFallback),e.onExhausted&&(n.onExhausted=e.onExhausted),o=_e([{name:e.name??"primary",adapter:o},{name:"fallback",adapter:e.fallback}],n)}return r.adapter=o,r}function rr(){return Me()}function nr(t,e,r){let o=w(e);return J(o,a=>{if(!a||a.length===0)return v(null);let s=r?.tools;return t.invoke(a,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,tools:s,systemPrompt:r?.systemPrompt})})}function N(t,e){return it("ai",t,e)}function or(t){return t!=null&&typeof t.then=="function"}function ar(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function sr(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var ir=3e4;function xt(t,e){if(t.status==="settled"){let o=t.cache;if(o!==void 0)return Promise.resolve(o)}let r=e?.timeoutMs??ir;return new Promise((o,n)=>{let a=new X,s=t.subscribe(i=>{for(let l of i){if(l[0]===q){a.cancel(),s(),o(l[1]);return}if(l[0]===Y){a.cancel(),s(),n(l[1]);return}if(l[0]===re){a.cancel(),s(),n(new Error("firstDataFromNode: completed without producing a value"));return}}});a.start(r,()=>{s(),n(new Error(`firstDataFromNode: timed out after ${r}ms`))})})}async function ue(t){return or(t)?ue(await t):ar(t)?xt(t):sr(t)?xt(w(t)):t}function de(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function lr(t,e){let r=w(t),o=e?.refreshTrigger!=null?w(e.refreshTrigger):null;return o==null?se([r],(n,a,s)=>{if(s.store.emitted===!0)return;let l=n[0],m=l!=null&&l.length>0?l.at(-1):s.prevData[0];if(m!==void 0)return s.store.emitted=!0,a.emit(m),{invalidate:()=>{s.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context")}):se([r,o],(n,a,s)=>{let i=n[1];if(!(i!=null&&i.length>0))return;let m=n[0],d=m!=null&&m.length>0?m.at(-1):s.prevData[0];a.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:N("frozen_context")})}function ur(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function dr(t,e,r,o){let n=o?.format??"text",a=o?.retries??0,s=o?.cache??!1,i=s?new Map:null,l=x(e,d=>{if(d.some(c=>c==null))return[];let u=typeof r=="string"?r:r(...d);if(!u)return[];let p=[];return o?.systemPrompt&&p.push({role:"system",content:o.systemPrompt}),p.push({role:"user",content:u}),p},{name:o?.name?`${o.name}::messages`:"prompt_node::messages",meta:N("prompt_node"),initial:[]});return J(l,d=>{if(!d||d.length===0)return v(null);let u=s?JSON.stringify(d.map(c=>[c.role,c.content])):"";if(i?.has(u))return v(i.get(u));async function p(c){try{let f=await new Promise((T,C)=>{let b=t.invoke(d,{model:o?.model,temperature:o?.temperature,maxTokens:o?.maxTokens,systemPrompt:o?.systemPrompt});b&&typeof b.then=="function"?b.then(T,C):b&&typeof b.subscribe=="function"?T(b.cache):T(b)}),y=ur(f),g;return n==="json"?g=JSON.parse(de(y)):g=y,i?.set(u,g),g}catch(f){if(c>0)return p(c-1);throw f}}return p(a)})}function mr(t,e,r,o){let n=o?.name??"llm",a=o?.format??"text",s=De(`${n}/stream`),i=x(e,d=>{if(d.some(c=>c==null))return[];let u=typeof r=="string"?r:r(...d);if(!u)return[];let p=[];return o?.systemPrompt&&p.push({role:"system",content:o.systemPrompt}),p.push({role:"user",content:u}),p}),l=J(i,d=>{let u=d;if(!u||u.length===0)return v(null);let p=new AbortController;async function*c(){let f="",y=0;try{for await(let T of t.stream(u,{model:o?.model,temperature:o?.temperature,maxTokens:o?.maxTokens,systemPrompt:o?.systemPrompt,signal:p.signal})){if(T.type!=="token")continue;let C=T.delta;f+=C,s.publish({source:n,token:C,accumulated:f,index:y++})}let g;if(a==="json")try{g=JSON.parse(de(f))}catch{g=null}else g=f;yield g}finally{p.abort()}}return w(c())}),m=K(l);return{output:l,stream:s,dispose:()=>{m(),s.destroy()}}}function cr(t,e,r,o,n,a){let s=v(0,{name:`${e}/cancel`}),i=0,l=[...o,s],m=a?.name??e,d=a?.format??"text",u=De(`${m}/stream`),p=x(l,b=>{let A=b.slice(0,-1);if(A.some(B=>B==null))return[];let O=typeof n=="string"?n:n(...A);if(!O)return[];let U=[];return a?.systemPrompt&&U.push({role:"system",content:a.systemPrompt}),U.push({role:"user",content:O}),U}),c=J(p,b=>{let A=b;if(!A||A.length===0)return v(null);let O=new AbortController;async function*U(){let B="",V=0;try{for await(let H of r.stream(A,{model:a?.model,temperature:a?.temperature,maxTokens:a?.maxTokens,systemPrompt:a?.systemPrompt,signal:O.signal})){if(H.type!=="token")continue;let $=H.delta;B+=$,u.publish({source:m,token:$,accumulated:B,index:V++})}let _;if(d==="json")try{_=JSON.parse(de(B))}catch{_=null}else _=B;yield _}finally{O.abort()}}return w(U())}),f=K(c),y=x([c],([b])=>{if(b!=null)return b},{name:`${e}/filter`});t.add(y,{name:`${e}/raw`});let g=dt(t,`${e}/gate`,`${e}/raw`,a?.gate),T=g.reject.bind(g),C={...g,reject(b=1){T(b),s.emit(++i)}};return{output:g.node,stream:u,gate:C,dispose:()=>{f(),u.destroy()}}}function pr(t,e){let r=e?.separator??`
|
|
2
|
+
|
|
3
|
+
`,o=t.map(s=>typeof s=="string"?v(s):w(s)),n=x(o,s=>s.filter(i=>i!=null&&i!=="").join(r),{name:e?.name??"systemPrompt",describeKind:"derived",meta:N("system_prompt"),initial:""}),a=K(n);return Object.assign(n,{dispose:a})}var fr=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens;function gr(t,e){let r=e?.charsPerToken??4;return x([t.latest],([o])=>{if(o==null)return{chunkCount:0,charCount:0,estimatedTokens:0};let n=o,a=n.accumulated.length;return{chunkCount:n.index+1,charCount:a,estimatedTokens:Math.ceil(a/r)}},{name:e?.name??"cost-meter",describeKind:"derived",initial:{chunkCount:0,charCount:0,estimatedTokens:0},meta:N("cost_meter_extractor"),equals:fr})}var yr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let o=t[r],n=e[r];if(o.label!==n.label||o.pattern!==n.pattern||o.match!==n.match||o.position!==n.position)return!1}return!0};function hr(t,e){let r=e.maxPatternLength??128;return x([t.latest],([o],n)=>{if(o==null)return[];let a=o.accumulated;"flags"in n.store||(n.store.flags=[],n.store.scannedTo=0);let s=n.store.flags,i=n.store.scannedTo,l=Math.max(0,i-r),m=a.slice(l),d=!1;for(let{pattern:u,label:p}of e.patterns){let c=new RegExp(u.source,`${u.flags.replace("g","")}g`);for(let f of m.matchAll(c)){let y=l+f.index;y+f[0].length<=i||(s.push({label:p,pattern:u,match:f[0],position:y}),d=!0)}}return n.store.scannedTo=a.length,d?[...s]:s.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:N("keyword_flag_extractor"),equals:yr})}function br(t,e,r){return x([t.latest],([o])=>o==null?null:e(o.accumulated),{name:r?.name??"extractor",describeKind:"derived",initial:null,meta:N("stream_extractor"),...r?.equals?{equals:r.equals}:{}})}var Tr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let o=t[r],n=e[r];if(o.startIndex!==n.startIndex||o.name!==n.name||o.raw!==n.raw)return!1}return!0};function Mr(t,e){return x([t.latest],([r],o)=>{if(r==null)return[];let n=r.accumulated;"calls"in o.store||(o.store.calls=[],o.store.scanFrom=0);let a=o.store.calls,s=o.store.scanFrom,i=!1;for(;s<n.length;){let l=n.indexOf("{",s);if(l===-1){o.store.scanFrom=n.length;break}let m=0,d=-1,u=!1;for(let c=l;c<n.length;c++){let f=n[c];if(u)f==="\\"&&c+1<n.length?c++:f==='"'&&(u=!1);else if(f==='"')u=!0;else if(f==="{")m++;else if(f==="}"&&(m--,m===0)){d=c;break}}if(d===-1){o.store.scanFrom=l;break}let p=n.slice(l,d+1);try{let c=JSON.parse(p);typeof c.name=="string"&&c.arguments!=null&&typeof c.arguments=="object"&&(a.push({name:c.name,arguments:c.arguments,raw:p,startIndex:l}),i=!0)}catch{}s=d+1,o.store.scanFrom=s}return i?[...a]:a.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:N("tool_call_extractor"),equals:Tr})}function kr(t,e,r,o){let n=r*(o?.hardMultiplier??1.5),a=typeof e!="function",s=[t.latest];return a&&s.push(e),x(s,i=>{let l=i[0];if(l==null)return"allow";let m=a?i[1]??0:e(l.accumulated);return m>=n?"block":m>=r?"review":"allow"},{name:o?.name??"content-gate",initial:"allow"})}function vr(t,e,r,o){let n=r??(()=>"[REDACTED]");function a(s){let i=s;for(let l of e){let m=l.global?l:new RegExp(l.source,`${l.flags}g`);i=i.replace(m,d=>n(d,l))}return i}return x([t.latest],([s])=>{if(s==null)return{source:"",token:"",accumulated:"",index:-1};let i=s,l=a(i.accumulated),m=a(i.token);return{source:i.source,token:m,accumulated:l,index:i.index}},{name:o?.name??"redactor"})}var Ee=class extends Z{_log;messages;latest;messageCount;constructor(e,r={}){super(e,r.graph),this._log=ge([],{name:"messages",maxSize:r.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=x([this.messages],([o])=>{let n=o;return n.length===0?null:n[n.length-1]},{name:"latest",describeKind:"derived",meta:N("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(K(this.latest)),this.messageCount=x([this.messages],([o])=>o.length,{name:"messageCount",describeKind:"derived",meta:N("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(K(this.messageCount))}append(e,r,o){this._log.append({role:e,content:r,...o})}appendToolResult(e,r){this._log.append({role:"tool",content:r,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function ze(t,e){return new Ee(t,e)}var Ie=class extends Z{definitions;schemas;constructor(e,r={}){super(e,r.graph),this.definitions=v(new Map,{name:"definitions",describeKind:"state",meta:N("tool_definitions")}),this.add(this.definitions,{name:"definitions"}),this.schemas=x([this.definitions],([o])=>[...(o??new Map).values()],{name:"schemas",describeKind:"derived",meta:N("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(K(this.schemas))}register(e){let r=this.definitions.cache,o=new Map(r);o.set(e.name,e),this.definitions.emit(o)}unregister(e){let r=this.definitions.cache;if(!r.has(e))return;let o=new Map(r);o.delete(e),this.definitions.emit(o)}async execute(e,r){let n=this.definitions.cache.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);let a=n.handler(r);return ue(a)}getDefinition(e){return this.definitions.cache?.get(e)}};function Je(t,e){return new Ie(t,e)}var Oe=class extends Z{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;turnCount;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,r){if(super(e,r.graph),this.chat=ze(`${e}-chat`,{maxMessages:r.maxMessages}),this.mount("chat",this.chat),this.tools=Je(`${e}-tools`),this.mount("tools",this.tools),r.tools)for(let M of r.tools)this.tools.register(M);this.status=v("idle",{name:"status",describeKind:"state",meta:N("agent_status")}),this.add(this.status,{name:"status"}),this.turn=v(0,{name:"turn",describeKind:"state",meta:N("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.turnCount=this.turn,this.aborted=v(!1,{name:"aborted",describeKind:"state",meta:N("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let o=0,n=this.turn.subscribe(M=>{for(let h of M)h[0]===q&&(o=h[1])}),a=!1,s=this.aborted.subscribe(M=>{for(let h of M)h[0]===q&&(a=h[1])}),i=r.adapter,l=r.systemPrompt,m=r.model,d=r.temperature,u=r.maxTokens,p=r.maxTurns??10,c=r.stopWhen,f=this.chat,y=this.tools,g=this.status,T=this.turn,C=this.aborted,b=se([g],(M,h,k)=>{if(ke(M,k.prevData,0,"idle")!=="thinking"||a||o>=p){h.down([[fe]]);return}let I=f.allMessages();if(I.length===0){h.down([[fe]]);return}let S=y.schemas.cache??[];h.emit({messages:I,tools:S})},{name:"promptInput",describeKind:"derived",meta:N("agent_prompt_input")}),A=J(b,M=>{let h=new AbortController;return this._currentAbortController=h,a&&h.abort(new Error("agentLoop: aborted")),w(Promise.resolve(i.invoke(M.messages,{tools:M.tools.length>0?M.tools:void 0,systemPrompt:l,model:m,temperature:d,maxTokens:u,signal:h.signal})),{signal:h.signal})},{equals:()=>!1}),O=v(null,{name:"lastResponse",describeKind:"state",meta:N("agent_last_response")});this.lastResponse=O;let U=se([O,g],(M,h,k)=>{let R=ke(M,k.prevData,0,null);if(ke(M,k.prevData,1,"idle")!=="acting"){h.down([[fe]]);return}let S=R?.toolCalls;if(S==null||S.length===0){h.down([[fe]]);return}h.emit(S)},{name:"toolCalls",describeKind:"derived",meta:N("agent_tool_calls")}),B=r.interceptToolCalls?r.interceptToolCalls(U):U;this.toolCalls=B;let V=(M,h)=>{if(M===h)return!0;if(M.length!==h.length)return!1;for(let k=0;k<M.length;k++){let R=M[k],I=h[k];if(R?.id!==I?.id||R?.content!==I?.content)return!1}return!0},_=J(B,M=>{if(M==null||M.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsNode gating invariant broken (should emit RESOLVED for empty). Audit toolCallsNode.");let h=M.map(k=>xr(k,y));return x(h,k=>k.map((R,I)=>{let S=R;return S!=null&&typeof S=="object"&&"id"in S&&"content"in S?S:{id:M[I].id,content:JSON.stringify(R??null)}}),{name:"toolResults_batch",equals:V})});this.toolResults=_;let H=ie([A],([M])=>{if(a)return;let h=M,k=o+1,R=h.toolCalls!=null&&h.toolCalls.length>0,I=h.finishReason==="end_turn"&&(!h.toolCalls||h.toolCalls.length===0),S=c?.(h)===!0,ee=k>=p,te=S||I||!R||ee?"done":"acting";ae(()=>{O.emit(h),g.emit(te),T.emit(k),f.append("assistant",h.content,{toolCalls:h.toolCalls})})}),$=ie([_],([M])=>{if(a)return;let h=M;if(h.length===0)return;let k=o>=p?"done":"thinking";ae(()=>{g.emit(k);for(let R of h)f.appendToolResult(R.id,R.content)})}),F=ie([C],([M])=>{M===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),g.emit("done"))}),L=K(H),E=K($),P=K(F);this._terminalResult=se([g,O],(M,h,k)=>{let R=ke(M,k.prevData,0,"idle"),I=ke(M,k.prevData,1,null);if(R==="done"){if(I!=null){h.emit({response:I,runVersion:this._runVersion});return}let S=new Error("agentLoop: aborted");S.name="AbortError",h.down([[Y,S]]);return}if(R==="error"){h.down([[Y,new Error("agentLoop: errored")]]);return}h.down([[fe]])},{name:"terminalResult",describeKind:"derived",meta:N("agent_terminal_result")}),this.addDisposer(n),this.addDisposer(s),this.addDisposer(L),this.addDisposer(E),this.addDisposer(P),this._disposeRunWiring=()=>{}}async run(e,r){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let o=++this._runVersion;ae(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let n;if(r!=null)if(r.aborted)this.aborted.emit(!0);else{let a=()=>this.aborted.emit(!0);r.addEventListener("abort",a,{once:!0}),n=()=>r.removeEventListener("abort",a)}try{return(await st(this._terminalResult,{predicate:s=>s!=null&&typeof s=="object"&&s.runVersion===o})).response}finally{n?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function xr(t,e){let r=rt(()=>w(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),o=x([r],([n])=>({id:t.id,content:typeof n=="string"?n:JSON.stringify(n)}));return lt(o,n=>({id:t.id,content:JSON.stringify({error:String(n)})}))}function ke(t,e,r,o){let n=t[r];if(n!=null&&n.length>0)return n[n.length-1];let a=e[r];return a!==void 0?a:o}function Rr(t,e){return new Oe(t,e)}function Lr(t,e,r){let o=w(t),n=r?.condition!=null?w(r.condition):null,a=v(null,{name:r?.name?`${r.name}::null`:"handoff::null"});if(n==null)return J(o,i=>{if(i==null)return a;let l=v(i);return e(l)});let s=x([o,n],([i,l])=>({v:i,open:l===!0}),{name:r?.name?`${r.name}::router`:"handoff::router",describeKind:"derived"});return J(s,({v:i,open:l})=>{if(i==null)return a;if(!l)return v(i);let m=v(i);return e(m)})}function wr(t,e,r){let o=w(t),n=e.map(s=>w(s)),a=[o,...n];return x(a,s=>{let i=s[0]??[],l=s.slice(1);return i.filter(m=>{for(let d of l)if(d!=null&&!d(m))return!1;return!0})},{name:r?.name??"tool-selector",describeKind:"derived",meta:N("tool_selector"),equals:(s,i)=>{let l=s,m=i;if(l.length!==m.length)return!1;for(let d=0;d<l.length;d++)if(l[d]!==m[d])return!1;return!0}})}function Nr(t){return{persistence:.5,structure:.5,personalValue:.5}}function Cr(t={}){let e=t.scoreFn??Nr,r=t.persistenceThreshold??.3,o=t.personalValueThreshold??.3,n=t.requireStructured??!1;return a=>{let s=e(a);return!(s.persistence<r||s.personalValue<o||n&&s.structure<=0)}}function Ye(t,e){return(r,o)=>{let n=[...o.keys()].slice(0,100),a=[{role:"system",content:t},{role:"user",content:JSON.stringify({input:r,existingKeys:n})}];return Pe(s=>{let i=!0,l=e.adapter.invoke(a,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),d=w(l).subscribe(u=>{if(!i)return;let p=!1;for(let c of u){if(p)break;if(c[0]===q){let f=c[1];try{let y=JSON.parse(f.content);s.emit(y),s.down([[re]])}catch{s.down([[Y,new Error("llmExtractor: failed to parse LLM response as JSON")]])}p=!0}else c[0]===Y?(s.down([[Y,c[1]]]),p=!0):c[0]===re?(s.down([[re]]),p=!0):s.down([[c[0],c[1]]])}});return()=>{d(),i=!1}})}}function Qe(t,e){return r=>{let o=[...r.entries()].map(([a,s])=>({key:a,value:s})),n=[{role:"system",content:t},{role:"user",content:JSON.stringify({memories:o})}];return Pe(a=>{let s=!0,i=e.adapter.invoke(n,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),m=w(i).subscribe(d=>{if(!s)return;let u=!1;for(let p of d){if(u)break;if(p[0]===q){let c=p[1];try{let f=JSON.parse(c.content);a.emit(f),a.down([[re]])}catch{a.down([[Y,new Error("llmConsolidator: failed to parse LLM response as JSON")]])}u=!0}else p[0]===Y?(a.down([[Y,p[1]]]),u=!0):p[0]===re?(a.down([[re]]),u=!0):a.down([[p[0],p[1]]])}});return()=>{m(),s=!1}})}}var Xe=Math.LN2/604800;function ve(t){return t instanceof Map?t:new Map}function Ar(t,e,r){let o=new Z(t,r.graph),n=[],a;if(r.extractFn)a=r.extractFn;else if(r.adapter&&r.extractPrompt)a=Ye(r.extractPrompt,{adapter:r.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(b,A)=>b==null?{upsert:[]}:a(b,A),i=e;if(r.admissionFilter){let b=w(e),A=r.admissionFilter;i=x([b],([O])=>{if(A(O))return O},{name:"admissionFilter",describeKind:"derived"})}let l;r.consolidateFn?l=r.consolidateFn:r.adapter&&r.consolidatePrompt&&(l=Qe(r.consolidatePrompt,{adapter:r.adapter}));let m=r.consolidateTrigger;if(!m&&l&&r.reflection?.enabled!==!1){let b=r.reflection?.interval??3e5;m=ot(b,{period:b})}let d={score:r.score,cost:r.cost,budget:r.budget??2e3,context:r.context,consolidate:l,consolidateTrigger:m},u=ut(i,s,d);o.add(u.store.entries,{name:"store"}),o.add(u.compact,{name:"compact"}),o.add(u.size,{name:"size"});let p=null;r.vectorDimensions&&r.vectorDimensions>0&&r.embedFn&&(p=pt({dimension:r.vectorDimensions}),o.add(p.entries,{name:"vectorIndex"}));let c=null;r.enableKnowledgeGraph&&(c=ft(`${t}-kg`),o.mount("kg",c));let f=null;if(r.tiers){let b=r.tiers,A=b.decayRate??Xe,O=b.maxActive??1e3,U=b.archiveThreshold??.1,B=b.permanentFilter??(()=>!1),V=ct({name:"permanent"});o.add(V.entries,{name:"permanent"});let _=new Set,H=h=>_.has(h)?"permanent":ve(u.store.entries.cache).has(h)?"active":"archived",$=(h,k)=>{_.add(h),V.upsert(h,k)},F=new Map,L=u.store.entries,E=r.context?w(r.context):v(null),P=ie([L,E],([h,k])=>{let R=ve(h),I=W(),S=[],ee=[];for(let[D,Q]of R){if(F.has(D)||F.set(D,I),B(D,Q)){ee.push({key:D,value:Q});continue}let z=r.score(Q,k),j=F.get(D)??I,G=Number(I-j)/1e9;mt(z,G,A)<U&&S.push(D)}for(let D of F.keys())R.has(D)||F.delete(D);for(let{key:D,value:Q}of ee)_.has(D)||$(D,Q);let te=R.size-_.size;if(te>O){let D=[...R.entries()].filter(([z])=>!_.has(z)).map(([z,j])=>({key:z,score:r.score(j,k)})).sort((z,j)=>z.score-j.score),Q=te-O;for(let z=0;z<Q&&z<D.length;z++){let j=D[z].key;S.includes(j)||S.push(j)}}S.length>0&&ae(()=>{for(let D of S)u.store.delete(D)})});n.push(P.subscribe(()=>{}));let M=null;b.archiveTier&&(M=o.attachStorage([b.archiveTier],b.archiveStorageOptions??{})),f={permanent:V,activeEntries:L,archiveHandle:M,tierOf:H,markPermanent:$}}if(p||c){let b=r.embedFn,A=r.entityFn,O=u.store.entries,U=ie([O],([B])=>{let V=ve(B);for(let[_,H]of V){if(p&&b){let $=b(H);$&&p.upsert(_,$,H)}if(c&&A){let $=A(_,H);if($){for(let F of $.entities??[])c.upsertEntity(F.id,F.value);for(let F of $.relations??[])c.link(F.from,F.to,F.relation,F.weight)}}}});n.push(U.subscribe(()=>{}))}let y=null,g=null,T=null,C=null;if(p||c){let b=r.retrieval?.topK??20,A=r.retrieval?.graphDepth??1,O=r.budget??2e3,U=r.cost,B=r.score,V=r.contextOf,_=r.contextWeight??0,H=r.context?w(r.context):v(null),$=(M,h)=>{if(!M||!h)return 0;let k=Math.min(M.length,h.length),R=0;for(;R<k&&M[R]===h[R];)R++;return R},F=(M,h,k)=>{let R=new Map,I=[];if(p&&k.vector){I=p.search(k.vector,b);for(let j of I){let G=M.get(j.id);G&&R.set(j.id,{value:G,sources:new Set(["vector"])})}}let S=[];if(c){let j=[...k.entityIds??[],...R.keys()],G=new Set,me=j;for(let ce=0;ce<A;ce++){let oe=[];for(let be of me){if(G.has(be))continue;G.add(be);let xe=c.related(be);for(let wt of xe){let pe=wt.to;if(!G.has(pe)){oe.push(pe);let et=M.get(pe);if(et){let tt=R.get(pe);tt?tt.sources.add("graph"):R.set(pe,{value:et,sources:new Set(["graph"])}),S.push(pe)}}}}me=oe}}for(let[j,G]of M)R.has(j)||R.set(j,{value:G,sources:new Set(["store"])});let ee=k.context?.length??0,te=[];for(let[j,{value:G,sources:me}]of R){let ce=V?V(G):void 0,oe=B(G,h);if(_>0&&ee>0){let xe=$(k.context,ce);xe>0&&(oe=oe*(1+_*xe/ee))}let be=ce?{key:j,value:G,score:oe,sources:[...me],context:ce}:{key:j,value:G,score:oe,sources:[...me]};te.push(be)}te.sort((j,G)=>G.score-j.score);let D=[],Q=0;for(let j of te){let G=U(j.value);if(Q+G>O&&D.length>0)break;D.push(j),Q+=G}return{packed:D,trace:{vectorCandidates:I,graphExpanded:S,ranked:te,packed:D}}},L=v([],{name:"retrieval",describeKind:"state",meta:N("retrieval_pipeline")});o.add(L,{name:"retrieval"}),y=L;let E=v(null,{name:"retrievalTrace",describeKind:"state",meta:N("retrieval_trace")});o.add(E,{name:"retrievalTrace"}),g=E,T=M=>{let h=ve(u.store.entries.cache),{packed:k,trace:R}=F(h,H.cache,M);return ae(()=>{L.emit(k),E.emit(R)}),k},C=M=>{let h=w(M);return x([u.store.entries,H,h],([k,R,I])=>{if(I==null)return[];let S=ve(k);return F(S,R,I).packed},{name:"retrievalReactive",describeKind:"derived",meta:N("retrieval_reactive"),initial:[]})}}return o.addDisposer(()=>{for(let b of n)b();n.length=0}),Object.assign(o,{distillBundle:u,compact:u.compact,size:u.size,vectors:p,kg:c,memoryTiers:f,retrieval:y,retrievalTrace:g,retrieve:T,retrieveReactive:C})}function Sr(t,e,r){let o=t.describe({actor:e,detail:"full"}),n=r?.groupByTags??!0,a=r?.separator??`
|
|
4
|
+
`,s=[],i=r?.sinceVersion;for(let[l,m]of Object.entries(o.nodes)){let d=m.meta??{},u=d.description,p=d.format;if(!u&&!p)continue;if(i!=null&&m.v!=null){let T=i.get(l);if(T!=null&&T.id===m.v.id&&m.v.version<=T.version)continue}let c=u??l,f=m.value,y=d.unit,g;p==="currency"&&typeof f=="number"?g=`$${f.toFixed(2)}`:p==="percentage"&&typeof f=="number"?g=`${(f*100).toFixed(1)}%`:f==null?g="(no value)":g=String(f),y&&p!=="currency"&&p!=="percentage"&&(g=`${g} ${y}`),s.push({path:l,description:c,formatted:g})}if(s.length===0)return"";if(n){let l=new Map,m=[];for(let u of s){let c=o.nodes[u.path].meta?.tags;if(c&&c.length>0){let f=c[0],y=l.get(f);y||(y=[],l.set(f,y)),y.push(u)}else m.push(u)}if(l.size===0)return s.map(u=>`- ${u.description}: ${u.formatted}`).join(a);let d=[];for(let[u,p]of[...l.entries()].sort((c,f)=>c[0].localeCompare(f[0])))d.push(`[${u}]${a}${p.map(c=>`- ${c.description}: ${c.formatted}`).join(a)}`);return m.length>0&&d.push(m.map(u=>`- ${u.description}: ${u.formatted}`).join(a)),d.join(a+a)}return s.map(l=>`- ${l.description}: ${l.formatted}`).join(a)}var Rt=new Set(["state","derived","producer","operator","effect"]);function Ze(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let o=new Set(Object.keys(r.nodes));for(let[n,a]of Object.entries(r.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${n}": must be an object`);continue}let s=a;if((typeof s.type!="string"||!Rt.has(s.type))&&e.push(`Node "${n}": invalid type "${String(s.type)}" (expected: ${[...Rt].join(", ")})`),Array.isArray(s.deps))for(let i of s.deps)typeof i=="string"&&!o.has(i)&&e.push(`Node "${n}": dep "${i}" does not reference an existing node`)}if(!Array.isArray(r.edges))r.edges!==void 0&&e.push("'edges' must be an array");else{let n=new Set;for(let a=0;a<r.edges.length;a++){let s=r.edges[a];if(s==null||typeof s!="object"){e.push(`Edge [${a}]: must be an object`);continue}let i=s;(typeof i.from!="string"||!o.has(i.from))&&e.push(`Edge [${a}]: 'from' "${String(i.from)}" does not reference an existing node`),(typeof i.to!="string"||!o.has(i.to))&&e.push(`Edge [${a}]: 'to' "${String(i.to)}" does not reference an existing node`);let l=`${i.from}->${i.to}`;n.has(l)&&e.push(`Edge [${a}]: duplicate edge ${l}`),n.add(l)}}return{valid:e.length===0,errors:e}}var Lt=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
5
|
+
|
|
6
|
+
Given a natural-language description, produce a JSON graph definition with this structure:
|
|
7
|
+
|
|
8
|
+
{
|
|
9
|
+
"name": "<graph_name>",
|
|
10
|
+
"nodes": {
|
|
11
|
+
"<node_name>": {
|
|
12
|
+
"type": "state" | "derived" | "producer" | "operator" | "effect",
|
|
13
|
+
"value": <initial_value_or_null>,
|
|
14
|
+
"deps": ["<dep_node_name>", ...],
|
|
15
|
+
"meta": {
|
|
16
|
+
"description": "<human-readable purpose>",
|
|
17
|
+
"type": "string" | "number" | "boolean" | "integer" | "enum",
|
|
18
|
+
"range": [min, max],
|
|
19
|
+
"values": ["a", "b"],
|
|
20
|
+
"format": "currency" | "percentage" | "status",
|
|
21
|
+
"access": "human" | "llm" | "both" | "system",
|
|
22
|
+
"unit": "<unit>",
|
|
23
|
+
"tags": ["<tag>"]
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"edges": [
|
|
28
|
+
{ "from": "<source_node>", "to": "<target_node>" }
|
|
29
|
+
]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
Rules:
|
|
33
|
+
- "state" nodes have no deps and hold user/LLM-writable values (knobs).
|
|
34
|
+
- "derived" nodes have deps and compute from them.
|
|
35
|
+
- "effect" nodes have deps but produce side effects (no return value).
|
|
36
|
+
- "producer" nodes have no deps but generate values asynchronously.
|
|
37
|
+
- Edges wire output of one node as input to another. They must match deps.
|
|
38
|
+
- meta.description is required for every node.
|
|
39
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Er(t,e,r){let n=[{role:"system",content:r?.systemPromptExtra?`${Lt}
|
|
40
|
+
|
|
41
|
+
${r.systemPromptExtra}`:Lt},{role:"user",content:t}],a=e.invoke(n,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens}),i=(await ue(a)).content.trim();i.startsWith("```")&&(i=de(i));let l;try{l=JSON.parse(i)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${i.slice(0,200)}`)}let m=Ze(l);if(!m.valid)throw new Error(`graphFromSpec: invalid graph definition:
|
|
42
|
+
${m.errors.join(`
|
|
43
|
+
`)}`);let d=l;return d.version===void 0&&(d.version=1),Array.isArray(d.subgraphs)||(d.subgraphs=[]),Z.fromSnapshot(d,r?.build)}function Ir(t){let e={},r=t.type;return r==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):r==="integer"?e.type="integer":r==="number"?e.type="number":r==="boolean"?e.type="boolean":r==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function Or(t,e){let r=t.describe({actor:e,detail:"full"}),o=[],n=[],a=[];for(let[s,i]of Object.entries(r.nodes)){if(i.type!=="state"||s.includes("::__meta__::")||i.status==="completed"||i.status==="errored")continue;let l=i.meta??{},m=l.access;if(m==="human"||m==="system")continue;let d=l.description??`Set the value of ${s}`,u=Ir(l),p={type:"object",required:["value"],properties:{value:u},additionalProperties:!1},c=s.replace(/::/g,"__");o.push({type:"function",function:{name:c,description:d,parameters:p}}),n.push({name:s,description:d,inputSchema:p});let f=t,y=e,g=i.v;a.push({name:s,description:d,parameters:p,handler(T){return f.set(s,T.value,y?{actor:y}:void 0),T.value},...g!=null?{version:{id:g.id,version:g.version}}:{}})}return{openai:o,mcp:n,definitions:a}}var Pr=`You are a reactive graph optimizer for GraphReFly.
|
|
44
|
+
|
|
45
|
+
Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
|
|
46
|
+
|
|
47
|
+
Return ONLY valid JSON with this structure:
|
|
48
|
+
{
|
|
49
|
+
"summary": "<one-line summary of the strategy>",
|
|
50
|
+
"reasoning": "<explanation of why these changes help>",
|
|
51
|
+
"operations": [
|
|
52
|
+
{ "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
|
|
53
|
+
{ "type": "remove_node", "name": "<name>" },
|
|
54
|
+
{ "type": "connect", "from": "<source>", "to": "<target>" },
|
|
55
|
+
{ "type": "disconnect", "from": "<source>", "to": "<target>" },
|
|
56
|
+
{ "type": "set_value", "name": "<name>", "value": <new_value> },
|
|
57
|
+
{ "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
|
|
58
|
+
]
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
Rules:
|
|
62
|
+
- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
|
|
63
|
+
- Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
|
|
64
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function jr(t,e,r,o){let{expand:n,...a}=t.describe({actor:o?.actor,detail:"standard"}),s=[{role:"system",content:Pr},{role:"user",content:JSON.stringify({graph:a,problem:e})}],i=r.invoke(s,{model:o?.model,temperature:o?.temperature??0,maxTokens:o?.maxTokens}),m=(await ue(i)).content.trim();m.startsWith("```")&&(m=m.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(m)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${m.slice(0,200)}`)}let u=d;if(typeof u.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof u.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(u.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:u.summary,reasoning:u.reasoning,operations:u.operations}}export{Ft as a,Gt as b,Ge as c,yt as d,$t as e,Wt as f,Kt as g,Be as h,Ne as i,We as j,Vt as k,Ke as l,Ve as m,He as n,he as o,qe as p,tr as q,rr as r,nr as s,lr as t,dr as u,mr as v,cr as w,pr as x,gr as y,hr as z,br as A,Mr as B,kr as C,vr as D,Ee as E,ze as F,Ie as G,Je as H,Oe as I,Rr as J,Lr as K,wr as L,Cr as M,Ye as N,Qe as O,Xe as P,Ar as Q,Sr as R,Ze as S,Er as T,Or as U,jr as V,_r as W};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{E as c,m,o as u}from"./chunk-W4TSQ6RJ.js";import{b as f,c as h}from"./chunk-CK2E7BTU.js";var p=class{_version=0;_store=new Map;_maxSize;_defaultTtl;constructor(t={}){let{maxSize:e,defaultTtl:i}=t;if(e!==void 0&&e<1)throw new RangeError("maxSize must be >= 1");if(i!==void 0&&i<=0)throw new RangeError("defaultTtl must be positive");this._maxSize=e,this._defaultTtl=i}get version(){return this._version}get size(){return this._store.size}has(t){let e=this._store.get(t);return e===void 0?!1:this._isExpired(e)?(this._store.delete(t),this._version+=1,!1):(this._touchLru(t,e),!0)}get(t){let e=this._store.get(t);if(e!==void 0){if(this._isExpired(e)){this._store.delete(t),this._version+=1;return}return this._touchLru(t,e),e.value}}set(t,e,i){let s=this._resolveExpiresAt(i);this._store.has(t)&&this._store.delete(t),this._store.set(t,{value:e,expiresAt:s}),this._evictLruWhileOver(),this._version+=1}setMany(t,e){let i=this._resolveExpiresAt(e),s=0;try{for(let[d,n]of t)this._store.has(d)&&this._store.delete(d),this._store.set(d,{value:n,expiresAt:i}),s+=1}finally{s>0&&(this._evictLruWhileOver(),this._version+=1)}}delete(t){let e=this._store.delete(t);return e&&(this._version+=1),e}deleteMany(t){let e=0;try{for(let i of t)this._store.delete(i)&&(e+=1)}finally{e>0&&(this._version+=1)}return e}clear(){let t=this._store.size;return t===0?0:(this._store.clear(),this._version+=1,t)}pruneExpired(){let t=u(),e=0;for(let[i,s]of this._store)this._isExpired(s,t)&&(this._store.delete(i),e+=1);return e>0&&(this._version+=1),e}toMap(){let t=u(),e=new Map;for(let[i,s]of this._store)this._isExpired(s,t)||e.set(i,s.value);return e}_resolveExpiresAt(t){let e=t??this._defaultTtl;if(e!==void 0){if(!Number.isFinite(e)||e<=0)throw new RangeError(`MapBackend: ttl must be a positive finite number (got ${e})`);return u()+e*1e9}}_isExpired(t,e){return t.expiresAt===void 0?!1:(e??u())>=t.expiresAt}_touchLru(t,e){this._store.delete(t),this._store.set(t,e)}_evictLruWhileOver(){if(this._maxSize!==void 0)for(;this._store.size>this._maxSize;){let t=this._store.keys().next().value;if(t===void 0)break;this._store.delete(t)}}};function x(v={}){let{name:t,maxSize:e,defaultTtl:i,versioning:s,backend:d}=v,n=d??new p({maxSize:e,defaultTtl:i}),l=c(n.toMap(),{name:t,describeKind:"state",equals:(r,a)=>r===a,...s!=null?{versioning:s}:{}});function _(){let r=n.toMap();m(()=>{l.down([[h]]),l.down([[f,r]])})}function o(r){let a=n.version;try{return r()}finally{n.version!==a&&_()}}return{entries:l,has(r){return o(()=>n.has(r))},get(r){return o(()=>n.get(r))},set(r,a,b){o(()=>n.set(r,a,b?.ttl))},setMany(r,a){o(()=>n.setMany(r,a?.ttl))},delete(r){o(()=>n.delete(r))},deleteMany(r){o(()=>n.deleteMany(r))},clear(){o(()=>n.clear())},pruneExpired(){o(()=>n.pruneExpired())},get size(){return n.size},dispose(){}}}export{p as a,x as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as f}from"./chunk-I6VIH3VA.js";import{randomBytes as g}from"crypto";import{mkdirSync as y,readdirSync as S,readFileSync as m,renameSync as T,unlinkSync as h,writeFileSync as k}from"fs";import{basename as w,dirname as N,join as d}from"path";import{DatabaseSync as R}from"sqlite";function F(u){let s=new TextEncoder,i=new TextDecoder("utf-8",{fatal:!0}),n=e=>{let t="";for(let r of e){if(r.length===1&&/[a-zA-Z0-9_-]/.test(r)){t+=r;continue}for(let a of s.encode(r))t+=`%${a.toString(16).padStart(2,"0")}`}return d(u,`${t}.json`)},p=e=>{if(!e.endsWith(".json"))return null;let t=e.slice(0,-5),r=[],a=l=>{for(let o=0;o<l.length;o++)r.push(l.charCodeAt(o))},c=0;for(;c<t.length;){let l=t[c];if(l==="%"&&c+2<t.length){let o=t.slice(c+1,c+3);if(/^[0-9a-f]{2}$/i.test(o)){r.push(Number.parseInt(o,16)),c+=3;continue}}a(l),c+=1}try{return i.decode(new Uint8Array(r))}catch{return null}};return{save(e,t){y(u,{recursive:!0});let r=n(e),a=`${f(t)}
|
|
2
|
+
`,c=w(r),l=N(r),o=d(l,`.${c}.${g(8).toString("hex")}.tmp`);try{k(o,a,"utf8"),T(o,r)}catch(E){try{h(o)}catch{}throw E}},load(e){try{let t=m(n(e),"utf8").trim();return t?JSON.parse(t):null}catch{return null}},clear(e){try{h(n(e))}catch(t){if(t.code!=="ENOENT")throw t}},list(){try{let e=S(u),t=[];for(let r of e){if(r.startsWith("."))continue;let a=p(r);a!==null&&t.push(a)}return t.sort()}catch(e){if(e.code==="ENOENT")return[];throw e}}}}function L(u){let s=new R(u);return s.exec("CREATE TABLE IF NOT EXISTS graphrefly_checkpoint (k TEXT PRIMARY KEY, v TEXT NOT NULL)"),{save(i,n){let p=f(n);s.prepare("INSERT OR REPLACE INTO graphrefly_checkpoint (k, v) VALUES (?, ?)").run(i,p)},load(i){let n=s.prepare("SELECT v FROM graphrefly_checkpoint WHERE k = ?").get(i);return n===void 0||typeof n.v!="string"||n.v.trim()===""?null:JSON.parse(n.v)},clear(i){s.prepare("DELETE FROM graphrefly_checkpoint WHERE k = ?").run(i)},list(){return s.prepare("SELECT k FROM graphrefly_checkpoint ORDER BY k").all().map(n=>n.k)},close(){try{s.close()}catch{}}}}export{F as a,L as b};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as G}from"./chunk-5Z4HDCO6.js";import{k as z}from"./chunk-MGKAO4EK.js";import{D as H,E as M,G as N,o as R}from"./chunk-W4TSQ6RJ.js";function q(t){for(let c of t){let m=c.codePointAt(0);if(m>=19968&&m<=40959||m>=13312&&m<=19903||m>=12288&&m<=12351||m>=12352&&m<=12447||m>=12448&&m<=12543||m>=44032&&m<=55215||m>=65280&&m<=65519)return!0}return!1}var E=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011"]),F=new Set([".",",","!","?",":",";",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]);function D(t){return t.replace(/[\t\n\r\f ]+/g," ").replace(/^ | $/g,"")}function O(t){let c=new Intl.Segmenter(void 0,{granularity:"word"}),m=[];for(let f of c.segment(t)){let h=f.segment,w=f.isWordLike??!1,u=[],s=[],r=[],p="",n=null;for(let i of h){let S;i===" "?S="space":i==="\u200B"?S="zero-width-break":i==="\xAD"?S="soft-hyphen":i===`
|
|
2
|
+
`?S="hard-break":S="text",n!==null&&S===n?p+=i:(n!==null&&(u.push(p),s.push(n==="text"&&w),r.push(n)),p=i,n=S)}n!==null&&(u.push(p),s.push(n==="text"&&w),r.push(n)),m.push({texts:u,isWordLike:s,kinds:r})}return m}function V(t,c,m,f,h){let w=D(t);if(w.length===0)return[];let u=O(w),s=new Intl.Segmenter(void 0,{granularity:"grapheme"}),r=[],p=[],n=[];for(let g of u)for(let o=0;o<g.texts.length;o++)r.push(g.texts[o]),p.push(g.kinds[o]),n.push(g.isWordLike[o]);let i=[],S=[],B=[];for(let g=0;g<r.length;g++){let o=r[g],y=p[g],I=n[g];if(y==="text"&&!I&&i.length>0&&S[S.length-1]==="text"&&o.length===1&&(F.has(o)||E.has(o))){i[i.length-1]+=o;continue}if(o==="-"&&i.length>0&&S[S.length-1]==="text"&&B[B.length-1]){i[i.length-1]+=o;continue}i.push(o),S.push(y),B.push(I)}let l=f.get(c);l||(l=new Map,f.set(c,l));function b(g){let o=l.get(g);if(o===void 0){h&&(h.misses+=1);let y=m.measureSegment(g,c).width;o=Number.isFinite(y)&&y>=0?y:0,l.set(g,o)}else h&&(h.hits+=1);return o}let d=[];for(let g=0;g<i.length;g++){let o=i[g],y=S[g];if(y!=="text"){d.push({text:o,width:y==="space"?b(" ")*o.length:0,kind:y,graphemeWidths:null});continue}if(q(o)){let a="";for(let x of s.segment(o)){let k=x.segment;if(a.length>0&&E.has(k)){a+=k;continue}if(a.length>0){let L=b(a);d.push({text:a,width:L,kind:"text",graphemeWidths:null})}a=k}if(a.length>0){let x=b(a);d.push({text:a,width:x,kind:"text",graphemeWidths:null})}continue}let I=b(o),e=null;if(B[g]&&o.length>1){let a=[];for(let x of s.segment(o))a.push(b(x.segment));a.length>1&&(e=a)}d.push({text:o,width:I,kind:"text",graphemeWidths:e})}return d}function J(t,c,m,f,h){if(t.length===0)return{lines:[],lineCount:0};let w=[],u=0,s=!1,r=0,p=0,n=0,i=0,S=-1,B=0,l=h.get(f);l||(l=new Map,h.set(f,l));let b=l.get("-");b===void 0&&(b=m.measureSegment("-",f).width,l.set("-",b));function d(e=n,a=i,x=u){let k="";for(let L=r;L<e;L++){let W=t[L];if(!(W.kind==="soft-hyphen"||W.kind==="hard-break"))if(L===r&&p>0&&W.graphemeWidths){let P=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(W.text)].map(K=>K.segment);k+=P.slice(p).join("")}else k+=W.text}if(a>0&&e<t.length){let L=t[e],v=[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(L.text)].map(K=>K.segment),P=r===e?p:0;k+=v.slice(P,a).join("")}e>0&&t[e-1]?.kind==="soft-hyphen"&&!(r===e&&p>0)&&(k+="-"),w.push({text:k,width:x,startSegment:r,startGrapheme:p,endSegment:e,endGrapheme:a}),u=0,s=!1,S=-1,B=0}function g(e){return e==="space"||e==="zero-width-break"||e==="soft-hyphen"}function o(e,a,x){s=!0,r=e,p=a,n=e+1,i=0,u=x}function y(e,a,x){s=!0,r=e,p=a,n=e,i=a+1,u=x}for(let e=0;e<t.length;e++){let a=t[e];if(a.kind==="hard-break"){s?d():w.push({text:"",width:0,startSegment:e,startGrapheme:0,endSegment:e,endGrapheme:0}),r=e+1,p=0;continue}let x=a.width;if(!s){x>c&&a.graphemeWidths?I(e,0,a.graphemeWidths):o(e,0,x),g(a.kind)&&(S=e+1,B=a.kind==="space"?u-x:u);continue}let k=u+x;if(k>c+.005){if(g(a.kind)){u+=x,n=e+1,i=0,d(e+1,0,a.kind==="space"?u-x:u);continue}if(S>=0){d(S,0,B),e--;continue}if(x>c&&a.graphemeWidths){d(),I(e,0,a.graphemeWidths);continue}d(),e--;continue}u=k,n=e+1,i=0,g(a.kind)&&(S=e+1,B=a.kind==="space"?u-x:u)}return s&&d(),{lines:w,lineCount:w.length};function I(e,a,x){for(let k=a;k<x.length;k++){let L=x[k];if(!s){y(e,k,L);continue}u+L>c+.005?(d(),y(e,k,L)):(u+=L,n=e,i=k+1)}s&&n===e&&i===x.length&&(n=e+1,i=0)}}function A(t){return t==="space"||t==="zero-width-break"||t==="soft-hyphen"}var T=null;function _(){return T===null&&(T=new Intl.Segmenter(void 0,{granularity:"grapheme"})),T}function j(t,c,m){if(c===0&&m<0)return t.text;let f=[..._().segment(t.text)].map(w=>w.segment),h=m<0?f.length:m;return f.slice(c,h).join("")}function C(t,c,m,f,h,w){let u="";for(let s=c;s<f;s++){let r=t[s];r.kind==="soft-hyphen"||r.kind==="hard-break"||(s===c&&m>0?u+=j(r,m,-1):u+=r.text)}if(h>0&&f<t.length){let s=t[f];u+=j(s,c===f?m:0,h)}return w&&(u+="-"),u}function $(t){if(!t?.adapter||!t.font)return 0;let c=t.cache;if(c){let m=c.get(t.font);m||(m=new Map,c.set(t.font,m));let f=m.get("-");return f===void 0&&(f=t.adapter.measureSegment("-",t.font).width,m.set("-",f)),f}return t.adapter.measureSegment("-",t.font).width}function te(t,c,m,f){let h=c.segmentIndex,w=c.graphemeIndex;if(h>=t.length)return null;if(w===0){for(;h<t.length;){let e=t[h];if(e.kind==="hard-break")return{text:"",width:0,start:{segmentIndex:c.segmentIndex,graphemeIndex:0},end:{segmentIndex:h+1,graphemeIndex:0}};if(e.kind==="space"||e.kind==="zero-width-break"||e.kind==="soft-hyphen"){h+=1;continue}break}if(h>=t.length)return null}let u=$(f),s=h,r=h===c.segmentIndex?w:0,p=0,n=s,i=0,S=!1,B=-1,l=0,b=0,d=!1,g=(e,a,x,k)=>{B=e,l=a,b=x,d=k==="soft-hyphen"},o=(e,a,x)=>{for(let k=a;k<x.length;k++){let L=x[k];if(!S){p=L,n=e,i=k+1,S=!0;continue}if(p+L>m+.005)return!0;p+=L,n=e,i=k+1}return n===e&&i===x.length&&(n=e+1,i=0),!1};if(r>0&&s<t.length){let e=t[s];if(e.graphemeWidths){if(o(s,r,e.graphemeWidths))return{text:C(t,s,r,n,i,!1),width:p,start:{segmentIndex:s,graphemeIndex:r},end:{segmentIndex:n,graphemeIndex:i}};h=n}}for(;h<t.length;){let e=t[h];if(e.kind==="hard-break"){if(S){let k=n>0&&t[n-1]?.kind==="soft-hyphen";return{text:C(t,s,r,n,i,k),width:p+(k?u:0),start:{segmentIndex:s,graphemeIndex:r},end:{segmentIndex:n,graphemeIndex:i}}}return{text:"",width:0,start:{segmentIndex:s,graphemeIndex:r},end:{segmentIndex:h+1,graphemeIndex:0}}}let a=e.width;if(!S){if(a>m&&e.graphemeWidths){if(o(h,0,e.graphemeWidths))return{text:C(t,s,r,n,i,!1),width:p,start:{segmentIndex:s,graphemeIndex:r},end:{segmentIndex:n,graphemeIndex:i}};h=n;continue}p=a,n=h+1,i=0,S=!0,A(e.kind)&&g(h+1,0,e.kind==="space"?p-a:p,e.kind),h+=1;continue}let x=p+a;if(x>m+.005){if(A(e.kind)){n=h+1,i=0;let L=e.kind==="soft-hyphen",W=e.kind==="space"?p:p+(L?u:0);return{text:C(t,s,r,n,i,L),width:W,start:{segmentIndex:s,graphemeIndex:r},end:{segmentIndex:n,graphemeIndex:i}}}return B>=0?{text:C(t,s,r,B,l,d),width:b+(d?u:0),start:{segmentIndex:s,graphemeIndex:r},end:{segmentIndex:B,graphemeIndex:l}}:a>m&&e.graphemeWidths?{text:C(t,s,r,n,i,!1),width:p,start:{segmentIndex:s,graphemeIndex:r},end:{segmentIndex:n,graphemeIndex:i}}:{text:C(t,s,r,n,i,!1),width:p,start:{segmentIndex:s,graphemeIndex:r},end:{segmentIndex:n,graphemeIndex:i}}}p=x,n=h+1,i=0,A(e.kind)&&g(h+1,0,e.kind==="space"?p-a:p,e.kind),h+=1}if(!S)return null;let y=n>0&&t[n-1]?.kind==="soft-hyphen";return{text:C(t,s,r,n,i,y),width:p+(y?u:0),start:{segmentIndex:s,graphemeIndex:r},end:{segmentIndex:n,graphemeIndex:i}}}function ne(t,c,m=0){let f=[t];for(let h=0;h<c.length;h++){let w=c[h],u=[];for(let s=0;s<f.length;s++){let r=f[s];if(w.right<=r.left||w.left>=r.right){u.push(r);continue}w.left>r.left&&u.push({left:r.left,right:w.left}),w.right<r.right&&u.push({left:w.right,right:r.right})}f=u}return m>0?f.filter(h=>h.right-h.left>=m):f}function Q(t,c,m){let f=[],h=new Intl.Segmenter(void 0,{granularity:"grapheme"});for(let w=0;w<t.lines.length;w++){let u=t.lines[w],s=w*m,r=0;for(let p=u.startSegment;p<c.length;p++){let n=c[p];if(n.kind==="soft-hyphen"||n.kind==="hard-break"){if(p>=u.endSegment&&u.endGrapheme===0)break;continue}let i=[...h.segment(n.text)].map(l=>l.segment);if(i.length===0)continue;let S=p===u.startSegment?u.startGrapheme:0,B;if(p<u.endSegment)B=i.length;else if(p===u.endSegment&&u.endGrapheme>0)B=u.endGrapheme;else break;for(let l=S;l<B;l++){let b=n.graphemeWidths?n.graphemeWidths[l]:n.width/i.length;f.push({x:r,y:s,width:b,height:m,line:w}),r+=b}}}return f}function re(t){let{adapter:c,name:m="reactive-layout"}=t,f=new z(m),h=new Map,w=M(t.text??"",{name:"text"}),u=M(t.font??"16px sans-serif",{name:"font"}),s=M(t.lineHeight??20,{name:"line-height"}),r=M(Math.max(0,t.maxWidth??800),{name:"max-width"});function p(l,b){if(l===null||b===null)return l===b;if(l.length!==b.length)return!1;for(let d=0;d<l.length;d++)if(l[d]!==b[d])return!1;return!0}let n=H([w,u],(l,b,d)=>{let g=l[0],o=g!=null&&g.length>0?g.at(-1):d.prevData[0],y=l[1],I=y!=null&&y.length>0?y.at(-1):d.prevData[1],e=R(),a={hits:0,misses:0},x=V(o,I,c,h,a),k=R()-e,L=a.hits+a.misses,W=L===0?1:a.hits/L,v=n.meta;v&&(G(v["cache-hit-rate"],W),G(v["segment-count"],x.length),G(v["layout-time-ns"],k)),b.emit(x);let P=()=>{h.clear(),c.clearCache?.()};return{deactivate:P,invalidate:P}},{name:"segments",describeKind:"derived",meta:{"cache-hit-rate":0,"segment-count":0,"layout-time-ns":0},equals:(l,b)=>{let d=l,g=b;if(d==null||g==null)return d===g;if(d.length!==g.length)return!1;for(let o=0;o<d.length;o++){let y=d[o],I=g[o];if(y.text!==I.text||y.width!==I.width||y.kind!==I.kind||!p(y.graphemeWidths??null,I.graphemeWidths??null))return!1}return!0}}),i=N([n,r,u],([l,b,d])=>J(l,b,c,d,h),{name:"line-breaks",equals:(l,b)=>{let d=l,g=b;if(d==null||g==null)return d===g;if(d.lineCount!==g.lineCount)return!1;for(let o=0;o<d.lines.length;o++){let y=d.lines[o],I=g.lines[o];if(y.text!==I.text||y.width!==I.width||y.startSegment!==I.startSegment||y.startGrapheme!==I.startGrapheme||y.endSegment!==I.endSegment||y.endGrapheme!==I.endGrapheme)return!1}return!0}}),S=N([i,s],([l,b])=>l.lineCount*b,{name:"height"}),B=N([i,n,s],([l,b,d])=>Q(l,b,d),{name:"char-positions",equals:(l,b)=>{let d=l,g=b;if(d==null||g==null)return d===g;if(d.length!==g.length)return!1;for(let o=0;o<d.length;o++)if(d[o].x!==g[o].x||d[o].y!==g[o].y||d[o].width!==g[o].width)return!1;return!0}});return f.add(w,{name:"text"}),f.add(u,{name:"font"}),f.add(s,{name:"line-height"}),f.add(r,{name:"max-width"}),f.add(n,{name:"segments"}),f.add(i,{name:"line-breaks"}),f.add(S,{name:"height"}),f.add(B,{name:"char-positions"}),{graph:f,setText:l=>f.set("text",l),setFont:l=>f.set("font",l),setLineHeight:l=>f.set("line-height",l),setMaxWidth:l=>f.set("max-width",Math.max(0,l)),segments:n,lineBreaks:i,height:S,charPositions:B}}export{V as a,J as b,te as c,ne as d,Q as e,re as f};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{k as C}from"./chunk-MGKAO4EK.js";import{E as w,G as E,o as x}from"./chunk-W4TSQ6RJ.js";import{b as z}from"./chunk-QYADASLV.js";var F={};z(F,{collection:()=>G,decay:()=>K,knowledgeGraph:()=>O,lightCollection:()=>S,vectorIndex:()=>L});function K(s,a,l,r=0){if(!Number.isFinite(s))return r;if(!Number.isFinite(a)||a<=0||!Number.isFinite(l)||l<=0)return Math.max(r,s);let y=s*Math.exp(-l*a);return Math.max(r,y)}function V(s){if(s!==void 0&&s<1)throw new RangeError("maxSize must be >= 1")}function M(s){return new Map(s)}function T(s){return s.cache??new Map}function N(s){return s.cache??[]}function I(s,a){let l=Math.max(s.length,a.length),r=0,y=0,p=0;for(let o=0;o<l;o+=1){let n=s[o]??0,e=a[o]??0;r+=n*e,y+=n*n,p+=e*e}return y===0||p===0?0:r/Math.sqrt(y*p)}function S(s={}){let a=s.maxSize,l=s.policy??"fifo";V(a);let r=w(new Map,{name:s.name,describeKind:"state"});function y(o){if(a!==void 0)for(;o.size>a;){let n;for(let e of o.values()){if(!n){n=e;continue}let i=l==="lru"?e.lastAccessNs:e.createdAtNs,t=l==="lru"?n.lastAccessNs:n.createdAtNs;i<t&&(n=e)}if(!n)break;o.delete(n.id)}}function p(o){r.emit(o)}return{entries:r,upsert(o,n){let e=x(),i=T(r),t=i.get(o),m=M(i);m.set(o,{id:o,value:n,createdAtNs:t?.createdAtNs??e,lastAccessNs:e}),y(m),p(m)},remove(o){let n=M(T(r));n.delete(o)&&p(n)},clear(){T(r).size!==0&&p(new Map)},get(o){let n=T(r),e=n.get(o);if(e){if(l==="lru"){let i=x(),t=M(n);t.set(o,{...e,lastAccessNs:i}),p(t)}return e.value}},has(o){return T(r).has(o)}}}function G(s,a={}){let l=a.maxSize,r=a.policy??"lru",y=a.decayRate??0,p=a.minScore??0,o=a.score??(()=>1);V(l);let n=new C(s),e=w(new Map,{name:"items",describeKind:"state"}),i=E([e],([c])=>{let d=c??new Map,u=x(),h=[...d.values()].map(f=>{let b=(u-f.lastAccessNs)/1e9;return{...f,score:K(f.baseScore,b,y,p)}});return h.sort((f,b)=>b.score-f.score||b.lastAccessNs-f.lastAccessNs),h},{name:"ranked",describeKind:"derived"}),t=E([e],([c])=>(c??new Map).size,{name:"size",describeKind:"derived",initial:0});i.subscribe(()=>{}),t.subscribe(()=>{}),n.add(e,{name:"items"}),n.add(i,{name:"ranked"}),n.add(t,{name:"size"});function m(c,d){let u=(d-c.lastAccessNs)/1e9;return K(c.baseScore,u,y,p)}function v(c){if(l!==void 0)for(;c.size>l;){let d=x(),u,h=Number.POSITIVE_INFINITY;for(let f of c.values()){let b=m(f,d);if(b<h){u=f,h=b;continue}if(b===h&&u){let A=r==="lru"?f.lastAccessNs:f.createdAtNs,R=r==="lru"?u.lastAccessNs:u.createdAtNs;A<R&&(u=f)}}if(!u)break;c.delete(u.id)}}function g(c){e.emit(c)}return Object.assign(n,{upsert(c,d,u){let h=x(),f=T(e),b=f.get(c),A=u?.score??o(d),R=M(f);R.set(c,{id:c,value:d,baseScore:A,createdAtNs:b?.createdAtNs??h,lastAccessNs:h}),v(R),g(R)},remove(c){let d=M(T(e));d.delete(c)&&g(d)},clear(){T(e).size!==0&&g(new Map)},getItem(c){let d=T(e),u=d.get(c);if(u){if(r==="lru"){let h=M(d);h.set(c,{...u,lastAccessNs:x()}),g(h)}return u}}})}function L(s={}){let a=s.backend??"flat",l=s.dimension,r;if(a==="hnsw"&&(r=s.hnswFactory?.(),!r))throw new Error('vectorIndex backend "hnsw" requires an optional dependency adapter; install your HNSW package and provide `hnswFactory`.');let y=w(new Map,{describeKind:"state",name:"vector-index"});function p(n){if(l!==void 0&&n.length!==l)throw new RangeError(`vector dimension mismatch: expected ${l}, got ${n.length}`)}function o(n){y.emit(n)}return{backend:a,entries:y,upsert(n,e,i){p(e);let t=M(T(y));t.set(n,{id:n,vector:[...e],meta:i}),a==="hnsw"&&r.upsert(n,e,i),o(t)},remove(n){let e=M(T(y));e.delete(n)&&(a==="hnsw"&&r.remove(n),o(e))},clear(){T(y).size!==0&&(a==="hnsw"&&r.clear(),o(new Map))},search(n,e=5){return p(n),e<=0?[]:a==="hnsw"?r.search(n,e):[...T(y).values()].map(t=>({id:t.id,score:I(n,t.vector),meta:t.meta})).sort((t,m)=>m.score-t.score).slice(0,e)}}}function O(s){let a=new C(s),l=w(new Map,{name:"entities",describeKind:"state"}),r=w([],{name:"edges",describeKind:"state"}),y=E([r],([e])=>{let i=e??[],t=new Map;for(let m of i){let v=t.get(m.from)??[];t.set(m.from,Object.freeze([...v,m]))}return t},{name:"adjacency",describeKind:"derived",initial:new Map});y.subscribe(()=>{}),a.add(l,{name:"entities"}),a.add(r,{name:"edges"}),a.add(y,{name:"adjacency"});function p(e){l.emit(e)}function o(e){r.emit(e)}return Object.assign(a,{upsertEntity(e,i){let t=M(T(l));t.set(e,i),p(t)},removeEntity(e){let i=M(T(l)),t=i.delete(e),m=N(r),v=m.filter(g=>g.from!==e&&g.to!==e);!t&&v.length===m.length||(p(i),o(v))},link(e,i,t,m=1){let v=`${e}\0${i}\0${t}`,g=N(r),k=new Set(g.map(d=>`${d.from}\0${d.to}\0${d.relation}`)),c=[...g];if(k.has(v))for(let d=0;d<c.length;d+=1){let u=c[d];if(u.from===e&&u.to===i&&u.relation===t){c[d]={...u,weight:m};break}}else c.push({from:e,to:i,relation:t,weight:m});o(c)},unlink(e,i,t){let m=N(r),v=m.filter(g=>t===void 0?!(g.from===e&&g.to===i):!(g.from===e&&g.to===i&&g.relation===t));v.length!==m.length&&o(v)},related(e,i){return N(r).filter(t=>(t.from===e||t.to===e)&&(i===void 0||t.relation===i))}})}export{K as a,S as b,G as c,L as d,O as e,F as f};
|