@graphrefly/graphrefly 0.30.0 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{cascading-dNCtjW8j.d.cts → cascading-BfQmSmjU.d.cts} +21 -2
- package/dist/{cascading-BszPheHD.d.ts → cascading-D3sapjue.d.ts} +21 -2
- package/dist/chunk-2JNT5NDF.js +61 -0
- package/dist/{chunk-DDPYNMGG.js → chunk-2RH4QNDQ.js} +1 -1
- package/dist/chunk-4JBKKUCJ.js +7 -0
- package/dist/{chunk-SLMYTGTU.js → chunk-4UUDNFYG.js} +1 -1
- package/dist/chunk-4VXL3UZK.js +1 -0
- package/dist/{chunk-SHYH5SXV.js → chunk-4YGJ7KZ6.js} +1 -1
- package/dist/{chunk-GJR3P6JG.js → chunk-5PBXUVHI.js} +1 -1
- package/dist/{chunk-W4TSQ6RJ.js → chunk-7AJKUA36.js} +1 -1
- package/dist/{chunk-XQAXYVXX.js → chunk-7EMUF2RY.js} +1 -1
- package/dist/chunk-7JZ3YORY.js +80 -0
- package/dist/chunk-7QMVU3IX.js +1 -0
- package/dist/{chunk-WANIEEKV.js → chunk-7QS77X6G.js} +1 -1
- package/dist/{chunk-BA5URFYW.js → chunk-A4JT4SAD.js} +1 -1
- package/dist/{chunk-Y36UZ5VS.js → chunk-BU4SUZSA.js} +1 -1
- package/dist/{chunk-P7JXGKDO.js → chunk-CNXUW2CU.js} +1 -1
- package/dist/{chunk-Y32RJO24.js → chunk-CZVYLXFK.js} +1 -1
- package/dist/{chunk-567NWZ3T.js → chunk-DWIAG62L.js} +1 -1
- package/dist/chunk-EIFHFDFD.js +1 -0
- package/dist/chunk-FTA5TB2A.js +1 -0
- package/dist/{chunk-T5SHIKJD.js → chunk-JAHAJU4G.js} +1 -1
- package/dist/{chunk-AV3PIDFQ.js → chunk-JYMNVEH6.js} +1 -1
- package/dist/{chunk-5Z4HDCO6.js → chunk-K54OKWNY.js} +1 -1
- package/dist/chunk-KD3IYBTD.js +3 -0
- package/dist/{chunk-3NEPQO2E.js → chunk-LG73TUF4.js} +2 -2
- package/dist/chunk-LJGPOJHS.js +1 -0
- package/dist/chunk-LWGLBCMU.js +1 -0
- package/dist/{chunk-BKPLTBL5.js → chunk-M2VFLRPJ.js} +1 -1
- package/dist/{chunk-GNCBXARM.js → chunk-MFNOZ5E6.js} +1 -1
- package/dist/{chunk-TWMEGG45.js → chunk-N2KKISCE.js} +1 -1
- package/dist/chunk-PNTBXOQ6.js +5 -0
- package/dist/{chunk-73Z3W2RN.js → chunk-PWKLZ2XU.js} +1 -1
- package/dist/{chunk-7TDOES3L.js → chunk-Q2SY7M7K.js} +1 -1
- package/dist/{chunk-OL33ZI6R.js → chunk-RWGJQQLT.js} +1 -1
- package/dist/chunk-SGS4OJGS.js +1 -0
- package/dist/{chunk-4OFIQ66T.js → chunk-TOCCHQI6.js} +1 -1
- package/dist/chunk-UMH3HSP7.js +1 -0
- package/dist/{chunk-XHVB6G6M.js → chunk-UXEB35L4.js} +1 -1
- package/dist/{chunk-33FA6V4B.js → chunk-VXJX3ZZP.js} +1 -1
- package/dist/{chunk-BZP5T4X6.js → chunk-W6FQIFVE.js} +1 -1
- package/dist/{chunk-RD52SNH2.js → chunk-WE32AFFA.js} +1 -1
- package/dist/{chunk-KA6MMXIY.js → chunk-WF3V5X2L.js} +1 -1
- package/dist/chunk-WQ7I7JVU.js +1 -0
- package/dist/{chunk-4JJCCD5S.js → chunk-X4OOM6QU.js} +1 -1
- package/dist/{chunk-AUY2YKCO.js → chunk-XRSHMHEG.js} +1 -1
- package/dist/chunk-Y26UN6J5.js +18 -0
- package/dist/{chunk-VWPRPPKR.js → chunk-ZWETYYQG.js} +1 -1
- package/dist/compat/index.cjs +2 -2
- package/dist/compat/index.d.cts +5 -5
- package/dist/compat/index.d.ts +5 -5
- package/dist/compat/index.js +1 -1
- package/dist/compat/jotai/index.cjs +1 -1
- package/dist/compat/jotai/index.js +1 -1
- package/dist/compat/nanostores/index.cjs +1 -1
- package/dist/compat/nanostores/index.js +1 -1
- package/dist/compat/nestjs/index.cjs +5 -5
- package/dist/compat/nestjs/index.d.cts +3 -3
- package/dist/compat/nestjs/index.d.ts +3 -3
- package/dist/compat/nestjs/index.js +1 -1
- package/dist/compat/zustand/index.cjs +2 -2
- package/dist/compat/zustand/index.d.cts +2 -2
- package/dist/compat/zustand/index.d.ts +2 -2
- package/dist/compat/zustand/index.js +1 -1
- package/dist/{composite-DGspwCqk.d.ts → composite-BY9hMxN7.d.ts} +1 -1
- package/dist/{composite-nrRumJ7l.d.cts → composite-CH0S8DFn.d.cts} +1 -1
- package/dist/content-addressed-storage-BUiREIuj.d.ts +124 -0
- package/dist/content-addressed-storage-DqIWCmZG.d.cts +124 -0
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.js +1 -1
- package/dist/extra/browser.cjs +1 -1
- package/dist/extra/browser.js +1 -1
- package/dist/extra/index.cjs +18 -18
- package/dist/extra/index.d.cts +7 -6
- package/dist/extra/index.d.ts +7 -6
- package/dist/extra/index.js +1 -1
- package/dist/extra/node.cjs +2 -2
- package/dist/extra/node.js +1 -1
- package/dist/extra/operators.cjs +1 -1
- package/dist/extra/operators.d.cts +41 -1
- package/dist/extra/operators.d.ts +41 -1
- package/dist/extra/operators.js +1 -1
- package/dist/extra/reactive.cjs +1 -1
- package/dist/extra/reactive.d.cts +1 -1
- package/dist/extra/reactive.d.ts +1 -1
- package/dist/extra/reactive.js +1 -1
- package/dist/extra/sources.cjs +1 -1
- package/dist/extra/sources.d.cts +62 -2
- package/dist/extra/sources.d.ts +62 -2
- package/dist/extra/sources.js +1 -1
- package/dist/extra/storage-browser.cjs +1 -1
- package/dist/extra/storage-browser.js +1 -1
- package/dist/{fallback-BaTS7vVY.d.cts → fallback-Cb3GH1O7.d.cts} +6 -14
- package/dist/{fallback-eOm3LNxP.d.ts → fallback-DRjJ_ZM8.d.ts} +6 -14
- package/dist/graph/index.cjs +4 -4
- package/dist/graph/index.d.cts +3 -3
- package/dist/graph/index.d.ts +3 -3
- package/dist/graph/index.js +1 -1
- package/dist/{graph-CWeI0aHd.d.ts → graph-BOhEGJ6E.d.ts} +10 -0
- package/dist/{graph-C4Uxwv0T.d.cts → graph-CdJeX7O7.d.cts} +10 -0
- package/dist/{index-B-z8WaSd.d.cts → index-BDLy6CQ9.d.cts} +1 -1
- package/dist/{index-iBp74eGU.d.cts → index-BJDXj9Wf.d.cts} +2 -2
- package/dist/{index-BBINVimG.d.ts → index-BUZPTPSQ.d.ts} +2 -2
- package/dist/{index-DnrZghBB.d.ts → index-BbcSZCAG.d.ts} +1 -1
- package/dist/{index-lKuLYmHO.d.cts → index-BiGeETJs.d.cts} +1 -1
- package/dist/{index-BHu_Wba0.d.cts → index-BmZb8fNF.d.cts} +3 -3
- package/dist/{index-Docdiu9a.d.ts → index-Bnmttu35.d.ts} +1 -1
- package/dist/{index-D6ajK8Mh.d.cts → index-BuN2wGJs.d.cts} +517 -134
- package/dist/{index-Cy7eFeIX.d.cts → index-BwdPDWI4.d.cts} +1 -1
- package/dist/{index-DylQCKEL.d.cts → index-BzxU4yhV.d.cts} +11 -2
- package/dist/{index-D9Y_u6BG.d.cts → index-C-Gsh-0a.d.cts} +2 -2
- package/dist/{index-ybtSyjWB.d.cts → index-C22aTC1X.d.cts} +5 -5
- package/dist/{index-yIdWFo2b.d.cts → index-C4QTaDli.d.cts} +2 -2
- package/dist/{index-BJHQUCZx.d.ts → index-C7RqYbOZ.d.ts} +82 -7
- package/dist/{index-C5Ghnp5B.d.ts → index-C9qCLIN4.d.ts} +2 -2
- package/dist/{index-DVNLe3pS.d.cts → index-CCdg0JLX.d.cts} +1 -1
- package/dist/{index-B5iVOD7w.d.ts → index-CEoU-r-g.d.ts} +2 -2
- package/dist/{index-CfFYyLR8.d.ts → index-CHfBm51k.d.ts} +11 -2
- package/dist/{index-Dljd76bC.d.ts → index-CNyiYQWF.d.ts} +5 -5
- package/dist/{index-C6NBfXj-.d.ts → index-CVevMZ0n.d.ts} +2 -2
- package/dist/{index-DGb1awva.d.ts → index-CZUzi6Dy.d.ts} +2 -2
- package/dist/{index-FrYrV-Vf.d.ts → index-Ckl03Q0s.d.ts} +1 -1
- package/dist/{index-Bvi5uJxX.d.ts → index-CmSjld-4.d.ts} +1 -1
- package/dist/{index-9iguV3bF.d.cts → index-CnjUhRbs.d.cts} +2 -2
- package/dist/{index-C98oJsEs.d.cts → index-D3HcdZ4d.d.cts} +1 -1
- package/dist/{index-IZ3l_vQ9.d.ts → index-DD1czHj3.d.ts} +1 -1
- package/dist/{index-BS220yqj.d.cts → index-DNhTQReY.d.cts} +82 -7
- package/dist/{index-UZO988ox.d.cts → index-DSawGt8n.d.cts} +2 -2
- package/dist/{index-CcpEvuPl.d.cts → index-DUkuH3jP.d.cts} +1 -1
- package/dist/{index-CRAkoq-y.d.cts → index-DY2QbdoP.d.cts} +1 -1
- package/dist/{index-CvS9IuTG.d.ts → index-Dbmj0iYR.d.ts} +1 -1
- package/dist/{index-ClgKmOHe.d.ts → index-DhlAMlm9.d.ts} +517 -134
- package/dist/{index-ClB7TCfL.d.cts → index-DlGaEBW5.d.cts} +2 -2
- package/dist/{index-CotRMjtJ.d.ts → index-Dp_pS7Bw.d.ts} +1 -1
- package/dist/{index-Cc8VQIgL.d.ts → index-Dxk-pUQI.d.ts} +2 -2
- package/dist/{index-DBQUKh59.d.cts → index-EGjF6iSY.d.cts} +3 -3
- package/dist/{index-D9HrBx2J.d.ts → index-LGzAYqdR.d.ts} +1 -1
- package/dist/{index-DR3gf_DG.d.cts → index-LzCJ0kMT.d.cts} +2 -2
- package/dist/{index-RQg6lTrN.d.ts → index-MV2yGIAq.d.ts} +2 -2
- package/dist/{index-Bs3-LC83.d.cts → index-_BXz9K7b.d.cts} +1 -1
- package/dist/{index-SSGqF8mI.d.cts → index-aBqZUx3B.d.cts} +1 -1
- package/dist/{index-CFW32Dy1.d.ts → index-eYHRkoK-.d.ts} +1 -1
- package/dist/{index-B2HBxvMb.d.ts → index-gXTVbSax.d.ts} +3 -3
- package/dist/{index-B8Aj_z8S.d.cts → index-j33Lfb1G.d.cts} +23 -2
- package/dist/{index-BEpRsvhg.d.ts → index-lpGUhTBn.d.ts} +3 -3
- package/dist/{index-BXbQUn4n.d.ts → index-zMQIQuDu.d.ts} +23 -2
- package/dist/index.cjs +106 -125
- package/dist/index.d.cts +34 -33
- package/dist/index.d.ts +34 -33
- package/dist/index.js +1 -1
- package/dist/patterns/ai/browser.cjs +5 -22
- package/dist/patterns/ai/browser.d.cts +3 -3
- package/dist/patterns/ai/browser.d.ts +3 -3
- package/dist/patterns/ai/browser.js +1 -1
- package/dist/patterns/ai/index.cjs +30 -44
- package/dist/patterns/ai/index.d.cts +13 -11
- package/dist/patterns/ai/index.d.ts +13 -11
- package/dist/patterns/ai/index.js +1 -1
- package/dist/patterns/ai/node.cjs +2 -2
- package/dist/patterns/ai/node.d.cts +5 -4
- package/dist/patterns/ai/node.d.ts +5 -4
- package/dist/patterns/ai/node.js +1 -1
- package/dist/patterns/audit/index.cjs +3 -3
- package/dist/patterns/audit/index.d.cts +3 -3
- package/dist/patterns/audit/index.d.ts +3 -3
- package/dist/patterns/audit/index.js +1 -1
- package/dist/patterns/cqrs/index.cjs +6 -6
- package/dist/patterns/cqrs/index.d.cts +2 -2
- package/dist/patterns/cqrs/index.d.ts +2 -2
- package/dist/patterns/cqrs/index.js +1 -1
- package/dist/patterns/demo-shell/index.cjs +2 -2
- package/dist/patterns/demo-shell/index.d.cts +3 -3
- package/dist/patterns/demo-shell/index.d.ts +3 -3
- package/dist/patterns/demo-shell/index.js +1 -1
- package/dist/patterns/domain-templates/index.cjs +6 -6
- package/dist/patterns/domain-templates/index.d.cts +2 -2
- package/dist/patterns/domain-templates/index.d.ts +2 -2
- package/dist/patterns/domain-templates/index.js +1 -1
- package/dist/patterns/graphspec/index.cjs +27 -25
- package/dist/patterns/graphspec/index.d.cts +3 -3
- package/dist/patterns/graphspec/index.d.ts +3 -3
- package/dist/patterns/graphspec/index.js +1 -1
- package/dist/patterns/guarded-execution/index.cjs +7 -7
- package/dist/patterns/guarded-execution/index.d.cts +4 -4
- package/dist/patterns/guarded-execution/index.d.ts +4 -4
- package/dist/patterns/guarded-execution/index.js +1 -1
- package/dist/patterns/harness/index.cjs +12 -11
- package/dist/patterns/harness/index.d.cts +6 -6
- package/dist/patterns/harness/index.d.ts +6 -6
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/job-queue/index.cjs +5 -5
- package/dist/patterns/job-queue/index.d.cts +2 -2
- package/dist/patterns/job-queue/index.d.ts +2 -2
- package/dist/patterns/job-queue/index.js +1 -1
- package/dist/patterns/lens/index.cjs +5 -5
- package/dist/patterns/lens/index.d.cts +4 -4
- package/dist/patterns/lens/index.d.ts +4 -4
- package/dist/patterns/lens/index.js +1 -1
- package/dist/patterns/memory/index.cjs +4 -4
- package/dist/patterns/memory/index.d.cts +2 -2
- package/dist/patterns/memory/index.d.ts +2 -2
- package/dist/patterns/memory/index.js +1 -1
- package/dist/patterns/messaging/index.cjs +5 -5
- package/dist/patterns/messaging/index.d.cts +2 -2
- package/dist/patterns/messaging/index.d.ts +2 -2
- package/dist/patterns/messaging/index.js +1 -1
- package/dist/patterns/orchestration/index.cjs +7 -7
- package/dist/patterns/orchestration/index.d.cts +2 -2
- package/dist/patterns/orchestration/index.d.ts +2 -2
- package/dist/patterns/orchestration/index.js +1 -1
- package/dist/patterns/reactive-layout/index.cjs +2 -2
- package/dist/patterns/reactive-layout/index.d.cts +3 -3
- package/dist/patterns/reactive-layout/index.d.ts +3 -3
- package/dist/patterns/reactive-layout/index.js +1 -1
- package/dist/patterns/reduction/index.cjs +5 -5
- package/dist/patterns/reduction/index.d.cts +2 -2
- package/dist/patterns/reduction/index.d.ts +2 -2
- package/dist/patterns/reduction/index.js +1 -1
- package/dist/patterns/refine-loop/index.cjs +8 -8
- package/dist/patterns/refine-loop/index.d.cts +3 -3
- package/dist/patterns/refine-loop/index.d.ts +3 -3
- package/dist/patterns/refine-loop/index.js +1 -1
- package/dist/patterns/resilient-pipeline/index.cjs +1 -1
- package/dist/patterns/resilient-pipeline/index.d.cts +3 -3
- package/dist/patterns/resilient-pipeline/index.d.ts +3 -3
- package/dist/patterns/resilient-pipeline/index.js +1 -1
- package/dist/patterns/surface/index.cjs +15 -13
- package/dist/patterns/surface/index.d.cts +4 -4
- package/dist/patterns/surface/index.d.ts +4 -4
- package/dist/patterns/surface/index.js +1 -1
- package/dist/{reactive-layout-BAr6-_o5.d.ts → reactive-layout-Bq0rA2Wb.d.ts} +1 -1
- package/dist/{reactive-layout-5oEn8lHM.d.cts → reactive-layout-Dhhe54Oj.d.cts} +1 -1
- package/dist/{reactive-map-BvDrRuwt.d.ts → reactive-map-CtRaCddO.d.ts} +59 -1
- package/dist/{reactive-map-CmlPPKHN.d.cts → reactive-map-IJIfZxoh.d.cts} +59 -1
- package/dist/{resilience-XRUF267O.js → resilience-IVNDYORD.js} +1 -1
- package/dist/{topology-tree-CVREibAc.d.cts → topology-tree-CpSjvIXp.d.cts} +1 -1
- package/dist/{topology-tree-CkjojcB6.d.ts → topology-tree-DAbCV2Yw.d.ts} +1 -1
- package/dist/{types-O3GzJY2U.d.cts → types-BgMqbc7N.d.cts} +41 -14
- package/dist/{types-u64Ose53.d.ts → types-CdfO2QTt.d.ts} +41 -14
- package/package.json +1 -1
- package/dist/chunk-2GQREQ6C.js +0 -1
- package/dist/chunk-4C2OR2GH.js +0 -18
- package/dist/chunk-5JDE5JHE.js +0 -1
- package/dist/chunk-7JDLFI6N.js +0 -1
- package/dist/chunk-AMBYCIOH.js +0 -3
- package/dist/chunk-GLSM33ZM.js +0 -78
- package/dist/chunk-ISCENNXS.js +0 -1
- package/dist/chunk-IUK4EFCE.js +0 -1
- package/dist/chunk-KASHOCF5.js +0 -1
- package/dist/chunk-LI3E75VE.js +0 -64
- package/dist/chunk-MGKAO4EK.js +0 -7
- package/dist/chunk-NSG4C6BF.js +0 -23
- package/dist/chunk-VIEUJSTT.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { L as LLMAdapter, C as ChatMessage, a as LLMInvokeOptions } from './types-
|
|
1
|
+
import { L as LLMAdapter, C as ChatMessage, a as LLMInvokeOptions } from './types-BgMqbc7N.cjs';
|
|
2
2
|
import { a as CircuitBreakerOptions, e as CircuitBreaker } from './resilience-Q6Bt_7y0.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -176,5 +176,24 @@ declare class AllTiersExhaustedError extends Error {
|
|
|
176
176
|
constructor(report: CascadeExhaustionReport);
|
|
177
177
|
}
|
|
178
178
|
declare function cascadingLlmAdapter(tiers: readonly AdapterTier[], opts?: CascadingLlmAdapterOptions): LLMAdapter;
|
|
179
|
+
/**
|
|
180
|
+
* Tiny type-safe constructor for an {@link AdapterTier}. Cleans up the
|
|
181
|
+
* heterogeneous array-type cast users (and `browser-presets.ts`) had to write
|
|
182
|
+
* by hand. Per Wave A Unit 13 decision.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* ```ts
|
|
186
|
+
* cascadingLlmAdapter([
|
|
187
|
+
* tier("local", webllmAdapter(...)),
|
|
188
|
+
* tier("cloud", anthropicAdapter(...), { breaker: { failureThreshold: 5 } }),
|
|
189
|
+
* ]);
|
|
190
|
+
* ```
|
|
191
|
+
*
|
|
192
|
+
* @category ai
|
|
193
|
+
*/
|
|
194
|
+
declare function tier(name: string, adapter: LLMAdapter, opts?: {
|
|
195
|
+
breaker?: CircuitBreakerOptions | CircuitBreaker;
|
|
196
|
+
filter?: AdapterTier["filter"];
|
|
197
|
+
}): AdapterTier;
|
|
179
198
|
|
|
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 };
|
|
199
|
+
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, tier as t };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { L as LLMAdapter, C as ChatMessage, a as LLMInvokeOptions } from './types-
|
|
1
|
+
import { L as LLMAdapter, C as ChatMessage, a as LLMInvokeOptions } from './types-CdfO2QTt.js';
|
|
2
2
|
import { a as CircuitBreakerOptions, e as CircuitBreaker } from './resilience-CludlzcP.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -176,5 +176,24 @@ declare class AllTiersExhaustedError extends Error {
|
|
|
176
176
|
constructor(report: CascadeExhaustionReport);
|
|
177
177
|
}
|
|
178
178
|
declare function cascadingLlmAdapter(tiers: readonly AdapterTier[], opts?: CascadingLlmAdapterOptions): LLMAdapter;
|
|
179
|
+
/**
|
|
180
|
+
* Tiny type-safe constructor for an {@link AdapterTier}. Cleans up the
|
|
181
|
+
* heterogeneous array-type cast users (and `browser-presets.ts`) had to write
|
|
182
|
+
* by hand. Per Wave A Unit 13 decision.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* ```ts
|
|
186
|
+
* cascadingLlmAdapter([
|
|
187
|
+
* tier("local", webllmAdapter(...)),
|
|
188
|
+
* tier("cloud", anthropicAdapter(...), { breaker: { failureThreshold: 5 } }),
|
|
189
|
+
* ]);
|
|
190
|
+
* ```
|
|
191
|
+
*
|
|
192
|
+
* @category ai
|
|
193
|
+
*/
|
|
194
|
+
declare function tier(name: string, adapter: LLMAdapter, opts?: {
|
|
195
|
+
breaker?: CircuitBreakerOptions | CircuitBreaker;
|
|
196
|
+
filter?: AdapterTier["filter"];
|
|
197
|
+
}): AdapterTier;
|
|
179
198
|
|
|
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 };
|
|
199
|
+
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, tier as t };
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import{a as Pe,b as Fe,d as je,e as Ge}from"./chunk-TOCCHQI6.js";import{e as wt}from"./chunk-ZWETYYQG.js";import{h as Lt}from"./chunk-7JZ3YORY.js";import{e as Ze}from"./chunk-VXJX3ZZP.js";import{a as qt,b as Xt,c as Zt,d as er,e as tr,f as Xe,g as rr}from"./chunk-PNTBXOQ6.js";import{a as Je,b as ee,c as _e,d as fe,e as se,f as te,g as zt,h as Qe,i as Yt,j as Jt,k as Qt}from"./chunk-FTA5TB2A.js";import{c as Mt}from"./chunk-K54OKWNY.js";import{b as xt}from"./chunk-7QMVU3IX.js";import{b as yt,c as Oe,d as ht,f as Ye}from"./chunk-RWGJQQLT.js";import{b as De}from"./chunk-LWGLBCMU.js";import{b as ve}from"./chunk-XRSHMHEG.js";import{j as ce}from"./chunk-4JBKKUCJ.js";import{a as ae}from"./chunk-ESMPEKEV.js";import{R as Rt,s as kt,x as z}from"./chunk-WQ7I7JVU.js";import{B as V,f as bt,m as x,w as ue,y as Tt,z as vt}from"./chunk-UMH3HSP7.js";import{D as pe,E as w,F as Te,G as k,H as ne,m as Z,o as re,p as Ne}from"./chunk-7AJKUA36.js";import{b as Q,d as be,i as le,j as X}from"./chunk-CK2E7BTU.js";import{b as Ht}from"./chunk-QYADASLV.js";var on={};Ht(on,{AgentLoopGraph:()=>ze,AllTiersExhaustedError:()=>tr,BudgetExhaustedError:()=>We,ChatStreamGraph:()=>He,CircuitOpenError:()=>Oe,DEFAULT_DECAY_RATE:()=>Ce,FallbackMissError:()=>Jt,LLMTimeoutError:()=>ke,ReplayCacheMissError:()=>zt,ToolRegistryGraph:()=>qe,admissionFilter3D:()=>Vr,admissionScored:()=>Gt,agentLoop:()=>$r,agentMemory:()=>Ur,anthropicAdapter:()=>qt,canonicalJson:()=>Yt,cascadingLlmAdapter:()=>Xe,chatStream:()=>ut,composePricing:()=>lr,computePrice:()=>et,contentGate:()=>jr,costMeterExtractor:()=>Ir,createAdapter:()=>er,createCapabilitiesRegistry:()=>nr,createPricingRegistry:()=>sr,dryRunAdapter:()=>Je,fallbackAdapter:()=>Qt,fromLLM:()=>Mr,frozenContext:()=>Lr,gatedStream:()=>Sr,gaugesAsContext:()=>Qr,googleAdapter:()=>Xt,graphFromSpec:()=>Wt,graphFromSpecReactive:()=>Xr,handoff:()=>Wr,keywordFlagExtractor:()=>Dr,knobsAsTools:()=>en,llmConsolidator:()=>pt,llmExtractor:()=>mt,memoryRetrieval:()=>Jr,memoryWithKG:()=>qr,memoryWithTiers:()=>zr,memoryWithVectors:()=>Hr,observableAdapter:()=>or,openAICompatAdapter:()=>Zt,parseRateLimitFromError:()=>ot,pricingFor:()=>dr,promptNode:()=>dt,redactor:()=>Gr,registryPricing:()=>ir,resilientAdapter:()=>vr,streamExtractor:()=>_r,streamingPromptNode:()=>Ar,suggestStrategy:()=>Kt,suggestStrategyReactive:()=>rn,systemPromptBuilder:()=>Cr,tier:()=>rr,toolCallExtractor:()=>Fr,toolRegistry:()=>ct,toolSelector:()=>Kr,validateGraphDef:()=>nn,withBreaker:()=>tt,withBudgetGate:()=>nt,withDryRun:()=>cr,withRateLimiter:()=>st,withReplayCache:()=>Qe,withRetry:()=>it,withTimeout:()=>lt,zeroPrice:()=>$e});function Ae(r,e){return`${r}::${e}`}function nr(r){let e=De({name:"capabilitiesRegistry"}),t=i=>{e.set(Ae(i.provider,i.id),i)};if(r)for(let i of r)t(i);let n=(i,d)=>{let c=e.get(Ae(i,d));if(c)return c;let m=e.entries.cache;if(!m)return;let p;for(let[,h]of m){if(h.provider!==i)continue;let g=h.id;d.startsWith(g)&&(!p||g.length>p.id.length)&&(p=h)}return p},o=128,a=new Map,s=new Map,l=(i,d,c,m)=>{for(i.has(d)&&i.delete(d),i.set(d,c);i.size>m;){let p=i.keys().next().value;if(p===void 0)break;i.delete(p)}},u=k([e.entries],([i])=>Array.from(i.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:t,lookup:n,remove(i,d){let c=e.has(Ae(i,d));return c&&e.delete(Ae(i,d)),c},entries(){let i=e.entries.cache;return(function*(){if(i)for(let d of i.values())yield d})()},lookupNode(i,d){let c=Ae(i,d),m=a.get(c);if(m)return a.delete(c),a.set(c,m),m;let p=k([e.entries],()=>n(i,d),{name:`capabilitiesRegistry/lookup/${i}::${d}`,initial:void 0});return l(a,c,p,o),p},entriesNode:u,byProvider(i){let d=s.get(i);if(d)return s.delete(i),s.set(i,d),d;let c=k([u],([m])=>m.filter(p=>p.provider===i),{name:`capabilitiesRegistry/byProvider/${i}`,initial:[]});return l(s,i,c,o),c}}}function oe(r){let e=r.input,t=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 t;let n=0;for(let o of Object.values(e.extensions))n+=o;return t+n}function de(r){let e=r.output,t=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return t;let n=0;for(let o of Object.values(e.extensions))n+=o;return t+n}function Nt(){return{input:{regular:0},output:{regular:0}}}function or(r,e){let t=e?.logMax??1e3,n=ve(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:t}),o=w(null,{name:"adapterStats/lastCall"}),a=k([n.entries],([g])=>g.length,{name:"adapterStats/totalCalls",initial:0}),s=k([n.entries],([g])=>g.reduce((f,b)=>f+oe(b.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),l=k([n.entries],([g])=>g.reduce((f,b)=>f+de(b.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[V(a),V(s),V(l)],i=g=>{n.append(g),o.emit(g)},d=()=>{n.clear(),o.emit(null)},c=ee(r,{invoke(g,f){let b=re(),M=Ne(),v=r.model??f?.model??"",L=A=>(i(fe({provider:r.provider,model:r.model??f?.model??A.model??"",tier:f?.tier??A.tier,usage:A.usage??se(),startNs:b,startWallClockNs:M,method:"invoke"})),A),R=A=>{let G=A;i(fe({provider:r.provider,model:v,tier:f?.tier,usage:se(),startNs:b,startWallClockNs:M,method:"invoke",error:{type:G?.name??"Error",message:G?.message??String(A)}}))};return _e(r.invoke(g,f),{onResp:L,onError:R,name:"adapterStats/invokeTap"})},async*stream(g,f){let b=re(),M=Ne(),v=r.model??f?.model??"",L;try{for await(let R of r.stream(g,f))R.type==="usage"&&(L=R.usage),yield R;i(fe({provider:r.provider,model:v,tier:f?.tier,usage:L??se(),startNs:b,startWallClockNs:M,method:"stream"}))}catch(R){let A=R;throw i(fe({provider:r.provider,model:v,tier:f?.tier,usage:L??se(),startNs:b,startWallClockNs:M,method:"stream",error:{type:A?.name??"Error",message:A?.message??String(R)}})),R}}});te(c,"observableAdapter",r);let m=!1;return{adapter:c,stats:{lastCall:o,allCalls:n,totalCalls:a,totalInputTokens:s,totalOutputTokens:l,reset:d,dispose:()=>{if(!m){m=!0;for(let g of u)g();u.length=0}}}}}function ar(r,e){return r==null?0:typeof r=="number"?r:r.thresholdTokens!=null&&r.pricePerMillionAbove!=null&&e>r.thresholdTokens?r.pricePerMillionAbove:r.pricePerMillion}function $e(r="USD"){return{total:0,currency:r}}function et(r,e,t){let n=oe(r),o=e.currency??"USD",a=t?.withBreakdown===!0,s=a?{}:null,l=0,u=(f,b,M)=>{if(!b||M==null)return;let v=ar(M,n),L=b*v/1e6;l+=L,a&&(s[f]=(s[f]??0)+L)},i=r.input,d=e.input;if(d&&(u("input.regular",i.regular,d.regular),u("input.cacheRead",i.cacheRead??0,d.cacheRead),u("input.cacheWrite5m",i.cacheWrite5m??0,d.cacheWrite5m),u("input.cacheWrite1h",i.cacheWrite1h??0,d.cacheWrite1h),u("input.cacheWriteOther",i.cacheWriteOther??0,d.cacheWriteOther),u("input.audio",i.audio??0,d.audio),u("input.image",i.image??0,d.image),u("input.video",i.video??0,d.video),u("input.toolUse",i.toolUse??0,d.toolUse),i.extensions&&d.extensions))for(let[f,b]of Object.entries(i.extensions))u(`input.ext.${f}`,b,d.extensions[f]);let c=r.output,m=e.output;if(m&&(u("output.regular",c.regular,m.regular),u("output.reasoning",c.reasoning??0,m.reasoning),u("output.audio",c.audio??0,m.audio),u("output.predictionAccepted",c.predictionAccepted??0,m.predictionAccepted),u("output.predictionRejected",c.predictionRejected??0,m.predictionRejected),c.extensions&&m.extensions))for(let[f,b]of Object.entries(c.extensions))u(`output.ext.${f}`,b,m.extensions[f]);let p=t?.tier;if(p&&e.tierMultipliers){let f=e.tierMultipliers[p];if(f!=null&&(l*=f,a))for(let b of Object.keys(s))s[b]*=f}let h=r.auxiliary,g=e.auxiliary;if(h&&g)for(let[f,b]of Object.entries(h)){let M=g[f];if(M==null||!b)continue;let v=b*M;l+=v,a&&(s[`auxiliary.${f}`]=v)}return a?{total:l,currency:o,breakdown:s}:{total:l,currency:o}}function Be(r,e){return`${r}::${e}`}function sr(r){let e=new Map,t=new Map,n=(o,a,s)=>{e.set(Be(o,a),{provider:o,model:a,pricing:s});let l=t.get(o);l||(l=new Set,t.set(o,l)),l.add(a)};if(r)for(let[o,a,s]of r)n(o,a,s);return{register:n,lookup(o,a){let s=e.get(Be(o,a));if(s)return s.pricing;let l=t.get(o);if(!l)return;let u;for(let i of l)if(a.startsWith(i)&&(!u||i.length>u.key.length)){let d=e.get(Be(o,i));d&&(u={key:i,pricing:d.pricing})}return u?.pricing},remove(o,a){let s=e.delete(Be(o,a));if(s){let l=t.get(o);l?.delete(a),l&&l.size===0&&t.delete(o)}return s},entries(){let o=e.values();return(function*(){for(let{provider:a,model:s,pricing:l}of o)yield[a,s,l]})()}}}function ir(r,e="USD"){return(t,n)=>{let o=r.lookup(n.provider,n.model);return o?et(t,o,{tier:n.tier,withBreakdown:n.withBreakdown}):$e(e)}}function lr(...r){return(e,t)=>{for(let n of r){let o=n(e,t);if(o.total!==0)return o}return r.length>0?r[0](e,t):$e()}}function dr(r,e,t){return r?.pricing?et(e,r.pricing,t):$e()}function tt(r,e={}){let t=e.breaker??ht(e),n=ee(r,{async invoke(o,a){if(!t.canExecute())throw new Oe;try{let s=await ue(x(r.invoke(o,a)));return t.recordSuccess(),s}catch(s){throw t.recordFailure(s),s}},async*stream(o,a){if(!t.canExecute())throw new Oe;try{for await(let s of r.stream(o,a))yield s;t.recordSuccess()}catch(s){throw t.recordFailure(s),s}}});return te(n,"withBreaker",r),{adapter:n,breaker:t}}var We=class extends Error{constructor(t,n,o){super(`Budget exhausted: ${t} (limit=${n}, observed=${o})`);this.which=t;this.limit=n;this.observed=o}name="BudgetExhaustedError"},rt=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),At=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function nt(r,e){let t=ve(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),n=w(At(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=k([n],([i])=>{let d=i;return!(e.caps.calls!=null&&d.calls>=e.caps.calls||e.caps.inputTokens!=null&&d.inputTokens>=e.caps.inputTokens||e.caps.outputTokens!=null&&d.outputTokens>=e.caps.outputTokens||e.caps.usd!=null&&d.usd>=e.caps.usd)},{name:e.name?`${e.name}/isOpen`:"budgetGate/isOpen",initial:!0});if(V(o),e.onExhausted!=null){let i=e.onExhausted,d=!1,c=!0;o.subscribe(m=>{for(let p of m)if(p[0]===Q){let h=p[1];if(d&&c&&h===!1){let g=St(n.cache??rt,e.caps);g&&i(g)}c=h,d=!0}})}let a=()=>{if(o.cache===!1){let i=n.cache??rt,d=St(i,e.caps);return new We(d??"budget",e.caps[d??"calls"]??0,ur(i,d??"calls"))}},s=(i,d)=>{let c=r.provider,m=fe({provider:c,model:d.model,tier:d.tier,usage:i,startNs:d.startNs,method:d.method,...d.error?{error:d.error}:{}});t.append(m);let p=n.cache??rt,h=e.pricingFn?p.usd+e.pricingFn(i,{model:d.model,provider:c,tier:d.tier}).total:p.usd;n.emit({calls:p.calls+1,inputTokens:p.inputTokens+oe(i),outputTokens:p.outputTokens+de(i),usd:h})},l=()=>{t.clear(),n.emit(At())},u=ee(r,{invoke(i,d){let c=a();if(c)return Promise.reject(c);let m=re(),p=r.model??d?.model??"",h=f=>(s(f.usage??se(),{model:r.model??d?.model??f.model??"",tier:d?.tier??f.tier,startNs:m,method:"invoke"}),f),g=f=>{let b=f;s(se(),{model:p,tier:d?.tier,startNs:m,method:"invoke",error:{type:b?.name??"Error",message:b?.message??String(f)}})};return _e(r.invoke(i,d),{onResp:h,onError:g,name:"budgetGate/invokeTap"})},async*stream(i,d){let c=a();if(c)throw c;let m=re(),p;try{for await(let h of r.stream(i,d))h.type==="usage"&&(p=h.usage),yield h;s(p??se(),{model:r.model??d?.model??"",tier:d?.tier,startNs:m,method:"stream"})}catch(h){let g=h;throw s(p??se(),{model:r.model??d?.model??"",tier:d?.tier,startNs:m,method:"stream",error:{type:g?.name??"Error",message:g?.message??String(h)}}),h}}});return te(u,"withBudgetGate",r),{adapter:u,budget:{totals:n,isOpen:o,log:t,reset:l}}}function St(r,e){if(e.calls!=null&&r.calls>=e.calls)return"calls";if(e.inputTokens!=null&&r.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&r.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&r.usd>=e.usd)return"usd"}function ur(r,e){switch(e){case"calls":return r.calls;case"inputTokens":return r.inputTokens;case"outputTokens":return r.outputTokens;case"usd":return r.usd}}function cr(r,e){let t=e.mock??Je({provider:r.provider,model:r.model}),n=typeof e.enabled=="boolean"?e.enabled:void 0,o=n===void 0?x(e.enabled):void 0,a;o&&(a=V(o));let s=()=>n!==void 0?n:!!o?.cache,l=ee(r,{invoke(i,d){return s()?t.invoke(i,d):r.invoke(i,d)},stream(i,d){return s()?t.stream(i,d):r.stream(i,d)}});return te(l,"withDryRun",r),{adapter:l,dispose:()=>{a&&(a(),a=void 0)}}}function ot(r){if(r==null||typeof r!="object")return;let e=r,t=e.status,n=mr(e.headers);if(t!==429&&t!==503&&!br(e.message))return;let o={},a=n("retry-after"),s=fr(a);s!=null&&(o.retryAfterMs=s);let l=n("anthropic-ratelimit-requests-reset");if(l){let p=Ct(l);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let u=n("anthropic-ratelimit-tokens-reset");if(u){let p=Ct(u);p!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,p))}let i=Ke(n,"x-ratelimit-limit-requests");i!=null&&(o.rpmCap=i);let d=Ke(n,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let c=Ke(n,"x-ratelimit-remaining-requests"),m=Ke(n,"x-ratelimit-remaining-tokens");if(c!=null&&i!=null&&i>0&&(o.usageHint??={},o.usageHint.rpm=1-c/i),m!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-m/d),o.retryAfterMs==null&&e.message){let p=yr(e.message);p!=null&&(o.retryAfterMs=p)}return e.headers&&(o.metadata={headers:pr(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function mr(r){if(!r)return()=>{};if(typeof r.get=="function"){let n=r;return o=>n.get(o)??n.get(o.toLowerCase())??void 0}let e=r,t={};for(let[n,o]of Object.entries(e)){let a=Array.isArray(o)?o.join(", "):o;a!=null&&(t[n.toLowerCase()]=a)}return n=>t[n.toLowerCase()]}function pr(r){let e={};if(typeof r.forEach=="function")return r.forEach((t,n)=>{e[n]=t}),e;for(let[t,n]of Object.entries(r))n!=null&&(e[t]=Array.isArray(n)?n.join(", "):n);return e}function Ke(r,e){let t=r(e);if(t==null)return;let n=Number(t);return Number.isFinite(n)?n:void 0}function fr(r){if(!r)return;let e=r.trim(),t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n)){let o=n-Date.now();if(o>0)return o}}function Ct(r){if(!r)return;let e=Date.parse(r);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var gr=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function yr(r){let e=gr.exec(r);if(!e)return;let t=Number(e[1]);if(!Number.isFinite(t))return;let n=(e[2]??"s").toLowerCase();if(n==="ms")return t;if(n.startsWith("s"))return t*1e3;if(n.startsWith("m"))return t*6e4}var hr=/rate\s*limit|too\s*many\s*requests|quota|429/i;function br(r){return!!r&&hr.test(r)}function at(r){let e=new Error(r);return e.name="AbortError",e}function It(r={}){let e=Math.max(1,r.burstMultiplier??1),t=r.clampCooldownMs??6e4,n=r.rpm!=null?x(r.rpm):w(Number.POSITIVE_INFINITY),o=r.tpm!=null?x(r.tpm):w(Number.POSITIVE_INFINITY),a=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),s=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),l=w({},{name:"adaptiveRateLimiter/lastSignal"}),u=k([n,a],([N,D])=>Math.min(Number(N??1/0),Number(D??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),i=k([o,s],([N,D])=>Math.min(Number(N??1/0),Number(D??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=Me(Number(n.cache??Number.POSITIVE_INFINITY),e),c=Me(Number(o.cache??Number.POSITIVE_INFINITY),e),m=!1,p=!1,h=u.subscribe(N=>{for(let D of N)if(D[0]===Q){let F=Number(D[1]);Number.isFinite(F)&&F>0?(d=Me(F,e),m=!1):F===1/0?(d=Me(1/0,e),m=!1):F<=0&&(m=!0)}}),g=i.subscribe(N=>{for(let D of N)if(D[0]===Q){let F=Number(D[1]);Number.isFinite(F)&&F>0?(c=Me(F,e),p=!1):F===1/0?(c=Me(1/0,e),p=!1):F<=0&&(p=!0)}}),f=0,b=new ae,M=new ae,v;r.adaptation!=null&&(v=x(r.adaptation).subscribe(D=>{for(let F of D)F[0]===Q&&L(F[1])}));function L(N){if(l.emit(N),N.rpmCap!=null&&Number.isFinite(N.rpmCap)&&N.rpmCap>=0&&(a.emit(N.rpmCap),Number.isFinite(t)&&t>0&&b.start(t,()=>a.emit(Number.POSITIVE_INFINITY))),N.tpmCap!=null&&Number.isFinite(N.tpmCap)&&N.tpmCap>=0&&(s.emit(N.tpmCap),Number.isFinite(t)&&t>0&&M.start(t,()=>s.emit(Number.POSITIVE_INFINITY))),N.retryAfterMs!=null&&N.retryAfterMs>0){let D=re()+N.retryAfterMs*1e6;D>f&&(f=D)}}let R=w(0,{name:"adaptiveRateLimiter/pending"}),A=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),G=w(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),W=N=>{R.emit((R.cache??0)+N)},I=()=>{A.emit(d.available()),G.emit(c.available())};async function O(N={}){let D=N.requestCost??1,F=N.tokenCost??0,Y=N.signal;W(1);try{for(;;){if(Y?.aborted)throw at("AdaptiveRateLimiter.acquire aborted");let P=re();if(f>P){let B=Math.ceil((f-P)/1e6);await Ve(B,Y);continue}if(D>0&&m||F>0&&p){await Ve(250,Y);continue}let T=d,y=c;if(!T.tryConsume(D)){await Ve(Et(T,D),Y);continue}if(!(F>0?y.tryConsume(F):!0)){T.putBack(D),await Ve(Et(y,F),Y);continue}I();return}}finally{W(-1)}}function S(N){N>0?c.tryConsume(N):N<0&&c.putBack(-N),I()}function _(){h(),g(),v?.(),b.cancel(),M.cancel()}return{effectiveRpm:u,effectiveTpm:i,lastSignal:l,pending:R,rpmAvailable:A,tpmAvailable:G,acquire:O,recordUsage:S,recordSignal:L,dispose:_}}function Me(r,e){if(!Number.isFinite(r)||r===1/0)return Ye(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let t=Math.max(1,r*e),n=r/60;return Ye(t,n)}function Et(r,e){let t=r.available(),n=Math.max(0,e-t);return n<=0?25:Math.min(5e3,Math.max(50,n*100))}function Ve(r,e){return r<=0?Promise.resolve():e?.aborted?Promise.reject(at("AdaptiveRateLimiter.acquire aborted")):new Promise((t,n)=>{let o=new ae,a,s=()=>{o.cancel(),e&&a&&e.removeEventListener("abort",a)};o.start(r,()=>{s(),t()}),e&&(a=()=>{s(),n(at("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",a,{once:!0}))})}function st(r,e={}){let t=e.limiter??It({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),n=(s,l)=>e.costFn?e.costFn(s,l):0,o=s=>{let l=ot(s);l&&t.recordSignal(l)},a=ee(r,{async invoke(s,l){let u=n(s,l);await t.acquire({requestCost:1,tokenCost:u,signal:l?.signal});try{let i=await ue(x(r.invoke(s,l))),d=i.usage??Nt(),m=oe(d)+de(d)-u;return m>0&&t.recordUsage(m),i}catch(i){throw o(i),i}},async*stream(s,l){let u=n(s,l);await t.acquire({requestCost:1,tokenCost:u,signal:l?.signal});try{let i=0;for await(let c of r.stream(s,l))c.type==="usage"&&(i=oe(c.usage)+de(c.usage)),yield c;let d=i-u;d>0&&t.recordUsage(d)}catch(i){throw o(i),i}}});return te(a,"withRateLimiter",r),{adapter:a,limiter:t}}function Ue(r="aborted"){let e=new Error(r);return e.name="AbortError",e}function Ot(r,e){return r<=0?Promise.resolve():e?.aborted?Promise.reject(Ue()):new Promise((t,n)=>{let o=new ae,a,s=()=>{o.cancel(),e&&a&&e.removeEventListener("abort",a)};o.start(r,()=>{s(),t()}),e&&(a=()=>{s(),n(Ue())},e.addEventListener("abort",a,{once:!0}))})}function it(r,e={}){let t=e.attempts??3,n=e.baseDelayMs??500,o=e.maxDelayMs??1e4,a=e.strategy??"decorrelated",s=e.jitter??!0,l=e.shouldRetry??Tr,u=e.retryStreaming??!0,i=(c,m)=>{if(a==="decorrelated"){let f=Math.min(o,Math.max(n,m*3));return n+Math.random()*(f-n)}let p=a==="exp"?n*2**(c-1):n*c,h=Math.min(o,p);if(!s)return h;let g=h*(.5+Math.random());return Math.min(o,g)},d=ee(r,{async invoke(c,m){if(m?.signal?.aborted)throw Ue();let p,h=n;for(let g=1;g<=t;g++)try{return await ue(x(r.invoke(c,m)))}catch(f){if(p=f,g>=t||!l(f,g))throw f;let b=i(g,h);h=b,await Ot(b,m?.signal)}throw p},async*stream(c,m){if(m?.signal?.aborted)throw Ue();if(!u){for await(let g of r.stream(c,m))yield g;return}let p,h=n;for(let g=1;g<=t;g++){let f=!1;try{for await(let b of r.stream(c,m))f=!0,yield b;return}catch(b){if(p=b,f||g>=t||!l(b,g))throw b;let M=i(g,h);h=M,await Ot(M,m?.signal)}}throw p}});return te(d,"withRetry",r),d}function Tr(r,e){if(r==null)return!1;let t=r;return t.name==="LLMTimeoutError"?!0:t.name==="AbortError"||t.message==="aborted"||t.name==="DOMException"&&t.code!=null&&Number(t.code)===20||t.name==="BudgetExhaustedError"||t.name==="CircuitOpenError"?!1:t.status!=null?t.status===429||t.status>=500&&t.status<600:t.code&&typeof t.code=="string"&&/^E[A-Z]+$/.test(t.code)?!0:t.message?/network|timeout|socket|fetch|econn|eai_/i.test(t.message):!1}var ke=class extends Error{constructor(t){super(`LLM call timed out after ${t}ms`);this.ms=t}name="LLMTimeoutError"};function lt(r,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let t=a=>{let s=new AbortController,l=!1,u,i=new ae;return a&&(a.aborted?s.abort(a.reason):(u=()=>{i.cancel(),s.abort(a.reason)},a.addEventListener("abort",u,{once:!0}))),i.start(e,()=>{l=!0,s.abort(new ke(e))}),{signal:s.signal,cancel:()=>{i.cancel(),a&&u&&a.removeEventListener("abort",u)},timedOut:()=>l}},n=(a,s)=>{if(!s||a instanceof ke)throw a;let l=a;if(l?.name==="AbortError"||l?.name==="DOMException"&&Number(l.code)===20||a?.message==="aborted"){let i=new ke(e);throw i.cause=a,i}throw a},o=ee(r,{async invoke(a,s){let{signal:l,cancel:u,timedOut:i}=t(s?.signal);try{return await ue(x(r.invoke(a,{...s,signal:l})))}catch(d){return n(d,i())}finally{u()}},async*stream(a,s){let{signal:l,cancel:u,timedOut:i}=t(s?.signal);try{for await(let d of r.stream(a,{...s,signal:l}))yield d}catch(d){n(d,i())}finally{u()}}});return te(o,"withTimeout",r),o}function vr(r,e={}){let t={adapter:r},n=r;if(e.rateLimit){let o=st(n,e.rateLimit);n=o.adapter,t.rateLimiter=o.limiter}if(e.budget){let o=nt(n,e.budget);n=o.adapter,t.budget=o.budget}if(e.breaker){let o=tt(n,e.breaker);n=o.adapter,t.breaker=o.breaker}if(e.timeoutMs!=null&&(n=lt(n,e.timeoutMs)),e.retry&&(n=it(n,e.retry)),e.fallback){if(e.name==="fallback")throw new RangeError('resilientAdapter: `name` cannot be "fallback" \u2014 collides with the secondary tier label.');let o={};e.onFallback&&(o.onFallback=e.onFallback),e.onExhausted&&(o.onExhausted=e.onExhausted),n=Xe([{name:e.name??"primary",adapter:n},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(n=Qe(n,e.cache)),t.adapter=n,t}function Mr(r,e,t){let n=x(e);return z(n,a=>{if(!a||a.length===0)return w(null);let s=t?.tools;return r.invoke(a,{model:t?.model,temperature:t?.temperature,maxTokens:t?.maxTokens,tools:s,systemPrompt:t?.systemPrompt})})}function C(r,e){return Mt("ai",r,e)}function kr(r){return r!=null&&typeof r.then=="function"}function Rr(r){return typeof r=="object"&&r!==null&&"subscribe"in r&&typeof r.subscribe=="function"&&"cache"in r}function xr(r){return r!=null&&typeof r=="object"&&Symbol.asyncIterator in r&&typeof r[Symbol.asyncIterator]=="function"}var wr=3e4;function Dt(r,e){if(r.status==="settled"){let n=r.cache;if(n!==void 0)return Promise.resolve(n)}let t=e?.timeoutMs??wr;return new Promise((n,o)=>{let a=new ae,s=r.subscribe(l=>{for(let u of l){if(u[0]===Q){a.cancel(),s(),n(u[1]);return}if(u[0]===X){a.cancel(),s(),o(u[1]);return}if(u[0]===le){a.cancel(),s(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});a.start(t,()=>{s(),o(new Error(`firstDataFromNode: timed out after ${t}ms`))})})}async function ge(r){return kr(r)?ge(await r):Rr(r)?Dt(r):xr(r)?Dt(x(r)):r}function Re(r){let e=r.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:r}function Lr(r,e){let t=x(r),n=e?.refreshTrigger!=null?x(e.refreshTrigger):null;return n==null?pe([t],(o,a,s)=>{if(s.store.emitted===!0)return;let u=o[0],i=u!=null&&u.length>0?u.at(-1):s.prevData[0];if(i!==void 0)return s.store.emitted=!0,a.emit(i),{invalidate:()=>{s.store.emitted=!1}}},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:C("frozen_context")}):pe([t,n],(o,a,s)=>{let l=o[1];if(!(l!=null&&l.length>0))return;let i=o[0],d=i!=null&&i.length>0?i.at(-1):s.prevData[0];a.emit(d)},{name:e?.name??"frozenContext",describeKind:"derived",initial:null,meta:C("frozen_context")})}function _t(r){return r!=null&&typeof r=="object"&&"content"in r?String(r.content):typeof r=="string"?r:String(r)}function Nr(r,e=200){return r.length<=e?r:`${r.slice(0,e)}\u2026`}function dt(r,e,t,n){let o=n?.format??"text",a=n?.name??"prompt_node",s=k(e,u=>{if(u.some(d=>d==null))return[];let i=typeof t=="string"?t:t(...u);return i?[{role:"user",content:i}]:[]},{name:`${a}::messages`,meta:C("prompt_node")});return z(s,u=>!u||u.length===0?w(null):Te(i=>{let d=!1,c=!1,m,p={model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt};if(n?.abort){let b=vt(n.abort);p.signal=b.signal,m=b.dispose}let h;try{h=r.invoke(u,p)}catch(b){return d=!0,i.down([[X,b]]),()=>{m?.()}}let f=x(h).subscribe(b=>{if(!(c||d))for(let M of b){if(d)return;if(M[0]===Q){let v=M[1];try{let L=_t(v),R=o==="json"?JSON.parse(Re(L)):L;i.emit(R)}catch(L){let R=_t(v),A=new Error(`promptNode: failed to parse LLM response as JSON: ${L.message}
|
|
2
|
+
Raw content (first 200 chars): ${Nr(R)}`);d=!0,i.down([[X,A]]);return}}else if(M[0]===X){d=!0,i.down([[X,M[1]]]);return}else if(M[0]===le){d=!0,i.down([[le]]);return}else i.down([M])}});return()=>{c=!0,f(),m?.()}},{name:`${a}::call`,meta:C("prompt_node::call")}),{name:`${a}::output`,meta:n?.meta?{...C("prompt_node::output"),...n.meta}:C("prompt_node::output")})}async function Pt(r,e,t,n){let o="",a=0;for await(let s of r.stream(e,t))n.publish({...s,seq:a++,ts:Ne()}),s.type==="token"&&(o+=s.delta);return o}function Ft(r,e){if(e==="json")try{return JSON.parse(Re(r))}catch(t){let n=r.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${t.message}; content preview: ${n}`)}return r}function jt(r,e){return k([r.latest],([t],n)=>{let o=n.store;if(t==null)return o.acc??"";let a=t;return a.seq===0&&(o.acc=""),a.type==="token"&&(o.acc=(o.acc??"")+a.delta),o.acc??""},{name:e,meta:C("accumulated_text"),initial:""})}function Ar(r,e,t,n){let o=n?.name??"llm",a=n?.format??"text",s=Ze(`${o}/stream`,{...n?.retainedLimit!=null?{retainedLimit:n.retainedLimit}:{}}),l=k(e,c=>{if(c.some(p=>p==null))return[];let m=typeof t=="string"?t:t(...c);return m?[{role:"user",content:m}]:[]},{name:`${o}::messages`,meta:C("prompt_node::messages"),initial:[]}),u=z(l,c=>{let m=c;if(!m||m.length===0)return w(null);let p=new AbortController;async function*h(){try{let g=await Pt(r,m,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,signal:p.signal},s);yield Ft(g,a)}finally{p.abort()}}return x(h())}),i=jt(s,`${o}::accumulatedText`),d=V(u);return{output:u,deltaTopic:s,accumulatedText:i,dispose:()=>{d(),s.destroy()}}}function Sr(r,e,t,n,o,a){let s=w(0,{name:`${e}/cancel`}),l=0,u=[...n,s],i=a?.name??e,d=a?.format??"text",c=Ze(`${i}/stream`,{...a?.retainedLimit!=null?{retainedLimit:a.retainedLimit}:{}}),m=k(u,L=>{let R=L.slice(0,-1);if(R.some(G=>G==null))return[];let A=typeof o=="string"?o:o(...R);return A?[{role:"user",content:A}]:[]},{name:`${i}::messages`,meta:C("prompt_node::messages"),initial:[]}),p=z(m,L=>{let R=L;if(!R||R.length===0)return w(null);let A=new AbortController;async function*G(){try{let W=await Pt(t,R,{model:a?.model,temperature:a?.temperature,maxTokens:a?.maxTokens,systemPrompt:a?.systemPrompt,signal:A.signal},c);yield Ft(W,d)}finally{A.abort()}}return x(G())}),h=jt(c,`${i}::accumulatedText`),g=k([p],([L])=>{if(L!=null)return L},{name:`${e}/filter`});r.add(g,{name:`${e}/raw`});let f=wt(r,`${e}/gate`,`${e}/raw`,a?.gate),b=V(p),M=f.reject.bind(f),v={...f,reject(L=1){Z(()=>{M(L),s.emit(++l)})}};return{output:f.node,deltaTopic:c,accumulatedText:h,gate:v,dispose:()=>{b(),c.destroy()}}}function Cr(r,e){let t=e?.separator??`
|
|
3
|
+
|
|
4
|
+
`,n=r.map(s=>typeof s=="string"?w(s):x(s)),o=k(n,s=>s.filter(l=>l!=null&&l!=="").join(t),{name:e?.name??"systemPrompt",describeKind:"derived",meta:C("system_prompt"),initial:""}),a=V(o);return Object.assign(o,{dispose:a})}var Er=(r,e)=>r===e?!0:r.chunkCount===e.chunkCount&&r.charCount===e.charCount&&r.estimatedTokens===e.estimatedTokens&&r.estimated===e.estimated;function Ir(r,e){let t=e?.charsPerToken??4,n={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return k([r.latest],([o],a)=>{if(o==null)return n;let s=o;"chunkCount"in a.store||(a.store.chunkCount=0,a.store.charCount=0,a.store.usageTokens=0,a.store.sawUsage=!1);let l=a.store;s.type==="token"?(l.chunkCount+=1,l.charCount+=s.delta.length):s.type==="usage"&&(l.sawUsage=!0,l.usageTokens=oe(s.usage)+de(s.usage));let u=l.sawUsage?l.usageTokens:Math.ceil(l.charCount/t);return{chunkCount:l.chunkCount,charCount:l.charCount,estimatedTokens:u,estimated:!l.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:n,meta:C("cost_meter_extractor"),equals:Er})}var Or=(r,e)=>{if(r===e)return!0;if(r==null||e==null)return r===e;if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],o=e[t];if(n.label!==o.label||n.pattern!==o.pattern||n.match!==o.match||n.position!==o.position)return!1}return!0};function Dr(r,e){let t=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>t)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${t}); raise the option or shorten the pattern.`);let n=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return k([r],([o],a)=>{if(o==null)return[];let s=o;"flags"in a.store||(a.store.flags=[],a.store.scannedTo=0);let l=a.store.flags,u=a.store.scannedTo,i=Math.max(0,u-t),d=s.slice(i),c=!1;for(let{pattern:m,label:p,compiled:h}of n){h.lastIndex=0;for(let g of d.matchAll(h)){let f=i+(g.index??0);f+g[0].length<=u||(l.push({label:p,pattern:m,match:g[0],position:f}),c=!0)}}return a.store.scannedTo=s.length,c?[...l]:l.slice()},{name:e.name??"keyword-flag-extractor",describeKind:"derived",initial:[],meta:C("keyword_flag_extractor"),equals:Or})}function _r(r,e,t){return k([r],([n])=>n==null?null:e(n),{name:t?.name??"extractor",describeKind:"derived",initial:null,meta:C("stream_extractor"),...t?.equals?{equals:t.equals}:{}})}var Pr=(r,e)=>{if(r===e)return!0;if(r==null||e==null)return r===e;if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],o=e[t];if(n.startIndex!==o.startIndex||n.name!==o.name||n.raw!==o.raw)return!1}return!0};function Fr(r,e){return k([r],([t],n)=>{if(t==null)return[];let o=t;"calls"in n.store||(n.store.calls=[],n.store.scanFrom=0);let a=n.store.calls,s=n.store.scanFrom,l=!1;for(;s<o.length;){let u=o.indexOf("{",s);if(u===-1){n.store.scanFrom=o.length;break}let i=0,d=-1,c=!1;for(let p=u;p<o.length;p++){let h=o[p];if(c)h==="\\"&&p+1<o.length?p++:h==='"'&&(c=!1);else if(h==='"')c=!0;else if(h==="{")i++;else if(h==="}"&&(i--,i===0)){d=p;break}}if(d===-1){n.store.scanFrom=u;break}let m=o.slice(u,d+1);try{let p=JSON.parse(m);typeof p.name=="string"&&p.arguments!=null&&typeof p.arguments=="object"&&(a.push({name:p.name,arguments:p.arguments,raw:m,startIndex:u}),l=!0)}catch{}s=d+1,n.store.scanFrom=s}return l?[...a]:a.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:C("tool_call_extractor"),equals:Pr})}function jr(r,e,t,n){let o=t*(n?.hardMultiplier??1.5),a=typeof e!="function",s=[r];return a&&s.push(e),k(s,l=>{let u=l[0]??"";if(u.length===0)return"allow";let i=a?l[1]??0:e(u);return i>=o?"block":i>=t?"review":"allow"},{name:n?.name??"content-gate",initial:"allow"})}function Gr(r,e,t,n){let o=t??(()=>"[REDACTED]");function a(s){let l=s;for(let u of e){let i=u.global?u:new RegExp(u.source,`${u.flags}g`);l=l.replace(i,d=>o(d,u))}return l}return k([r],([s])=>a(s??""),{name:n?.name??"redactor",initial:""})}var He=class extends ce{_log;messages;latest;messageCount;constructor(e,t={}){super(e,t.graph),this._log=ve([],{name:"messages",maxSize:t.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=k([this.messages],([n])=>{let o=n;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:C("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(V(this.latest)),this.messageCount=k([this.messages],([n])=>n.length,{name:"messageCount",describeKind:"derived",meta:C("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(V(this.messageCount))}append(e,t,n){this._log.append({role:e,content:t,...n})}appendToolResult(e,t){this._log.append({role:"tool",content:t,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function ut(r,e){return new He(r,e)}var qe=class extends ce{definitions;schemas;_bundle;constructor(e,t={}){super(e,t.graph),this._bundle=De({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=k([this.definitions],([n])=>[...(n??new Map).values()],{name:"schemas",describeKind:"derived",meta:C("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(V(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}async execute(e,t){let n=this._bundle.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);let o=n.handler(t);return ge(o)}executeReactive(e,t){let n=this._bundle.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);return x(n.handler(t))}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function ct(r,e){return new qe(r,e)}var ze=class extends ce{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,t){if(super(e,t.graph),this.chat=ut(`${e}-chat`,{maxMessages:t.maxMessages}),this.mount("chat",this.chat),this.tools=ct(`${e}-tools`),this.mount("tools",this.tools),t.tools)for(let T of t.tools)this.tools.register(T);this.status=w("idle",{name:"status",describeKind:"state",meta:C("agent_status")}),this.add(this.status,{name:"status"}),this.turn=w(0,{name:"turn",describeKind:"state",meta:C("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.aborted=w(!1,{name:"aborted",describeKind:"state",meta:C("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let n=0,o=this.turn.subscribe(T=>{for(let y of T)y[0]===Q&&(n=y[1])}),a=!1,s=this.aborted.subscribe(T=>{for(let y of T)y[0]===Q&&(a=y[1])}),l=t.adapter,u=t.systemPrompt,i=t.model,d=t.temperature,c=t.maxTokens,m=t.maxTurns??10,p=t.stopWhen,h=this.chat,g=this.tools,f=this.status,b=this.turn,M=this.aborted,v=pe([f],(T,y,E)=>{if(Se(T,E.prevData,0,"idle")!=="thinking"||a||n>=m){y.down([[be]]);return}let B=h.allMessages();if(B.length===0){y.down([[be]]);return}let K=g.schemas.cache??[];y.emit({messages:B,tools:K})},{name:"promptInput",describeKind:"derived",meta:C("agent_prompt_input")}),L=z(v,T=>{let y=new AbortController;return this._currentAbortController=y,a&&y.abort(new Error("agentLoop: aborted")),x(l.invoke(T.messages,{tools:T.tools.length>0?T.tools:void 0,systemPrompt:u,model:i,temperature:d,maxTokens:c,signal:y.signal}),{signal:y.signal})},{equals:()=>!1}),R=w(null,{name:"lastResponse",describeKind:"state",meta:C("agent_last_response")});this.lastResponse=R;let A=pe([R,f],(T,y,E)=>{let j=Se(T,E.prevData,0,null);if(Se(T,E.prevData,1,"idle")!=="acting"){y.down([[be]]);return}let K=j?.toolCalls;if(K==null||K.length===0){y.down([[be]]);return}y.emit(K)},{name:"toolCallsRaw",describeKind:"derived",meta:C("agent_tool_calls_raw")}),G=t.interceptToolCalls?t.interceptToolCalls(A):A;this.toolCalls=G;let W=(T,y)=>{if(T===y)return!0;if(T.length!==y.length)return!1;for(let E=0;E<T.length;E++){let j=T[E],B=y[E];if(j?.id!==B?.id||j?.content!==B?.content)return!1}return!0},I=z(G,T=>{if(T==null||T.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsRaw gating invariant broken (should emit RESOLVED for empty). Audit toolCallsRaw.");let y=T.map(E=>Br(E,g));return k(y,E=>E.map((j,B)=>{let K=j;return K!=null&&typeof K=="object"&&"id"in K&&"content"in K?K:{id:T[B].id,content:JSON.stringify(j??null)}}),{name:"toolResults_batch",equals:W})});this.toolResults=I;let O=ne([L],([T])=>{if(a)return;let y=T,E=n+1,j=y.toolCalls!=null&&y.toolCalls.length>0,B=y.finishReason==="end_turn"&&(!y.toolCalls||y.toolCalls.length===0),K=p?.(y)===!0,$=E>=m,J=K||B||!j||$?"done":"acting";Z(()=>{R.emit(y),f.emit(J),b.emit(E),h.append("assistant",y.content,{toolCalls:y.toolCalls})})}),S=ne([I],([T])=>{if(a)return;let y=T;if(y.length===0)return;let E=n>=m?"done":"thinking";Z(()=>{f.emit(E);for(let j of y)h.appendToolResult(j.id,j.content)})}),_=f.cache??"idle",N=f.subscribe(T=>{for(let y of T)y[0]===Q&&(_=y[1])}),D=ne([M],([T])=>{T===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),_!=="done"&&f.emit("done"))}),F=V(O),Y=V(S),P=V(D);this._terminalResult=pe([f,R],(T,y,E)=>{let j=Se(T,E.prevData,0,"idle"),B=Se(T,E.prevData,1,null);if(j==="done"){if(B!=null){y.emit({response:B,runVersion:this._runVersion});return}let K=new Error("agentLoop: aborted");K.name="AbortError",y.down([[X,K]]);return}if(j==="error"){y.down([[X,new Error("agentLoop: errored")]]);return}y.down([[be]])},{name:"terminalResult",describeKind:"derived",meta:C("agent_terminal_result")}),this.add(v,{name:"promptInput"}),this.add(L,{name:"llmResponse"}),this.add(this.lastResponse,{name:"lastResponse"}),this.toolCalls===A?this.add(this.toolCalls,{name:"toolCalls"}):(this.add(A,{name:"toolCallsRaw"}),this.add(this.toolCalls,{name:"toolCalls"})),this.add(I,{name:"toolResults"}),this.add(this._terminalResult,{name:"terminalResult"}),this.addDisposer(o),this.addDisposer(s),this.addDisposer(N),this.addDisposer(F),this.addDisposer(Y),this.addDisposer(P),this._disposeRunWiring=()=>{}}async run(e,t){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let n=++this._runVersion;Z(()=>{this.turn.emit(0),this.aborted.emit(!1),this.status.emit("idle")}),e!=null&&this.chat.append("user",e),this.status.emit("thinking");let o;if(t!=null)if(t.aborted)this.aborted.emit(!0);else{let a=()=>this.aborted.emit(!0);t.addEventListener("abort",a,{once:!0}),o=()=>t.removeEventListener("abort",a)}try{return(await Tt(this._terminalResult,{predicate:s=>s!=null&&typeof s=="object"&&s.runVersion===n})).response}finally{o?.(),this._running=!1,this._currentAbortController=null}}abort(){this.aborted.emit(!0)}destroy(){try{this._disposeRunWiring()}catch{}super.destroy()}};function Br(r,e){let t=yt(()=>x(Promise.resolve().then(()=>e.execute(r.name,r.arguments))),{count:1}),n=k([t],([o])=>({id:r.id,content:typeof o=="string"?o:JSON.stringify(o)}));return Rt(n,o=>({id:r.id,content:JSON.stringify({error:String(o)})}))}function Se(r,e,t,n){let o=r[t];if(o!=null&&o.length>0)return o[o.length-1];let a=e[t];return a!==void 0?a:n}function $r(r,e){return new ze(r,e)}function Wr(r,e,t){let n=x(r),o=t?.condition!=null?x(t.condition):null,a=w(null,{name:t?.name?`${t.name}::null`:"handoff::null"});if(o==null)return z(n,l=>{if(l==null)return a;let u=w(l);return e(u)});let s=k([n,o],([l,u])=>({v:l,open:u===!0}),{name:t?.name?`${t.name}::router`:"handoff::router",describeKind:"derived"});return z(s,({v:l,open:u})=>{if(l==null)return a;if(!u)return w(l);let i=w(l);return e(i)})}function Kr(r,e,t){let n=x(r),o=e.map(s=>x(s)),a=[n,...o];return k(a,s=>{let l=s[0]??[],u=s.slice(1);return l.filter(i=>{for(let d of u)if(d!=null&&!d(i))return!1;return!0})},{name:t?.name??"tool-selector",describeKind:"derived",meta:C("tool_selector"),equals:(s,l)=>{let u=s,i=l;if(u.length!==i.length)return!1;for(let d=0;d<u.length;d++)if(u[d]!==i[d])return!1;return!0}})}function Gt(r){let e=r.thresholds??{};return t=>{let n=r.scoreFn(t);for(let o of Object.keys(e)){let a=e[o];if(a===void 0)continue;let s=n[o];if((Number.isFinite(s)?s:Number.NEGATIVE_INFINITY)<a)return!1}return!0}}function Vr(r){let e={persistence:r.persistenceThreshold??.3,personalValue:r.personalValueThreshold??.3},t=Gt({scoreFn:r.scoreFn,thresholds:e});return r.requireStructured?n=>{if(!t(n))return!1;let o=r.scoreFn(n).structure;return Number.isFinite(o)&&o>0}:t}function Bt(r,e,t,n){let o=t.name??n;return a=>{let s=w(a);return dt(t.adapter,[s],l=>e(l),{name:o,format:"json",systemPrompt:r,model:t.model,temperature:t.temperature??0,maxTokens:t.maxTokens})}}function mt(r,e){let t=e.maxExistingKeys??100,n=Bt(r,o=>JSON.stringify({input:o.raw,existingKeys:o.existingKeys}),e,"llmExtractor");return(o,a)=>{let s=t===Number.POSITIVE_INFINITY?[...a.keys()]:[...a.keys()].slice(0,t);return n({raw:o,existingKeys:s})}}function pt(r,e){let t=Bt(r,n=>JSON.stringify({memories:n}),e,"llmConsolidator");return n=>{let o=[...n.entries()].map(([a,s])=>({key:a,value:s}));return t(o)}}var Ce=Math.LN2/604800;function Ee(r){return r instanceof Map?r:new Map}function Ur(r,e,t){let n=new ce(r,t.graph),o=[],a;if(t.extractFn)a=t.extractFn;else if(t.adapter&&t.extractPrompt)a=mt(t.extractPrompt,{adapter:t.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(v,L)=>v==null?{upsert:[]}:a(v,L),l=e;if(t.admissionFilter){let v=x(e),L=t.admissionFilter;l=k([v],([R])=>{if(L(R))return R},{name:"admissionFilter",describeKind:"derived"})}let u;t.consolidateFn?u=t.consolidateFn:t.adapter&&t.consolidatePrompt&&(u=pt(t.consolidatePrompt,{adapter:t.adapter}));let i=t.consolidateTrigger;if(!i&&u&&t.reflection?.enabled!==!1){let v=t.reflection?.interval??3e5;i=bt(v,{period:v})}let d={score:t.score,cost:t.cost,budget:t.budget??2e3,context:t.context,consolidate:u,consolidateTrigger:i},c=xt(l,s,d);n.add(c.store.entries,{name:"store"}),n.add(c.compact,{name:"compact"}),n.add(c.size,{name:"size"});let m=null;t.vectorDimensions&&t.vectorDimensions>0&&t.embedFn&&(m=je({dimension:t.vectorDimensions}),n.add(m.entries,{name:"vectorIndex"}));let p=null;t.enableKnowledgeGraph&&(p=Ge(`${r}-kg`),n.mount("kg",p));let h=null;if(t.tiers){let v=t.tiers,L=v.decayRate??Ce,R=v.maxActive??1e3,A=v.archiveThreshold??.1,G=v.permanentFilter??(()=>!1),W=Fe({name:"permanent"});n.add(W.entries,{name:"permanent"});let I=new Set,O=P=>I.has(P)?"permanent":Ee(c.store.entries.cache).has(P)?"active":"archived",S=(P,T)=>{I.add(P),W.upsert(P,T)},_=new Map,N=c.store.entries,D=t.context?x(t.context):w(null),F=ne([N,D],([P,T])=>{let y=Ee(P),E=re(),j=[],B=[];for(let[$,J]of y){if(_.has($)||_.set($,E),G($,J)){B.push({key:$,value:J});continue}let H=t.score(J,T),ie=_.get($)??E,q=Number(E-ie)/1e9;Pe(H,q,L)<A&&j.push($)}for(let $ of _.keys())y.has($)||_.delete($);for(let{key:$,value:J}of B)I.has($)||S($,J);let K=y.size-I.size;if(K>R){let $=[...y.entries()].filter(([H])=>!I.has(H)).map(([H,ie])=>({key:H,score:t.score(ie,T)})).sort((H,ie)=>H.score-ie.score),J=K-R;for(let H=0;H<J&&H<$.length;H++){let ie=$[H].key;j.includes(ie)||j.push(ie)}}j.length>0&&Z(()=>{for(let $ of j)c.store.delete($)})});o.push(F.subscribe(()=>{}));let Y=null;v.archiveTier&&(Y=n.attachStorage([v.archiveTier],v.archiveStorageOptions??{})),h={permanent:W,activeEntries:N,archiveHandle:Y,tierOf:O,markPermanent:S}}if(m||p){let v=t.embedFn,L=t.entityFn,R=c.store.entries,A=ne([R],([G])=>{let W=Ee(G);for(let[I,O]of W){if(m&&v){let S=v(O);S&&m.upsert(I,S,O)}if(p&&L){let S=L(I,O);if(S){for(let _ of S.entities??[])p.upsertEntity(_.id,_.value);for(let _ of S.relations??[])p.link(_.from,_.to,_.relation,_.weight)}}}});o.push(A.subscribe(()=>{}))}let g=null,f=null,b=null,M=null;if(m||p){let v=t.retrieval?.topK??20,L=t.retrieval?.graphDepth??1,R=t.budget??2e3,A=t.cost,G=t.score,W=t.contextOf,I=t.contextWeight??0,O=t.context?x(t.context):w(null),S=(P,T)=>{if(!P||!T)return 0;let y=Math.min(P.length,T.length),E=0;for(;E<y&&P[E]===T[E];)E++;return E},_=(P,T,y)=>{let E=new Map,j=[];if(m&&y.vector){j=m.search(y.vector,v);for(let q of j){let U=P.get(q.id);U&&E.set(q.id,{value:U,sources:new Set(["vector"])})}}let B=[];if(p){let q=[...y.entityIds??[],...E.keys()],U=new Set,we=q;for(let ye=0;ye<L;ye++){let me=[];for(let Le of we){if(U.has(Le))continue;U.add(Le);let Ie=p.related(Le);for(let Ut of Ie){let he=Ut.to;if(!U.has(he)){me.push(he);let ft=P.get(he);if(ft){let gt=E.get(he);gt?gt.sources.add("graph"):E.set(he,{value:ft,sources:new Set(["graph"])}),B.push(he)}}}}we=me}}for(let[q,U]of P)E.has(q)||E.set(q,{value:U,sources:new Set(["store"])});let K=y.context?.length??0,$=[];for(let[q,{value:U,sources:we}]of E){let ye=W?W(U):void 0,me=G(U,T);if(I>0&&K>0){let Ie=S(y.context,ye);Ie>0&&(me=me*(1+I*Ie/K))}let Le=ye?{key:q,value:U,score:me,sources:[...we],context:ye}:{key:q,value:U,score:me,sources:[...we]};$.push(Le)}$.sort((q,U)=>U.score-q.score);let J=[],H=0;for(let q of $){let U=A(q.value);if(H+U>R&&J.length>0)break;J.push(q),H+=U}return{packed:J,trace:{vectorCandidates:j,graphExpanded:B,ranked:$,packed:J}}},N=(P,T)=>{if(P===T)return!0;if(P.length!==T.length)return!1;for(let y=0;y<P.length;y++)if(P[y]!==T[y])return!1;return!0},D=w([],{name:"retrieval",describeKind:"state",meta:C("retrieval_pipeline"),equals:N});n.add(D,{name:"retrieval"}),g=D;let F=w(null,{name:"retrievalTrace",describeKind:"state",meta:C("retrieval_trace")});n.add(F,{name:"retrievalTrace"}),f=F,b=P=>{let T=Ee(c.store.entries.cache),{packed:y,trace:E}=_(T,O.cache,P);return Z(()=>{D.emit(y),F.emit(E)}),y},M=P=>{let T=x(P),y=k([c.store.entries,O,T],([j,B,K])=>{if(K==null)return{packed:[],trace:null};let $=Ee(j),{packed:J,trace:H}=_($,B,K);return{packed:J,trace:H}},{name:"retrievalReactive::result",describeKind:"derived",meta:C("retrieval_reactive_result"),initial:{packed:[],trace:null}}),E=ne([y],([j])=>{let B=j;Z(()=>{D.emit(B.packed),B.trace&&F.emit(B.trace)})});return o.push(E.subscribe(()=>{})),k([y],([j])=>j.packed,{name:"retrievalReactive",describeKind:"derived",meta:C("retrieval_reactive"),initial:[],equals:N})}}return n.addDisposer(()=>{for(let v of o)v();o.length=0}),Object.assign(n,{distillBundle:c,compact:c.compact,size:c.size,vectors:m,kg:p,memoryTiers:h,retrieval:g,retrievalTrace:f,retrieve:b,retrieveReactive:M})}function xe(r){return r instanceof Map?r:new Map}function Hr(r,e,t){let n=je({dimension:t.dimension});r.add(n.entries,{name:"vectorIndex"});let a=ne([e.store.entries],([s])=>{let l=xe(s);for(let[u,i]of l){let d=t.embedFn(i);d&&n.upsert(u,d,i)}}).subscribe(()=>{});return r.addDisposer(a),{vectors:n,dispose:()=>a()}}function qr(r,e,t,n){let o=Ge(`${t}-kg`);r.mount(t,o);let s=ne([e.store.entries],([l])=>{let u=xe(l);for(let[i,d]of u){let c=n.entityFn(i,d);if(c){for(let m of c.entities??[])o.upsertEntity(m.id,m.value);for(let m of c.relations??[])o.link(m.from,m.to,m.relation,m.weight)}}}).subscribe(()=>{});return r.addDisposer(s),{kg:o,dispose:()=>s()}}function zr(r,e,t){let n=t.decayRate??Ce,o=t.maxActive??1e3,a=t.archiveThreshold??.1,s=t.permanentFilter??(()=>!1),l=Fe({name:"permanent"});r.add(l.entries,{name:"permanent"});let u=new Set,i=M=>u.has(M)?"permanent":xe(e.store.entries.cache).has(M)?"active":"archived",d=(M,v)=>{u.add(M),l.upsert(M,v)},c=new Map,m=e.store.entries,p=t.context?x(t.context):w(null),g=ne([m,p],([M,v])=>{let L=xe(M),R=re(),A=[],G=[];for(let[I,O]of L){if(c.has(I)||c.set(I,R),s(I,O)){G.push({key:I,value:O});continue}let S=t.score(O,v),_=c.get(I)??R,N=Number(R-_)/1e9;Pe(S,N,n)<a&&A.push(I)}for(let I of c.keys())L.has(I)||c.delete(I);for(let{key:I,value:O}of G)u.has(I)||d(I,O);let W=L.size-u.size;if(W>o){let I=[...L.entries()].filter(([S])=>!u.has(S)).map(([S,_])=>({key:S,score:t.score(_,v)})).sort((S,_)=>S.score-_.score),O=W-o;for(let S=0;S<O&&S<I.length;S++){let _=I[S].key;A.includes(_)||A.push(_)}}A.length>0&&Z(()=>{for(let I of A)e.store.delete(I)})}).subscribe(()=>{}),f=null;t.archiveTier&&(f=r.attachStorage([t.archiveTier],t.archiveStorageOptions??{}));let b=()=>{g(),f?.dispose()};return r.addDisposer(b),{tiers:{permanent:l,activeEntries:m,archiveHandle:f,tierOf:i,markPermanent:d},dispose:b}}function Yr(r,e){if(!r||!e)return 0;let t=Math.min(r.length,e.length),n=0;for(;n<t&&r[n]===e[n];)n++;return n}function Jr(r,e,t,n,o){let a=o.topK??20,s=o.graphDepth??1,l=o.budget??2e3,u=o.contextWeight??0,i=o.context?x(o.context):w(null),d=(f,b,M)=>{let v=new Map,L=[];if(t&&M.vector){L=t.search(M.vector,a);for(let O of L){let S=f.get(O.id);S&&v.set(O.id,{value:S,sources:new Set(["vector"])})}}let R=[];if(n){let O=[...M.entityIds??[],...v.keys()],S=new Set,_=O;for(let N=0;N<s;N++){let D=[];for(let F of _)if(!S.has(F)){S.add(F);for(let Y of n.related(F)){let P=Y.to;if(!S.has(P)){D.push(P);let T=f.get(P);if(T){let y=v.get(P);y?y.sources.add("graph"):v.set(P,{value:T,sources:new Set(["graph"])}),R.push(P)}}}}_=D}}for(let[O,S]of f)v.has(O)||v.set(O,{value:S,sources:new Set(["store"])});let A=M.context?.length??0,G=[];for(let[O,{value:S,sources:_}]of v){let N=o.contextOf?o.contextOf(S):void 0,D=o.score(S,b);if(u>0&&A>0){let Y=Yr(M.context,N);Y>0&&(D=D*(1+u*Y/A))}let F=N?{key:O,value:S,score:D,sources:[..._],context:N}:{key:O,value:S,score:D,sources:[..._]};G.push(F)}G.sort((O,S)=>S.score-O.score);let W=[],I=0;for(let O of G){let S=o.cost(O.value);if(I+S>l&&W.length>0)break;W.push(O),I+=S}return{packed:W,trace:{vectorCandidates:L,graphExpanded:R,ranked:G,packed:W}}},c=(f,b)=>{if(f===b)return!0;if(f.length!==b.length)return!1;for(let M=0;M<f.length;M++)if(f[M]!==b[M])return!1;return!0},m=w([],{name:"retrieval",describeKind:"state",meta:C("retrieval_pipeline"),equals:c});r.add(m,{name:"retrieval"});let p=w(null,{name:"retrievalTrace",describeKind:"state",meta:C("retrieval_trace")});return r.add(p,{name:"retrievalTrace"}),{retrieval:m,retrievalTrace:p,retrieve:f=>{let b=xe(e.store.entries.cache),{packed:M,trace:v}=d(b,i.cache,f);return Z(()=>{m.emit(M),p.emit(v)}),M},retrieveReactive:f=>{let b=x(f),M=k([e.store.entries,i,b],([R,A,G])=>{if(G==null)return{packed:[],trace:null};let W=xe(R),{packed:I,trace:O}=d(W,A,G);return{packed:I,trace:O}},{name:"retrievalReactive::result",describeKind:"derived",meta:C("retrieval_reactive_result"),initial:{packed:[],trace:null}}),L=ne([M],([R])=>{let A=R;Z(()=>{m.emit(A.packed),A.trace&&p.emit(A.trace)})}).subscribe(()=>{});return r.addDisposer(L),k([M],([R])=>R.packed,{name:"retrievalReactive",describeKind:"derived",meta:C("retrieval_reactive"),initial:[],equals:c})}}}function Qr(r,e,t){let n=r.describe({actor:e,detail:"full"}),o=t?.groupByTags??!0,a=t?.separator??`
|
|
5
|
+
`,s=[],l=t?.sinceVersion;for(let[u,i]of Object.entries(n.nodes)){let d=i.meta??{},c=d.description,m=d.format;if(!c&&!m)continue;if(l!=null&&i.v!=null){let b=l.get(u);if(b!=null&&b.id===i.v.id&&i.v.version<=b.version)continue}let p=c??u,h=i.value,g=d.unit,f;m==="currency"&&typeof h=="number"?f=`$${h.toFixed(2)}`:m==="percentage"&&typeof h=="number"?f=`${(h*100).toFixed(1)}%`:h==null?f="(no value)":f=String(h),g&&m!=="currency"&&m!=="percentage"&&(f=`${f} ${g}`),s.push({path:u,description:p,formatted:f})}if(s.length===0)return"";if(o){let u=new Map,i=[];for(let c of s){let p=n.nodes[c.path].meta?.tags;if(p&&p.length>0){let h=p[0],g=u.get(h);g||(g=[],u.set(h,g)),g.push(c)}else i.push(c)}if(u.size===0)return s.map(c=>`- ${c.description}: ${c.formatted}`).join(a);let d=[];for(let[c,m]of[...u.entries()].sort((p,h)=>p[0].localeCompare(h[0])))d.push(`[${c}]${a}${m.map(p=>`- ${p.description}: ${p.formatted}`).join(a)}`);return i.length>0&&d.push(i.map(c=>`- ${c.description}: ${c.formatted}`).join(a)),d.join(a+a)}return s.map(u=>`- ${u.description}: ${u.formatted}`).join(a)}var $t=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
6
|
+
|
|
7
|
+
Given a natural-language description, produce a JSON graph specification with this structure:
|
|
8
|
+
|
|
9
|
+
{
|
|
10
|
+
"name": "<graph_name>",
|
|
11
|
+
"nodes": {
|
|
12
|
+
"<node_name>": {
|
|
13
|
+
"type": "state" | "derived" | "producer" | "effect" | "operator",
|
|
14
|
+
"initial": <initial_value_for_state_nodes>,
|
|
15
|
+
"deps": ["<dep_node_name>", ...],
|
|
16
|
+
"meta": {
|
|
17
|
+
"description": "<human-readable purpose>",
|
|
18
|
+
"type": "string" | "number" | "boolean" | "integer" | "enum",
|
|
19
|
+
"range": [min, max],
|
|
20
|
+
"values": ["a", "b"],
|
|
21
|
+
"format": "currency" | "percentage" | "status",
|
|
22
|
+
"access": "human" | "llm" | "both" | "system",
|
|
23
|
+
"unit": "<unit>",
|
|
24
|
+
"tags": ["<tag>"]
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
Rules:
|
|
31
|
+
- "state" nodes have no deps and hold user/LLM-writable values (knobs). Use "initial" for the starting value.
|
|
32
|
+
- "derived" nodes have deps and compute from them (pure, no side effects).
|
|
33
|
+
- "effect" nodes have deps but produce side effects (no return value).
|
|
34
|
+
- "producer" nodes have no deps but generate values asynchronously.
|
|
35
|
+
- "operator" nodes are parameterized transformations with deps.
|
|
36
|
+
- Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
|
|
37
|
+
- meta.description is required for every node.
|
|
38
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Wt(r,e,t){let o=[{role:"system",content:t?.systemPromptExtra?`${$t}
|
|
39
|
+
|
|
40
|
+
${t.systemPromptExtra}`:$t},{role:"user",content:r}],a=e.invoke(o,{model:t?.model,temperature:t?.temperature??0,maxTokens:t?.maxTokens,signal:t?.signal}),l=(await ge(a)).content.trim();l.startsWith("```")&&(l=Re(l));let u;try{u=JSON.parse(l)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${l.slice(0,200)}`)}return Lt(u,{catalog:t?.catalog})}function Xr(r,e,t){let n=x(r);return z(n,o=>!o||typeof o!="string"||o.trim().length===0?w(null):Te(a=>{let s=new AbortController,l=!1;return Wt(o,e,{...t,signal:s.signal}).then(u=>{if(l){u.destroy();return}a.emit(u),a.down([[le]])}).catch(u=>{l||a.down([[X,u]])}),()=>{l=!0,s.abort()}},{name:"graphFromSpec::call"}))}function Zr(r){let e={},t=r.type;return t==="enum"&&Array.isArray(r.values)?(e.type="string",e.enum=r.values):t==="integer"?e.type="integer":t==="number"?e.type="number":t==="boolean"?e.type="boolean":t==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(r.range)&&r.range.length===2&&(e.minimum=r.range[0],e.maximum=r.range[1]),typeof r.format=="string"&&(e.description=`Format: ${r.format}`),typeof r.unit=="string"&&(e.description?e.description+=` (${r.unit})`:e.description=`Unit: ${r.unit}`),e}function en(r,e){let t=r.describe({actor:e,detail:"full"}),n=[],o=[],a=[];for(let[s,l]of Object.entries(t.nodes)){if(l.type!=="state"||s.includes("::__meta__::")||l.status==="completed"||l.status==="errored")continue;let u=l.meta??{},i=u.access;if(i==="human"||i==="system")continue;let d=u.description??`Set the value of ${s}`,c=Zr(u),m={type:"object",required:["value"],properties:{value:c},additionalProperties:!1},p=s.replace(/::/g,"__");n.push({type:"function",function:{name:p,description:d,parameters:m}}),o.push({name:s,description:d,inputSchema:m});let h=r,g=e,f=l.v;a.push({name:s,description:d,parameters:m,handler(b){return h.set(s,b.value,g?{actor:g}:void 0),b.value},...f!=null?{version:{id:f.id,version:f.version}}:{}})}return{openai:n,mcp:o,definitions:a}}var tn=`You are a reactive graph optimizer for GraphReFly.
|
|
41
|
+
|
|
42
|
+
Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
|
|
43
|
+
|
|
44
|
+
Return ONLY valid JSON with this structure:
|
|
45
|
+
{
|
|
46
|
+
"summary": "<one-line summary of the strategy>",
|
|
47
|
+
"reasoning": "<explanation of why these changes help>",
|
|
48
|
+
"operations": [
|
|
49
|
+
{ "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
|
|
50
|
+
{ "type": "remove_node", "name": "<name>" },
|
|
51
|
+
{ "type": "connect", "from": "<source>", "to": "<target>" },
|
|
52
|
+
{ "type": "disconnect", "from": "<source>", "to": "<target>" },
|
|
53
|
+
{ "type": "set_value", "name": "<name>", "value": <new_value> },
|
|
54
|
+
{ "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
|
|
55
|
+
]
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
Rules:
|
|
59
|
+
- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
|
|
60
|
+
- Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
|
|
61
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Kt(r,e,t,n){let{expand:o,...a}=r.describe({actor:n?.actor,detail:"standard"}),s=[{role:"system",content:tn},{role:"user",content:JSON.stringify({graph:a,problem:e})}],l=t.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens,signal:n?.signal}),i=(await ge(l)).content.trim();i.startsWith("```")&&(i=i.replace(/^```(?:json)?\s*/,"").replace(/\s*```$/,""));let d;try{d=JSON.parse(i)}catch{throw new Error(`suggestStrategy: LLM response is not valid JSON: ${i.slice(0,200)}`)}let c=d;if(typeof c.summary!="string")throw new Error("suggestStrategy: missing 'summary' in response");if(typeof c.reasoning!="string")throw new Error("suggestStrategy: missing 'reasoning' in response");if(!Array.isArray(c.operations))throw new Error("suggestStrategy: missing 'operations' array in response");return{summary:c.summary,reasoning:c.reasoning,operations:c.operations}}function rn(r,e,t,n){let o=x(e),a=kt(o,r);return z(a,s=>{if(s==null)return w(null);let[l,u]=s;return!u||!l||typeof l!="string"||l.trim().length===0?w(null):u.destroyed?w(null):Te(i=>{let d=new AbortController,c=!1;return Kt(u,l,t,{...n,signal:d.signal}).then(m=>{c||(i.emit(m),i.down([[le]]))}).catch(m=>{c||i.down([[X,m]])}),()=>{c=!0,d.abort()}},{name:"suggestStrategy::call"})})}var Vt=new Set(["state","derived","producer","operator","effect"]);function nn(r){let e=[];if(r==null||typeof r!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let t=r;if((typeof t.name!="string"||t.name.length===0)&&e.push("Missing or empty 'name' field"),t.nodes==null||typeof t.nodes!="object"||Array.isArray(t.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let n=new Set(Object.keys(t.nodes));for(let[o,a]of Object.entries(t.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${o}": must be an object`);continue}let s=a;if((typeof s.type!="string"||!Vt.has(s.type))&&e.push(`Node "${o}": invalid type "${String(s.type)}" (expected: ${[...Vt].join(", ")})`),Array.isArray(s.deps))for(let l of s.deps)typeof l=="string"&&!n.has(l)&&e.push(`Node "${o}": dep "${l}" does not reference an existing node`)}if(!Array.isArray(t.edges))t.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let a=0;a<t.edges.length;a++){let s=t.edges[a];if(s==null||typeof s!="object"){e.push(`Edge [${a}]: must be an object`);continue}let l=s;(typeof l.from!="string"||!n.has(l.from))&&e.push(`Edge [${a}]: 'from' "${String(l.from)}" does not reference an existing node`),(typeof l.to!="string"||!n.has(l.to))&&e.push(`Edge [${a}]: 'to' "${String(l.to)}" does not reference an existing node`);let u=`${l.from}->${l.to}`;o.has(u)&&e.push(`Edge [${a}]: duplicate edge ${u}`),o.add(u)}}return{valid:e.length===0,errors:e}}export{nr as a,or as b,$e as c,et as d,sr as e,ir as f,lr as g,dr as h,tt as i,We as j,nt as k,cr as l,ot as m,st as n,it as o,ke as p,lt as q,vr as r,Mr as s,Lr as t,dt as u,Ar as v,Sr as w,Cr as x,Ir as y,Dr as z,_r as A,Fr as B,jr as C,Gr as D,He as E,ut as F,qe as G,ct as H,ze as I,$r as J,Wr as K,Kr as L,Gt as M,Vr as N,mt as O,pt as P,Ce as Q,Ur as R,Hr as S,qr as T,zr as U,Jr as V,Qr as W,Wt as X,Xr as Y,en as Z,Kt as _,rn as $,nn as aa,on as ba};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as q}from"./chunk-
|
|
1
|
+
import{c as q}from"./chunk-K54OKWNY.js";import{b as v}from"./chunk-4UUDNFYG.js";import{b as T}from"./chunk-LWGLBCMU.js";import{b as y}from"./chunk-XRSHMHEG.js";import{j as g}from"./chunk-4JBKKUCJ.js";import{B as d}from"./chunk-UMH3HSP7.js";import{D as w,G as h}from"./chunk-7AJKUA36.js";import{b as N}from"./chunk-QYADASLV.js";var $={};N($,{JobFlowGraph:()=>u,JobQueueGraph:()=>p,jobFlow:()=>k,jobQueue:()=>E});var x=2147483647;function J(s,e){if(!Number.isFinite(s)||!Number.isInteger(s)||s<0)throw new Error(`${e} must be a non-negative integer`);return s}function c(s,e){return q("job_queue",s,e)}var p=class extends g{_pending;_jobs;_seq=0;pending;jobs;depth;constructor(e,t={}){super(e,t.graph),this._pending=v([],{name:"pending"}),this._jobs=T({name:"jobs"}),this.pending=this._pending.items,this.jobs=this._jobs.entries,this.add(this.pending,{name:"pending"}),this.add(this.jobs,{name:"jobs"}),this.depth=h([this.pending],([n])=>n.length,{name:"depth",describeKind:"derived",meta:c("queue_depth"),initial:0}),this.add(this.depth,{name:"depth"}),this.addDisposer(d(this.depth))}enqueue(e,t={}){let n=t.id??`${this.name}-${++this._seq}`;if(this._jobs.get(n)!==void 0)throw new Error(`jobQueue("${this.name}"): duplicate job id "${n}"`);let m={id:n,payload:e,attempts:0,metadata:Object.freeze({...t.metadata??{}}),state:"queued"};return this._jobs.set(n,m),this._pending.append(n),n}claim(e=1){let t=J(e,"job queue claim limit");if(t===0)return[];let n=[];for(;n.length<t&&this.pending.cache.length!==0;){let a=this._pending.pop(0),o=this._jobs.get(a);if(!o||o.state!=="queued")continue;let i={...o,state:"inflight",attempts:o.attempts+1};this._jobs.set(a,i),n.push(i)}return n}ack(e){let t=this._jobs.get(e);return!t||t.state!=="inflight"?!1:(this._jobs.delete(e),!0)}nack(e,t={}){let n=this._jobs.get(e);return!n||n.state!=="inflight"?!1:t.requeue??!0?(this._jobs.set(e,{...n,state:"queued"}),this._pending.append(e),!0):(this._jobs.delete(e),!0)}},u=class extends g{_stageNames;_queues=new Map;_completed;completed;completedCount;constructor(e,t={}){super(e,t.graph);let n=(t.stages??["incoming","processing","done"]).map(o=>o.trim());if(n.length<2)throw new Error(`jobFlow("${e}"): requires at least 2 stages`);if(new Set(n).size!==n.length)throw new Error(`jobFlow("${e}"): stage names must be unique`);this._stageNames=Object.freeze([...n]);for(let o of this._stageNames){let i=E(`${e}-${o}`);this._queues.set(o,i),this.mount(o,i)}this._completed=y([],{name:"completed"}),this.completed=this._completed.entries,this.add(this.completed,{name:"completed"}),this.completedCount=h([this.completed],([o])=>o.length,{name:"completedCount",describeKind:"derived",meta:c("job_flow_completed_count"),initial:0}),this.add(this.completedCount,{name:"completedCount"}),this.addDisposer(d(this.completedCount));let a=Math.max(1,J(t.maxPerPump??x,"job flow maxPerPump"));for(let o=0;o<this._stageNames.length;o+=1){let i=this._stageNames[o],l=this.queue(i),b=o+1<this._stageNames.length?this.queue(this._stageNames[o+1]):null,_=w([l.pending],()=>{let f=0;for(;f<a;){let j=l.claim(1);if(j.length===0)break;let r=j[0];if(!r)break;b?b.enqueue(r.payload,{metadata:{...r.metadata,job_flow_from:i}}):this._completed.append(r),l.ack(r.id),f+=1}},{name:`pump_${i}`,describeKind:"effect",meta:c("job_flow_pump")});this.add(_,{name:`pump_${i}`}),this.addDisposer(d(_))}}stages(){return this._stageNames}queue(e){let t=this._queues.get(e);if(!t)throw new Error(`jobFlow("${this.name}"): unknown stage "${e}"`);return t}enqueue(e,t={}){return this.queue(this._stageNames[0]).enqueue(e,t)}retainedCompleted(){return this.completed.cache}};function E(s,e){return new p(s,e)}function k(s,e){return new u(s,e)}export{p as a,u as b,E as c,k as d,$ as e};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{a as Se}from"./chunk-SGS4OJGS.js";import{a as Le}from"./chunk-ESMPEKEV.js";import{a as re,b as _e}from"./chunk-N2KKISCE.js";import{B as Ee}from"./chunk-UMH3HSP7.js";import{A as we,C as L,E as ne,F as Me,G as Oe,e as $e,f as Te,i as Y,k as Ne,l as xe,m as Ae,o as K,p as Pe,s as W}from"./chunk-7AJKUA36.js";import{b as Q,c as me,d as be,e as Z,f as ye,g as ve,h as z,i as ee,j as te}from"./chunk-CK2E7BTU.js";function Ie(e,t,r,n={}){let o=t in e.nodes,s=r in e.nodes;if(!o)return se(t,r,"no-such-from");if(!s)return se(t,r,"no-such-to");let i=n.maxDepth;if(i!=null&&(!Number.isInteger(i)||i<0))throw new Error("explainPath: maxDepth must be an integer >= 0");if(t===r){if(n.findCycle===!0){let u=lt(e,t,n);if(u!=null)return u}let l=oe(t,e.nodes[t],0,n);return ie(t,r,[l])}if(i===0)return se(t,r,"no-path");let a=je(e,t,r,i);return a.found?ie(t,r,Be(e,a.pathOrder,n)):se(t,r,a.truncated?"max-depth-exceeded":"no-path")}function je(e,t,r,n){let o=new Map,s=[{path:r,depth:0}],i=new Set([r]),a=0,l=!1;for(;a<s.length;){let h=s[a++];if(h.path===t)break;if(n!=null&&h.depth>=n){let g=e.nodes[h.path];g?.deps&&g.deps.length>0&&(l=!0);continue}let p=e.nodes[h.path];if(p==null)continue;let f=p.deps??[],c=new Map;for(let g=0;g<f.length;g++){let b=f[g];if(!b)continue;let v=c.get(b);v==null&&(v=[],c.set(b,v)),v.push(g)}for(let[g,b]of c)i.has(g)||(i.add(g),o.set(g,{from:h.path,depIndices:b}),s.push({path:g,depth:h.depth+1}))}if(!o.has(t))return{found:!1,pathOrder:[],truncated:l};let u=[{path:t}],d=t;for(;d!==r;){let h=o.get(d);if(h==null)return{found:!1,pathOrder:[],truncated:!1};u[u.length-1].depIndices=h.depIndices,u.push({path:h.from}),d=h.from}return{found:!0,pathOrder:u,truncated:!1}}function lt(e,t,r){let n=e.nodes[t];if(n==null)return null;let o=n.deps??[],s=[];for(let a=0;a<o.length;a++)o[a]===t&&s.push(a);if(s.length>0){let a=oe(t,n,0,r);a.dep_index=s[0];let l=oe(t,n,1,r);return ie(t,t,[a,l])}let i=null;for(let a=0;a<o.length;a++){let l=o[a];if(!l||l===t)continue;let u=je(e,l,t,r.maxDepth);u.found&&(i==null||u.pathOrder.length<i.pathOrder.length)&&(i=u,i={found:!0,pathOrder:[{path:t,depIndices:[a]},...u.pathOrder],truncated:!1})}return i==null?null:ie(t,t,Be(e,i.pathOrder,r))}function Be(e,t,r){return t.map((n,o)=>{let s=e.nodes[n.path],i=oe(n.path,s,o,r);return n.depIndices!=null&&n.depIndices.length>0&&(i.dep_index=n.depIndices[0],n.depIndices.length>1&&(i.dep_indices=[...n.depIndices])),i})}function oe(e,t,r,n){let o={path:e,type:t.type,hop:r};t.status!==void 0&&(o.status=t.status),"value"in t&&(o.value=t.value),t.v!=null&&(o.v=t.v);let s=n.annotations?.get(e)??t.annotation;s!=null&&(o.annotation=s);let i=n.lastMutations?.get(e)??t.lastMutation;return i!=null&&(o.lastMutation=i),o}function ie(e,t,r){return Fe(e,t,!0,"ok",r)}function se(e,t,r){return Fe(e,t,!1,r,[])}function Fe(e,t,r,n,o){let s=ct(e,t,r,n,o);return{from:e,to:t,found:r,reason:n,steps:o,text:s,toJSON(){return{from:e,to:t,found:r,reason:n,steps:o}}}}function ct(e,t,r,n,o){if(!r)switch(n){case"no-such-from":return`explainPath: no node named "${e}"`;case"no-such-to":return`explainPath: no node named "${t}"`;case"max-depth-exceeded":return`explainPath: no path from "${e}" to "${t}" within maxDepth`;default:return`explainPath: no path from "${e}" to "${t}"`}let s=[`Causal path: ${e} \u2192 ${t} (${o.length} step(s))`];for(let i of o){let l=` ${i.hop===0?"\xB7":"\u2193"} ${i.path} (${i.type}${i.status?`/${i.status}`:""})`;if(s.push(l),"value"in i&&s.push(` value: ${dt(i.value)}`),i.annotation!=null&&s.push(` annotation: ${i.annotation}`),i.lastMutation!=null){let u=i.lastMutation.actor;s.push(` actor: ${u.type}${u.id?`:${u.id}`:""}`)}}return s.join(`
|
|
2
|
+
`)}function dt(e){if(e===void 0)return"<sentinel>";if(e===null)return"null";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);try{let t=JSON.stringify(e);return t.length>80?`${t.slice(0,77)}...`:t}catch{return String(e)}}var A={object:56,array:64,string:40,number:8,boolean:4,null:0,undefined:0,symbol:40,bigint:16,function:120,map:72,set:72,mapEntry:40,setEntry:24,date:24,regexp:48,error:64,url:80,promise:48,weakmap:40,weakset:40},ft=Symbol.for("sizeof");function He(e){let t=new WeakSet,r=new WeakSet,n=[e],o=0;for(;n.length>0;){let s=n.pop();o+=pt(s,t,r,n)}return o}function pt(e,t,r,n){if(e==null)return 0;switch(typeof e){case"number":return A.number;case"boolean":return A.boolean;case"string":return A.string+e.length*2;case"bigint":return A.bigint+ht(e);case"symbol":return A.symbol;case"function":return t.has(e)?0:(t.add(e),A.function);case"undefined":return 0}let s=e;if(t.has(s))return 0;t.add(s);let i=s[ft];if(typeof i=="function")try{let u=i.call(s);if(typeof u=="number"&&Number.isFinite(u))return u}catch{}if(s instanceof Date)return A.date;if(s instanceof RegExp)return A.regexp+s.source.length*2;if(s instanceof Error){let u=s.message?s.message.length*2:0,d=s.stack?s.stack.length*2:0;return A.error+u+d}if(typeof URL<"u"&&s instanceof URL)return A.url+s.href.length*2;if(typeof Promise<"u"&&s instanceof Promise)return A.promise;if(s instanceof WeakMap)return A.weakmap;if(s instanceof WeakSet)return A.weakset;if(s instanceof Map){let u=A.map;for(let[d,h]of s)u+=A.mapEntry,n.push(d),n.push(h);return u}if(s instanceof Set){let u=A.set;for(let d of s)u+=A.setEntry,n.push(d);return u}if(Array.isArray(s)){let u=A.array+s.length*8;for(let d of s)n.push(d);return u}if(s instanceof ArrayBuffer)return r.has(s)?0:(r.add(s),s.byteLength);if(ArrayBuffer.isView(s)){let u=s;return r.has(u.buffer)?48:(r.add(u.buffer),u.buffer.byteLength+48)}let a=A.object,l=Object.keys(s);for(let u of l){a+=A.string+u.length*2;try{n.push(s[u])}catch{}}return a}function ht(e){let t=e<0n?-e:e;if(t===0n)return 0;let r=t.toString(2).length;return Math.ceil(r/32)*8}function Ve(e,t){let r=t?.topN??10,n=e.describe({detail:"standard"}),o=[],s=e._collectObserveTargets;typeof s=="function"&&s.call(e,"",o);let i=new Map;for(let[p,f]of o)i.set(p,f);let a=[];for(let[p,f]of Object.entries(n.nodes)){let c=i.get(p),g=c instanceof L?c:null,b=g?He(g.cache):0,v=g?g._sinkCount:0,w=f.deps?.length??0,m=f.type==="effect"&&v===0,y=v===0?f.type==="effect"?"orphan-effect":f.type==="derived"?"idle-derived":f.type==="producer"?"idle-producer":null:null;a.push({path:p,type:f.type,status:f.status??"unknown",valueSizeBytes:b,subscriberCount:v,depCount:w,isOrphanEffect:m,orphanKind:y})}let l=a.reduce((p,f)=>p+f.valueSizeBytes,0),u=(p,f)=>[...a].sort(f??((c,g)=>g[p]-c[p])).slice(0,r),d=a.filter(p=>p.orphanKind!=null),h=a.filter(p=>p.isOrphanEffect);return{nodeCount:a.length,edgeCount:n.edges.length,subgraphCount:n.subgraphs.length,nodes:a,totalValueSizeBytes:l,hotspots:{byValueSize:u("valueSizeBytes"),bySubscriberCount:u("subscriberCount"),byDepCount:u("depCount")},orphans:d,orphanEffects:h}}function Re(e){return e>=768&&e<=879||e>=1155&&e<=1161||e>=1425&&e<=1469||e>=1552&&e<=1562||e>=1611&&e<=1631||e>=1648&&e===1648||e>=1750&&e<=1756||e>=1759&&e<=1764||e>=1767&&e<=1768||e>=1770&&e<=1773||e>=1840&&e<=1866||e>=1958&&e<=1968||e>=2304&&e<=2307||e>=2362&&e<=2383||e>=2385&&e<=2391||e>=2402&&e<=2403||e>=2433&&e<=2435||e>=2492&&e<=2509||e>=2561&&e<=2563||e>=2620&&e<=2641||e>=2672&&e<=2673||e>=2677&&e===2677||e>=3633&&e===3633||e>=3636&&e<=3642||e>=3655&&e<=3662||e>=3761&&e===3761||e>=3764&&e<=3772||e>=3784&&e<=3790||e>=7616&&e<=7679||e>=8400&&e<=8447||e>=65024&&e<=65039||e>=65056&&e<=65071||e===8205?0:e>=4352&&e<=4447||e>=8986&&e<=8987||e>=9001&&e<=9002||e>=9193&&e<=9203||e>=9208&&e<=9210||e>=9725&&e<=9726||e>=9748&&e<=9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e>=9898&&e<=9899||e>=9917&&e<=9918||e>=9924&&e<=9925||e===9934||e===9940||e===9962||e>=9970&&e<=9971||e===9973||e===9978||e===9981||e===9986||e===9989||e>=9992&&e<=9997||e===9999||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e>=10548&&e<=10549||e>=11013&&e<=11015||e>=11035&&e<=11036||e===11088||e===11093||e>=11904&&e<=12350||e>=12352&&e<=12447||e>=12448&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12784&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=40959||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65131||e>=65281&&e<=65376||e>=65504&&e<=65510||e>=126980&&e===126980||e===127183||e>=127344&&e<=127345||e===127358||e===127359||e===127374||e>=127377&&e<=127386||e>=127456&&e<=127487||e>=127488&&e<=127490||e===127514||e===127535||e>=127538&&e<=127546||e>=127568&&e<=127569||e>=127744&&e<=129535||e>=129536&&e<=129791||e>=129792&&e<=130047||e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}function ae(e){let t=0;for(let r of e)t+=Re(r.codePointAt(0));return t}function ze(e,t){if(t<=0)return"";let r=0,n="";for(let o of e){let s=Re(o.codePointAt(0));if(r+s>t){if(t<=1)return"\u2026";for(;r+1>t&&n.length>0;){let i=[...n].pop();n=n.slice(0,-i.length),r-=Re(i.codePointAt(0))}return`${n}\u2026`}n+=o,r+=s}return n}var gt={horizontal:"\u2500",vertical:"\u2502",cornerTL:"\u250C",cornerTR:"\u2510",cornerBL:"\u2514",cornerBR:"\u2518",tDown:"\u252C",tUp:"\u2534",tRight:"\u251C",tLeft:"\u2524",cross:"\u253C",arrowRight:"\u25B6",arrowDown:"\u25BC",arrowLeft:"\u25C0",arrowUp:"\u25B2",boxTL:"\u250C",boxTR:"\u2510",boxBL:"\u2514",boxBR:"\u2518",boxH:"\u2500",boxV:"\u2502"},mt={horizontal:"-",vertical:"|",cornerTL:"+",cornerTR:"+",cornerBL:"+",cornerBR:"+",tDown:"+",tUp:"+",tRight:"+",tLeft:"+",cross:"+",arrowRight:">",arrowDown:"v",arrowLeft:"<",arrowUp:"^",boxTL:"+",boxTR:"+",boxBL:"+",boxBR:"+",boxH:"-",boxV:"|"};function Ue(e,t){let r=t.charset==="ascii"?mt:gt,n=e.width,o=e.height,s=Array.from({length:o},()=>Array.from({length:n},()=>" ")),i=Array.from({length:o},()=>Array.from({length:n},()=>"empty"));for(let a of e.edges)yt(s,i,r,a);for(let a of e.boxes)bt(s,i,r,a,t.labelOf(a.id));return s.map(a=>Ot(a.join(""))).join(`
|
|
3
|
+
`)}function bt(e,t,r,n,o){let{x:s,y:i,w:a,h:l}=n;if(a<2||l<2){l>0&&Ke(e,t,s,i,a,o);return}V(e,t,s,i,r.boxTL);for(let d=s+1;d<s+a-1;d+=1)V(e,t,d,i,r.boxH);V(e,t,s+a-1,i,r.boxTR);for(let d=i+1;d<i+l-1;d+=1){V(e,t,s,d,r.boxV);for(let h=s+1;h<s+a-1;h+=1)Je(e,t,h,d," ","empty");V(e,t,s+a-1,d,r.boxV)}V(e,t,s,i+l-1,r.boxBL);for(let d=s+1;d<s+a-1;d+=1)V(e,t,d,i+l-1,r.boxH);V(e,t,s+a-1,i+l-1,r.boxBR);let u=i+Math.floor(l/2);Ke(e,t,s+1,u,a-2,o)}function V(e,t,r,n,o){Je(e,t,r,n,o,o===" "?"empty":o==="\u2500"||o==="-"?"boxH":o==="\u2502"||o==="|"?"boxV":"boxCorner")}function Je(e,t,r,n,o,s){if(n<0||n>=e.length)return;let i=e[n];r<0||r>=i.length||(i[r]=o,t[n][r]=s)}function Ke(e,t,r,n,o,s){if(n<0||n>=e.length)return;let i=r,a=o;for(let l of s){let u=ae(l);if(u!==0){if(a<u)break;i>=0&&i<e[n].length&&(e[n][i]=l,t[n][i]="label",u===2&&i+1<e[n].length&&(e[n][i+1]="",t[n][i+1]="label")),i+=u,a-=u}}for(;a>0;)i>=0&&i<e[n].length&&(e[n][i]=" ",t[n][i]="empty"),i+=1,a-=1}function yt(e,t,r,n){let o=n.points;if(o.length<2)return;for(let l=0;l+1<o.length;l+=1)vt(e,t,r,o[l],o[l+1]);for(let l=1;l+1<o.length;l+=1){let u=o[l-1],d=o[l],h=o[l+1],p=xt(u,d,h,r);p&&qe(e,t,d.x,d.y,p,"edgeCorner")}let s=o[o.length-1],i=o[o.length-2],a=wt(i,s,r);a&&qe(e,t,s.x,s.y,a,"arrow")}function vt(e,t,r,n,o){if(!(n.x===o.x&&n.y===o.y)){if(n.y===o.y){let s=n.y,i=Math.min(n.x,o.x),a=Math.max(n.x,o.x);for(let l=i;l<=a;l+=1)We(e,t,l,s,r,"h")}else if(n.x===o.x){let s=n.x,i=Math.min(n.y,o.y),a=Math.max(n.y,o.y);for(let l=i;l<=a;l+=1)We(e,t,s,l,r,"v")}}}function We(e,t,r,n,o,s){if(n<0||n>=e.length)return;let i=e[n];if(r<0||r>=i.length)return;let a=t[n][r];if(!(a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label")){if(a==="empty"){i[r]=s==="h"?o.horizontal:o.vertical,t[n][r]=s==="h"?"edgeH":"edgeV";return}if(a==="edgeH"&&s==="v"){i[r]=o.cross,t[n][r]="edgeCorner";return}if(a==="edgeV"&&s==="h"){i[r]=o.cross,t[n][r]="edgeCorner";return}}}function qe(e,t,r,n,o,s){if(n<0||n>=e.length)return;let i=e[n];if(r<0||r>=i.length)return;let a=t[n][r];a==="boxH"||a==="boxV"||a==="boxCorner"||a==="label"||(i[r]=o,t[n][r]=s)}function xt(e,t,r,n){let o=e.y===t.y,s=t.y===r.y;if(o===s)return;if(o){let l=e.x<t.x,u=r.y>t.y;return l&&u?n.cornerTR:l&&!u?n.cornerBR:!l&&u?n.cornerTL:n.cornerBL}let i=e.y<t.y,a=r.x>t.x;return i&&a?n.cornerBL:i&&!a?n.cornerBR:!i&&a?n.cornerTL:n.cornerTR}function wt(e,t,r){if(t.x>e.x)return r.arrowRight;if(t.x<e.x)return r.arrowLeft;if(t.y>e.y)return r.arrowDown;if(t.y<e.y)return r.arrowUp}function Ot(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===32;)t-=1;return e.slice(0,t)}function Qe(e){let t=Et(e);_t(t),St(t),Rt(t),Dt(t,e);let r=kt(t,e),{width:n,height:o}=Tt(t),s=[];for(let i of t.layers)for(let a of i)a.isVirtual||s.push({id:a.id,layer:a.layer,order:a.order,x:a.x,y:a.y,w:a.w,h:a.h});return{boxes:s,edges:r,width:n,height:o}}function Et(e){let t=new Map;for(let o of e.nodes)t.set(o,{id:o,isVirtual:!1,layer:-1,order:0,x:0,y:0,w:e.widthCells(o),h:e.heightCells(o),in:[],out:[]});let r=[],n=0;for(let o of e.edges){if(o.from===o.to)continue;let s=t.get(o.from),i=t.get(o.to);if(!s||!i)continue;let a={chainId:n++,chainFrom:o.from,chainTo:o.to,fromId:o.from,toId:o.to,hopIndex:0,chainLen:1};s.out.push(a),i.in.push(a),r.push(a)}return{nodes:t,layers:[],hops:r}}function _t(e){let t=new Map;for(let s of e.nodes.values())t.set(s.id,s.in.length);let r=[];for(let s of e.nodes.values())(t.get(s.id)??0)===0&&(s.layer=0,r.push(s));let n=new Set,o=0;for(;o<r.length;){let s=r[o++];if(!n.has(s.id)){n.add(s.id);for(let i of s.out){let a=e.nodes.get(i.toId);a.layer=Math.max(a.layer,s.layer+1);let l=(t.get(a.id)??0)-1;t.set(a.id,l),l<=0&&r.push(a)}}}for(let s of e.nodes.values())s.layer<0&&(s.layer=0)}function St(e){let t=Math.max(0,...Array.from(e.nodes.values(),s=>s.layer)),r=Array.from({length:t+1},()=>[]);for(let s of e.nodes.values())r[s.layer].push(s);let n=[],o=0;for(let s of e.hops){let i=e.nodes.get(s.fromId),a=e.nodes.get(s.toId),l=a.layer-i.layer;if(l<=0){i.out=i.out.filter(h=>h!==s),a.in=a.in.filter(h=>h!==s);continue}if(l===1){s.hopIndex=0,s.chainLen=1,n.push(s);continue}i.out=i.out.filter(h=>h!==s),a.in=a.in.filter(h=>h!==s);let u=i;for(let h=1;h<l;h+=1){let p=`__virt_${o++}__`,f={id:p,isVirtual:!0,layer:i.layer+h,order:0,x:0,y:0,w:0,h:1,in:[],out:[]};e.nodes.set(p,f),r[f.layer].push(f);let c={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:p,hopIndex:h-1,chainLen:l};u.out.push(c),f.in.push(c),n.push(c),u=f}let d={chainId:s.chainId,chainFrom:s.chainFrom,chainTo:s.chainTo,fromId:u.id,toId:a.id,hopIndex:l-1,chainLen:l};u.out.push(d),a.in.push(d),n.push(d)}for(let s of r)for(let i=0;i<s.length;i+=1)s[i].order=i;e.layers=r,e.hops=n}function Rt(e){for(let r=0;r<4;r+=1){for(let n=1;n<e.layers.length;n+=1)Ye(e,e.layers[n],"in"),ue(e.layers[n]);for(let n=e.layers.length-2;n>=0;n-=1)Ye(e,e.layers[n],"out"),ue(e.layers[n])}for(let r=0;r<2;r+=1){let n=!1;for(let o=1;o<e.layers.length;o+=1){let s=e.layers[o];for(let i=0;i+1<s.length;i+=1){let a=Xe(e,s[i],s[i+1],"in");[s[i],s[i+1]]=[s[i+1],s[i]],ue(s),Xe(e,s[i],s[i+1],"in")<a?n=!0:([s[i],s[i+1]]=[s[i+1],s[i]],ue(s))}}if(!n)break}}function Ye(e,t,r){let n=new Map;for(let o of t){let s=r==="in"?o.in:o.out;if(s.length===0){n.set(o.id,o.order);continue}let i=0,a=0;for(let l of s){let u=e.nodes.get(r==="in"?l.fromId:l.toId);u&&(i+=u.order,a+=1)}n.set(o.id,a===0?o.order:i/a)}t.sort((o,s)=>{let i=n.get(o.id),a=n.get(s.id);return i!==a?i-a:o.order-s.order})}function ue(e){for(let t=0;t<e.length;t+=1)e[t].order=t}function Xe(e,t,r,n){let o=n==="in"?t.in:t.out,s=n==="in"?r.in:r.out,i=0;for(let a of o)for(let l of s){let u=e.nodes.get(n==="in"?a.fromId:a.toId)?.order??0,d=e.nodes.get(n==="in"?l.fromId:l.toId)?.order??0;(t.order<r.order&&u>d||t.order>r.order&&u<d)&&(i+=1)}return i}function Dt(e,t){t.direction==="LR"?Gt(e,t):Ct(e,t)}function Gt(e,t){let r=[],n=0;for(let o=0;o<e.layers.length;o+=1){r.push(n);let s=0;for(let i of e.layers[o])s=Math.max(s,i.w);n+=s+t.layerGap}for(let o=0;o<e.layers.length;o+=1)for(let s of e.layers[o])s.x=r[o];for(let o of e.layers){let s=0;for(let i of o)i.y=s,s+=i.h+t.nodeGap}Ze(e,t,"y")}function Ct(e,t){let r=[],n=0;for(let o=0;o<e.layers.length;o+=1){r.push(n);let s=0;for(let i of e.layers[o])s=Math.max(s,i.h);n+=s+t.layerGap}for(let o=0;o<e.layers.length;o+=1)for(let s of e.layers[o])s.y=r[o];for(let o of e.layers){let s=0;for(let i of o)i.x=s,s+=i.w+t.nodeGap}Ze(e,t,"x")}function Ze(e,t,r){let n=s=>r==="y"?s.h:s.w,o=t.nodeGap;for(let s=0;s<2;s+=1){let i=s===0?e.layers.slice(1):e.layers.slice(0,-1).reverse();for(let a of i){let l=new Map;for(let d of a){let h=s===0?d.in:d.out;if(h.length===0)continue;let p=[];for(let c of h){let g=e.nodes.get(s===0?c.fromId:c.toId);if(!g)continue;let b=r==="y"?g.y:g.x;p.push(b+Math.floor(n(g)/2))}if(p.length===0)continue;p.sort((c,g)=>c-g);let f=p[Math.floor(p.length/2)];l.set(d.id,f-Math.floor(n(d)/2))}let u=0;for(let d of a){let h=l.get(d.id),p=r==="y"?d.y:d.x,c=Math.max(h??p,u);r==="y"?d.y=c:d.x=c,u=c+n(d)+o}}}}function kt(e,t){let r=new Map;for(let u of e.hops){let d=r.get(u.chainId);d?d.push(u):r.set(u.chainId,[u])}for(let u of r.values())u.sort((d,h)=>d.hopIndex-h.hopIndex);let n=t.direction==="LR",o=u=>n?u.x:u.y,s=u=>n?u.w:u.h,i=u=>n?u.y+Math.floor(u.h/2):u.x+Math.floor(u.w/2),a=new Map;for(let u=0;u+1<e.layers.length;u+=1){let d=e.layers[u],h=e.layers[u+1],p=0;for(let _ of d)p=Math.max(p,o(_)+s(_));let f=Number.POSITIVE_INFINITY;for(let _ of h)f=Math.min(f,o(_));let c=Number.isFinite(f)?f-1:p,g=Math.max(1,c-p+1),b=[];for(let _ of d)for(let R of _.out)b.push(R);b.sort((_,R)=>{let k=i(e.nodes.get(_.fromId)),$=i(e.nodes.get(R.fromId));if(k!==$)return k-$;let G=i(e.nodes.get(_.toId)),D=i(e.nodes.get(R.toId));return G-D});let v=[],w=new Map;for(let _ of b){let R=i(e.nodes.get(_.fromId)),k=i(e.nodes.get(_.toId)),$=Math.min(R,k),G=Math.max(R,k),D=-1;for(let P=0;P<v.length;P+=1){let F=v[P],H=!0;for(let U of F)if(U.lo<=G&&$<=U.hi){H=!1;break}if(H){F.push({lo:$,hi:G}),D=P;break}}D<0&&(v.push([{lo:$,hi:G}]),D=v.length-1),w.set(_,D)}let m=v.length,y=g>=Math.max(3,m+2),S=y?p+1:p,x=y?c-1:c,O=Math.max(1,x-S+1);for(let _ of b){let R=w.get(_),k;if(m<=1)k=S+Math.floor(O/2);else{let $=(O-1)/(m-1);k=S+Math.floor(R*$)}a.set(_,Math.max(p,Math.min(c,k)))}}let l=[];for(let[,u]of r){let d=[];for(let p=0;p<u.length;p+=1){let f=u[p],c=e.nodes.get(f.fromId),g=e.nodes.get(f.toId),b=a.get(f),v=c.isVirtual?o(c):o(c)+s(c),w=g.isVirtual?o(g):o(g)-1,m=i(c),y=i(g);p===0&&le(d,n,v,m),m!==y&&(le(d,n,b,m),le(d,n,b,y)),le(d,n,w,y)}let h=u[0];l.push({from:h.chainFrom,to:h.chainTo,points:$t(d)})}return l}function le(e,t,r,n){e.push(t?{x:r,y:n}:{x:n,y:r})}function $t(e){let t=[];for(let r of e){let n=t[t.length-1];(!n||n.x!==r.x||n.y!==r.y)&&t.push(r)}return t}function Tt(e){let t=0,r=0;for(let n of e.layers)for(let o of n)t=Math.max(t,o.x+o.w),r=Math.max(r,o.y+o.h);return{width:t,height:r}}var Nt=24,At=4,Pt=1,Mt=3;function et(e,t){let r=Lt(t.direction),n=Math.max(3,t.maxLabelWidth??Nt),o=t.asciiCharset??"unicode",s=Object.keys(e.nodes).sort(),i=new Set(s),a=e.edges.filter(f=>i.has(f.from)&&i.has(f.to)),l=new Map,u=new Map;for(let f of s){let c=ze(f,n);l.set(f,c),u.set(f,ae(c)+4)}let d=Qe({nodes:s,edges:a,widthCells:f=>u.get(f)??3,heightCells:()=>Mt,layerGap:At,nodeGap:Pt,direction:r}),h=Ue(d,{charset:o,labelOf:f=>l.get(f)??f}),p=t.logger;return p&&p(h),h}function Lt(e){if(e===void 0||e==="LR")return"LR";if(e==="TD")return"TD";throw new Error(`ascii describe supports direction "LR" or "TD" only; got ${String(e)}`)}var N="::",B="__meta__",q=1;function tt(e,t){let r=Math.max(16,e.size*4),n=0;for(;e.size>0;){if(n++>=r){console.error(`[Graph "${t}".destroy] disposer drain exceeded cap (${r}); ${e.size} disposer(s) discarded`),e.clear();return}let o=e.values().next();if(o.done)return;let s=o.value;e.delete(s);try{s()}catch(i){console.error(`[Graph "${t}".destroy] disposer threw:`,i)}}}function It(e){let t=[];for(let r of Object.keys(e).sort()){let n=e[r].v;n!=null&&t.push(`${r} ${n.id} ${n.version}`)}return t.join(`
|
|
4
|
+
`)}function nt(e){if(e.version!==q)throw new Error(`unsupported snapshot version ${String(e.version)} (expected ${q})`);for(let t of["name","nodes","edges","subgraphs"])if(!(t in e))throw new Error(`snapshot missing required key "${t}"`);if(typeof e.name!="string")throw new TypeError("snapshot 'name' must be a string");if(typeof e.nodes!="object"||e.nodes===null||Array.isArray(e.nodes))throw new TypeError("snapshot 'nodes' must be an object");if(!Array.isArray(e.edges))throw new TypeError("snapshot 'edges' must be an array");if(!Array.isArray(e.subgraphs))throw new TypeError("snapshot 'subgraphs' must be an array")}function jt(e,t){let r=new WeakMap,n=(o,s)=>{if(Object.is(o,s))return!0;if(o==null||s==null||typeof o!="object"||typeof s!="object")return!1;let i=r.get(o);if(i==null&&(i=new WeakSet,r.set(o,i)),i.has(s))return!0;i.add(s);let a=o.constructor,l=s.constructor;if(a!==l)return!1;if(o instanceof Date)return o.getTime()===s.getTime();if(o instanceof RegExp)return o.source===s.source&&o.flags===s.flags;if(Array.isArray(o)){let p=s;if(o.length!==p.length)return!1;for(let f=0;f<o.length;f++)if(!n(o[f],p[f]))return!1;return!0}if(o instanceof Map){let p=s;if(o.size!==p.size)return!1;for(let[f,c]of o)if(!p.has(f)||!n(c,p.get(f)))return!1;return!0}if(o instanceof Set){let p=s;if(o.size!==p.size)return!1;for(let f of o){let c=!1;for(let g of p)if(n(f,g)){c=!0;break}if(!c)return!1}return!0}if(ArrayBuffer.isView(o)){let p=o,f=s;if(p.length!==f.length)return!1;for(let c=0;c<p.length;c++)if(p[c]!==f[c])return!1;return!0}let u=Object.keys(o),d=Object.keys(s);if(u.length!==d.length)return!1;let h=new Set(d);for(let p of u)if(!h.has(p)||!n(o[p],s[p]))return!1;return!0};return n(e,t)}function Ge(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(Ge);let t=e,r=Object.keys(t).sort(),n={};for(let o of r)n[o]=Ge(t[o]);return n}function Bt(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Ft(e){return e.replaceAll("\\","\\\\").replaceAll('"','\\"')}function Ht(e){return e==="TD"?"down":e==="BT"?"up":e==="RL"?"left":"right"}function ot(e){let t=new Set,r=[];function n(o,s){let i=`${o}\0${s}`;t.has(i)||(t.add(i),r.push([o,s]))}for(let[o,s]of Object.entries(e.nodes)){let i=s.deps;if(i)for(let a of i)n(a,o)}for(let o of e.edges)n(o.from,o.to);return r}function it(e){if(e===void 0)return"LR";if(e==="TD"||e==="LR"||e==="BT"||e==="RL")return e;throw new Error(`invalid diagram direction ${String(e)}; expected one of: TD, LR, BT, RL`)}function Vt(e,t){let r=t.includeEdges??!0,n=t.includeSubgraphs??!0,{expand:o,...s}=e,i={...s,edges:r?e.edges:[],subgraphs:n?e.subgraphs:[]},a=JSON.stringify(Ge(i),null,t.indent??2);return t.logger?.(a),a}function zt(e,t){let r=t.includeEdges??!0,n=t.includeSubgraphs??!0,o=[];o.push(`Graph ${e.name}`),o.push("Nodes:");for(let i of Object.keys(e.nodes).sort()){let a=e.nodes[i];o.push(`- ${i} (${a.type}/${a.status}): ${de(a.value)}`)}if(r){o.push("Edges:");for(let i of e.edges)o.push(`- ${i.from} -> ${i.to}`)}if(n){o.push("Subgraphs:");for(let i of e.subgraphs)o.push(`- ${i}`)}let s=o.join(`
|
|
5
|
+
`);return t.logger?.(s),s}function at(e,t){let r=it(t.direction),n=Object.keys(e.nodes).sort(),o=new Map;for(let i=0;i<n.length;i+=1)o.set(n[i],`n${i}`);let s=[`flowchart ${r}`];for(let i of n){let a=o.get(i);s.push(` ${a}["${Bt(i)}"]`)}for(let[i,a]of ot(e)){let l=o.get(i),u=o.get(a);!l||!u||s.push(` ${l} --> ${u}`)}return s.join(`
|
|
6
|
+
`)}function Kt(e,t){let r=at(e,t);return Wt(r)}function Wt(e,t){let r=t?.theme??"default",n=t?.autoSync??!0,s=JSON.stringify({code:e,mermaid:{theme:r},autoSync:n}),i=new TextEncoder().encode(s),a="";for(let u=0;u<i.length;u++)a+=String.fromCharCode(i[u]);return`https://mermaid.live/edit#base64:${globalThis.btoa(a).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`}function qt(e,t){let r=it(t.direction),n=Object.keys(e.nodes).sort(),o=new Map;for(let i=0;i<n.length;i+=1)o.set(n[i],`n${i}`);let s=[`direction: ${Ht(r)}`];for(let i of n){let a=o.get(i);s.push(`${a}: "${Ft(i)}"`)}for(let[i,a]of ot(e)){let l=o.get(i),u=o.get(a);!l||!u||s.push(`${l} -> ${u}`)}return s.join(`
|
|
7
|
+
`)}function Ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ce(e){let t="^";for(let r=0;r<e.length;r+=1){let n=e[r];if(n==="*"){t+=".*";continue}if(n==="?"){t+=".";continue}if(n==="["){let o=e.indexOf("]",r+1);if(o<=r+1){t+="\\[";continue}let s=e.slice(r+1,o);s.startsWith("!")&&(s=`^${s.slice(1)}`),s=s.replace(/\\/g,"\\\\"),t+=`[${s}]`,r=o;continue}t+=Ut(n)}return t+="$",new RegExp(t)}var Jt={data:"\x1B[32m",dirty:"\x1B[33m",resolved:"\x1B[36m",invalidate:"\x1B[93m",pause:"\x1B[90m",resume:"\x1B[96m",complete:"\x1B[34m",error:"\x1B[31m",teardown:"\x1B[91m",derived:"\x1B[35m",path:"\x1B[90m",reset:"\x1B[0m"},Yt={data:"",dirty:"",resolved:"",invalidate:"",pause:"",resume:"",complete:"",error:"",teardown:"",derived:"",path:"",reset:""};function de(e){if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean"||e==null)return String(e);try{return JSON.stringify(e)}catch{return"[unserializable]"}}function Xt(e){return e==="none"?Yt:e==="ansi"||e==null?Jt:{data:e.data??"",dirty:e.dirty??"",resolved:e.resolved??"",invalidate:e.invalidate??"",pause:e.pause??"",resume:e.resume??"",complete:e.complete??"",error:e.error??"",teardown:e.teardown??"",derived:e.derived??"",path:e.path??"",reset:e.reset??""}}function rt(e){if(e==null)return{};let t=e.detail;return t==="full"?{...e,structured:e.structured??!0,timeline:e.timeline??!0,causal:e.causal??!0,derived:e.derived??!0}:t==="minimal"?{...e,structured:e.structured??!0}:e.format==="stage-log"?{...e,structured:e.structured??!0,timeline:e.timeline??!0}:e}function Qt(e,t,r){for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);if(o<32||o===127)throw new Error(`Graph "${t}": ${r} "${e}" must not contain control character (U+${o.toString(16).padStart(4,"0").toUpperCase()} at index ${n})`)}}function De(e,t,r){if(e==="")throw new Error(`Graph "${t}": ${r} name must be non-empty`);if(e.includes(N))throw new Error(`Graph "${t}": ${r} "${e}" must not contain '${N}' (path separator)`);if(e===B)throw new Error(`Graph "${t}": ${r} name "${B}" is reserved for meta companion paths`);Qt(e,t,r)}function Zt(e,t){if(e==="")throw new Error(`Graph "${t}": resolve path must be non-empty`);let r=e.split(N);for(let n of r)if(n==="")throw new Error(`Graph "${t}": resolve path has empty segment`);return r}function en(e,t){let r=!1;for(let o of e)if(!t.isMetaPassthrough(o[0])){r=!0;break}return r?e.filter(o=>t.isMetaPassthrough(o[0])):e}function ut(e){for(let t of e._mounts.values())ut(t);for(let t of e._nodes.values())try{t.down([[z]],{internal:!0})}catch{}}var Ce=class e{name;opts;config;_nodes=new Map;_nodeToName=new WeakMap;_mounts=new Map;_parent=void 0;_storageDisposers=new Set;_disposers=new Set;_destroyed=!1;_topology;_topologyEmitters=new Set;constructor(t,r){if(t==="")throw new Error("Graph name must be non-empty");if(t.includes(N))throw new Error(`Graph name must not contain '${N}' (got "${t}")`);if(t===B)throw new Error(`Graph name "${B}" is reserved for meta companion paths`);this.name=t,this.opts=Object.freeze({...r??{}}),this.config=r?.config??we,this._traceRing=new Se(r?.traceCapacity??1e3),r?.versioning!=null&&this.setVersioning(r.versioning)}ancestors(t=!0){let r=[],n=t?this:this._parent;for(;n!=null;)r.push(n),n=n._parent;return r}get topology(){return this._topology==null&&(this._topology=Me(t=>{let r=n=>{t.emit(n)};return this._topologyEmitters.add(r),()=>{this._topologyEmitters.delete(r)}},{name:`${this.name}_topology`})),this._topology}_emitTopology(t){if(!(this._topology==null||this._topologyEmitters.size===0))for(let r of this._topologyEmitters)r(t)}add(t,r){let n=t.name,o=r?.name??n;if(o==null||o==="")throw new Error(`Graph "${this.name}": graph.add requires a non-empty name \u2014 pass via opts.name or set it on the node (e.g. state(0, { name: "x" }))`);let s=o,i=r?.annotation;if(De(s,this.name,"add"),this._mounts.has(s))throw new Error(`Graph "${this.name}": name "${s}" is already a mount point`);if(this._nodes.has(s))throw new Error(`Graph "${this.name}": node "${s}" already exists`);let a=this._nodeToName.get(t);if(a!==void 0)throw new Error(`Graph "${this.name}": node instance already registered as "${a}"`);return this._nodes.set(s,t),this._nodeToName.set(t,s),this._emitTopology({kind:"added",name:s,nodeKind:"node"}),i!=null&&(this._annotations.set(s,i),this.config.inspectorEnabled&&this._traceRing.push({path:s,annotation:i,timestamp_ns:K()})),t}setVersioning(t){if(t!=null)for(let r of this._nodes.values())r instanceof L&&r._applyVersioning(t)}remove(t){De(t,this.name,"remove");let r=this._mounts.get(t);if(r){let s={kind:"mount",nodes:[],mounts:[]},i=[];r._collectObserveTargets("",i);for(let[a,l]of i)a.includes(`${N}${B}${N}`)||s.nodes.push(a);return s.nodes.sort(),s.mounts.push(t),s.mounts.push(...r._collectSubgraphs(`${t}${N}`)),this._mounts.delete(t),r._parent=void 0,ut(r),this._emitTopology({kind:"removed",name:t,nodeKind:"mount",audit:s}),s}let n=this._nodes.get(t);if(!n)throw new Error(`Graph "${this.name}": unknown node or mount "${t}"`);this._nodes.delete(t),this._nodeToName.delete(n),n.down([[z]],{internal:!0});let o={kind:"node",nodes:[t],mounts:[]};return this._emitTopology({kind:"removed",name:t,nodeKind:"node",audit:o}),o}removeAll(t){let r=typeof t=="function"?t:(()=>{let s=ce(t);return i=>s.test(i)})(),n={kind:"mount",nodes:[],mounts:[]},o=[...this._nodes.keys(),...this._mounts.keys()].filter(s=>r(s));for(let s of o){let i=this.remove(s);n.nodes.push(...i.nodes),n.mounts.push(...i.mounts)}return n.nodes.sort(),n.mounts.sort(),n}[Symbol.iterator](){let t=[...this._nodes.keys()].sort(),r=this._nodes,n=0;return{[Symbol.iterator](){return this},next(){if(n>=t.length)return{value:void 0,done:!0};let o=t[n++];return{value:[o,r.get(o)],done:!1}}}}node(t){if(t==="")throw new Error(`Graph "${this.name}": node name must be non-empty`);if(t.includes(N))return this.resolve(t);let r=this._nodes.get(t);if(!r)throw new Error(`Graph "${this.name}": unknown node "${t}"`);return r}get(t){return this.node(t).cache}set(t,r,n){let o=n?.internal===!0;this.node(t).down([[Q,r]],{actor:n?.actor,internal:o,delivery:"write"})}setAll(t,r){let n=Symbol.iterator in t?t:Object.entries(t);Ae(()=>{for(let[o,s]of n)this.set(o,s,r)})}invalidate(t,r){let n=r?.internal===!0;this.node(t).down([[Z]],{actor:r?.actor,internal:n,delivery:"write"})}error(t,r,n){let o=n?.internal===!0;this.node(t).down([[te,r]],{actor:n?.actor,internal:o,delivery:"write"})}complete(t,r){let n=r?.internal===!0;this.node(t).down([[ee]],{actor:r?.actor,internal:n,delivery:"write"})}edges(t){let r=t?.recursive===!0,n=new Map;if(!r){for(let[l,u]of this._nodes)n.set(u,l);let a=[];for(let[l,u]of this._nodes)if(u instanceof L)for(let d of u._deps){let h=n.get(d.node);h!=null&&a.push([h,l])}return a.sort((l,u)=>l[0]<u[0]?-1:l[0]>u[0]?1:l[1]<u[1]?-1:l[1]>u[1]?1:0),a}let o=[];this._collectObserveTargets("",o);let s=new Map;for(let[a,l]of o)s.set(l,a);let i=[];for(let[a,l]of o)if(l instanceof L)for(let u of l._deps){let d=s.get(u.node);d!=null&&i.push([d,a])}return i.sort((a,l)=>a[0]<l[0]?-1:a[0]>l[0]?1:a[1]<l[1]?-1:a[1]>l[1]?1:0),i}mount(t,r){if(De(t,this.name,"mount"),this._nodes.has(t))throw new Error(`Graph "${this.name}": cannot mount at "${t}" \u2014 node with that name exists`);if(this._mounts.has(t))throw new Error(`Graph "${this.name}": mount "${t}" already exists`);if(r===this)throw new Error(`Graph "${this.name}": cannot mount a graph into itself`);if(r._parent!=null)throw new Error(`Graph "${this.name}": this child graph is already mounted on "${r._parent.name}"`);for(let n=this;n!=null;n=n._parent)if(n===r)throw new Error(`Graph "${this.name}": mount("${t}", \u2026) would create a mount cycle`);return this._mounts.set(t,r),r._parent=this,this._emitTopology({kind:"added",name:t,nodeKind:"mount"}),r}resolve(t){let r=Zt(t,this.name);return this._resolveFromSegments(r)}tryResolve(t){try{return this.resolve(t)}catch{return}}_resolveFromSegments(t){let r=t;if(r[0]===this.name&&(r=r.slice(1),r.length===0))throw new Error(`Graph "${this.name}": resolve path ends at graph name only`);let n=r[0],o=r.slice(1);if(o.length===0){let a=this._nodes.get(n);if(a)return a;throw this._mounts.has(n)?new Error(`Graph "${this.name}": path ends at subgraph "${n}" \u2014 not a node (GRAPHREFLY-SPEC \xA73.5)`):new Error(`Graph "${this.name}": unknown name "${n}"`)}let s=this._nodes.get(n);if(s&&o.length>0&&o[0]===B)return this._resolveMetaChainFromNode(s,o,r.join(N));let i=this._mounts.get(n);if(!i)throw this._nodes.has(n)?new Error(`Graph "${this.name}": "${n}" is a node; trailing path "${o.join(N)}" is invalid`):new Error(`Graph "${this.name}": unknown mount or node "${n}"`);return i.resolve(o.join(N))}_resolveMetaChainFromNode(t,r,n){let o=t,s=0,i=[...r];for(;s<i.length;){if(i[s]!==B)throw new Error(`Graph "${this.name}": expected ${B} segment in meta path "${n}"`);if(s+1>=i.length)throw new Error(`Graph "${this.name}": meta path requires a key after ${B} in "${n}"`);let a=i[s+1],l=o.meta[a];if(!l)throw new Error(`Graph "${this.name}": unknown meta "${a}" in path "${n}"`);o=l,s+=2}return o}signal(t,r){if(r?.internal!==!0){for(let o of t)if(this.config.messageTier(o[0])===3)throw new Error(`Graph "${this.name}": Graph.signal() rejects tier-3 messages (DATA / RESOLVED). Broadcast is for control-plane tiers (START / DIRTY / INVALIDATE / PAUSE / RESUME / COMPLETE / ERROR / TEARDOWN). For per-node value writes, use Graph.set or graph.node(name).down(...).`)}let n=[];if(this._signalDeliver(t,r??{},new Set,n),n.length>0)throw n[0]}_signalDeliver(t,r,n,o){for(let l of this._mounts.values())l._signalDeliver(t,r,n,o);let i=r.internal===!0?{internal:!0}:{actor:r.actor,delivery:"signal"},a=en(t,this.config);for(let l of[...this._nodes.keys()].sort()){let u=this._nodes.get(l);if(!n.has(u)){n.add(u);try{u.down(t,i)}catch(d){if(d instanceof W)throw d;o.push(d)}a.length!==0&&this._signalMetaSubtree(u,a,n,i,o)}}}_signalMetaSubtree(t,r,n,o,s){for(let i of Object.keys(t.meta).sort()){let a=t.meta[i];if(!n.has(a)){n.add(a);try{a.down(r,o)}catch(l){if(l instanceof W)throw l;s.push(l)}this._signalMetaSubtree(a,r,n,o,s)}}}describe(t){if(t?.reactive===!0)return this._describeReactive(t);let r=t?.actor,n=t?.filter,o=re(t?.detail,t?.fields),s=t?.format==="spec",i=s?re("minimal"):o,a=[];this._collectObserveTargets("",a);let l=new Map;for(let[x,O]of a)l.set(O,x);let u=[];{let x=a.map(([,R])=>R),O=new Set(l.values()),_=0;for(;x.length>0;){let R=x.shift();if(R instanceof L)for(let k of R._deps){let $=k.node;if(l.has($))continue;let G=$.name??"",D=G;if(!D||O.has(D))if(G){let P=2;for(;O.has(`${G}#${P}`);)P++;D=`${G}#${P}`}else for(D=`__internal__/${_++}`;O.has(D);)D=`__internal__/${_++}`;l.set($,D),O.add(D),u.push([D,$]),x.push($)}}}let d=[...a,...u],h={};for(let[x,O]of d){if(r!=null&&!O.allowsObserve(r))continue;let _=_e(O,i),R=O instanceof L?O._deps.map(D=>l.get(D.node)??D.node.name??""):[],{name:k,...$}=_,G={...$,deps:R};if(!s){let D=this._annotations.get(x);D!=null&&(G.annotation=D)}if(n!=null)if(typeof n=="function"){let D=n;if(!(D.length>=2?D(x,G):D(G)))continue}else{let D=!0;for(let[P,F]of Object.entries(n)){let H=P==="deps_includes"?"depsIncludes":P==="meta_has"?"metaHas":P;if(H==="depsIncludes"){if(!G.deps.includes(String(F))){D=!1;break}continue}if(H==="metaHas"){if(!Object.hasOwn(G.meta??{},String(F))){D=!1;break}continue}if(G[H]!==F){D=!1;break}}if(!D)continue}h[x]=G}let p=new Set(Object.keys(h)),f=[];for(let[x,O]of d)if(O instanceof L)for(let _ of O._deps){let R=l.get(_.node);R!=null&&f.push([R,x])}f.sort((x,O)=>x[0]<O[0]?-1:x[0]>O[0]?1:x[1]<O[1]?-1:x[1]>O[1]?1:0);let c=f.map(([x,O])=>({from:x,to:O}));(r!=null||n!=null)&&(c=c.filter(x=>p.has(x.from)&&p.has(x.to)));let g=this._collectSubgraphs(""),b=r!=null||n!=null?g.filter(x=>{let O=`${x}${N}`;return[...p].some(_=>_===x||_.startsWith(O))}):g,v=this,w=t,m={name:this.name,nodes:h,edges:c,subgraphs:b,expand(x){let O={...w,format:void 0};return Array.isArray(x)?(O.fields=x,O.detail=void 0):(O.detail=x,O.fields=void 0),v.describe(O)}},y=t??{},S=y.format;return S==="json"?Vt(m,y):S==="pretty"?zt(m,y):S==="mermaid"?at(m,y):S==="mermaid-url"?Kt(m,y):S==="d2"?qt(m,y):S==="ascii"?et(m,y):m}_collectSubgraphs(t){let r=[];for(let n of[...this._mounts.keys()].sort()){let o=t===""?n:`${t}${n}`;r.push(o),r.push(...this._mounts.get(n)._collectSubgraphs(`${o}${N}`))}return r}resourceProfile(t){return Ve(this,t)}reachable(t,r,n={}){return n.withDetail===!0?st(this.describe(),t,r,{...n,withDetail:!0}):st(this.describe(),t,r,n)}explain(t,r,n){return n?.reactive===!0?this._explainReactive(t,r,n):this._explainStatic(t,r,n)}_explainStatic(t,r,n){let o=this.describe({detail:"full"}),s=new Map(this._annotations),i=new Map;for(let[a,l]of Object.entries(o.nodes))l.lastMutation!=null&&i.set(a,l.lastMutation);return Ie(o,t,r,{...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{},annotations:s,lastMutations:i})}_describeReactive(t){let r={...t,reactive:!1},n=t.reactiveName??"describe",o=0,s=ne(o,{name:`${n}_version`}),i=this.observe({timeline:!0,structured:!0}),a=!1,l=!1,u=()=>{a||l||(a=!0,xe(()=>{a=!1,!l&&(o+=1,s.emit(o))}))},d=i.onEvent(b=>{let v=b.type;v!=="data"&&v!=="error"&&v!=="complete"&&v!=="teardown"||u()}),h=[],p=new WeakSet,f=b=>{if(p.has(b)||l)return;p.add(b);let v=b.topology.subscribe(w=>{for(let m of w){if(m[0]!==Q)continue;let y=m[1];if(u(),y.kind==="added"&&y.nodeKind==="mount"){let S=b._mounts.get(y.name);S!=null&&f(S)}}});h.push(v);for(let w of b._mounts.keys()){let m=b._mounts.get(w);m!=null&&f(m)}};f(this);let c;try{c=Oe([s],()=>this.describe(r),{name:n,describeKind:"derived",meta:{domain:"audit",kind:"describe"},equals:(b,v)=>b===v})}catch(b){d();for(let v of h)v();throw i.dispose(),b}let g=Ee(c);return{node:c,dispose(){l=!0,d();for(let b of h)b();h.length=0,i.dispose(),g()}}}_explainReactive(t,r,n){let o=0,s=ne(o,{name:"explain_version"}),i=this.observe({timeline:!0,structured:!0}),a=!1,l=!1,u=i.onEvent(f=>{let c=f.type;c!=="data"&&c!=="error"&&c!=="complete"&&c!=="teardown"||a||l||(a=!0,xe(()=>{a=!1,!l&&(o+=1,s.emit(o))}))}),d={...n?.maxDepth!=null?{maxDepth:n.maxDepth}:{},...n?.findCycle===!0?{findCycle:!0}:{}},h;try{h=Oe([s],()=>this._explainStatic(t,r,d),{name:n?.name??"explain",describeKind:"derived",meta:{domain:"audit",kind:"explain_path",from:t,to:r},equals:(f,c)=>f.found===c.found&&f.reason===c.reason&&f.steps.length===c.steps.length&&nn(f.steps,c.steps)})}catch(f){throw u(),i.dispose(),f}let p=Ee(h);return{node:h,dispose(){l=!0,u(),i.dispose(),p()}}}_pathsMatching(t){let r=ce(t),n=[];return this._collectObserveTargets("",n),n.map(([o])=>o).filter(o=>r.test(o))}_collectObserveTargets(t,r){for(let n of[...this._mounts.keys()].sort()){let o=t===""?n:`${t}${N}${n}`;this._mounts.get(n)._collectObserveTargets(o,r)}for(let n of[...this._nodes.keys()].sort()){let o=this._nodes.get(n),s=t===""?n:`${t}${N}${n}`;r.push([s,o]),this._appendMetaObserveTargets(s,o,r)}}_appendMetaObserveTargets(t,r,n){for(let o of Object.keys(r.meta).sort()){let s=r.meta[o],i=`${t}${N}${B}${N}${o}`;n.push([i,s]),this._appendMetaObserveTargets(i,s,n)}}observe(t,r){let n=typeof t=="string",s=rt(n?r:t),i=s.structured===!0||s.timeline===!0||s.causal===!0||s.derived===!0||s.detail==="minimal"||s.detail==="full"||s.format!=null,a=s.actor;if(n){let d=t,h=this.resolve(d);if(a!=null&&!h.allowsObserve(a))throw new W({actor:a,action:"observe",nodeName:d});return i?this._buildStructuredObserver([[d,h]],s,"one"):{subscribe(p){return h.subscribe(p)},up(p){try{h.up?.(p)}catch(f){if(f instanceof W)return;throw f}}}}let l=[];this._collectObserveTargets("",l),l.sort((d,h)=>d[0]<h[0]?-1:d[0]>h[0]?1:0);let u=a==null?l:l.filter(([,d])=>d.allowsObserve(a));return i?this._buildStructuredObserver(u,s,"all"):{subscribe:d=>{let h=u.map(([p,f])=>f.subscribe(c=>{d(p,c)}));return()=>{for(let p of h)p()}},up:(d,h)=>{try{this.resolve(d).up?.(h)}catch(p){if(p instanceof W)return;throw p}}}}_buildStructuredObserver(t,r,n){let o=n==="one"?t[0]?.[0]:void 0,s=i=>{if(n==="one"&&o!=null){let d=this.resolve(o);return this._buildStructuredObserver([[o,d]],i,"one")}let a=[];this._collectObserveTargets("",a),a.sort((d,h)=>d[0]<h[0]?-1:d[0]>h[0]?1:0);let l=i.actor,u=l==null?a:a.filter(([,d])=>d.allowsObserve(l));return this._buildStructuredObserver(u,i,"all")};return this._createObserveResult(t,r,s)}_createObserveResult(t,r,n){let o=r.timeline===!0,s=r.causal===!0,i=r.derived===!0,a=r.detail==="minimal",l=this.config.inspectorEnabled,u=(s||i)&&l,d=r.maxEvents,h=d!=null&&d>0?new Se(d):null,p=[],f=new Set,c={},g=new Set,b=0,v=0,w=0,m=0,y=0,S=0,x=!1,O=!1,_=0,R=new Map,k=new Map,$=new Map,G=E=>{h?h.push(E):p.push(E);for(let T of f)T(E)},D=()=>o?{timestamp_ns:K(),in_batch:Ne(),batch_id:_}:{},P=(E,T)=>{if(!(!u||!(E instanceof L)))return E._setInspectorHook(I=>{if(I.kind==="dep_message")R.set(E,I.depIndex);else if(I.kind==="run"){let J=I.batchData.map((C,M)=>C!=null&&C.length>0?C.at(-1):I.prevData[M]);k.set(E,J);let j=I.batchData.map(C=>C!=null?[...C]:void 0);$.set(E,j),i&&G({type:"derived",path:T,dep_values:J,dep_batches:j,...D()})}})},F=E=>{let T=R.get(E),I=k.get(E);if(!s||I==null)return{};let j=(T!=null&&T>=0&&E instanceof L?E._deps[T]:void 0)?.node,C=j?.v,M=$.get(E);return{trigger_dep_index:T,trigger_dep_name:j?.name,...C!=null?{trigger_version:{id:C.id,version:C.version}}:{},dep_values:[...I],...M!=null?{dep_batches:M}:{}}},H=[],U=[];for(let[E,T]of t){let I=P(T,E);I&&H.push(I),U.push(T.subscribe(J=>{_++;for(let j of J){let C=j[0],M=D();if(C===Q){c[E]=j[1];let ge=T instanceof L?T.lastMutation?.actor??Y:Y;G({type:"data",path:E,data:j[1],actor:ge,...M,...F(T)})}else if(a)C===me?b++:C===be?v++:C===Z?w++:C===ye?m++:C===ve?y++:C===z?S++:C===ee&&!g.has(E)?x=!0:C===te&&(O=!0,g.add(E));else if(C===me)b++,G({type:"dirty",path:E,...M});else if(C===be)v++,G({type:"resolved",path:E,...M,...F(T)});else if(C===Z)w++,G({type:"invalidate",path:E,...M});else if(C===ye)m++,G({type:"pause",path:E,lockId:j[1],...M});else if(C===ve)y++,G({type:"resume",path:E,lockId:j[1],...M});else if(C===ee)g.has(E)||(x=!0),G({type:"complete",path:E,...M});else if(C===te){O=!0,g.add(E);let ge=T instanceof L?T.lastMutation?.actor??Y:Y;G({type:"error",path:E,data:j[1],actor:ge,...M})}else C===z&&(S++,G({type:"teardown",path:E,...M}))}}))}let fe=!1,pe=()=>{if(!fe){fe=!0;for(let E of U)E();for(let E of H)E();for(let E of X)E({value:void 0,done:!0});X.length=0}},he=[],X=[];f.add(E=>{let T=X.shift();T?T({value:E,done:!1}):he.push(E)});let ke={get values(){return c},get dirtyCount(){return b},get resolvedCount(){return v},get invalidateCount(){return w},get pauseCount(){return m},get resumeCount(){return y},get teardownCount(){return S},get events(){return h?h.toArray():[...p]},get anyCompletedCleanly(){return x},get anyErrored(){return O},get completedWithoutErrors(){return x&&!O},onEvent(E){return f.add(E),()=>f.delete(E)},dispose:pe,expand(E){pe();let T={...r};return typeof E=="string"?T.detail=E:Object.assign(T,E),n(rt(T))},[Symbol.asyncIterator](){return{next(){return he.length>0?Promise.resolve({value:he.shift(),done:!1}):fe?Promise.resolve({value:void 0,done:!0}):new Promise(E=>X.push(E))},return(){return pe(),Promise.resolve({value:void 0,done:!0})}}}};return r.format!=null&&this._attachFormatLogger(ke,r),ke}_attachFormatLogger(t,r){let n=r.format;if(n==null)return;let o=r.logger??(c=>console.log(c)),s=r.includeTypes?new Set(r.includeTypes):null,i=r.excludeTypes?new Set(r.excludeTypes):null,a=s==null&&i==null?()=>!0:c=>(s==null||s.has(c))&&(i==null||!i.has(c)),l=Xt(r.theme),u=n==="stage-log"?K():0,d=c=>c==null?"":r.stageLabels?.[c]??c,h=(c,g)=>c.length>g?`${c.slice(0,g-1)}\u2026`:c,p=c=>c.type==="data"||c.type==="error"?h(de(c.data),120):"",f=c=>{if(n==="stage-log"){let O=(K()-u)/1e9,_=d(c.path).padEnd(9);if(c.type==="data"){let R=p(c);return`[${O.toFixed(3)}s] ${_} \u2190${R?` ${R}`:""}`}if(c.type==="error"){let R=p(c);return`[${O.toFixed(3)}s] ${_} \u2717${R?` ${R}`:""}`}return c.type==="complete"?`[${O.toFixed(3)}s] ${_} \u25A0 complete`:`[${O.toFixed(3)}s] ${_} ${c.type}`}if(n==="json")try{return JSON.stringify(c)}catch{return JSON.stringify({type:c.type,path:c.path,data:"[unserializable]"})}let g=l[c.type]??"",b=c.path?`${l.path}${c.path}${l.reset} `:"",v=c.type==="data"||c.type==="error",w=c.type==="pause"||c.type==="resume",m=v?` ${de(c.data)}`:w?` ${de(c.lockId)}`:"",y=c.type==="data"||c.type==="resolved"||c.type==="derived"?c:void 0,S=y?.trigger_dep_name!=null?` <- ${y.trigger_dep_name}`:y?.trigger_dep_index!=null?` <- #${y.trigger_dep_index}`:"",x=c.in_batch?" [batch]":"";return`${b}${g}${c.type.toUpperCase()}${l.reset}${m}${S}${x}`};t.onEvent(c=>{a(c.type)&&o(f(c),c)})}addDisposer(t){return this._disposers.add(t),()=>{this._disposers.delete(t)}}destroy(){tt(this._disposers,this.name),this.signal([[z]],{internal:!0}),tt(this._storageDisposers,this.name);for(let t of[...this._mounts.values()])t._parent=void 0,t._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}get destroyed(){return this._destroyed}_destroyClearOnly(){for(let t of[...this._mounts.values()])t._parent=void 0,t._destroyClearOnly();this._mounts.clear(),this._nodes.clear(),this._parent=void 0,this._destroyed=!0}snapshot(t){let{expand:r,...n}=this.describe({detail:"full"}),o={};for(let a of Object.keys(n.nodes).sort()){let{lastMutation:l,guard:u,...d}=n.nodes[a];o[a]=d}let s=[...n.subgraphs].sort(),i={...n,version:1,nodes:o,subgraphs:s};if(t?.format==null)return i;if(t.format==="json-string")return JSON.stringify(i);if(t.format==="bytes"){if(t.codec==null)throw new Error("snapshot({format: 'bytes'}) requires a `codec` name");let a=this.config.lookupCodec(t.codec);if(a==null)throw new Error(`snapshot: codec "${t.codec}" is not registered on this graph's config. Call config.registerCodec(...) before creating nodes.`);return $e(a,a.encode(i))}throw new Error(`snapshot: unknown format "${String(t.format)}"`)}static decode(t,r){let n=r?.config??we,{codec:o,codecVersion:s,payload:i}=Te(t,n);return o.decode(i,s)}restore(t,r){if(nt(t),t.name!==this.name)throw new Error(`Graph "${this.name}": restore snapshot name "${t.name}" does not match this graph`);let n=r?.only==null?null:(Array.isArray(r.only)?r.only:[r.only]).map(s=>ce(s)),o=r?.includeProducers===!0;for(let s of Object.keys(t.nodes).sort()){if(n!==null&&!n.some(a=>a.test(s)))continue;let i=t.nodes[s];if(i!==void 0){if(!("value"in i)||i.value===void 0){"value"in i&&i.value===void 0&&r?.onError?.(s,new Error(`restore: slice.value is undefined for "${s}" (undefined is the global SENTINEL; not valid DATA)`));continue}if(!(i.type==="derived"||i.type==="effect")&&!(i.type==="producer"&&!o)){if(i.v!=null){let l=this.tryResolve(s)?.v;if(l!=null&&l.id===i.v.id&&l.version===i.v.version)continue}try{this.set(s,i.value)}catch(a){r?.onError?.(s,a)}}}}}static fromSnapshot(t,r){nt(t);let n=typeof r=="function"?r:r?.build,o=typeof r=="function"?void 0:r?.factories,s=new e(t.name);if(n)return n(s),s.restore(t),s;for(let f of[...t.subgraphs].sort((c,g)=>{let b=c.split(N).length,v=g.split(N).length;return b!==v?b-v:c<g?-1:c>g?1:0})){let c=f.split(N),g=s;for(let b of c)g._mounts.has(b)||g.mount(b,new e(b)),g=g._mounts.get(b)}let i=o?Object.entries(o).map(([f,c])=>({re:ce(f),factory:c})):[],a=f=>{for(let c of i)if(c.re.test(f))return c.factory},l=f=>{let c=f.split(N),g=c.pop();if(g==null||g.length===0)throw new Error(`invalid snapshot path "${f}"`);let b=s;for(let v of c){let w=b._mounts.get(v);if(!w)throw new Error(`unknown mount "${v}" in path "${f}"`);b=w}return[b,g]},u=Object.entries(t.nodes).filter(([f])=>!f.includes(`${N}${B}${N}`)).sort((f,c)=>f[0]<c[0]?-1:f[0]>c[0]?1:0),d=new Map(u),h=new Map,p=!0;for(;d.size>0&&p;){p=!1;for(let[f,c]of[...d.entries()]){let g=c?.deps??[];if(!g.every(S=>h.has(S)))continue;let[b,v]=l(f),w={...c?.meta??{}},m=a(f),y;if(c?.type==="state")y=ne(c.value,{meta:w});else{if(m==null)continue;y=m(v,{path:f,type:c.type,value:c.value,meta:w,deps:g,resolvedDeps:g.map(S=>h.get(S))})}b.add(y,{name:v}),h.set(f,y),d.delete(f),p=!0}}if(d.size>0){let f=[...d.keys()].sort().join(", ");throw new Error(`Graph.fromSnapshot could not reconstruct nodes without build callback: ${f}. Pass matching factories via fromSnapshot(data, { factories: { pattern: factoryFn } }).`)}return s.restore(t),s}toJSON(){return this.snapshot()}attachStorage(t,r={}){let n=t.map(u=>({tier:u,debounceMs:Math.max(0,u.debounceMs??0),compactEvery:Math.max(1,u.compactEvery??10),timer:void 0,seq:0,lastSnapshot:void 0,lastFingerprint:"",disposed:!1,savePending:void 0}));r.autoRestore===!0&&this._cascadeRestore(t,r.onError);let o=(u,d)=>{if(u.disposed)return;let h=It(d.nodes);if(u.lastSnapshot!=null&&h!==""&&h===u.lastFingerprint)return;let p=u.seq+1,f=Pe(),b=u.lastSnapshot==null||p%u.compactEvery===0?{mode:"full",snapshot:d,seq:p,timestamp_ns:f,format_version:q}:{mode:"diff",diff:tn(u.lastSnapshot,d),seq:p,timestamp_ns:f,format_version:q};if(u.tier.filter&&!u.tier.filter(this.name,b))return;let v;try{v=u.tier.save(this.name,b)}catch(w){r.onError?.(w,u.tier);return}if(v&&typeof v.then=="function"){let y=(u.savePending??Promise.resolve()).then(()=>v,()=>v).then(()=>{u.disposed||(u.seq=p,u.lastSnapshot=d,u.lastFingerprint=h)},S=>{r.onError?.(S,u.tier)});u.savePending=y.finally(()=>{u.savePending===y&&(u.savePending=void 0)})}else u.seq=p,u.lastSnapshot=d,u.lastFingerprint=h},s=(u,d)=>{try{o(u,d)}catch(h){r.onError?.(h,u.tier)}},i=(u,d)=>{if(!d.some(c=>{let g=this.config.messageTier(c[0]);return g>=3&&g<5}))return;if(r.filter){let c=this.tryResolve(u);if(c==null)return;let g=_e(c,re("standard"));if(!r.filter(u,g))return}let p,f=()=>(p==null&&(p=this.snapshot()),p);for(let c of n)c.disposed||(c.debounceMs===0?s(c,f()):(c.timer==null&&(c.timer=new Le),c.timer.start(c.debounceMs,()=>{c.disposed||s(c,this.snapshot())})))},a;if(r.paths!=null){let d=(typeof r.paths=="string"?this._pathsMatching(r.paths):r.paths).map(h=>{let p=this.tryResolve(h);return p==null?()=>{}:p.subscribe(f=>i(h,f))});a=()=>{for(let h of d)h()}}else a=this.observe().subscribe((u,d)=>i(u,d));let l=()=>{a();for(let u of n)u.disposed=!0,u.timer?.cancel();this._storageDisposers.delete(l)};return this._storageDisposers.add(l),{dispose:l}}async _cascadeRestore(t,r){for(let n of t){let o;try{o=await n.load(this.name)}catch(i){r?.(i,n);continue}if(o==null||typeof o!="object"||Array.isArray(o))continue;let s=o;try{if(s.mode==="full"&&s.snapshot!=null)return this.restore(s.snapshot),!0;if(s.version===q&&s.nodes!=null)return this.restore(s),!0}catch(i){r?.(i,n)}}return!1}static async fromStorage(t,r,n){for(let o of r){let s;try{s=await o.load(t)}catch(l){n?.onError?.(l,o);continue}if(s==null||typeof s!="object"||Array.isArray(s))continue;let i=s,a=i.mode==="full"&&i.snapshot!=null?i.snapshot:i.version===q&&i.nodes!=null?i:void 0;if(a!=null)try{return e.fromSnapshot(a,n)}catch(l){n?.onError?.(l,o)}}throw new Error(`Graph.fromStorage: no tier held a restorable record for "${t}" across ${r.length} tier(s)`)}_annotations=new Map;_traceRing;trace(t,r,n){if(t!=null&&r!=null){if(this.tryResolve(t)==null)return;if(this._annotations.set(t,r),this.config.inspectorEnabled){let o={path:t,annotation:r,timestamp_ns:K(),...n?.actor!=null?{actor:n.actor}:{}};this._traceRing.push(o)}return}return t!=null?this.config.inspectorEnabled?this._annotations.get(t):void 0:this.config.inspectorEnabled?this._traceRing.toArray():[]}annotation(t){return this._annotations.get(t)}clearTrace(){this._annotations.clear(),this._traceRing.clear()}pruneTrace(t){let r=this._traceRing.toArray().filter(o=>!t(o)),n=this._traceRing.size-r.length;this._traceRing.clear();for(let o of r)this._traceRing.push(o);return n}static diff(t,r){let n=new Set(Object.keys(t.nodes)),o=new Set(Object.keys(r.nodes)),s=[...o].filter(w=>!n.has(w)).sort(),i=[...n].filter(w=>!o.has(w)).sort(),a=[],l=[];for(let w of n){if(!o.has(w))continue;let m=t.nodes[w],y=r.nodes[w],S=m.v,x=y.v;S!=null&&x!=null&&S.id===x.id&&S.version!==x.version&&l.push({path:w,id:S.id,from:S.version,to:x.version});let O=S!=null&&x!=null&&S.id===x.id&&S.version===x.version;for(let _ of["type","status","sentinel"]){let R=m[_],k=y[_];R!==k&&a.push({path:w,field:_,from:R,to:k})}if(!O)for(let _ of["value","meta"]){let R=m[_],k=y[_];jt(R,k)||a.push({path:w,field:_,from:R,to:k})}}let u=w=>`${w.from} ${w.to}`,d=new Set(t.edges.map(u)),h=new Set(r.edges.map(u)),p=r.edges.filter(w=>!d.has(u(w))),f=t.edges.filter(w=>!h.has(u(w))),c=new Set(t.subgraphs),g=new Set(r.subgraphs),b=[...g].filter(w=>!c.has(w)).sort(),v=[...c].filter(w=>!g.has(w)).sort();return{nodesAdded:s,nodesRemoved:i,nodesChanged:a,versionChanges:l,edgesAdded:p,edgesRemoved:f,subgraphsAdded:b,subgraphsRemoved:v}}};function tn(e,t){let r=Ce.diff(e,t),n={};for(let o of r.nodesAdded){let s=t.nodes[o];s!=null&&(n[o]=s)}return{...r,nodesAddedFull:n}}function st(e,t,r,n={}){let o={paths:[],depths:new Map,truncated:!1};if(!t)return n.withDetail?o:[];if(!n.both&&r!=="upstream"&&r!=="downstream")throw new Error('reachable: direction must be "upstream" or "downstream"');let s=n.maxDepth;if(s!=null&&(!Number.isInteger(s)||s<0))throw new Error("reachable: maxDepth must be an integer >= 0");if(s===0)return n.withDetail?o:[];let i=new Map,a=new Map,l=new Map,u=new Map,d=new Set;for(let[m,y]of Object.entries(e.nodes)){if(!m)continue;d.add(m);let S=y.deps??[];i.set(m,S);for(let x of S)x&&(d.add(x),a.has(x)||a.set(x,new Set),a.get(x).add(m))}for(let m of e.edges){if(m==null||typeof m!="object")continue;let y=typeof m.from=="string"?m.from:"",S=typeof m.to=="string"?m.to:"";!y||!S||(d.add(y),d.add(S),u.has(y)||u.set(y,new Set),u.get(y).add(S),l.has(S)||l.set(S,new Set),l.get(S).add(y))}if(!d.has(t))return n.withDetail?o:[];let h=n.both===!0,p=m=>{if(h){let O=i.get(m)??[],_=l.get(m),R=a.get(m),k=u.get(m),$=[...O];return _&&$.push(..._),R&&$.push(...R),k&&$.push(...k),$}if(r==="upstream"){let O=i.get(m)??[],_=l.get(m);return _?[...O,..._]:O}let y=a.get(m),S=u.get(m),x=y?[...y]:[];return S&&x.push(...S),x},f=new Set([t]),c=new Map,g=[{path:t,depth:0}],b=0,v=!1;for(;b<g.length;){let m=g[b++];if(s!=null&&m.depth>=s){p(m.path).length>0&&(v=!0);continue}for(let y of p(m.path))!y||f.has(y)||(f.add(y),c.set(y,m.depth+1),g.push({path:y,depth:m.depth+1}))}let w=[...c.keys()].sort((m,y)=>m<y?-1:m>y?1:0);return n.withDetail?{paths:w,depths:c,truncated:v}:w}function nn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++){let n=e[r],o=t[r];if(n.path!==o.path||n.type!==o.type||n.status!==o.status||n.hop!==o.hop||n.dep_index!==o.dep_index||n.annotation!==o.annotation||n.value!==o.value||n.lastMutation!==o.lastMutation)return!1;let s=n.v,i=o.v;if(s!==i&&(s==null||i==null||s.id!==i.id||s.version!==i.version))return!1}return!0}export{ae as a,Ie as b,A as c,ft as d,He as e,Ve as f,B as g,q as h,Wt as i,Ce as j,tn as k,st as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{E as b,m as h}from"./chunk-
|
|
1
|
+
import{E as b,m as h}from"./chunk-7AJKUA36.js";import{b as p,c as l}from"./chunk-CK2E7BTU.js";var u=class{_version=0;_buf;constructor(e){this._buf=e?[...e]:[]}get version(){return this._version}get size(){return this._buf.length}at(e){if(!Number.isInteger(e))return;let n=e>=0?e:this._buf.length+e;if(!(n<0||n>=this._buf.length))return this._buf[n]}append(e){this._buf.push(e),this._version+=1}appendMany(e){if(e.length===0)return;let n=this._buf.length;this._buf.length=n+e.length;for(let i=0;i<e.length;i++)this._buf[n+i]=e[i];this._version+=1}insert(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insert: index ${e} out of range [0, ${this._buf.length}]`);this._buf.splice(e,0,n),this._version+=1}insertMany(e,n){if(!Number.isInteger(e)||e<0||e>this._buf.length)throw new RangeError(`insertMany: index ${e} out of range [0, ${this._buf.length}]`);n.length!==0&&(this._buf.splice(e,0,...n),this._version+=1)}pop(e){if(this._buf.length===0)throw new RangeError("pop from empty list");if(!Number.isInteger(e))throw new RangeError(`pop: index ${e} must be an integer`);let n=e>=0?e:this._buf.length+e;if(n<0||n>=this._buf.length)throw new RangeError(`pop: index ${e} out of range`);let[i]=this._buf.splice(n,1);return this._version+=1,i}clear(){let e=this._buf.length;return e===0?0:(this._buf.length=0,this._version+=1,e)}toArray(){return[...this._buf]}};function y(d,e={}){let{name:n,versioning:i,backend:f}=e,t=f??new u(d),a=b(t.toArray(),{name:n,describeKind:"state",equals:(r,o)=>r===o,...i!=null?{versioning:i}:{}});function v(){let r=t.toArray();h(()=>{a.down([[l]]),a.down([[p,r]])})}function s(r){let o=t.version;try{return r()}finally{t.version!==o&&v()}}return{items:a,get size(){return t.size},at(r){return t.at(r)},append(r){s(()=>t.append(r))},appendMany(r){s(()=>t.appendMany(r))},insert(r,o){s(()=>t.insert(r,o))},insertMany(r,o){s(()=>t.insertMany(r,o))},pop(r=-1){return s(()=>t.pop(r))},clear(){s(()=>t.clear())},dispose(){}}}export{u as a,y as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{m as x,w}from"./chunk-UMH3HSP7.js";import{i as g,j as p}from"./chunk-CK2E7BTU.js";async function k(o){let i=typeof o=="string"?new TextEncoder().encode(o):o,c=await globalThis.crypto.subtle.digest("SHA-256",i),t=new Uint8Array(c),n="";for(let r=0;r<t.length;r++)n+=b[t[r]];return n}var b=new Array(256);for(let o=0;o<256;o++)b[o]=o.toString(16).padStart(2,"0");var m=class extends Error{constructor(c,t){super(`content-addressed lookup miss in read-strict mode: ${c}`);this.key=c;this.context=t;this.name="ContentAddressedMissError"}};function T(o){let i=new Set,c=t=>{if(t===null||typeof t!="object")return t;let n=t;if(i.has(n))return{__cycle:!0};i.add(n);try{if(Array.isArray(t))return t.map(c);let r={};for(let d of Object.keys(t).sort())r[d]=c(t[d]);return r}finally{i.delete(n)}};return JSON.stringify(c(o))}function P(o){let{storage:i,keyContext:c,keyPrefix:t,mode:n="read-write"}=o,r=c??(e=>e);async function d(e){let s=T(r(e)),a=await k(s);return t?`${t}:${a}`:a}return{keyFor:d,async lookup(e){if(n==="write")return;let s=await d(e),a=await i.load(s);if(a==null){if(n==="read-strict")throw new m(s,e);return}return a},async store(e,s){if(n==="read")return;let a=await d(e);await i.save(a,s)},async forget(e){if(n==="read"||n==="write"||!i.clear)return;let s=await d(e);await i.clear(s)}}}function j(o,i={}){let c=i.keyFn??(n=>String(n)),t=new Map;return n=>{let r=c(n),d=t.get(r);if(d)return d;let e=o(n),s;e!=null&&typeof e.then=="function"?s=Promise.resolve(e):e!=null&&typeof e=="object"&&"subscribe"in e&&"cache"in e?s=w(e):e!=null&&typeof e=="object"&&Symbol.asyncIterator in e?s=(async()=>{let u=e[Symbol.asyncIterator]();try{let{value:l,done:f}=await u.next();if(f)throw new Error("singleFromAny: factory returned empty async iterable");return l}finally{await u.return?.()}})():e!=null&&typeof e=="object"&&Symbol.iterator in e?s=(async()=>{let u=e[Symbol.iterator]();try{let{value:l,done:f}=u.next();if(f)throw new Error("singleFromAny: factory returned empty iterable");return l}finally{u.return?.()}})():s=Promise.resolve(e);let a,y=()=>{t.get(r)===a&&t.delete(r)};return a=s.then(u=>(y(),u),u=>{throw y(),u}),t.set(r,a),a}}function K(o,i={}){let c=i.keyFn??(n=>String(n)),t=new Map;return n=>{let r=c(n),d=t.get(r);if(d)return d;let e=x(o(n));t.set(r,e);let s=e.subscribe(a=>{for(let y of a)if(y[0]===p||y[0]===g){t.get(r)===e&&t.delete(r),s();return}});return e}}export{k as a,m as b,T as c,P as d,j as e,K as f};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{e as P}from"./chunk-
|
|
1
|
+
import{e as P}from"./chunk-PWKLZ2XU.js";import{c as S}from"./chunk-K54OKWNY.js";import{a as w}from"./chunk-MFNOZ5E6.js";import{b as _}from"./chunk-LWGLBCMU.js";import{j as O,l as R}from"./chunk-4JBKKUCJ.js";import{B as T}from"./chunk-UMH3HSP7.js";import{E as k,G as x,o as H}from"./chunk-7AJKUA36.js";import{b as M}from"./chunk-QYADASLV.js";var B={};M(B,{LensGraph:()=>C,graphLens:()=>N,watchTopologyTree:()=>w});function v(e){return S("lens",e)}function E(e){let t=Object.keys(e.nodes),o=new Map,n=new Map;for(let s of t){let a=e.nodes[s]?.deps??[];o.set(s,a);for(let h of a)n.has(h)||n.set(h,new Set),n.get(h).add(s)}let r=[],c=[];for(let s of t)(o.get(s)??[]).length===0&&r.push(s),n.has(s)||c.push(s);r.sort(),c.sort();let p=e.edges.length,f=0,m=1,g=2,d=new Map;for(let s of t)d.set(s,f);let y=!1,l=new Map,u=s=>{let a=d.get(s)??f;if(a===m)return y=!0,0;if(a===g)return l.get(s)??0;d.set(s,m);let h=0,b=n.get(s);if(b!=null)for(let F of b){let G=u(F);G+1>h&&(h=G+1)}return d.set(s,g),l.set(s,h),h},i=0;for(let s of r){let a=u(s);a>i&&(i=a)}for(let s of t)d.get(s)===f&&u(s);return{nodeCount:t.length,edgeCount:p,subgraphCount:e.subgraphs.length,sources:r,sinks:c,depth:i,hasCycles:y}}function $(e){let t=[];for(let[o,n]of Object.entries(e.nodes)){if(n.status!=="errored")continue;let r={path:o,status:"errored"},c=R(e,o,"upstream",{});for(let p of c)if(p!==o&&e.nodes[p]?.status==="errored"){r.upstreamCause=p;break}t.push(r)}return t.sort((o,n)=>o.path<n.path?-1:o.path>n.path?1:0),{ok:t.length===0,problems:t}}function q(e,t){return e.nodeCount===t.nodeCount&&e.edgeCount===t.edgeCount&&e.subgraphCount===t.subgraphCount&&e.depth===t.depth&&e.hasCycles===t.hasCycles&&D(e.sources,t.sources)&&D(e.sinks,t.sinks)}function L(e,t){if(e.ok!==t.ok||e.problems.length!==t.problems.length)return!1;for(let o=0;o<e.problems.length;o++){let n=e.problems[o],r=t.problems[o];if(n.path!==r.path||n.status!==r.status||n.upstreamCause!==r.upstreamCause)return!1}return!0}function D(e,t){if(e.length!==t.length)return!1;for(let o=0;o<e.length;o++)if(e[o]!==t[o])return!1;return!0}var C=class extends O{stats;health;flow;_target;constructor(t,o={}){super(o.name??`${t.name}_lens`,o.graph),this._target=t;let n=0,r=0,c=k(0,{name:"stats_tick"}),p=k(0,{name:"health_tick"});this.add(c,{name:"stats_tick"}),this.add(p,{name:"health_tick"});let f={name:"flow"};o.maxFlowPaths!=null&&(f.maxSize=o.maxFlowPaths),this.flow=_(f),this.add(this.flow.entries,{name:"flow"});let m=o.pathFilter,g=w(t,(l,u,i)=>{if(n+=1,c.emit(n),r+=1,p.emit(r),l.kind==="removed")if(l.nodeKind==="node"){let s=`${i}${l.name}`;this.flow.delete(s)}else{let s=`${i}${l.name}::`,a=[];for(let h of l.audit.nodes){let b=h===""?`${i}${l.name}`:`${s}${h}`;a.push(b)}a.length>0&&this.flow.deleteMany(a)}});this.addDisposer(g);let d=t.observe({timeline:!0,structured:!0}),y=d.onEvent(l=>{let u=l.type;if((u==="error"||u==="complete"||u==="data"||u==="teardown")&&(r+=1,p.emit(r)),u==="data"){let i=l.path??"";if(!i||m!=null&&!m(i))return;let s=this.flow.get(i),a=s!=null?s.count+1:1;this.flow.set(i,{path:i,count:a,lastUpdate_ns:H()})}});this.addDisposer(()=>{y(),d.dispose()}),this.stats=x([c],()=>E(t.describe({detail:"minimal"})),{name:"stats",describeKind:"derived",equals:q,meta:v("stats")}),this.add(this.stats,{name:"stats"}),this.addDisposer(T(this.stats)),this.health=x([p],()=>$(t.describe({detail:"standard"})),{name:"health",describeKind:"derived",equals:L,meta:v("health")}),this.add(this.health,{name:"health"}),this.addDisposer(T(this.health))}why(t,o,n){let r=P(this._target,t,o,n);return this.addDisposer(r.dispose),r}get target(){return this._target}};function N(e,t){return new C(e,t)}export{C as a,N as b,B as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{j as _}from"./chunk-4JBKKUCJ.js";import{D as g,E as k}from"./chunk-7AJKUA36.js";import{b as R,c as T,d,h as A,i as O,j as D}from"./chunk-CK2E7BTU.js";function L(c,y,l,a){let s=new _(c,a);s.add(y,{name:"source"});let n=k(l,{meta:{kind:"stratify_rules"}});s.add(n,{name:"rules"});for(let f of l)E(s,y,n,f);return s}function E(c,y,l,a){let s=`branch/${a.name}`,n=Symbol("noValue"),f=!1,m=!1,p=!1,N=n,r=!1,h=l.cache??[];function v(o){if(p){p=!1;let t=N;if(N=n,t!==n){let i=h.find(u=>u.name===a.name),e=!1;try{e=i?.classify(t)??!1}catch{e=!1}e?(r=!1,o.emit(t)):r&&(r=!1,o.down([[T],[d]]))}else r?(r=!1,o.down([[T],[d]])):o.down([[d]])}}let S=g([],(o,t)=>{let i=y.subscribe(u=>{for(let b of u)w(b,0,t)}),e=l.subscribe(u=>{for(let b of u)w(b,1,t)});return()=>{i(),e()}},{describeKind:"derived",meta:{kind:"stratify_branch",branch:a.name},completeWhenDepsComplete:!1});function w(o,t,i){let e=o[0];return e===T?(t===0?(f=!0,r=!0):m=!0,!0):e===R||e===d?(t===0?(f=!1,p=!0,N=e===R?o[1]:n):(e===R&&(h=o[1]),m=!1),f||m||v(i),!0):e===O||e===D||e===A?(f=!1,m=!1,p=!1,N=n,r=!1,t===0&&i.down([o]),!0):t===1}if(c.add(S,{name:s}),a.ops){let o=a.ops(S),t=`branch/${a.name}/out`;c.add(o,{name:t})}}export{L as a};
|