@graphrefly/graphrefly 0.30.0 → 0.31.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-T5SHIKJD.js → chunk-3JRKP4BH.js} +1 -1
- package/dist/{chunk-GJR3P6JG.js → chunk-3Q2WXM6X.js} +1 -1
- package/dist/chunk-4KAUNEKV.js +3 -0
- package/dist/{chunk-SLMYTGTU.js → chunk-4UUDNFYG.js} +1 -1
- package/dist/chunk-4VXL3UZK.js +1 -0
- package/dist/{chunk-AV3PIDFQ.js → chunk-4ZPO2EL5.js} +1 -1
- package/dist/{chunk-VWPRPPKR.js → chunk-5LJAQTSS.js} +1 -1
- package/dist/{chunk-W4TSQ6RJ.js → chunk-7AJKUA36.js} +1 -1
- package/dist/{chunk-RD52SNH2.js → chunk-7EJTWGKW.js} +1 -1
- package/dist/{chunk-GNCBXARM.js → chunk-7EQPXQ7H.js} +1 -1
- package/dist/chunk-7QMVU3IX.js +1 -0
- package/dist/{chunk-BA5URFYW.js → chunk-A4JT4SAD.js} +1 -1
- package/dist/chunk-ASDKRNOJ.js +60 -0
- package/dist/{chunk-Y32RJO24.js → chunk-CZVYLXFK.js} +1 -1
- package/dist/{chunk-567NWZ3T.js → chunk-DWIAG62L.js} +1 -1
- package/dist/{chunk-33FA6V4B.js → chunk-EBQ6FXKW.js} +1 -1
- package/dist/chunk-FTA5TB2A.js +1 -0
- package/dist/{chunk-P7JXGKDO.js → chunk-GF5T7PGC.js} +1 -1
- package/dist/{chunk-WANIEEKV.js → chunk-I4U3TPK2.js} +1 -1
- package/dist/{chunk-KA6MMXIY.js → chunk-JMGGCSIC.js} +1 -1
- package/dist/chunk-JXRZXP3N.js +1 -0
- package/dist/{chunk-5Z4HDCO6.js → chunk-K54OKWNY.js} +1 -1
- package/dist/{chunk-DDPYNMGG.js → chunk-KN4Q5MQO.js} +1 -1
- package/dist/chunk-LWGLBCMU.js +1 -0
- package/dist/{chunk-TWMEGG45.js → chunk-N2KKISCE.js} +1 -1
- package/dist/{chunk-4OFIQ66T.js → chunk-OKQUPJRY.js} +1 -1
- package/dist/chunk-PNTBXOQ6.js +5 -0
- package/dist/chunk-PSQNYY72.js +7 -0
- package/dist/{chunk-XHVB6G6M.js → chunk-PZP4MEXK.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-UMH3HSP7.js +1 -0
- package/dist/{chunk-BZP5T4X6.js → chunk-W6FQIFVE.js} +1 -1
- package/dist/{chunk-SHYH5SXV.js → chunk-WLPVGXQ6.js} +1 -1
- package/dist/chunk-WQ7I7JVU.js +1 -0
- package/dist/{chunk-XQAXYVXX.js → chunk-WYJTXYWX.js} +1 -1
- package/dist/{chunk-3NEPQO2E.js → chunk-X2VHDT26.js} +1 -1
- package/dist/{chunk-GLSM33ZM.js → chunk-XEFAMCEA.js} +1 -1
- package/dist/{chunk-AUY2YKCO.js → chunk-XRSHMHEG.js} +1 -1
- package/dist/chunk-Y26UN6J5.js +18 -0
- package/dist/{chunk-BKPLTBL5.js → chunk-YQJPYEAL.js} +1 -1
- package/dist/{chunk-73Z3W2RN.js → chunk-YZ6VYLFD.js} +1 -1
- package/dist/{chunk-4JJCCD5S.js → chunk-YZKGGMPT.js} +1 -1
- package/dist/chunk-Z3UWIJ3A.js +1 -0
- package/dist/{chunk-Y36UZ5VS.js → chunk-ZM7C2FUM.js} +1 -1
- package/dist/compat/index.cjs +1 -1
- 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.js +1 -1
- package/dist/compat/zustand/index.cjs +1 -1
- 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 +6 -5
- package/dist/extra/index.d.ts +6 -5
- 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.js +1 -1
- package/dist/{index-ClB7TCfL.d.cts → index-BMe3pCom.d.cts} +1 -1
- package/dist/{index-Dljd76bC.d.ts → index-BXzl1NDD.d.ts} +1 -1
- package/dist/{index-ClgKmOHe.d.ts → index-Bd6oFZqO.d.ts} +223 -115
- package/dist/{index-BJHQUCZx.d.ts → index-CJymKyzT.d.ts} +81 -6
- package/dist/{index-D6ajK8Mh.d.cts → index-CZChc85Q.d.cts} +223 -115
- package/dist/{index-BXbQUn4n.d.ts → index-CcS0t-l2.d.ts} +1 -1
- package/dist/{index-B2HBxvMb.d.ts → index-CwhcFzTA.d.ts} +1 -1
- package/dist/{index-B8Aj_z8S.d.cts → index-D-kHVedZ.d.cts} +1 -1
- package/dist/{index-ybtSyjWB.d.cts → index-DD7RhHNJ.d.cts} +1 -1
- package/dist/{index-BHu_Wba0.d.cts → index-Dm3_D5Ta.d.cts} +1 -1
- package/dist/{index-Cc8VQIgL.d.ts → index-DxMS0cHM.d.ts} +1 -1
- package/dist/{index-BS220yqj.d.cts → index-gJQqJTKx.d.cts} +81 -6
- package/dist/index.cjs +99 -121
- package/dist/index.d.cts +14 -13
- package/dist/index.d.ts +14 -13
- 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 +27 -44
- package/dist/patterns/ai/index.d.cts +9 -7
- package/dist/patterns/ai/index.d.ts +9 -7
- 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.js +1 -1
- package/dist/patterns/cqrs/index.cjs +6 -6
- package/dist/patterns/cqrs/index.js +1 -1
- package/dist/patterns/demo-shell/index.cjs +1 -1
- package/dist/patterns/demo-shell/index.js +1 -1
- package/dist/patterns/domain-templates/index.cjs +4 -4
- package/dist/patterns/domain-templates/index.js +1 -1
- package/dist/patterns/graphspec/index.cjs +6 -6
- package/dist/patterns/graphspec/index.d.cts +2 -2
- package/dist/patterns/graphspec/index.d.ts +2 -2
- package/dist/patterns/graphspec/index.js +1 -1
- package/dist/patterns/guarded-execution/index.cjs +7 -7
- package/dist/patterns/guarded-execution/index.js +1 -1
- package/dist/patterns/harness/index.cjs +11 -11
- package/dist/patterns/harness/index.d.cts +2 -2
- package/dist/patterns/harness/index.d.ts +2 -2
- package/dist/patterns/harness/index.js +1 -1
- package/dist/patterns/job-queue/index.cjs +5 -5
- package/dist/patterns/job-queue/index.js +1 -1
- package/dist/patterns/lens/index.cjs +5 -5
- package/dist/patterns/lens/index.d.cts +2 -2
- package/dist/patterns/lens/index.d.ts +2 -2
- package/dist/patterns/lens/index.js +1 -1
- package/dist/patterns/memory/index.cjs +4 -4
- package/dist/patterns/memory/index.js +1 -1
- package/dist/patterns/messaging/index.cjs +5 -5
- package/dist/patterns/messaging/index.js +1 -1
- package/dist/patterns/orchestration/index.cjs +1 -1
- package/dist/patterns/orchestration/index.js +1 -1
- package/dist/patterns/reactive-layout/index.cjs +1 -1
- package/dist/patterns/reactive-layout/index.js +1 -1
- package/dist/patterns/reduction/index.cjs +5 -5
- package/dist/patterns/reduction/index.js +1 -1
- package/dist/patterns/refine-loop/index.cjs +8 -8
- package/dist/patterns/refine-loop/index.js +1 -1
- package/dist/patterns/resilient-pipeline/index.cjs +1 -1
- package/dist/patterns/resilient-pipeline/index.js +1 -1
- package/dist/patterns/surface/index.cjs +7 -7
- package/dist/patterns/surface/index.d.cts +3 -3
- package/dist/patterns/surface/index.d.ts +3 -3
- package/dist/patterns/surface/index.js +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/{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-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 };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as n}from"./chunk-
|
|
1
|
+
import{d as n}from"./chunk-YZ6VYLFD.js";import{j as a}from"./chunk-PSQNYY72.js";import{b as c}from"./chunk-QYADASLV.js";var s={};c(s,{GuardedExecutionGraph:()=>o,guardedExecution:()=>p});var o=class extends a{enforcer;violations;_target;_defaultActor;constructor(r,e){super(e.name??`${r.name}_guarded`,e.graph),this._target=r,this._defaultActor=e.actor;let t={mode:e.mode??"enforce",name:"enforcer"};e.violationsLimit!=null&&(t.violationsLimit=e.violationsLimit),this.enforcer=n(r,e.policies,t),this.violations=this.enforcer.violations,this.mount("enforcer",this.enforcer)}scopedDescribe(r){let e=r?.actor??this._defaultActor,t={...r,...e!=null?{actor:e}:{}};return this._target.describe(t)}get target(){return this._target}};function p(i,r){return new o(i,r)}export{o as a,p as b,s as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{j as _}from"./chunk-PSQNYY72.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};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{f as he}from"./chunk-EBQ6FXKW.js";import{j as fe}from"./chunk-PSQNYY72.js";import{x as ye}from"./chunk-WQ7I7JVU.js";import{D as be,E as T,G as v,H as q,m as ee,o as z}from"./chunk-7AJKUA36.js";import{b as P,j as Z}from"./chunk-CK2E7BTU.js";import{b as Ne}from"./chunk-QYADASLV.js";var we={};Ne(we,{blindVariation:()=>De,errorCritique:()=>Re,refineLoop:()=>Se});function Ie(n){if(typeof n!="object"||n===null)return!1;let l=n;return typeof l.subscribe=="function"&&typeof l.down=="function"&&typeof l.emit=="function"}function pe(n,l){if(n.length===0)return{best:null,bestScore:Number.NEGATIVE_INFINITY};if(n.length===1){let e=ne(l);return{best:n[0],bestScore:e}}if(l.some(e=>typeof e.candidateIndex=="number")){let e=new Array(n.length);for(let i=0;i<n.length;i++)e[i]={sum:0,count:0};for(let i of l){let d=i.candidateIndex;typeof d=="number"&&d>=0&&d<n.length&&(e[d].sum+=i.score,e[d].count+=1)}let s=n[0],o=e[0].count>0?e[0].sum/e[0].count:Number.NEGATIVE_INFINITY;for(let i=1;i<n.length;i++){let d=e[i].count>0?e[i].sum/e[i].count:Number.NEGATIVE_INFINITY;d>o&&(o=d,s=n[i])}return{best:s,bestScore:o}}let t=n[0],m=l[0]?.score??Number.NEGATIVE_INFINITY;for(let e=1;e<n.length;e++){let s=l[e]?.score??Number.NEGATIVE_INFINITY;s>m&&(m=s,t=n[e])}return{best:t,bestScore:m}}function ne(n){if(n.length===0)return Number.NEGATIVE_INFINITY;let l=0;for(let x of n)l+=x.score;return l/n.length}function Se(n,l,x,t){let m=t.name??"refine-loop",e=new fe(m,t.graph),s=Ie(t.dataset)?t.dataset:T(t.dataset,{name:"dataset"});e.add(s,{name:"dataset"});let o=T(0,{name:"iteration"});e.add(o,{name:"iteration"});let i=T(x,{name:"strategy",equals:()=>!1});e.add(i,{name:"strategy"});let d=T(null,{name:"lastFeedback"});e.add(d,{name:"lastFeedback"});let k=T([],{name:"prevCandidates"});e.add(k,{name:"prevCandidates"});let y=T(!1,{name:"paused"});e.add(y,{name:"paused"});let b=T("running",{name:"status"});e.add(b,{name:"status"});let E=T([],{name:"history",equals:()=>!1});e.add(E,{name:"history"});let h=T(null,{name:"best"});e.add(h,{name:"best"});let N=T(Number.NEGATIVE_INFINITY,{name:"score"});e.add(N,{name:"score"});let C=T(0,{name:"budget-used"});e.add(C,{name:"budget-used"});let R=he("stages");e.mount("stages",R);let A=R.topic("generate"),p=R.topic("evaluate"),G=R.topic("analyze"),te=R.topic("decide"),$=x,B=null,re=[];e.addDisposer(i.subscribe(r=>{for(let a of r)a[0]===P&&($=a[1])})),e.addDisposer(d.subscribe(r=>{for(let a of r)a[0]===P&&(B=a[1])})),e.addDisposer(k.subscribe(r=>{for(let a of r)a[0]===P&&(re=a[1])}));let I=ye(o,r=>{let a=$,c=r===0||B==null;return be([],(u,f)=>{let S=!1;try{let D=c?a.seed(n):a.generate(B,re);if(D instanceof Promise)return D.then(_=>{S||f.emit(_)},_=>{S||f.down([[Z,_]])}),()=>{S=!0};f.emit(D)}catch(D){S=!0,f.down([[Z,D]])}},{describeKind:"producer"})},{name:"candidates"});e.add(I,{name:"candidates"});let ae=q([I],(r,a,c)=>{let u=c.terminalDeps[0];u!==void 0&&u!==!0&&b.emit("errored")},{name:"error-watcher",errorWhenDepsError:!1});e.add(ae,{name:"error-watcher"}),e.addDisposer(ae.subscribe(()=>{}));let Y=v([I,o],([r,a])=>({iteration:a,candidates:r,timestamp_ns:z()}),{name:"generate-event"});e.add(Y,{name:"generate-event"}),e.addDisposer(Y.subscribe(()=>{}));let oe=q([Y],([r])=>{A.publish(r)},{name:"generate-publish"});e.add(oe,{name:"generate-publish"}),e.addDisposer(oe.subscribe(()=>{}));let ie=q([I],([r])=>{k.emit(r)},{name:"generate-mirror"});e.add(ie,{name:"generate-mirror"}),e.addDisposer(ie.subscribe(()=>{}));let V=l(I,s);e.add(V,{name:"scores"});let j=v([V,I,o],([r,a,c])=>({iteration:c,candidates:a,scores:r,timestamp_ns:z()}),{name:"evaluate-event"});e.add(j,{name:"evaluate-event"}),e.addDisposer(j.subscribe(()=>{}));let se=q([j],([r])=>{p.publish(r)},{name:"evaluate-publish"});e.add(se,{name:"evaluate-publish"}),e.addDisposer(se.subscribe(()=>{}));let L=v([V,I],([r,a])=>$.analyze(r,a),{name:"feedback"});e.add(L,{name:"feedback"});let M=v([L,I,o],([r,a,c])=>({iteration:c,candidates:a,feedback:r,timestamp_ns:z()}),{name:"analyze-event"});e.add(M,{name:"analyze-event"}),e.addDisposer(M.subscribe(()=>{}));let de=q([M],([r])=>{G.publish(r)},{name:"analyze-publish"});e.add(de,{name:"analyze-publish"}),e.addDisposer(de.subscribe(()=>{}));let H=v([E],([r])=>{let a=r;if(t.patience==null||a.length<=t.patience)return!1;let c=a.slice(-(t.patience+1)),u=c[0].bestScore;return c.slice(1).every(f=>f.bestScore<=u)},{name:"patience-check"});e.add(H,{name:"patience-check"});let W=v([N],([r])=>t.minScore!=null&&r>=t.minScore,{name:"min-score-check"});e.add(W,{name:"min-score-check"});let K=v([E],([r])=>{let a=r;if(t.minDelta==null||a.length<2)return!1;let c=a[a.length-2].bestScore,u=a[a.length-1].bestScore;return Math.abs(u-c)<t.minDelta},{name:"min-delta-check"});e.add(K,{name:"min-delta-check"});let U=v([C],([r])=>t.maxEvaluations!=null&&r>=t.maxEvaluations,{name:"max-evaluations-check"});e.add(U,{name:"max-evaluations-check"});let J=v([o],([r])=>t.maxIterations!=null&&r>=t.maxIterations,{name:"max-iterations-check"});e.add(J,{name:"max-iterations-check"});let le=v([C],([r])=>t.budget!=null&&r>=t.budget,{name:"budget-exhausted-check"});e.add(le,{name:"budget-exhausted-check"}),e.addDisposer(H.subscribe(()=>{})),e.addDisposer(W.subscribe(()=>{})),e.addDisposer(K.subscribe(()=>{})),e.addDisposer(U.subscribe(()=>{})),e.addDisposer(J.subscribe(()=>{})),e.addDisposer(le.subscribe(()=>{}));let ce=v([H,W,K,U,J],([r,a,c,u,f])=>r?{converged:!0,reason:"patience"}:a?{converged:!0,reason:"min-score"}:c?{converged:!0,reason:"min-delta"}:u?{converged:!0,reason:"max-evaluations"}:f?{converged:!0,reason:"max-iterations"}:{converged:!1},{name:"converged"});e.add(ce,{name:"converged"}),e.addDisposer(ce.subscribe(()=>{}));let ue=-1,me=q([L,V,I],([r,a,c])=>{let u=o.cache,f=r,S=c,D=a;if(u<=ue)return;ue=u;let{best:_,bestScore:ge}=pe(S,D),Te=E.cache,ve={n:u,candidates:S,scores:D,feedback:f,best:_,bestScore:ge,timestamp_ns:z()},F=[...Te,ve],Q=C.cache+S.length,g="continue",w,Ee=t.budget!=null&&Q>=t.budget,ke=y.cache;if(Ee)g="budget",w="budget";else if(t.minScore!=null&&f.score>=t.minScore)g="converged",w="min-score";else if(t.maxIterations!=null&&u>=t.maxIterations)g="converged",w="max-iterations";else if(t.maxEvaluations!=null&&Q>=t.maxEvaluations)g="converged",w="max-evaluations";else if(t.minDelta!=null&&F.length>=2){let O=F[F.length-2].bestScore,X=F[F.length-1].bestScore;Math.abs(X-O)<t.minDelta&&(g="converged",w="min-delta")}else if(t.patience!=null&&F.length>t.patience){let O=F.slice(-(t.patience+1)),X=O[0].bestScore;O.slice(1).every(xe=>xe.bestScore<=X)&&(g="converged",w="patience")}g==="continue"&&ke&&(g="paused"),ee(()=>{h.emit(_),N.emit(f.score),E.emit(F),C.emit(Q),d.emit(f),te.publish({iteration:u,decision:g,reason:w,timestamp_ns:z()}),g==="continue"?o.emit(u+1):b.emit(g==="converged"?"converged":g==="budget"?"budget":"paused")})},{name:"decide-bridge"});return e.add(me,{name:"decide-bridge"}),e.addDisposer(me.subscribe(()=>{})),Object.assign(e,{best:h,score:N,status:b,history:E,strategy:i,iteration:o,generate:A,evaluate:p,analyze:G,decide:te,setStrategy(r){i.emit(r)},pause(){y.emit(!0)},resume(){b.cache==="paused"&&ee(()=>{y.emit(!1),b.emit("running"),o.emit(o.cache+1)})}})}function De(n){let l=n.width??4;return{name:n.name??"blindVariation",seed(t){return[t]},analyze(t,m){let e=ne(t),s=null;for(let o of t)(!s||o.score<s.score)&&(s=o);return{summary:`blindVariation iteration: mean=${e.toFixed(3)}, n=${t.length}`,score:e,weakTasks:s?[s.taskId]:[]}},async generate(t,m){if(m.length===0)throw new Error("blindVariation.generate: empty candidate batch \u2014 cannot derive prior for teacher");let e=m[m.length-1],s=0,i={prior:e,reportCost:d=>{s+=d}};try{if(n.parallel!==!1)return await Promise.all(Array.from({length:l},()=>n.teacher(i)));let d=[];for(let k=0;k<l;k++)d.push(await n.teacher(i));return d}finally{if(n.tokens!=null&&s>0){let d=n.tokens.cache??0;n.tokens.emit(d+s)}}}}}function Fe(n){return typeof n=="object"&&n!==null&&n.kind==="errorCritique"}function Ce(n,l){return n.length===0?`No task scored below the batch mean (${l.score.toFixed(3)}). Reinforce the current direction.`:`Failures below threshold:
|
|
2
|
+
${n.map(t=>{let m=t.error!=null?` | error: ${t.error}`:"";return`- ${t.taskId} (score=${t.score.toFixed(3)})${m}`}).join(`
|
|
3
|
+
`)}`}function Re(n){let l=n.width??4,x=n.name??"errorCritique",t=n.maxFailureSamples??5,m=n.formatCritique??Ce;return{name:x,seed(e){return[e]},analyze(e,s){let o=ne(e),i=typeof n.failureThreshold=="function"?n.failureThreshold(e):n.failureThreshold,d=i===void 0&&!Number.isFinite(o),k=i??o,y=d?[...e].sort((p,G)=>p.score-G.score):e.filter(p=>p.score<k).slice().sort((p,G)=>p.score-G.score),b=y.slice(0,t),{best:E,bestScore:h}=pe(s,e),N={summary:"",score:o,weakTasks:b.map(p=>p.taskId)},C=m(b,N),R={kind:"errorCritique",best:E,failures:b,critiqueText:C},A=y.length>b.length?` (top ${b.length} retained)`:"";return{summary:`errorCritique iteration: mean=${o.toFixed(3)}, failures=${y.length}${A}/${e.length}, bestScore=${h.toFixed(3)}`,critique:R,weakTasks:b.map(p=>p.taskId),score:o}},async generate(e,s){if(s.length===0)throw new Error("errorCritique.generate: empty candidate batch \u2014 cannot derive prior for teacher");let o=Fe(e.critique)?e.critique:void 0,i=o!==void 0?o.best:s[s.length-1],d=o?.critiqueText??e.summary,k=o?.failures??[],y=0,E={prior:i,critique:d,failures:k,reportCost:h=>{y+=h}};try{if(n.parallel!==!1)return await Promise.all(Array.from({length:l},()=>n.teacher(E)));let h=[];for(let N=0;N<l;N++)h.push(await n.teacher(E));return h}finally{if(n.tokens!=null&&y>0){let h=n.tokens.cache??0;n.tokens.emit(h+y)}}}}}export{Se as a,De as b,Re as c,we as d};
|
|
@@ -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{
|
|
1
|
+
import{j as f}from"./chunk-PSQNYY72.js";import{E as d}from"./chunk-7AJKUA36.js";import{b as S}from"./chunk-CK2E7BTU.js";import{b}from"./chunk-QYADASLV.js";var g={};b(g,{create:()=>v});var m=()=>!1;function v(l){let o=new f("zustand"),t=d(void 0,{name:"state",equals:m});o.add(t,{name:"state"});let r=()=>t.cache,n=(e,s)=>{let a=t.cache,i=typeof e=="function"?e(a):e;t.emit(s?i:{...a,...i})},c={getState:r,setState:n,getInitialState:()=>T,subscribe:e=>{let s=!0,a=t.cache;return t.subscribe(i=>{for(let[u,p]of i)if(u===S){if(s){s=!1;continue}e(p,a),a=p}})},destroy:o.destroy.bind(o)},T=l(n,r,c);return t.emit(T),Object.assign(o,c)}export{v as a,g as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as I}from"./chunk-
|
|
1
|
+
import{c as I}from"./chunk-K54OKWNY.js";import{g as _,j as P}from"./chunk-PSQNYY72.js";import{D as y,E as K,G as E,m as F}from"./chunk-7AJKUA36.js";import{b as j,d as x,i as A,j as D}from"./chunk-CK2E7BTU.js";import{b as B}from"./chunk-QYADASLV.js";var ee={};B(ee,{approval:()=>V,branch:()=>U,gate:()=>z,join:()=>J,loop:()=>Q,onFailure:()=>Z,pipeline:()=>L,sensor:()=>Y,subPipeline:()=>X,task:()=>H});function O(e,n){if(typeof n=="string")return{node:e.resolve(n),path:n};let o=$(e,n);if(!o)throw new Error("orchestration dep node must already be registered in the graph so explicit edges can be recorded; pass a string path or register the node first");return{node:n,path:o}}function $(e,n){let o=e.describe(),r=`::${_}::`;for(let t of Object.keys(o.nodes).sort())if(!t.includes(r))try{if(e.resolve(t)===n)return t}catch{}}function w(e,n,o,r){e.add(o,{name:n})}function N(e,n){return I("orchestration",e,n)}function W(e){let n=r=>{let t=r.trim();return t.length===0?0:Number(t)},o;return typeof e=="string"?o=n(e):e===null?o=0:o=Number(e),Number.isFinite(o)?Math.max(0,Math.trunc(o)):1}function L(e,n){return new P(e,n)}function H(e,n,o,r){let a=(r?.deps??[]).map(i=>O(e,i)),{deps:s,...p}=r??{},T=(i,f,c)=>{let l=i.map((h,g)=>h!=null&&h.length>0?h.at(-1):c.prevData[g]);f.emit(o(l,c))},d=y(a.map(i=>i.node),T,{...p,name:n,describeKind:"derived",meta:N("task",r?.meta)});return w(e,n,d,a.flatMap(i=>i.path?[i.path]:[])),d}function U(e,n,o,r,t){let a=O(e,o),s=E([a.node],([p])=>({branch:r(p)?"then":"else",value:p}),{...t,name:n,meta:N("branch",t?.meta)});return w(e,n,s,a.path?[a.path]:[]),s}function V(e,n,o,r,t){let a=O(e,o),s=O(e,r),p=t?.isApproved??(d=>!!d),T=y([a.node,s.node],(d,i,f)=>{let c=d[0],l=d[1],h=l!=null&&l.length>0?l.at(-1):f.prevData[1];if(h===void 0||!p(h)){i.down([[x]]);return}if(c==null||c.length===0){l!=null&&l.length>0&&f.prevData[0]!==void 0?i.emit(f.prevData[0]):i.down([[x]]);return}for(let g of c)i.emit(g)},{...t,name:n,describeKind:"derived",meta:N("approval",t?.meta)});return w(e,n,T,[a.path,s.path].filter(d=>typeof d=="string")),T}function z(e,n,o,r){let t=r?.maxPending??1/0;if(t<1&&t!==1/0)throw new RangeError("gate: maxPending must be >= 1");let a=r?.startOpen??!1,s=O(e,o),p=K([],{name:"pending",equals:()=>!1}),T=K(a,{name:"isOpen"}),d=E([p],([u])=>u.length,{name:"count"}),i=[],f=!1,c=a,l=T.subscribe(u=>{for(let m of u)m[0]===j&&(c=m[1])});function h(){p.emit([...i])}function g(u){i.push(u),i.length>t&&i.shift(),h()}function R(u){let m=i.splice(0,u);return h(),m}function k(u){if(f)throw new Error(`gate: ${u}() called after gate was torn down`)}let b=y([s.node],(u,m,S)=>{let G=S.terminalDeps[0];if(G!==void 0){f=!0,i=[],h(),m.down(G===!0?[[A]]:[[D,G]]);return}let v=u[0];if(v==null||v.length===0){m.down([[x]]);return}for(let C of v)c?m.emit(C):(g(C),m.down([[x]]))},{name:n,describeKind:"derived",meta:N("gate",r?.meta)}),q={node:b,pending:p,count:d,isOpen:T,approve(u=1){k("approve");let m=R(u);for(let S of m){if(f)break;b.emit(S)}},reject(u=1){k("reject"),R(u)},modify(u,m=1){k("modify");let S=[...i],G=R(m);for(let v=0;v<G.length&&!f;v++)b.emit(u(G[v],v,S))},open(){k("open"),F(()=>{T.emit(!0);let u=R(i.length);for(let m of u){if(f)break;b.emit(m)}})},close(){k("close"),T.emit(!1)}};e.addDisposer(d.subscribe(()=>{})),e.addDisposer(l),w(e,n,b,s.path?[s.path]:[]);let M=new P(`${n}_state`);return M.add(p,{name:"pending"}),M.add(T,{name:"isOpen"}),M.add(d,{name:"count"}),e.mount(`${n}_state`,M),q}function J(e,n,o,r){let t=o.map(s=>O(e,s)),a=E(t.map(s=>s.node),s=>s,{...r,name:n,meta:N("join",r?.meta)});return w(e,n,a,t.flatMap(s=>s.path?[s.path]:[])),a}function Q(e,n,o,r,t){let a=O(e,o),s=t?.iterations,p=typeof s=="number"||s===void 0?void 0:O(e,s),T=typeof s=="number"?s:void 0,d=y(p?[a.node,p.node]:[a.node],(i,f,c)=>{let l=i[0],h=l!=null&&l.length>0?l.at(-1):c.prevData[0],g=p?i[1]:void 0,R=T??(p?g!=null&&g.length>0?g.at(-1):c.prevData[1]:1),k=W(R);for(let b=0;b<k;b+=1)h=r(h,b,f);f.emit(h)},{...t,name:n,describeKind:"derived",meta:N("loop",t?.meta)});return w(e,n,d,[a.path,p?.path].filter(i=>typeof i=="string")),d}function X(e,n,o,r){let t=o instanceof P?o:L(n,r);return typeof o=="function"&&o(t),e.mount(n,t),t}function Y(e,n,o,r){let t=y([],()=>{},{...r,name:n,initial:o,describeKind:"producer",meta:N("sensor",r?.meta)});return w(e,n,t,[]),{node:t,push(a){t.emit(a)},error(a){t.down([[D,a]])},complete(){t.down([[A]])}}}function Z(e,n,o,r,t){let a=O(e,o),s=!1,p=y([],(T,d)=>{let i=a.node.subscribe(f=>{for(let c of f){if(s)return;if(c[0]===D)try{d.emit(r(c[1],d))}catch(l){s=!0,d.down([[D,l]])}else d.down([c]),c[0]===A&&(s=!0)}});return()=>i()},{...t,name:n,describeKind:"derived",completeWhenDepsComplete:!1,errorWhenDepsError:!1,meta:N("onFailure",t?.meta)});return w(e,n,p,a.path?[a.path]:[]),p}export{L as a,H as b,U as c,V as d,z as e,J as f,Q as g,X as h,Y as i,Z as j,ee as k};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as Y,b as m,c as M,d as S,e as C,f as N,g as L,h as k,i as D,j as _,k as P,l as he,n as se,q as ie,r as fe,s as pe,t as _e,u as re}from"./chunk-CK2E7BTU.js";var De={name:"json",version:1,contentType:"application/json",encode(n){let e=JSON.stringify(n);return new TextEncoder().encode(e)},decode(n,e){let t=new TextDecoder().decode(n);return JSON.parse(t)}};function $e(n){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>n.encode(e),decode:(e,t)=>n.decode(e)}}function je(n,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:t=>e.compressSync(n.encode(t)),decode:(t,s)=>n.decode(e.decompressSync(t))}}var oe=1,ge=4;function ze(n,e){let t=new TextEncoder().encode(n.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${n.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let s=n.version;if(!Number.isInteger(s)||s<0||s>65535)throw new Error(`encodeEnvelope: codec.version ${s} out of u16 range (expected integer 0\u201365535)`);let i=2+t.length+2+e.length;if(i>4294967295)throw new Error(`encodeEnvelope: total envelope size ${i} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let r=new Uint8Array(i),a=0;return r[a++]=oe,r[a++]=t.length,r.set(t,a),a+=t.length,r[a++]=s>>>8&255,r[a++]=s&255,r.set(e,a),r}function qe(n,e){if(n.length<ge)throw new Error(`decodeEnvelope: bytes too short (${n.length} < ${ge})`);let t=0,s=n[t++];if(s!==oe)throw new Error(`decodeEnvelope: unsupported envelope version ${s} (expected ${oe})`);let i=n[t++];if(i===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+i+2>n.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+i+2} bytes, have ${n.length})`);let r=new TextDecoder().decode(n.subarray(t,t+i));t+=i;let a=(n[t]<<8|n[t+1])>>>0;t+=2;let o=n.subarray(t),d=e.lookupCodec(r);if(d==null)throw new Error(`decodeEnvelope: codec "${r}" not registered (envelope codec_v=${a})`);return{codec:d,codecVersion:a,payload:o}}function ye(n){n.registerCodec(De)}function Ke(n){if(n.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=n[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let t=JSON.parse(JSON.stringify(e.snapshot)),s=e.seq;for(let i=1;i<n.length;i++){let r=n[i];if(r.seq<=s)throw new Error(`WAL chain broken at index ${i}: seq=${r.seq} must exceed prev seq=${s}`);if(r.mode==="full"){t=JSON.parse(JSON.stringify(r.snapshot)),s=r.seq;continue}let a=r.diff;for(let d of a.nodesRemoved)delete t.nodes[d];let o=a.nodesAddedFull;if(o!=null)for(let[d,l]of Object.entries(o))t.nodes[d]=JSON.parse(JSON.stringify(l));for(let d of a.nodesChanged){let l=t.nodes[d.path];l!=null&&(l[d.field]=d.to)}s=r.seq}return t}var Oe={type:"system",id:""};function J(n){if(n==null)return Oe;let{type:e,id:t,...s}=n;return{type:e??"system",id:t??"",...s}}var O=0,U=!1,A=[],E=[],R=[],W=[];function me(){return O>0||U}function be(){return O>0}function ve(n){O>0?W.push(n):n()}function Xe(n){O+=1;let e=!1;try{n()}catch(t){throw e=!0,t}finally{if(O-=1,O===0)if(e){if(!U){let t=W.splice(0);for(let s of t)try{s()}catch{}A.length=0,E.length=0,R.length=0}}else Re()}}function Re(){let n=!U;n&&(U=!0);let e=[],t=0;try{for(;A.length>0||E.length>0||R.length>0||n&&W.length>0;){if(n&&W.length>0){let r=W.splice(0);for(let a of r)try{a()}catch(o){e.push(o)}continue}if(t+=1,t>1e3)throw A.length=0,E.length=0,R.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let i=(A.length>0?A:E.length>0?E:R).splice(0);for(let r of i)try{r()}catch(a){e.push(a)}}}finally{n&&(U=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function X(n,e,t){if(e.length===0)return;if(e.length===1){let l=t(e[0][0]);if(l<3||!me()){n(e);return}(l>=5?R:l===4?E:A).push(()=>n(e));return}let s=e.length,i=s,r=s,a=s,o=0;for(;o<s&&t(e[o][0])<3;)o++;for(i=o;o<s&&t(e[o][0])===3;)o++;for(r=o;o<s&&t(e[o][0])===4;)o++;a=o;let d=me();if(i>0){let l=e.slice(0,i);n(l)}if(r>i){let l=e.slice(i,r);d?A.push(()=>n(l)):n(l)}if(a>r){let l=e.slice(r,a);d?E.push(()=>n(l)):n(l)}if(s>a){let l=e.slice(a,s);d?R.push(()=>n(l)):n(l)}}function Qe(){return Math.trunc(performance.now()*1e6)}function we(){return Date.now()*1e6}var Z=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let s=this._messageTypes.get(t);return s!=null?s.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}};function xe(n){n.registerMessageType(Y,{tier:0,wireCrossing:!1}),n.registerMessageType(M,{tier:1,wireCrossing:!1}),n.registerMessageType(C,{tier:1,wireCrossing:!1,metaPassthrough:!1}),n.registerMessageType(N,{tier:2,wireCrossing:!1}),n.registerMessageType(L,{tier:2,wireCrossing:!1}),n.registerMessageType(m,{tier:3,wireCrossing:!0}),n.registerMessageType(S,{tier:3,wireCrossing:!0}),n.registerMessageType(D,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(_,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(k,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var F=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};function Te(n){return Array.isArray(n)?[...n]:[n]}function Fe(n,e){return n.has(e)||n.has("*")}function Ge(n){let e=[];return n((i,r)=>{e.push({kind:"allow",actions:new Set(Te(i)),where:r?.where??(()=>!0)})},(i,r)=>{e.push({kind:"deny",actions:new Set(Te(i)),where:r?.where??(()=>!0)})}),(i,r)=>{let a=!1,o=!1;for(let d of e)Fe(d.actions,r)&&d.where(i)&&(d.kind==="deny"?a=!0:o=!0);return a?!1:o}}function st(n){return Ge((e,t)=>{for(let s of n){let i=s.actorType==null?null:new Set(Array.isArray(s.actorType)?s.actorType:[s.actorType]),r=s.actorId==null?null:new Set(Array.isArray(s.actorId)?s.actorId:[s.actorId]),a=Object.entries(s.claims??{}),o=d=>{if(i!==null&&!i.has(String(d.type))||r!==null&&!r.has(String(d.id??"")))return!1;for(let[l,c]of a)if(d[l]!==c)return!1;return!0};s.effect==="deny"?t(s.action,{where:o}):e(s.action,{where:o})}})}var Ie=["human","llm","wallet","system"];function it(n){let e=Ie.filter(t=>n({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}function ae(n){if(n===void 0)return null;if(typeof n=="number"){if(!Number.isFinite(n))throw new TypeError(`Cannot hash non-finite number: ${n}`);if(Number.isInteger(n)&&!Number.isSafeInteger(n))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${n}. Cross-language cid parity is not guaranteed for unsafe integers.`);return n}if(typeof n=="string"||typeof n=="boolean"||n===null)return n;if(Array.isArray(n))return n.map(ae);if(typeof n=="object"&&n!==null){let e={};for(let t of Object.keys(n).sort())e[t]=ae(n[t]);return e}return null}var He=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ve=new TextEncoder;function Le(n){let e=Ve.encode(n),t=e.length,s=t*8,i=t+9+63&-64,r=new Uint8Array(i);r.set(e),r[t]=128;let a=new DataView(r.buffer);a.setUint32(i-4,s>>>0,!1),a.setUint32(i-8,Math.floor(s/4294967296)>>>0,!1);let o=1779033703,d=3144134277,l=1013904242,c=2773480762,u=1359893119,p=2600822924,h=528734635,b=1541459225,T=new Uint32Array(64),y=(w,g)=>w>>>g|w<<32-g;for(let w=0;w<i;w+=64){for(let f=0;f<16;f++)T[f]=a.getUint32(w+f*4,!1);for(let f=16;f<64;f++){let H=T[f-15],V=T[f-2],K=y(H,7)^y(H,18)^H>>>3,ne=y(V,17)^y(V,19)^V>>>10;T[f]=T[f-16]+K+T[f-7]+ne>>>0}let g=o,G=d,I=l,ee=c,x=u,z=p,q=h,te=b;for(let f=0;f<64;f++){let H=y(x,6)^y(x,11)^y(x,25),V=x&z^~x&q,K=te+H+V+He[f]+T[f]>>>0,ne=y(g,2)^y(g,13)^y(g,22),Se=g&G^g&I^G&I,Ce=ne+Se>>>0;te=q,q=z,z=x,x=ee+K>>>0,ee=I,I=G,G=g,g=K+Ce>>>0}o=o+g>>>0,d=d+G>>>0,l=l+I>>>0,c=c+ee>>>0,u=u+x>>>0,p=p+z>>>0,h=h+q>>>0,b=b+te>>>0}let v=w=>w.toString(16).padStart(8,"0");return v(o)+v(d)+v(l)+v(c)+v(u)+v(p)+v(h)+v(b)}function de(n){let e=ae(n??null),t=JSON.stringify(e);return Le(t).slice(0,16)}function Pe(){let n=globalThis.crypto;if(n?.randomUUID)return n.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function le(n,e,t){let s=t?.id??Pe();if(n===0)return{id:s,version:0};let r=(t?.hash??de)(e);return{id:s,version:0,cid:r,prev:null}}function Ne(n,e,t){n.version+=1,"cid"in n&&(n.prev=n.cid,n.cid=t(e))}function ot(n){return"cid"in n}var ke=()=>{},Ae=100;function Ee(n){return{node:n,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function ce(n){n.prevData=void 0,n.dirty=!1,n.involvedThisWave=!1,n.dataBatch.length=0,n.terminal=void 0}function Q(n){return n.length===0?n:typeof n[0]=="symbol"?[n]:n}var Ue=(n,e,t,s)=>{t.direction==="down-in"&&n._onDepMessage(t.depIndex,e)},We=(n,e,t,s)=>{let i=n;if(i._status==="completed"||i._status==="errored")return;let r=i._cached,a=r===void 0?[se]:[se,[m,r]];i._status==="dirty"&&a.push(P),X(e,a,i._config.tierOf)},B=new Z({onMessage:Ue,onSubscribe:We});xe(B);ye(B);function gt(n){if(B._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");n(B)}var $=class n{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,t,s){this._config=s.config??B,this._config.onMessage,this._optsName=s.name,this._describeKind=s.describeKind,this._equals=s.equals??Object.is,this._resubscribable=s.resubscribable??!1,this._resetOnTeardown=s.resetOnTeardown??!1,this._autoComplete=s.completeWhenDepsComplete??!0,this._autoError=s.errorWhenDepsError??!0,this._pausable=s.pausable??!0,this._guard=s.guard,this._fn=t,this._partial=s.partial??!1,this._cached=s.initial!==void 0?s.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=s.versioningHash??this._config.defaultHashFn??de;let i=s.versioning??this._config.defaultVersioning;this._versioningLevel=i,this._versioning=i!=null?le(i,this._cached===void 0?void 0:this._cached,{id:s.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Ee);let r={};for(let[o,d]of Object.entries(s.meta??{})){let l={initial:d,name:`${s.name??"node"}:meta:${o}`,describeKind:"state",config:this._config};s.guard!=null&&(l.guard=s.guard),r[o]=new n([],void 0,l)}Object.freeze(r),this.meta=r,this._hasMeta=Object.keys(r).length>0;let a=this;this._actions={emit(o){a._emit([[m,o]])},down(o){a._emit(Q(o))},up(o){a._emitUp(Q(o))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,t){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let s=this._versioningLevel;if(s!=null&&e<=s)return;let i=t?.hash??this._hashFn;i!==this._hashFn&&(this._hashFn=i);let r=this._cached===void 0?void 0:this._cached,a=this._versioning,o=a?.id??t?.id,d=a?.version??0,l=le(e,r,{id:o,hash:i});l.version=d,this._versioning=l,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let t=J(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let s of this._extraGuards)if(!s(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,s=e?.actor!=null;if(!t&&!s)return;let i=J(e?.actor),r=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(i,r))throw new F({actor:i,action:r,nodeName:this.name});if(this._extraGuards!=null){for(let a of this._extraGuards)if(!a(i,r))throw new F({actor:i,action:r,nodeName:this.name})}this._lastMutation={actor:i,timestamp_ns:we()}}down(e,t){let s=Q(e);s.length!==0&&(this._checkGuard(t),this._emit(s))}emit(e,t){this._checkGuard(t),this._emit([[m,e]])}up(e,t){if(this._deps.length===0)return;let s=Q(e);if(s.length===0)return;this._checkGuard(t);let i=t??{internal:!0};this._validateUpTiers(s);for(let r of this._deps)r.node.up?.(s,i)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let s of e){let i=t(s[0]);if(i===3||i===4)throw new Error(`Node "${this.name}": tier-${i} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,t){if(t!=null&&this._guard!=null){let d=J(t);if(!this._guard(d,"observe"))throw new F({actor:d,action:"observe",nodeName:this.name})}let i=this._isTerminal&&this._resubscribable;if(i){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)ce(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let r;try{r=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:i},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let a=this._isTerminal;if(this._sinkCount===1&&!a)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof r=="function")try{r()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let o=!1;return()=>{o||(o=!0,this._sinkCount-=1,this._removeSink(e),typeof r=="function"&&r(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[t]=this._sinks;this._sinks=t}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,t=0;try{for(let s=0;s<e;s++){let i=s,r=this._deps[s];r.unsub=ke,r.unsub=r.node.subscribe(a=>{if(r.unsub===null)return;let o=this._config.tierOf,d=!1;for(let l of a)o(l[0])>=3&&(d=!0),this._config.onMessage(this,l,{direction:"down-in",depIndex:i},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(s){this._deps[t].unsub=null;for(let i=0;i<t;i++){let r=this._deps[i];if(r.unsub!=null){let a=r.unsub;r.unsub=null;try{a()}catch{}ce(r)}}throw this._dirtyDepCount=0,s}}_addDep(e){for(let i=0;i<this._deps.length;i++)if(this._deps[i].node===e)return i;let t=this._deps.length,s=Ee(e);if(this._deps.push(s),this._sinks==null)return t;s.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ie),s.unsub=ke;try{s.unsub=e.subscribe(i=>{if(s.unsub===null)return;let r=this._config.tierOf,a=!1;for(let o of i)r(o[0])>=3&&(a=!0),this._config.onMessage(this,o,{direction:"down-in",depIndex:t},this._actions);a&&this._maybeRunFnOnSettlement()})}catch(i){throw s.unsub=null,this._deps.pop(),this._dirtyDepCount--,i}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(s){this._emit([[_,this._wrapFnError("cleanup threw",s)]])}else if(t!=null&&typeof t=="object"){let s=t.deactivate;if(typeof s=="function")try{s()}catch(i){this._emit([[_,this._wrapFnError("cleanup.deactivate threw",i)]])}}for(let s of this._deps){if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}}ce(s)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,t){let s=this._deps[e],i=t[0];if(this._inspectorHooks!=null){let r={kind:"dep_message",depIndex:e,message:t};for(let a of this._inspectorHooks)a(r)}if(i!==Y){if(i===M){this._depDirtied(s);return}if(i===C){this._depInvalidated(s),this._emit(pe);return}if(i===N||i===L){this._emit([t]);return}if(i===k){this._emit(re);return}if(i===m)this._depSettledAsData(s,t[1]);else if(i===S)this._depSettledAsResolved(s);else if(i===D)this._depSettledAsTerminal(s,!0);else if(i===_)this._depSettledAsTerminal(s,t[1]);else{this._emit([t]);return}if(!this._fn){(i===m||i===S)&&this._emit([t]),(i===D||i===_)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ie))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(fe),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[_,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(_e)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(a){this._emit([[_,this._wrapFnError("cleanup threw",a)]]);return}}else if(e!=null&&typeof e=="object"){let a=e.beforeRun;if(typeof a=="function"){e.beforeRun=void 0;try{a()}catch(o){this._emit([[_,this._wrapFnError("cleanup.beforeRun threw",o)]]);return}}}let t=this._deps.map(a=>a.involvedThisWave?a.dataBatch.length>0?[...a.dataBatch]:[]:void 0),s=this._deps.map(a=>a.prevData);for(let a=0;a<this._deps.length;a++){let o=t[a];o!=null&&o.length>0&&(this._deps[a].prevData=o[o.length-1])}let i=this._deps.map(a=>a.terminal),r={prevData:s,terminalDeps:i,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let a={kind:"run",batchData:t,prevData:s};for(let o of this._inspectorHooks)o(a)}this._isExecutingFn=!0;try{let a=this._fn(t,this._actions,r);if(typeof a=="function")this._cleanup=a;else if(a!=null&&typeof a=="object"){let o=a;(typeof o.beforeRun=="function"||typeof o.deactivate=="function"||typeof o.invalidate=="function")&&(this._cleanup=a)}}catch(a){this._emit([[_,this._wrapFnError("fn threw",a)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Ae?(this._rerunDepth=0,this._emit([[_,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Ae} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,t){let s=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${s}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[P,e[0]]:e;let s=!0,i=!1,r=!1,a=-1;for(let d of e){let l=t(d[0]);l<a&&(s=!1),l===3&&(i=!0),d[0]===M&&(r=!0),a=l}let o=e;if(!s){let d=e.map((l,c)=>({m:l,i:c,tier:t(l[0])}));d.sort((l,c)=>l.tier-c.tier||l.i-c.i),o=d.map(l=>l.m)}if(i&&!r&&this._status!=="dirty"){let d=0;for(;d<o.length&&t(o[d][0])===0;)d++;return d===0?[P,...o]:[...o.slice(0,d),P,...o.slice(d)]}return o}_emit(e){if(e.length===0)return;for(let o=0;o<e.length;o++){let d=e[o];if(d[0]===_&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let t=e;if(this._isTerminal&&!this._resubscribable){let o=e.filter(d=>d[0]===k||d[0]===C);if(o.length===0)return;t=o}t=this._frameBatch(t);let i=null;for(let o=0;o<t.length;o++){let d=t[o],l=d[0];if(l!==N&&l!==L){i?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${l===N?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let u=d[1];if(l===N)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(u),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(u))c=!1;else if(this._pauseLocks.delete(u),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?i?.push(d):i==null&&(i=t.slice(0,o))}if(i!=null){if(i.length===0)return;t=i}if(this._hasMeta&&t.some(o=>o[0]===k))for(let o of Object.keys(this.meta))try{this.meta[o]._emit(re)}catch{}let{finalMessages:r,equalsError:a}=this._updateState(t);if(r.length>0&&this._config.inspectorEnabled){let o=this._config.globalInspector;if(o!=null)try{o({kind:"emit",node:this,messages:r})}catch{}}if(r.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let o=this._config.tierOf,d=[];for(let l of r)o(l[0])===3?this._pauseBuffer.push(l):d.push(l);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(r);a!=null&&this._emit([[_,a]])}_updateState(e){let t=this._config.tierOf,s,i,r=-1,a=0;for(let c of e)t(c[0])===3&&a++;let o=a<=1,d=-1;if(this._versioning!=null&&a>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===m){d=c;break}}for(let c=0;c<e.length;c++){let u=e[c],p=u[0];if(p===m){if(u.length>=2){let h=!1;if(o&&this._cached!==void 0)try{h=this._equals(this._cached,u[1])}catch(b){i=this._wrapFnError("equals threw",b),r=c;break}if(h){s==null&&(s=e.slice(0,c)),s.push(he),this._status="resolved";continue}this._cached=u[1],this._versioning!=null&&(d<0||c===d)&&Ne(this._versioning,u[1],this._hashFn)}this._status="settled",s?.push(u)}else if(s?.push(u),p===M)this._status="dirty";else if(p===S)this._status="resolved";else if(p===D)this._status="completed";else if(p===_)this._status="errored";else if(p===C){this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let b=h.invalidate;if(typeof b=="function")try{b()}catch{}}}else p===k&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let l=r>=0?s??e.slice(0,r):s??e;return i!=null?{finalMessages:l,equalsError:i}:{finalMessages:l}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let s of t)s(e)};_dispatchOrAccumulate(e){if(be()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],ve(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}X(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);X(this._deliverToSinks,t,this._config.tierOf)}},Me=n=>Array.isArray(n),ue=n=>typeof n=="object"&&n!=null&&!Array.isArray(n);function j(n,e,t){let s=Me(n)?n:[],i=typeof n=="function"?n:typeof e=="function"?e:void 0,r={};return Me(n)?r=(ue(e)?e:t)??{}:ue(n)?r=n:r=(ue(e)?e:t)??{},new $(s,i,r)}function bt(n,e){return j([],{...e,initial:n})}function vt(n,e){return j((s,i,r)=>n(i,r)??void 0,{describeKind:"producer",...e})}function Be(n,e,t){return j(n,(i,r,a)=>{let o=i.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);r.emit(e(o,a))},{describeKind:"derived",...t})}function wt(n,e,t){return j(n,(i,r,a)=>{let o=i.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);return e(o,r,a)??void 0},{describeKind:"effect",...t})}function xt(n,e,t){let s=new Map;return n.forEach((i,r)=>{s.set(i,r)}),Be(n,(i,r)=>e(o=>{let d=s.get(o);if(d==null)throw new Error(`dynamicNode: untracked dep "${o.name??"<unnamed>"}"`);return i[d]},r),t)}function Tt(n,e){let t,s=new Map,i=(r,a,o)=>{let d=!1,l=c=>{let u=s.get(c);if(u!==void 0){if(u<r.length){let h=r[u];return h!=null&&h.length>0?h.at(-1):o.prevData[u]}return c.cache}d=!0;let p=t._addDep(c);return s.set(c,p),c.cache};try{let c=n(l,o);d||(a.emit(c),o.store.__autoTrackLastDiscoveryError!=null&&delete o.store.__autoTrackLastDiscoveryError)}catch(c){if(!d)throw c;o.store.__autoTrackLastDiscoveryError=c}};return t=new $([],i,{describeKind:"derived",...e}),t}function Nt(n,...e){let t=n;for(let s of e)t=s(t);return t}export{De as a,$e as b,je as c,oe as d,ze as e,qe as f,ye as g,Ke as h,Oe as i,J as j,me as k,ve as l,Xe as m,X as n,Qe as o,we as p,Z as q,xe as r,F as s,Ge as t,st as u,it as v,de as w,le as x,Ne as y,ot as z,B as A,gt as B,$ as C,j as D,bt as E,vt as F,Be as G,wt as H,xt as I,Tt as J,Nt as K};
|
|
1
|
+
import{a as Y,b as m,c as M,d as S,e as C,f as N,g as L,h as k,i as D,j as _,k as P,l as he,n as se,q as ie,r as fe,s as pe,t as _e,u as re}from"./chunk-CK2E7BTU.js";var De={name:"json",version:1,contentType:"application/json",encode(n){let e=JSON.stringify(n);return new TextEncoder().encode(e)},decode(n,e){let t=new TextDecoder().decode(n);return JSON.parse(t)}};function $e(n){return{name:"dag-cbor",version:1,contentType:"application/dag-cbor",encode:e=>n.encode(e),decode:(e,t)=>n.decode(e)}}function je(n,e){return{name:"dag-cbor-zstd",version:1,contentType:"application/dag-cbor+zstd",encode:t=>e.compressSync(n.encode(t)),decode:(t,s)=>n.decode(e.decompressSync(t))}}var oe=1,ge=4;function ze(n,e){let t=new TextEncoder().encode(n.name);if(t.length===0||t.length>255)throw new Error(`encodeEnvelope: codec name "${n.name}" encodes to ${t.length} bytes (must be 1\u2013255)`);let s=n.version;if(!Number.isInteger(s)||s<0||s>65535)throw new Error(`encodeEnvelope: codec.version ${s} out of u16 range (expected integer 0\u201365535)`);let i=2+t.length+2+e.length;if(i>4294967295)throw new Error(`encodeEnvelope: total envelope size ${i} exceeds 2^32-1 bytes (payload ${e.length} bytes)`);let r=new Uint8Array(i),a=0;return r[a++]=oe,r[a++]=t.length,r.set(t,a),a+=t.length,r[a++]=s>>>8&255,r[a++]=s&255,r.set(e,a),r}function qe(n,e){if(n.length<ge)throw new Error(`decodeEnvelope: bytes too short (${n.length} < ${ge})`);let t=0,s=n[t++];if(s!==oe)throw new Error(`decodeEnvelope: unsupported envelope version ${s} (expected ${oe})`);let i=n[t++];if(i===0)throw new Error("decodeEnvelope: name_len must be >= 1");if(t+i+2>n.length)throw new Error(`decodeEnvelope: envelope truncated (need ${t+i+2} bytes, have ${n.length})`);let r=new TextDecoder().decode(n.subarray(t,t+i));t+=i;let a=(n[t]<<8|n[t+1])>>>0;t+=2;let o=n.subarray(t),d=e.lookupCodec(r);if(d==null)throw new Error(`decodeEnvelope: codec "${r}" not registered (envelope codec_v=${a})`);return{codec:d,codecVersion:a,payload:o}}function ye(n){n.registerCodec(De)}function Ke(n){if(n.length===0)throw new Error("WAL is empty \u2014 need at least one full snapshot");let e=n[0];if(e.mode!=="full")throw new Error("WAL must start with a full record carrying a baseline snapshot");let t=JSON.parse(JSON.stringify(e.snapshot)),s=e.seq;for(let i=1;i<n.length;i++){let r=n[i];if(r.seq<=s)throw new Error(`WAL chain broken at index ${i}: seq=${r.seq} must exceed prev seq=${s}`);if(r.mode==="full"){t=JSON.parse(JSON.stringify(r.snapshot)),s=r.seq;continue}let a=r.diff;for(let d of a.nodesRemoved)delete t.nodes[d];let o=a.nodesAddedFull;if(o!=null)for(let[d,l]of Object.entries(o))t.nodes[d]=JSON.parse(JSON.stringify(l));for(let d of a.nodesChanged){let l=t.nodes[d.path];l!=null&&(l[d.field]=d.to)}s=r.seq}return t}var Oe={type:"system",id:""};function J(n){if(n==null)return Oe;let{type:e,id:t,...s}=n;return{type:e??"system",id:t??"",...s}}var O=0,U=!1,A=[],E=[],R=[],W=[];function me(){return O>0||U}function be(){return O>0}function ve(n){O>0?W.push(n):n()}function Xe(n){O+=1;let e=!1;try{n()}catch(t){throw e=!0,t}finally{if(O-=1,O===0)if(e){if(!U){let t=W.splice(0);for(let s of t)try{s()}catch{}A.length=0,E.length=0,R.length=0}}else Re()}}function Re(){let n=!U;n&&(U=!0);let e=[],t=0;try{for(;A.length>0||E.length>0||R.length>0||n&&W.length>0;){if(n&&W.length>0){let r=W.splice(0);for(let a of r)try{a()}catch(o){e.push(o)}continue}if(t+=1,t>1e3)throw A.length=0,E.length=0,R.length=0,new Error("batch drain exceeded 1000 iterations \u2014 likely a reactive cycle");let i=(A.length>0?A:E.length>0?E:R).splice(0);for(let r of i)try{r()}catch(a){e.push(a)}}}finally{n&&(U=!1)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"batch drain: multiple callbacks threw")}function X(n,e,t){if(e.length===0)return;if(e.length===1){let l=t(e[0][0]);if(l<3||!me()){n(e);return}(l>=5?R:l===4?E:A).push(()=>n(e));return}let s=e.length,i=s,r=s,a=s,o=0;for(;o<s&&t(e[o][0])<3;)o++;for(i=o;o<s&&t(e[o][0])===3;)o++;for(r=o;o<s&&t(e[o][0])===4;)o++;a=o;let d=me();if(i>0){let l=e.slice(0,i);n(l)}if(r>i){let l=e.slice(i,r);d?A.push(()=>n(l)):n(l)}if(a>r){let l=e.slice(r,a);d?E.push(()=>n(l)):n(l)}if(s>a){let l=e.slice(a,s);d?R.push(()=>n(l)):n(l)}}function Qe(){return Math.trunc(performance.now()*1e6)}function we(){return Date.now()*1e6}var Z=class{_messageTypes=new Map;_codecs=new Map;_onMessage;_onSubscribe;_defaultVersioning;_defaultHashFn;_inspectorEnabled=!(typeof process<"u"&&process.env?.NODE_ENV==="production");_globalInspector;_frozen=!1;tierOf;constructor(e){this._onMessage=e.onMessage,this._onSubscribe=e.onSubscribe,this._defaultVersioning=e.defaultVersioning,this._defaultHashFn=e.defaultHashFn,this.tierOf=t=>{let s=this._messageTypes.get(t);return s!=null?s.tier:1}}get onMessage(){return this._frozen=!0,this._onMessage}get onSubscribe(){return this._frozen=!0,this._onSubscribe}set onMessage(e){this._assertUnfrozen(),this._onMessage=e}set onSubscribe(e){this._assertUnfrozen(),this._onSubscribe=e}get defaultVersioning(){return this._defaultVersioning}set defaultVersioning(e){this._assertUnfrozen(),this._defaultVersioning=e}get defaultHashFn(){return this._defaultHashFn}set defaultHashFn(e){this._assertUnfrozen(),this._defaultHashFn=e}get inspectorEnabled(){return this._inspectorEnabled}set inspectorEnabled(e){this._inspectorEnabled=e}get globalInspector(){return this._globalInspector}set globalInspector(e){this._globalInspector=e}registerMessageType(e,t){return this._assertUnfrozen(),this._messageTypes.set(e,{tier:t.tier,wireCrossing:t.wireCrossing??t.tier>=3,metaPassthrough:t.metaPassthrough??!0}),this}messageTier(e){let t=this._messageTypes.get(e);return t!=null?t.tier:1}isWireCrossing(e){let t=this._messageTypes.get(e);return t!=null?t.wireCrossing:!0}isLocalOnly(e){return!this.isWireCrossing(e)}isMetaPassthrough(e){let t=this._messageTypes.get(e);return t!=null?t.metaPassthrough:!0}isKnownMessageType(e){return this._messageTypes.has(e)}registerCodec(e){return this._assertUnfrozen(),this._codecs.set(e.name,e),this}lookupCodec(e){return this._codecs.get(e)}_isFrozen(){return this._frozen}_assertUnfrozen(){if(this._frozen)throw new Error("GraphReFlyConfig is frozen: a node has already captured this config. Register custom types and set hooks before creating any node.")}};function xe(n){n.registerMessageType(Y,{tier:0,wireCrossing:!1}),n.registerMessageType(M,{tier:1,wireCrossing:!1}),n.registerMessageType(C,{tier:1,wireCrossing:!1,metaPassthrough:!1}),n.registerMessageType(N,{tier:2,wireCrossing:!1}),n.registerMessageType(L,{tier:2,wireCrossing:!1}),n.registerMessageType(m,{tier:3,wireCrossing:!0}),n.registerMessageType(S,{tier:3,wireCrossing:!0}),n.registerMessageType(D,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(_,{tier:4,wireCrossing:!0,metaPassthrough:!1}),n.registerMessageType(k,{tier:5,wireCrossing:!0,metaPassthrough:!1})}var F=class extends Error{actor;action;nodeName;constructor(e,t){super(t??`GuardDenied: action "${String(e.action)}" denied for actor type "${String(e.actor.type)}"`),this.name="GuardDenied",this.actor=e.actor,this.action=e.action,this.nodeName=e.nodeName}get node(){return this.nodeName}};function Te(n){return Array.isArray(n)?[...n]:[n]}function Fe(n,e){return n.has(e)||n.has("*")}function Ge(n){let e=[];return n((i,r)=>{e.push({kind:"allow",actions:new Set(Te(i)),where:r?.where??(()=>!0)})},(i,r)=>{e.push({kind:"deny",actions:new Set(Te(i)),where:r?.where??(()=>!0)})}),(i,r)=>{let a=!1,o=!1;for(let d of e)Fe(d.actions,r)&&d.where(i)&&(d.kind==="deny"?a=!0:o=!0);return a?!1:o}}function st(n){return Ge((e,t)=>{for(let s of n){let i=s.actorType==null?null:new Set(Array.isArray(s.actorType)?s.actorType:[s.actorType]),r=s.actorId==null?null:new Set(Array.isArray(s.actorId)?s.actorId:[s.actorId]),a=Object.entries(s.claims??{}),o=d=>{if(i!==null&&!i.has(String(d.type))||r!==null&&!r.has(String(d.id??"")))return!1;for(let[l,c]of a)if(d[l]!==c)return!1;return!0};s.effect==="deny"?t(s.action,{where:o}):e(s.action,{where:o})}})}var Ie=["human","llm","wallet","system"];function it(n){let e=Ie.filter(t=>n({type:t,id:""},"write"));return e.length===0?"restricted":e.includes("human")&&e.includes("llm")&&e.every(t=>t==="human"||t==="llm"||t==="system")?"both":e.length===1?e[0]:e.join("+")}function ae(n){if(n===void 0)return null;if(typeof n=="number"){if(!Number.isFinite(n))throw new TypeError(`Cannot hash non-finite number: ${n}`);if(Number.isInteger(n)&&!Number.isSafeInteger(n))throw new TypeError(`Cannot hash integer outside safe range (|n| > 2^53-1): ${n}. Cross-language cid parity is not guaranteed for unsafe integers.`);return n}if(typeof n=="string"||typeof n=="boolean"||n===null)return n;if(Array.isArray(n))return n.map(ae);if(typeof n=="object"&&n!==null){let e={};for(let t of Object.keys(n).sort())e[t]=ae(n[t]);return e}return null}var He=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ve=new TextEncoder;function Le(n){let e=Ve.encode(n),t=e.length,s=t*8,i=t+9+63&-64,r=new Uint8Array(i);r.set(e),r[t]=128;let a=new DataView(r.buffer);a.setUint32(i-4,s>>>0,!1),a.setUint32(i-8,Math.floor(s/4294967296)>>>0,!1);let o=1779033703,d=3144134277,l=1013904242,c=2773480762,u=1359893119,p=2600822924,h=528734635,b=1541459225,T=new Uint32Array(64),y=(w,g)=>w>>>g|w<<32-g;for(let w=0;w<i;w+=64){for(let f=0;f<16;f++)T[f]=a.getUint32(w+f*4,!1);for(let f=16;f<64;f++){let H=T[f-15],V=T[f-2],K=y(H,7)^y(H,18)^H>>>3,ne=y(V,17)^y(V,19)^V>>>10;T[f]=T[f-16]+K+T[f-7]+ne>>>0}let g=o,G=d,I=l,ee=c,x=u,z=p,q=h,te=b;for(let f=0;f<64;f++){let H=y(x,6)^y(x,11)^y(x,25),V=x&z^~x&q,K=te+H+V+He[f]+T[f]>>>0,ne=y(g,2)^y(g,13)^y(g,22),Se=g&G^g&I^G&I,Ce=ne+Se>>>0;te=q,q=z,z=x,x=ee+K>>>0,ee=I,I=G,G=g,g=K+Ce>>>0}o=o+g>>>0,d=d+G>>>0,l=l+I>>>0,c=c+ee>>>0,u=u+x>>>0,p=p+z>>>0,h=h+q>>>0,b=b+te>>>0}let v=w=>w.toString(16).padStart(8,"0");return v(o)+v(d)+v(l)+v(c)+v(u)+v(p)+v(h)+v(b)}function de(n){let e=ae(n??null),t=JSON.stringify(e);return Le(t).slice(0,16)}function Pe(){let n=globalThis.crypto;if(n?.randomUUID)return n.randomUUID();let e=()=>Math.floor(Math.random()*4294967296).toString(16).padStart(8,"0"),t=e()+e()+e()+e();return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-${(parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}-${t.slice(20,32)}`}function le(n,e,t){let s=t?.id??Pe();if(n===0)return{id:s,version:0};let r=(t?.hash??de)(e);return{id:s,version:0,cid:r,prev:null}}function Ne(n,e,t){n.version+=1,"cid"in n&&(n.prev=n.cid,n.cid=t(e))}function ot(n){return"cid"in n}var ke=()=>{},Ae=100;function Ee(n){return{node:n,unsub:null,prevData:void 0,dirty:!1,involvedThisWave:!1,dataBatch:[],terminal:void 0}}function ce(n){n.prevData=void 0,n.dirty=!1,n.involvedThisWave=!1,n.dataBatch.length=0,n.terminal=void 0}function Q(n){return n.length===0?n:typeof n[0]=="symbol"?[n]:n}var Ue=(n,e,t,s)=>{t.direction==="down-in"&&n._onDepMessage(t.depIndex,e)},We=(n,e,t,s)=>{let i=n;if(i._status==="completed"||i._status==="errored")return;let r=i._cached,a=r===void 0?[se]:[se,[m,r]];i._status==="dirty"&&a.push(P),X(e,a,i._config.tierOf)},B=new Z({onMessage:Ue,onSubscribe:We});xe(B);ye(B);function gt(n){if(B._isFrozen())throw new Error("configure() called after a node was created \u2014 the default GraphReFlyConfig is frozen. Call configure(...) at application startup, before any node factories run.");n(B)}var $=class n{_optsName;_describeKind;meta;_hasMeta;_config;_deps;_sinks=null;_sinkCount=0;_cached;_status;_cleanup;_store={};_waveHasNewData=!1;_hasNewTerminal=!1;_hasCalledFnOnce=!1;_paused=!1;_pendingWave=!1;_isExecutingFn=!1;_pendingRerun=!1;_rerunDepth=0;_dirtyDepCount=0;_batchPendingMessages=null;_pauseLocks=null;_pauseBuffer=null;_fn;_equals;_resubscribable;_resetOnTeardown;_autoComplete;_autoError;_pausable;_partial;_guard;_extraGuards;_hashFn;_versioning;_versioningLevel;_lastMutation;_inspectorHooks;_actions;constructor(e,t,s){this._config=s.config??B,this._config.onMessage,this._optsName=s.name,this._describeKind=s.describeKind,this._equals=s.equals??Object.is,this._resubscribable=s.resubscribable??!1,this._resetOnTeardown=s.resetOnTeardown??!1,this._autoComplete=s.completeWhenDepsComplete??!0,this._autoError=s.errorWhenDepsError??!0,this._pausable=s.pausable??!0,this._guard=s.guard,this._fn=t,this._partial=s.partial??!1,this._cached=s.initial!==void 0?s.initial:void 0,this._status=e.length===0&&t==null&&this._cached!==void 0?"settled":"sentinel",this._hashFn=s.versioningHash??this._config.defaultHashFn??de;let i=s.versioning??this._config.defaultVersioning;this._versioningLevel=i,this._versioning=i!=null?le(i,this._cached===void 0?void 0:this._cached,{id:s.versioningId,hash:this._hashFn}):void 0,this._deps=e.map(Ee);let r={};for(let[o,d]of Object.entries(s.meta??{})){let l={initial:d,name:`${s.name??"node"}:meta:${o}`,describeKind:"state",config:this._config};s.guard!=null&&(l.guard=s.guard),r[o]=new n([],void 0,l)}Object.freeze(r),this.meta=r,this._hasMeta=Object.keys(r).length>0;let a=this;this._actions={emit(o){a._emit([[m,o]])},down(o){a._emit(Q(o))},up(o){a._emitUp(Q(o))}},this.down=this.down.bind(this),this.up=this.up.bind(this)}get _isTerminal(){return this._status==="completed"||this._status==="errored"}get name(){return this._optsName}get status(){return this._status}get cache(){return this._cached===void 0?void 0:this._cached}get lastMutation(){return this._lastMutation}get v(){return this._versioning}hasGuard(){return this._guard!=null}_applyVersioning(e,t){if(this._isExecutingFn)throw new Error(`Node "${this.name}": _applyVersioning cannot run mid-fn \u2014 call it outside of \`_execFn\` (typically at graph setup time before the first subscribe).`);let s=this._versioningLevel;if(s!=null&&e<=s)return;let i=t?.hash??this._hashFn;i!==this._hashFn&&(this._hashFn=i);let r=this._cached===void 0?void 0:this._cached,a=this._versioning,o=a?.id??t?.id,d=a?.version??0,l=le(e,r,{id:o,hash:i});l.version=d,this._versioning=l,this._versioningLevel=e}_setInspectorHook(e){return e==null?()=>{}:(this._inspectorHooks==null&&(this._inspectorHooks=new Set),this._inspectorHooks.add(e),()=>{this._inspectorHooks?.delete(e),this._inspectorHooks?.size===0&&(this._inspectorHooks=void 0)})}_pushGuard(e){return this._extraGuards==null&&(this._extraGuards=new Set),this._extraGuards.add(e),()=>{this._extraGuards?.delete(e),this._extraGuards?.size===0&&(this._extraGuards=void 0)}}allowsObserve(e){if(this._guard==null&&this._extraGuards==null)return!0;let t=J(e);if(this._guard!=null&&!this._guard(t,"observe"))return!1;if(this._extraGuards!=null){for(let s of this._extraGuards)if(!s(t,"observe"))return!1}return!0}_checkGuard(e){if(e?.internal)return;let t=this._guard!=null||this._extraGuards!=null,s=e?.actor!=null;if(!t&&!s)return;let i=J(e?.actor),r=e?.delivery==="signal"?"signal":"write";if(this._guard!=null&&!this._guard(i,r))throw new F({actor:i,action:r,nodeName:this.name});if(this._extraGuards!=null){for(let a of this._extraGuards)if(!a(i,r))throw new F({actor:i,action:r,nodeName:this.name})}this._lastMutation={actor:i,timestamp_ns:we()}}down(e,t){let s=Q(e);s.length!==0&&(this._checkGuard(t),this._emit(s))}emit(e,t){this._checkGuard(t),this._emit([[m,e]])}up(e,t){if(this._deps.length===0)return;let s=Q(e);if(s.length===0)return;this._checkGuard(t);let i=t??{internal:!0};this._validateUpTiers(s);for(let r of this._deps)r.node.up?.(s,i)}_emitUp(e){if(this._deps.length!==0&&e.length!==0){this._validateUpTiers(e);for(let t of this._deps)t.node.up?.(e,{internal:!0})}}_validateUpTiers(e){let t=this._config.tierOf;for(let s of e){let i=t(s[0]);if(i===3||i===4)throw new Error(`Node "${this.name}": tier-${i} messages cannot flow up \u2014 DATA/RESOLVED/COMPLETE/ERROR are downstream-only. Use \`down(...)\` for value delivery; \`up(...)\` is for control signals (DIRTY, INVALIDATE, PAUSE, RESUME, TEARDOWN).`)}}subscribe(e,t){if(t!=null&&this._guard!=null){let d=J(t);if(!this._guard(d,"observe"))throw new F({actor:d,action:"observe",nodeName:this.name})}let i=this._isTerminal&&this._resubscribable;if(i){this._cached=void 0,this._status="sentinel",this._store={},this._hasCalledFnOnce=!1,this._waveHasNewData=!1,this._hasNewTerminal=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._isExecutingFn=!1,this._rerunDepth=0,this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null;for(let d of this._deps)ce(d);if(this._partial===!1){for(let d of this._deps)if(d.prevData!==void 0||d.dataBatch.length!==0||d.terminal!==void 0||d.dirty)throw new Error(`resubscribable-reset invariant: DepRecord not fully reset for node ${this._optsName??"(anonymous)"}`)}}this._sinkCount+=1;let r;try{r=this._config.onSubscribe(this,e,{sinkCount:this._sinkCount,afterTerminalReset:i},this._actions)}catch(d){throw this._sinkCount-=1,d}this._sinks==null?this._sinks=e:typeof this._sinks=="function"?this._sinks=new Set([this._sinks,e]):this._sinks.add(e);let a=this._isTerminal;if(this._sinkCount===1&&!a)try{this._activate()}catch(d){if(this._sinkCount-=1,this._removeSink(e),this._sinkCount===0&&(this._status="sentinel"),typeof r=="function")try{r()}catch{}throw d}this._status==="sentinel"&&this._cached===void 0&&(this._status="pending");let o=!1;return()=>{o||(o=!0,this._sinkCount-=1,this._removeSink(e),typeof r=="function"&&r(),this._sinks==null&&this._deactivate())}}_removeSink(e){if(this._sinks===e)this._sinks=null;else if(this._sinks!=null&&typeof this._sinks!="function")if(this._sinks.delete(e),this._sinks.size===1){let[t]=this._sinks;this._sinks=t}else this._sinks.size===0&&(this._sinks=null)}_activate(){if(this._deps.length===0){this._fn&&this._execFn();return}this._dirtyDepCount=0;let e=this._deps.length,t=0;try{for(let s=0;s<e;s++){let i=s,r=this._deps[s];r.unsub=ke,r.unsub=r.node.subscribe(a=>{if(r.unsub===null)return;let o=this._config.tierOf,d=!1;for(let l of a)o(l[0])>=3&&(d=!0),this._config.onMessage(this,l,{direction:"down-in",depIndex:i},this._actions);d&&this._maybeRunFnOnSettlement()}),t++}}catch(s){this._deps[t].unsub=null;for(let i=0;i<t;i++){let r=this._deps[i];if(r.unsub!=null){let a=r.unsub;r.unsub=null;try{a()}catch{}ce(r)}}throw this._dirtyDepCount=0,s}}_addDep(e){for(let i=0;i<this._deps.length;i++)if(this._deps[i].node===e)return i;let t=this._deps.length,s=Ee(e);if(this._deps.push(s),this._sinks==null)return t;s.dirty=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ie),s.unsub=ke;try{s.unsub=e.subscribe(i=>{if(s.unsub===null)return;let r=this._config.tierOf,a=!1;for(let o of i)r(o[0])>=3&&(a=!0),this._config.onMessage(this,o,{direction:"down-in",depIndex:t},this._actions);a&&this._maybeRunFnOnSettlement()})}catch(i){throw s.unsub=null,this._deps.pop(),this._dirtyDepCount--,i}return t}_deactivate(e=!1){let t=this._cleanup;if(this._cleanup=void 0,typeof t=="function")try{t()}catch(s){this._emit([[_,this._wrapFnError("cleanup threw",s)]])}else if(t!=null&&typeof t=="object"){let s=t.deactivate;if(typeof s=="function")try{s()}catch(i){this._emit([[_,this._wrapFnError("cleanup.deactivate threw",i)]])}}for(let s of this._deps){if(s.unsub!=null){let i=s.unsub;s.unsub=null;try{i()}catch{}}ce(s)}this._waveHasNewData=!1,this._hasNewTerminal=!1,this._hasCalledFnOnce=!1,this._paused=!1,this._pendingWave=!1,this._pendingRerun=!1,this._rerunDepth=0,this._store={},this._dirtyDepCount=0,this._pauseLocks=null,this._pauseBuffer=null,this._fn!=null&&(this._cached=void 0),e||(this._fn!=null||this._deps.length>0)&&(!this._isTerminal||this._resubscribable)&&(this._status="sentinel")}_onDepMessage(e,t){let s=this._deps[e],i=t[0];if(this._inspectorHooks!=null){let r={kind:"dep_message",depIndex:e,message:t};for(let a of this._inspectorHooks)a(r)}if(i!==Y){if(i===M){this._depDirtied(s);return}if(i===C){if(this._depInvalidated(s),this._cached===void 0)return;this._emit(pe);return}if(i===N||i===L){this._emit([t]);return}if(i===k){this._emit(re);return}if(i===m)this._depSettledAsData(s,t[1]);else if(i===S)this._depSettledAsResolved(s);else if(i===D)this._depSettledAsTerminal(s,!0);else if(i===_)this._depSettledAsTerminal(s,t[1]);else{this._emit([t]);return}if(!this._fn){(i===m||i===S)&&this._emit([t]),(i===D||i===_)&&this._maybeAutoTerminalAfterWave();return}}}_depDirtied(e){e.dirty||(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++,this._status!=="dirty"&&this._emit(ie))}_depSettledAsData(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.involvedThisWave=!0,e.dataBatch.push(t),this._waveHasNewData=!0}_depSettledAsResolved(e){e.dirty&&(e.dirty=!1,this._dirtyDepCount--)}_depSettledAsTerminal(e,t){e.dirty&&(e.dirty=!1,this._dirtyDepCount--),e.terminal=t,e.involvedThisWave=!0,this._hasNewTerminal=!0}_depInvalidated(e){e.prevData=void 0,e.terminal=void 0,e.dataBatch.length=0,e.dirty?e.involvedThisWave=!1:(e.dirty=!0,e.involvedThisWave=!0,this._dirtyDepCount++)}_maybeRunFnOnSettlement(){if(!(this._isTerminal&&!this._resubscribable)&&!(this._dirtyDepCount>0)){if(!this._partial&&!this._hasCalledFnOnce)for(let e=0;e<this._deps.length;e++){let t=this._deps[e];if(t.dataBatch.length===0&&t.prevData===void 0&&t.terminal===void 0){this._maybeAutoTerminalAfterWave();return}}if(this._paused){this._pendingWave=!0;return}if(!this._waveHasNewData&&!this._hasNewTerminal&&this._hasCalledFnOnce){this._clearWaveFlags(),this._emit(fe),this._maybeAutoTerminalAfterWave();return}this._fn&&this._execFn(),this._maybeAutoTerminalAfterWave()}}_maybeAutoTerminalAfterWave(){if(this._deps.length===0||this._isTerminal)return;let e=this._deps.find(t=>t.terminal!==void 0&&t.terminal!==!0);if(e!=null){this._autoError&&this._emit([[_,e.terminal]]);return}this._autoComplete&&this._deps.every(t=>t.terminal!==void 0)&&this._emit(_e)}_execFn(){if(!this._fn||this._isTerminal&&!this._resubscribable)return;if(this._isExecutingFn){this._pendingRerun=!0;return}let e=this._cleanup;if(typeof e=="function"){this._cleanup=void 0;try{e()}catch(a){this._emit([[_,this._wrapFnError("cleanup threw",a)]]);return}}else if(e!=null&&typeof e=="object"){let a=e.beforeRun;if(typeof a=="function"){e.beforeRun=void 0;try{a()}catch(o){this._emit([[_,this._wrapFnError("cleanup.beforeRun threw",o)]]);return}}}let t=this._deps.map(a=>a.involvedThisWave?a.dataBatch.length>0?[...a.dataBatch]:[]:void 0),s=this._deps.map(a=>a.prevData);for(let a=0;a<this._deps.length;a++){let o=t[a];o!=null&&o.length>0&&(this._deps[a].prevData=o[o.length-1])}let i=this._deps.map(a=>a.terminal),r={prevData:s,terminalDeps:i,store:this._store};if(this._hasCalledFnOnce=!0,this._clearWaveFlags(),this._inspectorHooks!=null){let a={kind:"run",batchData:t,prevData:s};for(let o of this._inspectorHooks)o(a)}this._isExecutingFn=!0;try{let a=this._fn(t,this._actions,r);if(typeof a=="function")this._cleanup=a;else if(a!=null&&typeof a=="object"){let o=a;(typeof o.beforeRun=="function"||typeof o.deactivate=="function"||typeof o.invalidate=="function")&&(this._cleanup=a)}}catch(a){this._emit([[_,this._wrapFnError("fn threw",a)]])}finally{this._isExecutingFn=!1,this._pendingRerun?(this._pendingRerun=!1,this._rerunDepth+=1,this._rerunDepth>Ae?(this._rerunDepth=0,this._emit([[_,new Error(`Node "${this.name}": _pendingRerun depth exceeded ${Ae} \u2014 likely a reactive cycle`)]])):this._maybeRunFnOnSettlement()):this._rerunDepth=0,this._clearWaveFlags()}}_clearWaveFlags(){this._waveHasNewData=!1,this._hasNewTerminal=!1;for(let e of this._deps)e.involvedThisWave=!1,e.dataBatch.length=0}_wrapFnError(e,t){let s=t instanceof Error?t.message:String(t);return new Error(`Node "${this.name}": ${e}: ${s}`,{cause:t})}_frameBatch(e){let t=this._config.tierOf;if(e.length===1)return t(e[0][0])===3&&this._status!=="dirty"?[P,e[0]]:e;let s=!0,i=!1,r=!1,a=-1;for(let d of e){let l=t(d[0]);l<a&&(s=!1),l===3&&(i=!0),d[0]===M&&(r=!0),a=l}let o=e;if(!s){let d=e.map((l,c)=>({m:l,i:c,tier:t(l[0])}));d.sort((l,c)=>l.tier-c.tier||l.i-c.i),o=d.map(l=>l.m)}if(i&&!r&&this._status!=="dirty"){let d=0;for(;d<o.length&&t(o[d][0])===0;)d++;return d===0?[P,...o]:[...o.slice(0,d),P,...o.slice(d)]}return o}_emit(e){if(e.length===0)return;for(let o=0;o<e.length;o++){let d=e[o];if(d[0]===_&&d[1]===void 0)throw new TypeError('[ERROR, payload] requires a non-undefined payload (spec \xA71.2). Pass an Error object or domain tag instead \u2014 e.g. node.down([[ERROR, new Error("reason")]])')}let t=e;if(this._isTerminal&&!this._resubscribable){let o=e.filter(d=>d[0]===k||d[0]===C);if(o.length===0)return;t=o}t=this._frameBatch(t);let i=null;for(let o=0;o<t.length;o++){let d=t[o],l=d[0];if(l!==N&&l!==L){i?.push(d);continue}if(d.length<2)throw new Error(`Node "${this.name}": [[${l===N?"PAUSE":"RESUME"}]] must carry a lockId payload \u2014 bare PAUSE/RESUME is a protocol violation (C0 rule). Use \`[[PAUSE, lockId]]\` / \`[[RESUME, lockId]]\`.`);let c=!0;if(this._pausable!==!1){let u=d[1];if(l===N)this._pauseLocks==null&&(this._pauseLocks=new Set),this._pauseLocks.add(u),this._paused=!0,this._pausable==="resumeAll"&&this._pauseBuffer==null&&(this._pauseBuffer=[]);else if(this._pauseLocks==null||!this._pauseLocks.has(u))c=!1;else if(this._pauseLocks.delete(u),this._pauseLocks.size===0){if(this._paused=!1,this._pauseBuffer!=null&&this._pauseBuffer.length>0){let p=this._pauseBuffer;this._pauseBuffer=[],this._emit(p)}this._pendingWave&&(this._pendingWave=!1,this._maybeRunFnOnSettlement())}}c?i?.push(d):i==null&&(i=t.slice(0,o))}if(i!=null){if(i.length===0)return;t=i}if(this._hasMeta&&t.some(o=>o[0]===k))for(let o of Object.keys(this.meta))try{this.meta[o]._emit(re)}catch{}let{finalMessages:r,equalsError:a}=this._updateState(t);if(r.length>0&&this._config.inspectorEnabled){let o=this._config.globalInspector;if(o!=null)try{o({kind:"emit",node:this,messages:r})}catch{}}if(r.length>0)if(this._paused&&this._pausable==="resumeAll"&&this._pauseBuffer!=null){let o=this._config.tierOf,d=[];for(let l of r)o(l[0])===3?this._pauseBuffer.push(l):d.push(l);d.length>0&&this._dispatchOrAccumulate(d)}else this._dispatchOrAccumulate(r);a!=null&&this._emit([[_,a]])}_updateState(e){let t=this._config.tierOf,s,i,r=-1,a=0;for(let c of e)t(c[0])===3&&a++;let o=a<=1,d=-1;if(this._versioning!=null&&a>1){for(let c=e.length-1;c>=0;c--)if(e[c][0]===m){d=c;break}}for(let c=0;c<e.length;c++){let u=e[c],p=u[0];if(p===m){if(u.length>=2){let h=!1;if(o&&this._cached!==void 0)try{h=this._equals(this._cached,u[1])}catch(b){i=this._wrapFnError("equals threw",b),r=c;break}if(h){s==null&&(s=e.slice(0,c)),s.push(he),this._status="resolved";continue}this._cached=u[1],this._versioning!=null&&(d<0||c===d)&&Ne(this._versioning,u[1],this._hashFn)}this._status="settled",s?.push(u)}else if(s?.push(u),p===M)this._status="dirty";else if(p===S)this._status="resolved";else if(p===D)this._status="completed";else if(p===_)this._status="errored";else if(p===C){this._cached=void 0,this._status="dirty";let h=this._cleanup;if(typeof h=="function"){this._cleanup=void 0;try{h()}catch{}}else if(h!=null&&typeof h=="object"){let b=h.invalidate;if(typeof b=="function")try{b()}catch{}}}else p===k&&(this._resetOnTeardown&&(this._cached=void 0),this._deactivate(!0),this._status="sentinel")}let l=r>=0?s??e.slice(0,r):s??e;return i!=null?{finalMessages:l,equalsError:i}:{finalMessages:l}}_deliverToSinks=e=>{if(this._sinks==null)return;if(typeof this._sinks=="function"){this._sinks(e);return}let t=[...this._sinks];for(let s of t)s(e)};_dispatchOrAccumulate(e){if(be()){this._batchPendingMessages===null&&(this._batchPendingMessages=[],ve(()=>this._flushBatchPending()));for(let t of e)this._batchPendingMessages.push(t);return}X(this._deliverToSinks,e,this._config.tierOf)}_flushBatchPending(){let e=this._batchPendingMessages;if(e===null||(this._batchPendingMessages=null,e.length===0))return;let t=this._frameBatch(e);X(this._deliverToSinks,t,this._config.tierOf)}},Me=n=>Array.isArray(n),ue=n=>typeof n=="object"&&n!=null&&!Array.isArray(n);function j(n,e,t){let s=Me(n)?n:[],i=typeof n=="function"?n:typeof e=="function"?e:void 0,r={};return Me(n)?r=(ue(e)?e:t)??{}:ue(n)?r=n:r=(ue(e)?e:t)??{},new $(s,i,r)}function bt(n,e){return j([],{...e,initial:n})}function vt(n,e){return j((s,i,r)=>n(i,r)??void 0,{describeKind:"producer",...e})}function Be(n,e,t){return j(n,(i,r,a)=>{let o=i.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);r.emit(e(o,a))},{describeKind:"derived",...t})}function wt(n,e,t){return j(n,(i,r,a)=>{let o=i.map((d,l)=>d!=null&&d.length>0?d.at(-1):a.prevData[l]);return e(o,r,a)??void 0},{describeKind:"effect",...t})}function xt(n,e,t){let s=new Map;return n.forEach((i,r)=>{s.set(i,r)}),Be(n,(i,r)=>e(o=>{let d=s.get(o);if(d==null)throw new Error(`dynamicNode: untracked dep "${o.name??"<unnamed>"}"`);return i[d]},r),t)}function Tt(n,e){let t,s=new Map,i=(r,a,o)=>{let d=!1,l=c=>{let u=s.get(c);if(u!==void 0){if(u<r.length){let h=r[u];return h!=null&&h.length>0?h.at(-1):o.prevData[u]}return c.cache}d=!0;let p=t._addDep(c);return s.set(c,p),c.cache};try{let c=n(l,o);d||(a.emit(c),o.store.__autoTrackLastDiscoveryError!=null&&delete o.store.__autoTrackLastDiscoveryError)}catch(c){if(!d)throw c;o.store.__autoTrackLastDiscoveryError=c}};return t=new $([],i,{describeKind:"derived",...e}),t}function Nt(n,...e){let t=n;for(let s of e)t=s(t);return t}export{De as a,$e as b,je as c,oe as d,ze as e,qe as f,ye as g,Ke as h,Oe as i,J as j,me as k,ve as l,Xe as m,X as n,Qe as o,we as p,Z as q,xe as r,F as s,Ge as t,st as u,it as v,de as w,le as x,Ne as y,ot as z,B as A,gt as B,$ as C,j as D,bt as E,vt as F,Be as G,wt as H,xt as I,Tt as J,Nt as K};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as H,b as T}from"./chunk-
|
|
1
|
+
import{a as H,b as T}from"./chunk-YZKGGMPT.js";import{j as q}from"./chunk-PSQNYY72.js";import{a as O,b as j}from"./chunk-N2KKISCE.js";import{E as d,G as o,H as x,m as A}from"./chunk-7AJKUA36.js";import{b as ae}from"./chunk-QYADASLV.js";var ie={};ae(ie,{demoShell:()=>re});function w(h){return Math.max(0,Math.min(1,h))}function re(h){let B=w(h?.mainRatio??.65),E=w(h?.sideSplit??.5),J=Math.max(0,h?.viewportWidth??1280),k=h?.nodeRegistry??new Map,p=h?.adapter??null,S=h?.layoutFont??"14px monospace",u=h?.onHighlight,t=new q("demo-shell"),F=d(B,{name:"pane/main-ratio"}),D=d(E,{name:"pane/side-split"}),g=d(null,{name:"pane/fullscreen"}),G=d(J,{name:"viewport/width"});t.add(F,{name:"pane/main-ratio"}),t.add(D,{name:"pane/side-split"}),t.add(g,{name:"pane/fullscreen"}),t.add(G,{name:"viewport/width"});let L=o([F,G,g],([e,a,n])=>{let l=e,r=a,i=n;return i==="main"?r:i==="graph"||i==="code"?0:Math.round(r*l)},{name:"pane/main-width"}),R=o([L,G,g],([e,a,n])=>{let l=n,r=a;return l==="main"?0:l==="graph"||l==="code"?r:r-e},{name:"pane/side-width"}),C=o([D,g],([e,a])=>{let n=a;return n==="graph"?1:n==="code"||n==="main"?0:w(e)},{name:"pane/graph-height-ratio"}),K=o([C,g],([e,a])=>{let n=a;return n==="code"?1:n==="graph"||n==="main"?0:1-e},{name:"pane/code-height-ratio"});t.add(L,{name:"pane/main-width"}),t.add(R,{name:"pane/side-width"}),t.add(C,{name:"pane/graph-height-ratio"}),t.add(K,{name:"pane/code-height-ratio"});let b=d(null,{name:"demo/graph-ref"}),m=d(0,{name:"demo/graph-tick"});t.add(b,{name:"demo/graph-ref"}),t.add(m,{name:"demo/graph-tick"});let Q=o([b,m],([e,a])=>{let n=e;return n?n.describe({format:"mermaid"}):""},{name:"graph/mermaid"}),z=o([b,m],([e,a])=>{let n=e;if(!n)return null;let{expand:l,...r}=n.describe({detail:"standard"});return r},{name:"graph/describe"});t.add(Q,{name:"graph/mermaid"}),t.add(z,{name:"graph/describe"});let M=d(null,{name:"hover/target"});t.add(M,{name:"hover/target"});let P=o([M],([e])=>{let a=e;if(!a)return null;let n=k.get(a.id);return n?n.codeLine:null},{name:"highlight/code-scroll"}),W=o([M],([e])=>{let a=e;if(!a)return null;let n=k.get(a.id);return n?n.visualSelector:null},{name:"highlight/visual"}),N=o([M],([e])=>{let a=e;return a?a.id:null},{name:"highlight/graph"});if(t.add(P,{name:"highlight/code-scroll"}),t.add(W,{name:"highlight/visual"}),t.add(N,{name:"highlight/graph"}),u?.codeScroll){let e=u.codeScroll,a=x([P],([n])=>{e(n)});t.add(a,{name:"highlight/apply-code-scroll"})}if(u?.visual){let e=u.visual,a=x([W],([n])=>{e(n)});t.add(a,{name:"highlight/apply-visual"})}if(u?.graph){let e=u.graph,a=x([N],([n])=>{e(n)});t.add(a,{name:"highlight/apply-graph"})}let _=d(null,{name:"inspect/selected-node"});t.add(_,{name:"inspect/selected-node"});let U=O("standard"),X=o([_,b,m],([e,a,n])=>{let l=a,r=e;if(!l||!r)return null;try{let i=l.resolve(r),s=j(i,U);return{path:r,...s,value:i.cache}}catch{return null}},{name:"inspect/node-detail"}),Y=o([b,m],([e,a])=>{let n=e;return n?n.trace():[]},{name:"inspect/trace-log"});t.add(X,{name:"inspect/node-detail"}),t.add(Y,{name:"inspect/trace-log"});let I=d(!1,{name:"meta/debug"});t.add(I,{name:"meta/debug"});let Z=o([I,m],([e,a])=>e?t.describe({format:"mermaid"}):"",{name:"meta/shell-mermaid"});t.add(Z,{name:"meta/shell-mermaid"});let V=d("",{name:"layout/code-text"});if(t.add(V,{name:"layout/code-text"}),p){let e=new Map,a=o([z],([r])=>{let i=r;if(!i)return new Map;let s=new Map;for(let[c]of Object.entries(i.nodes)){let f=H(c,S,p,e),v=T(f,1/0,p,S,e),y=v.lines.reduce((te,ne)=>Math.max(te,ne.width),0),ee=v.lineCount*20;s.set(c,{width:y,height:ee})}return s},{name:"layout/graph-labels",equals:(r,i)=>{if(r===i)return!0;let s=r,c=i;if(s.size!==c.size)return!1;for(let[f,v]of s){let y=c.get(f);if(!y||y.width!==v.width||y.height!==v.height)return!1}return!0}}),n=o([V,R],([r,i])=>{let s=r;if(!s)return{lineCount:0,lines:[]};let c=H(s,S,p,e),f=i-40;return T(c,Math.max(100,f),p,S,e)},{name:"layout/code-lines"}),l=o([a],([r])=>{let i=r;if(i.size===0)return 200;let s=0;for(let{width:c}of i.values())c>s&&(s=c);return Math.max(200,Math.round(s+80))},{name:"layout/side-width-hint"});t.add(a,{name:"layout/graph-labels"}),t.add(n,{name:"layout/code-lines"}),t.add(l,{name:"layout/side-width-hint"})}let $=0;return{graph:t,setMainRatio(e){t.set("pane/main-ratio",w(e))},setSideSplit(e){t.set("pane/side-split",w(e))},setFullscreen(e){t.set("pane/fullscreen",e)},setViewportWidth(e){t.set("viewport/width",Math.max(0,e))},setHoverTarget(e){t.set("hover/target",e)},setDemoGraph(e){t.set("demo/graph-ref",e)},bumpGraphTick(){t.set("demo/graph-tick",++$)},selectNode(e){t.set("inspect/selected-node",e)},setMetaDebug(e){t.set("meta/debug",e)},setCodeText(e){t.set("layout/code-text",e)},batch(e){A(e)},destroy(){t.destroy()}}}export{re as a,ie as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{b as x,c as D,d as $,e as S,f as A,g as R,h as T,i as F,j as y,k as P,l as V}from"./chunk-PSQNYY72.js";import{a as m,b as g,c as k,d as v,e as O,f as G,g as E,h as C}from"./chunk-7AJKUA36.js";import{b as u}from"./chunk-CK2E7BTU.js";import{b as _}from"./chunk-QYADASLV.js";var j={};_(j,{ENVELOPE_VERSION:()=>v,GRAPH_META_SEGMENT:()=>R,Graph:()=>y,JsonCodec:()=>m,SIZEOF_OVERHEAD:()=>D,SIZEOF_SYMBOL:()=>$,SNAPSHOT_VERSION:()=>T,createDagCborCodec:()=>g,createDagCborZstdCodec:()=>k,decodeEnvelope:()=>G,diffForWAL:()=>P,encodeEnvelope:()=>O,explainPath:()=>x,graphProfile:()=>A,mermaidLiveUrl:()=>F,reachable:()=>V,registerBuiltinCodecs:()=>E,replayWAL:()=>C,sizeof:()=>S,validateGraphObservability:()=>L,watchTopologyTree:()=>N});function N(p,n){let o=new Map,d=(s,a)=>{if(o.has(s))return;let c={off:()=>{},prefix:a};o.set(s,c);let f=s.topology.subscribe(l=>{for(let r of l){if(r[0]!==u)continue;let e=r[1];if(n(e,s,a),e.kind==="added"&&e.nodeKind==="mount"){let t=s._mounts.get(e.name);if(t instanceof y){let i=`${a}${e.name}::`;d(t,i)}}else if(e.kind==="removed"&&e.nodeKind==="mount"){let t=`${a}${e.name}::`;for(let[i,h]of Array.from(o.entries()))i!==p&&h.prefix.startsWith(t)&&(h.off(),o.delete(i))}}});c.off=f;for(let[l,r]of s._mounts)if(r instanceof y){let e=`${a}${l}::`;d(r,e)}};return d(p,""),()=>{for(let s of o.values())s.off();o.clear()}}function L(p,n={}){let o=[],d=n.requireFound??!0;if(n.skipDescribe!==!0)try{let r=p.describe(),e=new Set(Object.keys(r.nodes)),t=[];for(let[i,h]of Object.entries(r.nodes))for(let b of h.deps)b!==""&&!e.has(b)&&t.push(`${i} \u2192 ${b}`);for(let i of r.edges)e.has(i.from)||t.push(`edge.from: ${i.from}`),e.has(i.to)||t.push(`edge.to: ${i.to}`);t.length>0?o.push({kind:"describe",ok:!1,reason:`describe() has ${t.length} dangling pointer(s); nodes \u2289 deps`,danglingDeps:t}):o.push({kind:"describe",ok:!0,nodeCount:e.size,edgeCount:r.edges.length})}catch(r){o.push({kind:"describe",ok:!1,reason:`describe() threw: ${r instanceof Error?r.message:String(r)}`})}for(let r of n.formats??[])try{let e=p.describe({format:r});typeof e!="string"||e.length===0?o.push({kind:"describe-format",ok:!1,format:r,reason:`describe({ format: "${r}" }) returned empty or non-string output`}):o.push({kind:"describe-format",ok:!0,format:r,length:e.length})}catch(e){o.push({kind:"describe-format",ok:!1,format:r,reason:e instanceof Error?e.message:String(e)})}for(let r of n.paths??[])try{p.resolve(r),o.push({kind:"observe",ok:!0,path:r})}catch(e){o.push({kind:"observe",ok:!1,path:r,reason:e instanceof Error?e.message:String(e)})}for(let[r,e]of n.pairs??[])try{let t=p.explain(r,e);d&&t.found===!1?o.push({kind:"explain",ok:!1,from:r,to:e,reason:`explain(${r} \u2192 ${e}) found no path${t.reason?`: ${t.reason}`:""}`}):o.push({kind:"explain",ok:!0,from:r,to:e,found:t.found,steps:t.steps.length})}catch(t){o.push({kind:"explain",ok:!1,from:r,to:e,reason:t instanceof Error?t.message:String(t)})}let s=o.filter(r=>!r.ok),a=s.length===0,c=n.paths?.length??0,f=n.pairs?.length??0,l=n.formats?.length??0;return{ok:a,checks:o,failures:s,summary(){let r=[n.skipDescribe===!0?null:"describe",l>0?`${l} format${l===1?"":"s"}`:null,c>0?`${c} observe path${c===1?"":"s"}`:null,f>0?`${f} explain pair${f===1?"":"s"}`:null].filter(t=>t!=null),e=r.length>0?r.join(", "):"describe-only";return a?`validateGraphObservability: OK (${e})`:`validateGraphObservability: ${s.length} failure(s) across ${e}`}}}export{N as a,L as b,j as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as I}from"./chunk-LWGLBCMU.js";import{t as A,x as v}from"./chunk-WQ7I7JVU.js";import{m as p,r as y}from"./chunk-UMH3HSP7.js";import{E as R,G as w,m as h}from"./chunk-7AJKUA36.js";import{b}from"./chunk-CK2E7BTU.js";function z(t){return typeof t=="object"&&t!==null&&"cache"in t&&typeof t.subscribe=="function"}function F(t,a,e){let r=p(t),i=r.v!=null,g=R(e?.initialVerified??null,{...i?{meta:{sourceVersion:null}}:{}}),x=e?.trigger!==void 0&&e.trigger!==null,s=null;if(x&&e?.autoVerify?s=A(p(e.trigger),r):x?s=p(e.trigger):e?.autoVerify&&(s=r),s!==null){let d;if(s===r)d=v(r,c=>a(c));else{let c=r.cache;r.subscribe(f=>{for(let M of f)M[0]===b&&(c=M[1])}),d=v(s,()=>a(c))}y(d,c=>{h(()=>{if(g.down([[b,c]]),i){let f=r.v;f!=null&&g.meta.sourceVersion.down([[b,{id:f.id,version:f.version}]])}})})}return{node:r,verified:g,trigger:s}}function E(t){t.subscribe(()=>{})}function k(t){return t instanceof Map?t:new Map}function B(t,a){if(!Array.isArray(a.upsert))throw new TypeError("distill extraction requires upsert: Array<{ key, value }>");h(()=>{for(let{key:e,value:r}of a.upsert)t.set(e,r);for(let e of a.remove??[])t.delete(e)})}function G(t,a,e){let r=p(t),i=I(e.mapOptions??{}),g=e.budget??2e3,s=e.context!==void 0&&e.context!==null?p(e.context):R(null),d=k(i.entries.cache);i.entries.subscribe(o=>{for(let u of o)u[0]===b&&(d=k(u[1]))});let c=v(r,o=>a(o,d));if(y(c,o=>{B(i,o)}),e.evict){let o=new Map,u=w([i.entries],([l])=>{let m=[],N=k(l);for(let n of o.keys())N.has(n)||(o.get(n)(),o.delete(n));for(let[n,T]of N){let V=e.evict(n,T);if(z(V)){if(!o.has(n)){let S=y(V,D=>{D===!0&&i.has(n)&&i.delete(n)});o.set(n,S)}continue}if(typeof V=="boolean"){V&&m.push(n);continue}throw new TypeError("distill evict() must return boolean or Node<boolean>")}return m});y(u,l=>{for(let m of l)i.delete(m)})}let f=e.consolidateTrigger!==void 0&&e.consolidateTrigger!==null;if(e.consolidate&&f){let o=p(e.consolidateTrigger),u=v(o,()=>e.consolidate(d));y(u,l=>{B(i,l)})}let M=w([i.entries,s],([o,u])=>{let l=[...k(o).entries()].map(([n,T])=>({key:n,value:T,score:e.score(T,u),cost:e.cost(T)}));l.sort((n,T)=>T.score-n.score);let m=[],N=g;for(let n of l)n.cost<=N&&(m.push({key:n.key,value:n.value,score:n.score}),N-=n.cost);return m}),O=w([i.entries],([o])=>k(o).size);return E(M),E(O),{store:i,compact:M,size:O}}export{F as a,G as b};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{E as l,J as f}from"./chunk-
|
|
1
|
+
import{E as l,J as f}from"./chunk-7AJKUA36.js";import{b as m,j as d}from"./chunk-CK2E7BTU.js";import{b as p}from"./chunk-QYADASLV.js";var F={};p(F,{atom:()=>A});function A(s,n,e){if(typeof s=="function"){let t=s;return typeof n=="function"?b(t,n,e):b(t,void 0,n)}return v(s,n)}function c(s){let n=s.cache,e;if(s.subscribe(i=>{for(let[r,o]of i)r===m&&(n=o),r===d&&(e=o)})(),e)throw e;return n}function v(s,n){let e=l(s,{...n,resubscribable:!0,resetOnTeardown:!0});return{get:()=>e.status==="sentinel"?c(e):e.cache,set:t=>e.emit(t),update:t=>{let i=e.status==="sentinel"?c(e):e.cache;e.emit(t(i))},subscribe:t=>{let i=!0;return e.subscribe(r=>{for(let[o,a]of r)if(o===m){if(i){i=!1;continue}t(a)}})},meta:e.meta,_node:e}}function b(s,n,e){let t=f(r=>s(o=>{let a=o._node;return a.status==="sentinel"&&c(a),r(a)}),{...e,resubscribable:!0,resetOnTeardown:!0}),i={get:()=>t.status==="sentinel"?c(t):t.cache,subscribe:r=>{let o=!0;return t.subscribe(a=>{for(let[u,T]of a)if(u===m){if(o){o=!1;continue}r(T)}})},meta:t.meta,_node:t};if(n){let r=u=>u.get(),o=(u,T)=>u.set(T),a=i;return a.set=u=>n(r,o,u),a.update=u=>{let T=t.status==="sentinel"?c(t):t.cache;return n(r,o,u(T))},a}return i}export{A as a,F as b};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import{a as ht,b as bt,d as Tt,e as Mt}from"./chunk-OKQUPJRY.js";import{e as yt}from"./chunk-5LJAQTSS.js";import{h as vt}from"./chunk-XEFAMCEA.js";import{e as He}from"./chunk-EBQ6FXKW.js";import{a as jt,b as Wt,c as Ut,d as Kt,e as Vt,f as Ve,g as Ht}from"./chunk-PNTBXOQ6.js";import{a as Ue,b as H,c as Ee,d as pe,e as re,f as q,g as Ft,h as Ke,i as Gt,j as Bt,k as $t}from"./chunk-FTA5TB2A.js";import{c as pt}from"./chunk-K54OKWNY.js";import{b as gt}from"./chunk-7QMVU3IX.js";import{b as dt,c as Ae,d as ut,f as We}from"./chunk-RWGJQQLT.js";import{b as Se}from"./chunk-LWGLBCMU.js";import{b as Te}from"./chunk-XRSHMHEG.js";import{j as de}from"./chunk-PSQNYY72.js";import{a as te}from"./chunk-ESMPEKEV.js";import{R as ft,x as J}from"./chunk-WQ7I7JVU.js";import{B as F,f as ct,m as k,w as le,y as mt}from"./chunk-UMH3HSP7.js";import{D as ce,E as L,F as $e,G as M,H as me,m as se,o as X,p as Re}from"./chunk-7AJKUA36.js";import{b as V,d as be,i as ae,j as Q}from"./chunk-CK2E7BTU.js";import{b as Dt}from"./chunk-QYADASLV.js";var Vr={};Dt(Vr,{AgentLoopGraph:()=>Be,AllTiersExhaustedError:()=>Vt,BudgetExhaustedError:()=>Pe,ChatStreamGraph:()=>Fe,CircuitOpenError:()=>Ae,DEFAULT_DECAY_RATE:()=>st,FallbackMissError:()=>Bt,LLMTimeoutError:()=>ve,ReplayCacheMissError:()=>Ft,ToolRegistryGraph:()=>Ge,admissionFilter3D:()=>Dr,agentLoop:()=>Ir,agentMemory:()=>jr,anthropicAdapter:()=>jt,canonicalJson:()=>Gt,cascadingLlmAdapter:()=>Ve,chatStream:()=>rt,composePricing:()=>Xt,computePrice:()=>qe,contentGate:()=>Ar,costMeterExtractor:()=>xr,createAdapter:()=>Kt,createCapabilitiesRegistry:()=>qt,createPricingRegistry:()=>Yt,dryRunAdapter:()=>Ue,fallbackAdapter:()=>$t,fromLLM:()=>cr,frozenContext:()=>yr,gatedStream:()=>Mr,gaugesAsContext:()=>Fr,googleAdapter:()=>Wt,graphFromSpec:()=>Gr,handoff:()=>Or,keywordFlagExtractor:()=>wr,knobsAsTools:()=>$r,llmConsolidator:()=>at,llmExtractor:()=>ot,observableAdapter:()=>zt,openAICompatAdapter:()=>Ut,parseRateLimitFromError:()=>Qe,pricingFor:()=>Zt,promptNode:()=>br,redactor:()=>Sr,registryPricing:()=>Qt,resilientAdapter:()=>ur,streamExtractor:()=>Lr,streamingPromptNode:()=>Tr,suggestStrategy:()=>Ur,systemPromptBuilder:()=>vr,tier:()=>Ht,toolCallExtractor:()=>Cr,toolRegistry:()=>nt,toolSelector:()=>Pr,validateGraphDef:()=>Kr,withBreaker:()=>ze,withBudgetGate:()=>Ye,withDryRun:()=>tr,withRateLimiter:()=>Ze,withReplayCache:()=>Ke,withRetry:()=>et,withTimeout:()=>tt,zeroPrice:()=>Oe});function we(t,e){return`${t}::${e}`}function qt(t){let e=Se({name:"capabilitiesRegistry"}),r=i=>{e.set(we(i.provider,i.id),i)};if(t)for(let i of t)r(i);let n=(i,d)=>{let c=e.get(we(i,d));if(c)return c;let p=e.entries.cache;if(!p)return;let m;for(let[,g]of p){if(g.provider!==i)continue;let y=g.id;d.startsWith(y)&&(!m||y.length>m.id.length)&&(m=g)}return m},o=128,a=new Map,s=new Map,l=(i,d,c,p)=>{for(i.has(d)&&i.delete(d),i.set(d,c);i.size>p;){let m=i.keys().next().value;if(m===void 0)break;i.delete(m)}},u=M([e.entries],([i])=>Array.from(i.values()),{name:"capabilitiesRegistry/entries",initial:[]});return{register:r,lookup:n,remove(i,d){let c=e.has(we(i,d));return c&&e.delete(we(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=we(i,d),p=a.get(c);if(p)return a.delete(c),a.set(c,p),p;let m=M([e.entries],()=>n(i,d),{name:`capabilitiesRegistry/lookup/${i}::${d}`,initial:void 0});return l(a,c,m,o),m},entriesNode:u,byProvider(i){let d=s.get(i);if(d)return s.delete(i),s.set(i,d),d;let c=M([u],([p])=>p.filter(m=>m.provider===i),{name:`capabilitiesRegistry/byProvider/${i}`,initial:[]});return l(s,i,c,o),c}}}function Z(t){let e=t.input,r=e.regular+(e.cacheRead??0)+(e.cacheWrite5m??0)+(e.cacheWrite1h??0)+(e.cacheWriteOther??0)+(e.audio??0)+(e.image??0)+(e.video??0)+(e.toolUse??0);if(!e.extensions)return r;let n=0;for(let o of Object.values(e.extensions))n+=o;return r+n}function ie(t){let e=t.output,r=e.regular+(e.reasoning??0)+(e.audio??0)+(e.predictionAccepted??0)+(e.predictionRejected??0);if(!e.extensions)return r;let n=0;for(let o of Object.values(e.extensions))n+=o;return r+n}function kt(){return{input:{regular:0},output:{regular:0}}}function zt(t,e){let r=e?.logMax??1e3,n=Te(void 0,{name:e?.name?`${e.name}/stats`:"adapterStats",maxSize:r}),o=L(null,{name:"adapterStats/lastCall"}),a=M([n.entries],([y])=>y.length,{name:"adapterStats/totalCalls",initial:0}),s=M([n.entries],([y])=>y.reduce((f,b)=>f+Z(b.usage),0),{name:"adapterStats/totalInputTokens",initial:0}),l=M([n.entries],([y])=>y.reduce((f,b)=>f+ie(b.usage),0),{name:"adapterStats/totalOutputTokens",initial:0}),u=[F(a),F(s),F(l)],i=y=>{n.append(y),o.emit(y)},d=()=>{n.clear(),o.emit(null)},c=H(t,{invoke(y,f){let b=X(),O=Re(),v=t.model??f?.model??"",A=S=>(i(pe({provider:t.provider,model:t.model??f?.model??S.model??"",tier:f?.tier??S.tier,usage:S.usage??re(),startNs:b,startWallClockNs:O,method:"invoke"})),S),C=S=>{let $=S;i(pe({provider:t.provider,model:v,tier:f?.tier,usage:re(),startNs:b,startWallClockNs:O,method:"invoke",error:{type:$?.name??"Error",message:$?.message??String(S)}}))};return Ee(t.invoke(y,f),{onResp:A,onError:C,name:"adapterStats/invokeTap"})},async*stream(y,f){let b=X(),O=Re(),v=t.model??f?.model??"",A;try{for await(let C of t.stream(y,f))C.type==="usage"&&(A=C.usage),yield C;i(pe({provider:t.provider,model:v,tier:f?.tier,usage:A??re(),startNs:b,startWallClockNs:O,method:"stream"}))}catch(C){let S=C;throw i(pe({provider:t.provider,model:v,tier:f?.tier,usage:A??re(),startNs:b,startWallClockNs:O,method:"stream",error:{type:S?.name??"Error",message:S?.message??String(C)}})),C}}});q(c,"observableAdapter",t);let p=!1;return{adapter:c,stats:{lastCall:o,allCalls:n,totalCalls:a,totalInputTokens:s,totalOutputTokens:l,reset:d,dispose:()=>{if(!p){p=!0;for(let y of u)y();u.length=0}}}}}function Jt(t,e){return t==null?0:typeof t=="number"?t:t.thresholdTokens!=null&&t.pricePerMillionAbove!=null&&e>t.thresholdTokens?t.pricePerMillionAbove:t.pricePerMillion}function Oe(t="USD"){return{total:0,currency:t}}function qe(t,e,r){let n=Z(t),o=e.currency??"USD",a=r?.withBreakdown===!0,s=a?{}:null,l=0,u=(f,b,O)=>{if(!b||O==null)return;let v=Jt(O,n),A=b*v/1e6;l+=A,a&&(s[f]=(s[f]??0)+A)},i=t.input,d=e.input;if(d&&(u("input.regular",i.regular,d.regular),u("input.cacheRead",i.cacheRead??0,d.cacheRead),u("input.cacheWrite5m",i.cacheWrite5m??0,d.cacheWrite5m),u("input.cacheWrite1h",i.cacheWrite1h??0,d.cacheWrite1h),u("input.cacheWriteOther",i.cacheWriteOther??0,d.cacheWriteOther),u("input.audio",i.audio??0,d.audio),u("input.image",i.image??0,d.image),u("input.video",i.video??0,d.video),u("input.toolUse",i.toolUse??0,d.toolUse),i.extensions&&d.extensions))for(let[f,b]of Object.entries(i.extensions))u(`input.ext.${f}`,b,d.extensions[f]);let c=t.output,p=e.output;if(p&&(u("output.regular",c.regular,p.regular),u("output.reasoning",c.reasoning??0,p.reasoning),u("output.audio",c.audio??0,p.audio),u("output.predictionAccepted",c.predictionAccepted??0,p.predictionAccepted),u("output.predictionRejected",c.predictionRejected??0,p.predictionRejected),c.extensions&&p.extensions))for(let[f,b]of Object.entries(c.extensions))u(`output.ext.${f}`,b,p.extensions[f]);let m=r?.tier;if(m&&e.tierMultipliers){let f=e.tierMultipliers[m];if(f!=null&&(l*=f,a))for(let b of Object.keys(s))s[b]*=f}let g=t.auxiliary,y=e.auxiliary;if(g&&y)for(let[f,b]of Object.entries(g)){let O=y[f];if(O==null||!b)continue;let v=b*O;l+=v,a&&(s[`auxiliary.${f}`]=v)}return a?{total:l,currency:o,breakdown:s}:{total:l,currency:o}}function Ie(t,e){return`${t}::${e}`}function Yt(t){let e=new Map,r=new Map,n=(o,a,s)=>{e.set(Ie(o,a),{provider:o,model:a,pricing:s});let l=r.get(o);l||(l=new Set,r.set(o,l)),l.add(a)};if(t)for(let[o,a,s]of t)n(o,a,s);return{register:n,lookup(o,a){let s=e.get(Ie(o,a));if(s)return s.pricing;let l=r.get(o);if(!l)return;let u;for(let i of l)if(a.startsWith(i)&&(!u||i.length>u.key.length)){let d=e.get(Ie(o,i));d&&(u={key:i,pricing:d.pricing})}return u?.pricing},remove(o,a){let s=e.delete(Ie(o,a));if(s){let l=r.get(o);l?.delete(a),l&&l.size===0&&r.delete(o)}return s},entries(){let o=e.values();return(function*(){for(let{provider:a,model:s,pricing:l}of o)yield[a,s,l]})()}}}function Qt(t,e="USD"){return(r,n)=>{let o=t.lookup(n.provider,n.model);return o?qe(r,o,{tier:n.tier,withBreakdown:n.withBreakdown}):Oe(e)}}function Xt(...t){return(e,r)=>{for(let n of t){let o=n(e,r);if(o.total!==0)return o}return t.length>0?t[0](e,r):Oe()}}function Zt(t,e,r){return t?.pricing?qe(e,t.pricing,r):Oe()}function ze(t,e={}){let r=e.breaker??ut(e),n=H(t,{async invoke(o,a){if(!r.canExecute())throw new Ae;try{let s=await le(k(t.invoke(o,a)));return r.recordSuccess(),s}catch(s){throw r.recordFailure(s),s}},async*stream(o,a){if(!r.canExecute())throw new Ae;try{for await(let s of t.stream(o,a))yield s;r.recordSuccess()}catch(s){throw r.recordFailure(s),s}}});return q(n,"withBreaker",t),{adapter:n,breaker:r}}var Pe=class extends Error{constructor(r,n,o){super(`Budget exhausted: ${r} (limit=${n}, observed=${o})`);this.which=r;this.limit=n;this.observed=o}name="BudgetExhaustedError"},Je=Object.freeze({calls:0,inputTokens:0,outputTokens:0,usd:0}),xt=()=>({calls:0,inputTokens:0,outputTokens:0,usd:0});function Ye(t,e){let r=Te(void 0,{name:e.name?`${e.name}/log`:"budgetGate/log",maxSize:e.logMax??1e3}),n=L(xt(),{name:e.name?`${e.name}/totals`:"budgetGate/totals"}),o=M([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(F(o),e.onExhausted!=null){let i=e.onExhausted,d=!1,c=!0;o.subscribe(p=>{for(let m of p)if(m[0]===V){let g=m[1];if(d&&c&&g===!1){let y=Rt(n.cache??Je,e.caps);y&&i(y)}c=g,d=!0}})}let a=()=>{if(o.cache===!1){let i=n.cache??Je,d=Rt(i,e.caps);return new Pe(d??"budget",e.caps[d??"calls"]??0,er(i,d??"calls"))}},s=(i,d)=>{let c=t.provider,p=pe({provider:c,model:d.model,tier:d.tier,usage:i,startNs:d.startNs,method:d.method,...d.error?{error:d.error}:{}});r.append(p);let m=n.cache??Je,g=e.pricingFn?m.usd+e.pricingFn(i,{model:d.model,provider:c,tier:d.tier}).total:m.usd;n.emit({calls:m.calls+1,inputTokens:m.inputTokens+Z(i),outputTokens:m.outputTokens+ie(i),usd:g})},l=()=>{r.clear(),n.emit(xt())},u=H(t,{invoke(i,d){let c=a();if(c)return Promise.reject(c);let p=X(),m=t.model??d?.model??"",g=f=>(s(f.usage??re(),{model:t.model??d?.model??f.model??"",tier:d?.tier??f.tier,startNs:p,method:"invoke"}),f),y=f=>{let b=f;s(re(),{model:m,tier:d?.tier,startNs:p,method:"invoke",error:{type:b?.name??"Error",message:b?.message??String(f)}})};return Ee(t.invoke(i,d),{onResp:g,onError:y,name:"budgetGate/invokeTap"})},async*stream(i,d){let c=a();if(c)throw c;let p=X(),m;try{for await(let g of t.stream(i,d))g.type==="usage"&&(m=g.usage),yield g;s(m??re(),{model:t.model??d?.model??"",tier:d?.tier,startNs:p,method:"stream"})}catch(g){let y=g;throw s(m??re(),{model:t.model??d?.model??"",tier:d?.tier,startNs:p,method:"stream",error:{type:y?.name??"Error",message:y?.message??String(g)}}),g}}});return q(u,"withBudgetGate",t),{adapter:u,budget:{totals:n,isOpen:o,log:r,reset:l}}}function Rt(t,e){if(e.calls!=null&&t.calls>=e.calls)return"calls";if(e.inputTokens!=null&&t.inputTokens>=e.inputTokens)return"inputTokens";if(e.outputTokens!=null&&t.outputTokens>=e.outputTokens)return"outputTokens";if(e.usd!=null&&t.usd>=e.usd)return"usd"}function er(t,e){switch(e){case"calls":return t.calls;case"inputTokens":return t.inputTokens;case"outputTokens":return t.outputTokens;case"usd":return t.usd}}function tr(t,e){let r=e.mock??Ue({provider:t.provider,model:t.model}),n=typeof e.enabled=="boolean"?e.enabled:void 0,o=n===void 0?k(e.enabled):void 0,a;o&&(a=F(o));let s=()=>n!==void 0?n:!!o?.cache,l=H(t,{invoke(i,d){return s()?r.invoke(i,d):t.invoke(i,d)},stream(i,d){return s()?r.stream(i,d):t.stream(i,d)}});return q(l,"withDryRun",t),{adapter:l,dispose:()=>{a&&(a(),a=void 0)}}}function Qe(t){if(t==null||typeof t!="object")return;let e=t,r=e.status,n=rr(e.headers);if(r!==429&&r!==503&&!lr(e.message))return;let o={},a=n("retry-after"),s=or(a);s!=null&&(o.retryAfterMs=s);let l=n("anthropic-ratelimit-requests-reset");if(l){let m=wt(l);m!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,m))}let u=n("anthropic-ratelimit-tokens-reset");if(u){let m=wt(u);m!=null&&(o.retryAfterMs=Math.max(o.retryAfterMs??0,m))}let i=_e(n,"x-ratelimit-limit-requests");i!=null&&(o.rpmCap=i);let d=_e(n,"x-ratelimit-limit-tokens");d!=null&&(o.tpmCap=d);let c=_e(n,"x-ratelimit-remaining-requests"),p=_e(n,"x-ratelimit-remaining-tokens");if(c!=null&&i!=null&&i>0&&(o.usageHint??={},o.usageHint.rpm=1-c/i),p!=null&&d!=null&&d>0&&(o.usageHint??={},o.usageHint.tpm=1-p/d),o.retryAfterMs==null&&e.message){let m=sr(e.message);m!=null&&(o.retryAfterMs=m)}return e.headers&&(o.metadata={headers:nr(e.headers)}),o.retryAfterMs==null&&o.rpmCap==null&&o.tpmCap==null&&o.usageHint==null?o.metadata?o:void 0:o}function rr(t){if(!t)return()=>{};if(typeof t.get=="function"){let n=t;return o=>n.get(o)??n.get(o.toLowerCase())??void 0}let e=t,r={};for(let[n,o]of Object.entries(e)){let a=Array.isArray(o)?o.join(", "):o;a!=null&&(r[n.toLowerCase()]=a)}return n=>r[n.toLowerCase()]}function nr(t){let e={};if(typeof t.forEach=="function")return t.forEach((r,n)=>{e[n]=r}),e;for(let[r,n]of Object.entries(t))n!=null&&(e[r]=Array.isArray(n)?n.join(", "):n);return e}function _e(t,e){let r=t(e);if(r==null)return;let n=Number(r);return Number.isFinite(n)?n:void 0}function or(t){if(!t)return;let e=t.trim(),r=Number(e);if(Number.isFinite(r)&&r>=0)return r*1e3;let n=Date.parse(e);if(Number.isFinite(n)){let o=n-Date.now();if(o>0)return o}}function wt(t){if(!t)return;let e=Date.parse(t);if(Number.isFinite(e))return Math.max(0,e-Date.now())}var ar=/retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(ms|s|sec|seconds?|m|min|minutes?)/i;function sr(t){let e=ar.exec(t);if(!e)return;let r=Number(e[1]);if(!Number.isFinite(r))return;let n=(e[2]??"s").toLowerCase();if(n==="ms")return r;if(n.startsWith("s"))return r*1e3;if(n.startsWith("m"))return r*6e4}var ir=/rate\s*limit|too\s*many\s*requests|quota|429/i;function lr(t){return!!t&&ir.test(t)}function Xe(t){let e=new Error(t);return e.name="AbortError",e}function Nt(t={}){let e=Math.max(1,t.burstMultiplier??1),r=t.clampCooldownMs??6e4,n=t.rpm!=null?k(t.rpm):L(Number.POSITIVE_INFINITY),o=t.tpm!=null?k(t.tpm):L(Number.POSITIVE_INFINITY),a=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalRpmCap"}),s=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/signalTpmCap"}),l=L({},{name:"adaptiveRateLimiter/lastSignal"}),u=M([n,a],([w,I])=>Math.min(Number(w??1/0),Number(I??1/0)),{name:"adaptiveRateLimiter/effectiveRpm"}),i=M([o,s],([w,I])=>Math.min(Number(w??1/0),Number(I??1/0)),{name:"adaptiveRateLimiter/effectiveTpm"}),d=Me(Number(n.cache??Number.POSITIVE_INFINITY),e),c=Me(Number(o.cache??Number.POSITIVE_INFINITY),e),p=!1,m=!1,g=u.subscribe(w=>{for(let I of w)if(I[0]===V){let _=Number(I[1]);Number.isFinite(_)&&_>0?(d=Me(_,e),p=!1):_===1/0?(d=Me(1/0,e),p=!1):_<=0&&(p=!0)}}),y=i.subscribe(w=>{for(let I of w)if(I[0]===V){let _=Number(I[1]);Number.isFinite(_)&&_>0?(c=Me(_,e),m=!1):_===1/0?(c=Me(1/0,e),m=!1):_<=0&&(m=!0)}}),f=0,b=new te,O=new te,v;t.adaptation!=null&&(v=k(t.adaptation).subscribe(I=>{for(let _ of I)_[0]===V&&A(_[1])}));function A(w){if(l.emit(w),w.rpmCap!=null&&Number.isFinite(w.rpmCap)&&w.rpmCap>=0&&(a.emit(w.rpmCap),Number.isFinite(r)&&r>0&&b.start(r,()=>a.emit(Number.POSITIVE_INFINITY))),w.tpmCap!=null&&Number.isFinite(w.tpmCap)&&w.tpmCap>=0&&(s.emit(w.tpmCap),Number.isFinite(r)&&r>0&&O.start(r,()=>s.emit(Number.POSITIVE_INFINITY))),w.retryAfterMs!=null&&w.retryAfterMs>0){let I=X()+w.retryAfterMs*1e6;I>f&&(f=I)}}let C=L(0,{name:"adaptiveRateLimiter/pending"}),S=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/rpmAvailable"}),$=L(Number.POSITIVE_INFINITY,{name:"adaptiveRateLimiter/tpmAvailable"}),U=w=>{C.emit((C.cache??0)+w)},W=()=>{S.emit(d.available()),$.emit(c.available())};async function Y(w={}){let I=w.requestCost??1,_=w.tokenCost??0,T=w.signal;U(1);try{for(;;){if(T?.aborted)throw Xe("AdaptiveRateLimiter.acquire aborted");let h=X();if(f>h){let ne=Math.ceil((f-h)/1e6);await De(ne,T);continue}if(I>0&&p||_>0&&m){await De(250,T);continue}let x=d,R=c;if(!x.tryConsume(I)){await De(Lt(x,I),T);continue}if(!(_>0?R.tryConsume(_):!0)){x.putBack(I),await De(Lt(R,_),T);continue}W();return}}finally{U(-1)}}function K(w){w>0?c.tryConsume(w):w<0&&c.putBack(-w),W()}function G(){g(),y(),v?.(),b.cancel(),O.cancel()}return{effectiveRpm:u,effectiveTpm:i,lastSignal:l,pending:C,rpmAvailable:S,tpmAvailable:$,acquire:Y,recordUsage:K,recordSignal:A,dispose:G}}function Me(t,e){if(!Number.isFinite(t)||t===1/0)return We(Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER);let r=Math.max(1,t*e),n=t/60;return We(r,n)}function Lt(t,e){let r=t.available(),n=Math.max(0,e-r);return n<=0?25:Math.min(5e3,Math.max(50,n*100))}function De(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(Xe("AdaptiveRateLimiter.acquire aborted")):new Promise((r,n)=>{let o=new te,a,s=()=>{o.cancel(),e&&a&&e.removeEventListener("abort",a)};o.start(t,()=>{s(),r()}),e&&(a=()=>{s(),n(Xe("AdaptiveRateLimiter.acquire aborted"))},e.addEventListener("abort",a,{once:!0}))})}function Ze(t,e={}){let r=e.limiter??Nt({name:e.name??"rateLimiter",rpm:e.rpm,tpm:e.tpm,adaptation:e.adaptation,burstMultiplier:e.burstMultiplier}),n=(s,l)=>e.costFn?e.costFn(s,l):0,o=s=>{let l=Qe(s);l&&r.recordSignal(l)},a=H(t,{async invoke(s,l){let u=n(s,l);await r.acquire({requestCost:1,tokenCost:u,signal:l?.signal});try{let i=await le(k(t.invoke(s,l))),d=i.usage??kt(),p=Z(d)+ie(d)-u;return p>0&&r.recordUsage(p),i}catch(i){throw o(i),i}},async*stream(s,l){let u=n(s,l);await r.acquire({requestCost:1,tokenCost:u,signal:l?.signal});try{let i=0;for await(let c of t.stream(s,l))c.type==="usage"&&(i=Z(c.usage)+ie(c.usage)),yield c;let d=i-u;d>0&&r.recordUsage(d)}catch(i){throw o(i),i}}});return q(a,"withRateLimiter",t),{adapter:a,limiter:r}}function je(t="aborted"){let e=new Error(t);return e.name="AbortError",e}function Ct(t,e){return t<=0?Promise.resolve():e?.aborted?Promise.reject(je()):new Promise((r,n)=>{let o=new te,a,s=()=>{o.cancel(),e&&a&&e.removeEventListener("abort",a)};o.start(t,()=>{s(),r()}),e&&(a=()=>{s(),n(je())},e.addEventListener("abort",a,{once:!0}))})}function et(t,e={}){let r=e.attempts??3,n=e.baseDelayMs??500,o=e.maxDelayMs??1e4,a=e.strategy??"decorrelated",s=e.jitter??!0,l=e.shouldRetry??dr,u=e.retryStreaming??!0,i=(c,p)=>{if(a==="decorrelated"){let f=Math.min(o,Math.max(n,p*3));return n+Math.random()*(f-n)}let m=a==="exp"?n*2**(c-1):n*c,g=Math.min(o,m);if(!s)return g;let y=g*(.5+Math.random());return Math.min(o,y)},d=H(t,{async invoke(c,p){if(p?.signal?.aborted)throw je();let m,g=n;for(let y=1;y<=r;y++)try{return await le(k(t.invoke(c,p)))}catch(f){if(m=f,y>=r||!l(f,y))throw f;let b=i(y,g);g=b,await Ct(b,p?.signal)}throw m},async*stream(c,p){if(p?.signal?.aborted)throw je();if(!u){for await(let y of t.stream(c,p))yield y;return}let m,g=n;for(let y=1;y<=r;y++){let f=!1;try{for await(let b of t.stream(c,p))f=!0,yield b;return}catch(b){if(m=b,f||y>=r||!l(b,y))throw b;let O=i(y,g);g=O,await Ct(O,p?.signal)}}throw m}});return q(d,"withRetry",t),d}function dr(t,e){if(t==null)return!1;let r=t;return r.name==="LLMTimeoutError"?!0:r.name==="AbortError"||r.message==="aborted"||r.name==="DOMException"&&r.code!=null&&Number(r.code)===20||r.name==="BudgetExhaustedError"||r.name==="CircuitOpenError"?!1:r.status!=null?r.status===429||r.status>=500&&r.status<600:r.code&&typeof r.code=="string"&&/^E[A-Z]+$/.test(r.code)?!0:r.message?/network|timeout|socket|fetch|econn|eai_/i.test(r.message):!1}var ve=class extends Error{constructor(r){super(`LLM call timed out after ${r}ms`);this.ms=r}name="LLMTimeoutError"};function tt(t,e){if(e<=0)throw new RangeError("withTimeout: ms must be > 0");let r=a=>{let s=new AbortController,l=!1,u,i=new te;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 ve(e))}),{signal:s.signal,cancel:()=>{i.cancel(),a&&u&&a.removeEventListener("abort",u)},timedOut:()=>l}},n=(a,s)=>{if(!s||a instanceof ve)throw a;let l=a;if(l?.name==="AbortError"||l?.name==="DOMException"&&Number(l.code)===20||a?.message==="aborted"){let i=new ve(e);throw i.cause=a,i}throw a},o=H(t,{async invoke(a,s){let{signal:l,cancel:u,timedOut:i}=r(s?.signal);try{return await le(k(t.invoke(a,{...s,signal:l})))}catch(d){return n(d,i())}finally{u()}},async*stream(a,s){let{signal:l,cancel:u,timedOut:i}=r(s?.signal);try{for await(let d of t.stream(a,{...s,signal:l}))yield d}catch(d){n(d,i())}finally{u()}}});return q(o,"withTimeout",t),o}function ur(t,e={}){let r={adapter:t},n=t;if(e.rateLimit){let o=Ze(n,e.rateLimit);n=o.adapter,r.rateLimiter=o.limiter}if(e.budget){let o=Ye(n,e.budget);n=o.adapter,r.budget=o.budget}if(e.breaker){let o=ze(n,e.breaker);n=o.adapter,r.breaker=o.breaker}if(e.timeoutMs!=null&&(n=tt(n,e.timeoutMs)),e.retry&&(n=et(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=Ve([{name:e.name??"primary",adapter:n},{name:"fallback",adapter:e.fallback}],o)}return e.cache&&(n=Ke(n,e.cache)),r.adapter=n,r}function cr(t,e,r){let n=k(e);return J(n,a=>{if(!a||a.length===0)return L(null);let s=r?.tools;return t.invoke(a,{model:r?.model,temperature:r?.temperature,maxTokens:r?.maxTokens,tools:s,systemPrompt:r?.systemPrompt})})}function N(t,e){return pt("ai",t,e)}function mr(t){return t!=null&&typeof t.then=="function"}function pr(t){return typeof t=="object"&&t!==null&&"subscribe"in t&&typeof t.subscribe=="function"&&"cache"in t}function fr(t){return t!=null&&typeof t=="object"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}var gr=3e4;function At(t,e){if(t.status==="settled"){let n=t.cache;if(n!==void 0)return Promise.resolve(n)}let r=e?.timeoutMs??gr;return new Promise((n,o)=>{let a=new te,s=t.subscribe(l=>{for(let u of l){if(u[0]===V){a.cancel(),s(),n(u[1]);return}if(u[0]===Q){a.cancel(),s(),o(u[1]);return}if(u[0]===ae){a.cancel(),s(),o(new Error("firstDataFromNode: completed without producing a value"));return}}});a.start(r,()=>{s(),o(new Error(`firstDataFromNode: timed out after ${r}ms`))})})}async function fe(t){return mr(t)?fe(await t):pr(t)?At(t):fr(t)?At(k(t)):t}function ke(t){let e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```[\s\S]*$/);return e?e[1]:t}function yr(t,e){let r=k(t),n=e?.refreshTrigger!=null?k(e.refreshTrigger):null;return n==null?ce([r],(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:N("frozen_context")}):ce([r,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:N("frozen_context")})}function hr(t){return t!=null&&typeof t=="object"&&"content"in t?String(t.content):typeof t=="string"?t:String(t)}function br(t,e,r,n){let o=n?.format??"text",a=n?.retries??0,s=n?.cache??!1,l=s?new Map:null,u=M(e,d=>{if(d.some(m=>m==null))return[];let c=typeof r=="string"?r:r(...d);if(!c)return[];let p=[];return n?.systemPrompt&&p.push({role:"system",content:n.systemPrompt}),p.push({role:"user",content:c}),p},{name:n?.name?`${n.name}::messages`:"prompt_node::messages",meta:N("prompt_node"),initial:[]});return J(u,d=>{if(!d||d.length===0)return L(null);let c=s?JSON.stringify(d.map(m=>[m.role,m.content])):"";if(l?.has(c))return L(l.get(c));async function p(m){try{let g=await new Promise((b,O)=>{let v=t.invoke(d,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt});v&&typeof v.then=="function"?v.then(b,O):v&&typeof v.subscribe=="function"?b(v.cache):b(v)}),y=hr(g),f;return o==="json"?f=JSON.parse(ke(y)):f=y,l?.set(c,f),f}catch(g){if(m>0)return p(m-1);throw g}}return p(a)})}async function St(t,e,r,n){let o="",a=0;for await(let s of t.stream(e,r))n.publish({...s,seq:a++,ts:Re()}),s.type==="token"&&(o+=s.delta);return o}function Et(t,e){if(e==="json")try{return JSON.parse(ke(t))}catch(r){let n=t.slice(0,160);throw new Error(`streamingPromptNode: format:"json" \u2014 failed to parse accumulated text as JSON: ${r.message}; content preview: ${n}`)}return t}function It(t,e){return M([t.latest],([r],n)=>{let o=n.store;if(r==null)return o.acc??"";let a=r;return a.seq===0&&(o.acc=""),a.type==="token"&&(o.acc=(o.acc??"")+a.delta),o.acc??""},{name:e,meta:N("accumulated_text"),initial:""})}function Tr(t,e,r,n){let o=n?.name??"llm",a=n?.format??"text",s=He(`${o}/stream`,{...n?.retainedLimit!=null?{retainedLimit:n.retainedLimit}:{}}),l=M(e,c=>{if(c.some(m=>m==null))return[];let p=typeof r=="string"?r:r(...c);return p?[{role:"user",content:p}]:[]},{name:`${o}::messages`,meta:N("prompt_node::messages"),initial:[]}),u=J(l,c=>{let p=c;if(!p||p.length===0)return L(null);let m=new AbortController;async function*g(){try{let y=await St(t,p,{model:n?.model,temperature:n?.temperature,maxTokens:n?.maxTokens,systemPrompt:n?.systemPrompt,signal:m.signal},s);yield Et(y,a)}finally{m.abort()}}return k(g())}),i=It(s,`${o}::accumulatedText`),d=F(u);return{output:u,deltaTopic:s,accumulatedText:i,dispose:()=>{d(),s.destroy()}}}function Mr(t,e,r,n,o,a){let s=L(0,{name:`${e}/cancel`}),l=0,u=[...n,s],i=a?.name??e,d=a?.format??"text",c=He(`${i}/stream`,{...a?.retainedLimit!=null?{retainedLimit:a.retainedLimit}:{}}),p=M(u,A=>{let C=A.slice(0,-1);if(C.some($=>$==null))return[];let S=typeof o=="string"?o:o(...C);return S?[{role:"user",content:S}]:[]},{name:`${i}::messages`,meta:N("prompt_node::messages"),initial:[]}),m=J(p,A=>{let C=A;if(!C||C.length===0)return L(null);let S=new AbortController;async function*$(){try{let U=await St(r,C,{model:a?.model,temperature:a?.temperature,maxTokens:a?.maxTokens,systemPrompt:a?.systemPrompt,signal:S.signal},c);yield Et(U,d)}finally{S.abort()}}return k($())}),g=It(c,`${i}::accumulatedText`),y=M([m],([A])=>{if(A!=null)return A},{name:`${e}/filter`});t.add(y,{name:`${e}/raw`});let f=yt(t,`${e}/gate`,`${e}/raw`,a?.gate),b=F(m),O=f.reject.bind(f),v={...f,reject(A=1){se(()=>{O(A),s.emit(++l)})}};return{output:f.node,deltaTopic:c,accumulatedText:g,gate:v,dispose:()=>{b(),c.destroy()}}}function vr(t,e){let r=e?.separator??`
|
|
2
|
+
|
|
3
|
+
`,n=t.map(s=>typeof s=="string"?L(s):k(s)),o=M(n,s=>s.filter(l=>l!=null&&l!=="").join(r),{name:e?.name??"systemPrompt",describeKind:"derived",meta:N("system_prompt"),initial:""}),a=F(o);return Object.assign(o,{dispose:a})}var kr=(t,e)=>t===e?!0:t.chunkCount===e.chunkCount&&t.charCount===e.charCount&&t.estimatedTokens===e.estimatedTokens&&t.estimated===e.estimated;function xr(t,e){let r=e?.charsPerToken??4,n={chunkCount:0,charCount:0,estimatedTokens:0,estimated:!0};return M([t.latest],([o],a)=>{if(o==null)return n;let s=o;"chunkCount"in a.store||(a.store.chunkCount=0,a.store.charCount=0,a.store.usageTokens=0,a.store.sawUsage=!1);let l=a.store;s.type==="token"?(l.chunkCount+=1,l.charCount+=s.delta.length):s.type==="usage"&&(l.sawUsage=!0,l.usageTokens=Z(s.usage)+ie(s.usage));let u=l.sawUsage?l.usageTokens:Math.ceil(l.charCount/r);return{chunkCount:l.chunkCount,charCount:l.charCount,estimatedTokens:u,estimated:!l.sawUsage}},{name:e?.name??"cost-meter",describeKind:"derived",initial:n,meta:N("cost_meter_extractor"),equals:kr})}var Rr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let n=t[r],o=e[r];if(n.label!==o.label||n.pattern!==o.pattern||n.match!==o.match||n.position!==o.position)return!1}return!0};function wr(t,e){let r=e.maxPatternLength??128;for(let o of e.patterns)if(o.pattern.source.length>r)throw new Error(`keywordFlagExtractor: pattern "${o.label}" literal exceeds maxPatternLength (${o.pattern.source.length} > ${r}); raise the option or shorten the pattern.`);let n=e.patterns.map(o=>({label:o.label,pattern:o.pattern,compiled:new RegExp(o.pattern.source,`${o.pattern.flags.replace("g","")}g`)}));return M([t],([o],a)=>{if(o==null)return[];let s=o;"flags"in a.store||(a.store.flags=[],a.store.scannedTo=0);let l=a.store.flags,u=a.store.scannedTo,i=Math.max(0,u-r),d=s.slice(i),c=!1;for(let{pattern:p,label:m,compiled:g}of n){g.lastIndex=0;for(let y of d.matchAll(g)){let f=i+(y.index??0);f+y[0].length<=u||(l.push({label:m,pattern:p,match:y[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:N("keyword_flag_extractor"),equals:Rr})}function Lr(t,e,r){return M([t],([n])=>n==null?null:e(n),{name:r?.name??"extractor",describeKind:"derived",initial:null,meta:N("stream_extractor"),...r?.equals?{equals:r.equals}:{}})}var Nr=(t,e)=>{if(t===e)return!0;if(t==null||e==null)return t===e;if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let n=t[r],o=e[r];if(n.startIndex!==o.startIndex||n.name!==o.name||n.raw!==o.raw)return!1}return!0};function Cr(t,e){return M([t],([r],n)=>{if(r==null)return[];let o=r;"calls"in n.store||(n.store.calls=[],n.store.scanFrom=0);let a=n.store.calls,s=n.store.scanFrom,l=!1;for(;s<o.length;){let u=o.indexOf("{",s);if(u===-1){n.store.scanFrom=o.length;break}let i=0,d=-1,c=!1;for(let m=u;m<o.length;m++){let g=o[m];if(c)g==="\\"&&m+1<o.length?m++:g==='"'&&(c=!1);else if(g==='"')c=!0;else if(g==="{")i++;else if(g==="}"&&(i--,i===0)){d=m;break}}if(d===-1){n.store.scanFrom=u;break}let p=o.slice(u,d+1);try{let m=JSON.parse(p);typeof m.name=="string"&&m.arguments!=null&&typeof m.arguments=="object"&&(a.push({name:m.name,arguments:m.arguments,raw:p,startIndex:u}),l=!0)}catch{}s=d+1,n.store.scanFrom=s}return l?[...a]:a.slice()},{name:e?.name??"tool-call-extractor",describeKind:"derived",initial:[],meta:N("tool_call_extractor"),equals:Nr})}function Ar(t,e,r,n){let o=r*(n?.hardMultiplier??1.5),a=typeof e!="function",s=[t];return a&&s.push(e),M(s,l=>{let u=l[0]??"";if(u.length===0)return"allow";let i=a?l[1]??0:e(u);return i>=o?"block":i>=r?"review":"allow"},{name:n?.name??"content-gate",initial:"allow"})}function Sr(t,e,r,n){let o=r??(()=>"[REDACTED]");function a(s){let l=s;for(let u of e){let i=u.global?u:new RegExp(u.source,`${u.flags}g`);l=l.replace(i,d=>o(d,u))}return l}return M([t],([s])=>a(s??""),{name:n?.name??"redactor",initial:""})}var Fe=class extends de{_log;messages;latest;messageCount;constructor(e,r={}){super(e,r.graph),this._log=Te([],{name:"messages",maxSize:r.maxMessages}),this.messages=this._log.entries,this.add(this.messages,{name:"messages"}),this.latest=M([this.messages],([n])=>{let o=n;return o.length===0?null:o[o.length-1]},{name:"latest",describeKind:"derived",meta:N("chat_latest")}),this.add(this.latest,{name:"latest"}),this.addDisposer(F(this.latest)),this.messageCount=M([this.messages],([n])=>n.length,{name:"messageCount",describeKind:"derived",meta:N("chat_message_count"),initial:0}),this.add(this.messageCount,{name:"messageCount"}),this.addDisposer(F(this.messageCount))}append(e,r,n){this._log.append({role:e,content:r,...n})}appendToolResult(e,r){this._log.append({role:"tool",content:r,toolCallId:e})}clear(){this._log.clear()}allMessages(){return this.messages.cache}};function rt(t,e){return new Fe(t,e)}var Ge=class extends de{definitions;schemas;_bundle;constructor(e,r={}){super(e,r.graph),this._bundle=Se({name:"definitions"}),this.definitions=this._bundle.entries,this.add(this.definitions,{name:"definitions"}),this.schemas=M([this.definitions],([n])=>[...(n??new Map).values()],{name:"schemas",describeKind:"derived",meta:N("tool_schemas"),initial:[]}),this.add(this.schemas,{name:"schemas"}),this.addDisposer(F(this.schemas))}register(e){this._bundle.set(e.name,e)}unregister(e){this._bundle.delete(e)}async execute(e,r){let n=this._bundle.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);let o=n.handler(r);return fe(o)}executeReactive(e,r){let n=this._bundle.get(e);if(!n)throw new Error(`toolRegistry: unknown tool "${e}"`);return k(n.handler(r))}getDefinition(e){return this._bundle.entries.cache?.get(e)}};function nt(t,e){return new Ge(t,e)}var Be=class extends de{chat;tools;status;turn;aborted;lastResponse;toolCalls;toolResults;turnCount;_terminalResult;_disposeRunWiring;_runVersion=0;_running=!1;_currentAbortController=null;constructor(e,r){if(super(e,r.graph),this.chat=rt(`${e}-chat`,{maxMessages:r.maxMessages}),this.mount("chat",this.chat),this.tools=nt(`${e}-tools`),this.mount("tools",this.tools),r.tools)for(let T of r.tools)this.tools.register(T);this.status=L("idle",{name:"status",describeKind:"state",meta:N("agent_status")}),this.add(this.status,{name:"status"}),this.turn=L(0,{name:"turn",describeKind:"state",meta:N("agent_turn_count")}),this.add(this.turn,{name:"turn"}),this.turnCount=this.turn,this.aborted=L(!1,{name:"aborted",describeKind:"state",meta:N("agent_aborted")}),this.add(this.aborted,{name:"aborted"});let n=0,o=this.turn.subscribe(T=>{for(let h of T)h[0]===V&&(n=h[1])}),a=!1,s=this.aborted.subscribe(T=>{for(let h of T)h[0]===V&&(a=h[1])}),l=r.adapter,u=r.systemPrompt,i=r.model,d=r.temperature,c=r.maxTokens,p=r.maxTurns??10,m=r.stopWhen,g=this.chat,y=this.tools,f=this.status,b=this.turn,O=this.aborted,v=ce([f],(T,h,x)=>{if(Le(T,x.prevData,0,"idle")!=="thinking"||a||n>=p){h.down([[be]]);return}let P=g.allMessages();if(P.length===0){h.down([[be]]);return}let E=y.schemas.cache??[];h.emit({messages:P,tools:E})},{name:"promptInput",describeKind:"derived",meta:N("agent_prompt_input")}),A=J(v,T=>{let h=new AbortController;return this._currentAbortController=h,a&&h.abort(new Error("agentLoop: aborted")),k(Promise.resolve(l.invoke(T.messages,{tools:T.tools.length>0?T.tools:void 0,systemPrompt:u,model:i,temperature:d,maxTokens:c,signal:h.signal})),{signal:h.signal})},{equals:()=>!1}),C=L(null,{name:"lastResponse",describeKind:"state",meta:N("agent_last_response")});this.lastResponse=C;let S=ce([C,f],(T,h,x)=>{let R=Le(T,x.prevData,0,null);if(Le(T,x.prevData,1,"idle")!=="acting"){h.down([[be]]);return}let E=R?.toolCalls;if(E==null||E.length===0){h.down([[be]]);return}h.emit(E)},{name:"toolCalls",describeKind:"derived",meta:N("agent_tool_calls")}),$=r.interceptToolCalls?r.interceptToolCalls(S):S;this.toolCalls=$;let U=(T,h)=>{if(T===h)return!0;if(T.length!==h.length)return!1;for(let x=0;x<T.length;x++){let R=T[x],P=h[x];if(R?.id!==P?.id||R?.content!==P?.content)return!1}return!0},W=J($,T=>{if(T==null||T.length===0)throw new Error("agentLoop: toolResultsNode received an empty tool-call batch as DATA \u2014 toolCallsNode gating invariant broken (should emit RESOLVED for empty). Audit toolCallsNode.");let h=T.map(x=>Er(x,y));return M(h,x=>x.map((R,P)=>{let E=R;return E!=null&&typeof E=="object"&&"id"in E&&"content"in E?E:{id:T[P].id,content:JSON.stringify(R??null)}}),{name:"toolResults_batch",equals:U})});this.toolResults=W;let Y=me([A],([T])=>{if(a)return;let h=T,x=n+1,R=h.toolCalls!=null&&h.toolCalls.length>0,P=h.finishReason==="end_turn"&&(!h.toolCalls||h.toolCalls.length===0),E=m?.(h)===!0,ne=x>=p,oe=E||P||!R||ne?"done":"acting";se(()=>{C.emit(h),f.emit(oe),b.emit(x),g.append("assistant",h.content,{toolCalls:h.toolCalls})})}),K=me([W],([T])=>{if(a)return;let h=T;if(h.length===0)return;let x=n>=p?"done":"thinking";se(()=>{f.emit(x);for(let R of h)g.appendToolResult(R.id,R.content)})}),G=me([O],([T])=>{T===!0&&(this._currentAbortController?.abort(new Error("agentLoop: aborted")),f.emit("done"))}),w=F(Y),I=F(K),_=F(G);this._terminalResult=ce([f,C],(T,h,x)=>{let R=Le(T,x.prevData,0,"idle"),P=Le(T,x.prevData,1,null);if(R==="done"){if(P!=null){h.emit({response:P,runVersion:this._runVersion});return}let E=new Error("agentLoop: aborted");E.name="AbortError",h.down([[Q,E]]);return}if(R==="error"){h.down([[Q,new Error("agentLoop: errored")]]);return}h.down([[be]])},{name:"terminalResult",describeKind:"derived",meta:N("agent_terminal_result")}),this.addDisposer(o),this.addDisposer(s),this.addDisposer(w),this.addDisposer(I),this.addDisposer(_),this._disposeRunWiring=()=>{}}async run(e,r){if(this._running)throw new RangeError(`agentLoop "${this.name}": run() called while a previous run() is still pending \u2014 await the previous run before starting another, or call abort() first`);this._running=!0;let n=++this._runVersion;se(()=>{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(r!=null)if(r.aborted)this.aborted.emit(!0);else{let a=()=>this.aborted.emit(!0);r.addEventListener("abort",a,{once:!0}),o=()=>r.removeEventListener("abort",a)}try{return(await mt(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 Er(t,e){let r=dt(()=>k(Promise.resolve().then(()=>e.execute(t.name,t.arguments))),{count:1}),n=M([r],([o])=>({id:t.id,content:typeof o=="string"?o:JSON.stringify(o)}));return ft(n,o=>({id:t.id,content:JSON.stringify({error:String(o)})}))}function Le(t,e,r,n){let o=t[r];if(o!=null&&o.length>0)return o[o.length-1];let a=e[r];return a!==void 0?a:n}function Ir(t,e){return new Be(t,e)}function Or(t,e,r){let n=k(t),o=r?.condition!=null?k(r.condition):null,a=L(null,{name:r?.name?`${r.name}::null`:"handoff::null"});if(o==null)return J(n,l=>{if(l==null)return a;let u=L(l);return e(u)});let s=M([n,o],([l,u])=>({v:l,open:u===!0}),{name:r?.name?`${r.name}::router`:"handoff::router",describeKind:"derived"});return J(s,({v:l,open:u})=>{if(l==null)return a;if(!u)return L(l);let i=L(l);return e(i)})}function Pr(t,e,r){let n=k(t),o=e.map(s=>k(s)),a=[n,...o];return M(a,s=>{let l=s[0]??[],u=s.slice(1);return l.filter(i=>{for(let d of u)if(d!=null&&!d(i))return!1;return!0})},{name:r?.name??"tool-selector",describeKind:"derived",meta:N("tool_selector"),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 _r(t){return{persistence:.5,structure:.5,personalValue:.5}}function Dr(t={}){let e=t.scoreFn??_r,r=t.persistenceThreshold??.3,n=t.personalValueThreshold??.3,o=t.requireStructured??!1;return a=>{let s=e(a);return!(s.persistence<r||s.personalValue<n||o&&s.structure<=0)}}function ot(t,e){return(r,n)=>{let o=[...n.keys()].slice(0,100),a=[{role:"system",content:t},{role:"user",content:JSON.stringify({input:r,existingKeys:o})}];return $e(s=>{let l=!0,u=e.adapter.invoke(a,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),d=k(u).subscribe(c=>{if(!l)return;let p=!1;for(let m of c){if(p)break;if(m[0]===V){let g=m[1];try{let y=JSON.parse(g.content);s.emit(y),s.down([[ae]])}catch{s.down([[Q,new Error("llmExtractor: failed to parse LLM response as JSON")]])}p=!0}else m[0]===Q?(s.down([[Q,m[1]]]),p=!0):m[0]===ae?(s.down([[ae]]),p=!0):s.down([[m[0],m[1]]])}});return()=>{d(),l=!1}})}}function at(t,e){return r=>{let n=[...r.entries()].map(([a,s])=>({key:a,value:s})),o=[{role:"system",content:t},{role:"user",content:JSON.stringify({memories:n})}];return $e(a=>{let s=!0,l=e.adapter.invoke(o,{model:e.model,temperature:e.temperature??0,maxTokens:e.maxTokens}),i=k(l).subscribe(d=>{if(!s)return;let c=!1;for(let p of d){if(c)break;if(p[0]===V){let m=p[1];try{let g=JSON.parse(m.content);a.emit(g),a.down([[ae]])}catch{a.down([[Q,new Error("llmConsolidator: failed to parse LLM response as JSON")]])}c=!0}else p[0]===Q?(a.down([[Q,p[1]]]),c=!0):p[0]===ae?(a.down([[ae]]),c=!0):a.down([[p[0],p[1]]])}});return()=>{i(),s=!1}})}}var st=Math.LN2/604800;function Ne(t){return t instanceof Map?t:new Map}function jr(t,e,r){let n=new de(t,r.graph),o=[],a;if(r.extractFn)a=r.extractFn;else if(r.adapter&&r.extractPrompt)a=ot(r.extractPrompt,{adapter:r.adapter});else throw new Error("agentMemory: provide either extractFn or adapter + extractPrompt");let s=(v,A)=>v==null?{upsert:[]}:a(v,A),l=e;if(r.admissionFilter){let v=k(e),A=r.admissionFilter;l=M([v],([C])=>{if(A(C))return C},{name:"admissionFilter",describeKind:"derived"})}let u;r.consolidateFn?u=r.consolidateFn:r.adapter&&r.consolidatePrompt&&(u=at(r.consolidatePrompt,{adapter:r.adapter}));let i=r.consolidateTrigger;if(!i&&u&&r.reflection?.enabled!==!1){let v=r.reflection?.interval??3e5;i=ct(v,{period:v})}let d={score:r.score,cost:r.cost,budget:r.budget??2e3,context:r.context,consolidate:u,consolidateTrigger:i},c=gt(l,s,d);n.add(c.store.entries,{name:"store"}),n.add(c.compact,{name:"compact"}),n.add(c.size,{name:"size"});let p=null;r.vectorDimensions&&r.vectorDimensions>0&&r.embedFn&&(p=Tt({dimension:r.vectorDimensions}),n.add(p.entries,{name:"vectorIndex"}));let m=null;r.enableKnowledgeGraph&&(m=Mt(`${t}-kg`),n.mount("kg",m));let g=null;if(r.tiers){let v=r.tiers,A=v.decayRate??st,C=v.maxActive??1e3,S=v.archiveThreshold??.1,$=v.permanentFilter??(()=>!1),U=bt({name:"permanent"});n.add(U.entries,{name:"permanent"});let W=new Set,Y=h=>W.has(h)?"permanent":Ne(c.store.entries.cache).has(h)?"active":"archived",K=(h,x)=>{W.add(h),U.upsert(h,x)},G=new Map,w=c.store.entries,I=r.context?k(r.context):L(null),_=me([w,I],([h,x])=>{let R=Ne(h),P=X(),E=[],ne=[];for(let[j,ee]of R){if(G.has(j)||G.set(j,P),$(j,ee)){ne.push({key:j,value:ee});continue}let z=r.score(ee,x),D=G.get(j)??P,B=Number(P-D)/1e9;ht(z,B,A)<S&&E.push(j)}for(let j of G.keys())R.has(j)||G.delete(j);for(let{key:j,value:ee}of ne)W.has(j)||K(j,ee);let oe=R.size-W.size;if(oe>C){let j=[...R.entries()].filter(([z])=>!W.has(z)).map(([z,D])=>({key:z,score:r.score(D,x)})).sort((z,D)=>z.score-D.score),ee=oe-C;for(let z=0;z<ee&&z<j.length;z++){let D=j[z].key;E.includes(D)||E.push(D)}}E.length>0&&se(()=>{for(let j of E)c.store.delete(j)})});o.push(_.subscribe(()=>{}));let T=null;v.archiveTier&&(T=n.attachStorage([v.archiveTier],v.archiveStorageOptions??{})),g={permanent:U,activeEntries:w,archiveHandle:T,tierOf:Y,markPermanent:K}}if(p||m){let v=r.embedFn,A=r.entityFn,C=c.store.entries,S=me([C],([$])=>{let U=Ne($);for(let[W,Y]of U){if(p&&v){let K=v(Y);K&&p.upsert(W,K,Y)}if(m&&A){let K=A(W,Y);if(K){for(let G of K.entities??[])m.upsertEntity(G.id,G.value);for(let G of K.relations??[])m.link(G.from,G.to,G.relation,G.weight)}}}});o.push(S.subscribe(()=>{}))}let y=null,f=null,b=null,O=null;if(p||m){let v=r.retrieval?.topK??20,A=r.retrieval?.graphDepth??1,C=r.budget??2e3,S=r.cost,$=r.score,U=r.contextOf,W=r.contextWeight??0,Y=r.context?k(r.context):L(null),K=(T,h)=>{if(!T||!h)return 0;let x=Math.min(T.length,h.length),R=0;for(;R<x&&T[R]===h[R];)R++;return R},G=(T,h,x)=>{let R=new Map,P=[];if(p&&x.vector){P=p.search(x.vector,v);for(let D of P){let B=T.get(D.id);B&&R.set(D.id,{value:B,sources:new Set(["vector"])})}}let E=[];if(m){let D=[...x.entityIds??[],...R.keys()],B=new Set,ge=D;for(let ye=0;ye<A;ye++){let ue=[];for(let xe of ge){if(B.has(xe))continue;B.add(xe);let Ce=m.related(xe);for(let _t of Ce){let he=_t.to;if(!B.has(he)){ue.push(he);let it=T.get(he);if(it){let lt=R.get(he);lt?lt.sources.add("graph"):R.set(he,{value:it,sources:new Set(["graph"])}),E.push(he)}}}}ge=ue}}for(let[D,B]of T)R.has(D)||R.set(D,{value:B,sources:new Set(["store"])});let ne=x.context?.length??0,oe=[];for(let[D,{value:B,sources:ge}]of R){let ye=U?U(B):void 0,ue=$(B,h);if(W>0&&ne>0){let Ce=K(x.context,ye);Ce>0&&(ue=ue*(1+W*Ce/ne))}let xe=ye?{key:D,value:B,score:ue,sources:[...ge],context:ye}:{key:D,value:B,score:ue,sources:[...ge]};oe.push(xe)}oe.sort((D,B)=>B.score-D.score);let j=[],ee=0;for(let D of oe){let B=S(D.value);if(ee+B>C&&j.length>0)break;j.push(D),ee+=B}return{packed:j,trace:{vectorCandidates:P,graphExpanded:E,ranked:oe,packed:j}}},w=L([],{name:"retrieval",describeKind:"state",meta:N("retrieval_pipeline")});n.add(w,{name:"retrieval"}),y=w;let I=L(null,{name:"retrievalTrace",describeKind:"state",meta:N("retrieval_trace")});n.add(I,{name:"retrievalTrace"}),f=I,b=T=>{let h=Ne(c.store.entries.cache),{packed:x,trace:R}=G(h,Y.cache,T);return se(()=>{w.emit(x),I.emit(R)}),x},O=T=>{let h=k(T);return M([c.store.entries,Y,h],([x,R,P])=>{if(P==null)return[];let E=Ne(x);return G(E,R,P).packed},{name:"retrievalReactive",describeKind:"derived",meta:N("retrieval_reactive"),initial:[]})}}return n.addDisposer(()=>{for(let v of o)v();o.length=0}),Object.assign(n,{distillBundle:c,compact:c.compact,size:c.size,vectors:p,kg:m,memoryTiers:g,retrieval:y,retrievalTrace:f,retrieve:b,retrieveReactive:O})}function Fr(t,e,r){let n=t.describe({actor:e,detail:"full"}),o=r?.groupByTags??!0,a=r?.separator??`
|
|
4
|
+
`,s=[],l=r?.sinceVersion;for(let[u,i]of Object.entries(n.nodes)){let d=i.meta??{},c=d.description,p=d.format;if(!c&&!p)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 m=c??u,g=i.value,y=d.unit,f;p==="currency"&&typeof g=="number"?f=`$${g.toFixed(2)}`:p==="percentage"&&typeof g=="number"?f=`${(g*100).toFixed(1)}%`:g==null?f="(no value)":f=String(g),y&&p!=="currency"&&p!=="percentage"&&(f=`${f} ${y}`),s.push({path:u,description:m,formatted:f})}if(s.length===0)return"";if(o){let u=new Map,i=[];for(let c of s){let m=n.nodes[c.path].meta?.tags;if(m&&m.length>0){let g=m[0],y=u.get(g);y||(y=[],u.set(g,y)),y.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,p]of[...u.entries()].sort((m,g)=>m[0].localeCompare(g[0])))d.push(`[${c}]${a}${p.map(m=>`- ${m.description}: ${m.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 Ot=`You are a graph architect for GraphReFly, a reactive graph protocol.
|
|
5
|
+
|
|
6
|
+
Given a natural-language description, produce a JSON graph specification with this structure:
|
|
7
|
+
|
|
8
|
+
{
|
|
9
|
+
"name": "<graph_name>",
|
|
10
|
+
"nodes": {
|
|
11
|
+
"<node_name>": {
|
|
12
|
+
"type": "state" | "derived" | "producer" | "effect" | "operator",
|
|
13
|
+
"initial": <initial_value_for_state_nodes>,
|
|
14
|
+
"deps": ["<dep_node_name>", ...],
|
|
15
|
+
"meta": {
|
|
16
|
+
"description": "<human-readable purpose>",
|
|
17
|
+
"type": "string" | "number" | "boolean" | "integer" | "enum",
|
|
18
|
+
"range": [min, max],
|
|
19
|
+
"values": ["a", "b"],
|
|
20
|
+
"format": "currency" | "percentage" | "status",
|
|
21
|
+
"access": "human" | "llm" | "both" | "system",
|
|
22
|
+
"unit": "<unit>",
|
|
23
|
+
"tags": ["<tag>"]
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
Rules:
|
|
30
|
+
- "state" nodes have no deps and hold user/LLM-writable values (knobs). Use "initial" for the starting value.
|
|
31
|
+
- "derived" nodes have deps and compute from them (pure, no side effects).
|
|
32
|
+
- "effect" nodes have deps but produce side effects (no return value).
|
|
33
|
+
- "producer" nodes have no deps but generate values asynchronously.
|
|
34
|
+
- "operator" nodes are parameterized transformations with deps.
|
|
35
|
+
- Use "deps" inside each node to declare dependencies \u2014 no separate "edges" array.
|
|
36
|
+
- meta.description is required for every node.
|
|
37
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Gr(t,e,r){let o=[{role:"system",content:r?.systemPromptExtra?`${Ot}
|
|
38
|
+
|
|
39
|
+
${r.systemPromptExtra}`:Ot},{role:"user",content:t}],a=e.invoke(o,{model:r?.model,temperature:r?.temperature??0,maxTokens:r?.maxTokens}),l=(await fe(a)).content.trim();l.startsWith("```")&&(l=ke(l));let u;try{u=JSON.parse(l)}catch{throw new Error(`graphFromSpec: LLM response is not valid JSON: ${l.slice(0,200)}`)}return vt(u,{catalog:r?.catalog})}function Br(t){let e={},r=t.type;return r==="enum"&&Array.isArray(t.values)?(e.type="string",e.enum=t.values):r==="integer"?e.type="integer":r==="number"?e.type="number":r==="boolean"?e.type="boolean":r==="string"?e.type="string":e.type=["string","number","boolean"],Array.isArray(t.range)&&t.range.length===2&&(e.minimum=t.range[0],e.maximum=t.range[1]),typeof t.format=="string"&&(e.description=`Format: ${t.format}`),typeof t.unit=="string"&&(e.description?e.description+=` (${t.unit})`:e.description=`Unit: ${t.unit}`),e}function $r(t,e){let r=t.describe({actor:e,detail:"full"}),n=[],o=[],a=[];for(let[s,l]of Object.entries(r.nodes)){if(l.type!=="state"||s.includes("::__meta__::")||l.status==="completed"||l.status==="errored")continue;let u=l.meta??{},i=u.access;if(i==="human"||i==="system")continue;let d=u.description??`Set the value of ${s}`,c=Br(u),p={type:"object",required:["value"],properties:{value:c},additionalProperties:!1},m=s.replace(/::/g,"__");n.push({type:"function",function:{name:m,description:d,parameters:p}}),o.push({name:s,description:d,inputSchema:p});let g=t,y=e,f=l.v;a.push({name:s,description:d,parameters:p,handler(b){return g.set(s,b.value,y?{actor:y}:void 0),b.value},...f!=null?{version:{id:f.id,version:f.version}}:{}})}return{openai:n,mcp:o,definitions:a}}var Wr=`You are a reactive graph optimizer for GraphReFly.
|
|
40
|
+
|
|
41
|
+
Given a graph's current structure (from describe()) and a problem statement, suggest topology and parameter changes to solve the problem.
|
|
42
|
+
|
|
43
|
+
Return ONLY valid JSON with this structure:
|
|
44
|
+
{
|
|
45
|
+
"summary": "<one-line summary of the strategy>",
|
|
46
|
+
"reasoning": "<explanation of why these changes help>",
|
|
47
|
+
"operations": [
|
|
48
|
+
{ "type": "add_node", "name": "<name>", "nodeType": "state|derived|effect|producer|operator", "meta": {...}, "initial": <value> },
|
|
49
|
+
{ "type": "remove_node", "name": "<name>" },
|
|
50
|
+
{ "type": "connect", "from": "<source>", "to": "<target>" },
|
|
51
|
+
{ "type": "disconnect", "from": "<source>", "to": "<target>" },
|
|
52
|
+
{ "type": "set_value", "name": "<name>", "value": <new_value> },
|
|
53
|
+
{ "type": "update_meta", "name": "<name>", "key": "<meta_key>", "value": <new_value> }
|
|
54
|
+
]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
Rules:
|
|
58
|
+
- Only suggest operations that reference existing nodes (for remove/disconnect/set_value/update_meta) or new nodes you define (for add_node).
|
|
59
|
+
- Keep changes minimal \u2014 prefer the smallest set of operations that solves the problem.
|
|
60
|
+
- Return ONLY valid JSON, no markdown fences or commentary.`;async function Ur(t,e,r,n){let{expand:o,...a}=t.describe({actor:n?.actor,detail:"standard"}),s=[{role:"system",content:Wr},{role:"user",content:JSON.stringify({graph:a,problem:e})}],l=r.invoke(s,{model:n?.model,temperature:n?.temperature??0,maxTokens:n?.maxTokens}),i=(await fe(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}}var Pt=new Set(["state","derived","producer","operator","effect"]);function Kr(t){let e=[];if(t==null||typeof t!="object")return{valid:!1,errors:["Definition must be a non-null object"]};let r=t;if((typeof r.name!="string"||r.name.length===0)&&e.push("Missing or empty 'name' field"),r.nodes==null||typeof r.nodes!="object"||Array.isArray(r.nodes))return e.push("Missing or invalid 'nodes' field (must be an object)"),{valid:!1,errors:e};let n=new Set(Object.keys(r.nodes));for(let[o,a]of Object.entries(r.nodes)){if(a==null||typeof a!="object"){e.push(`Node "${o}": must be an object`);continue}let s=a;if((typeof s.type!="string"||!Pt.has(s.type))&&e.push(`Node "${o}": invalid type "${String(s.type)}" (expected: ${[...Pt].join(", ")})`),Array.isArray(s.deps))for(let l of s.deps)typeof l=="string"&&!n.has(l)&&e.push(`Node "${o}": dep "${l}" does not reference an existing node`)}if(!Array.isArray(r.edges))r.edges!==void 0&&e.push("'edges' must be an array");else{let o=new Set;for(let a=0;a<r.edges.length;a++){let s=r.edges[a];if(s==null||typeof s!="object"){e.push(`Edge [${a}]: must be an object`);continue}let l=s;(typeof l.from!="string"||!n.has(l.from))&&e.push(`Edge [${a}]: 'from' "${String(l.from)}" does not reference an existing node`),(typeof l.to!="string"||!n.has(l.to))&&e.push(`Edge [${a}]: 'to' "${String(l.to)}" does not reference an existing node`);let u=`${l.from}->${l.to}`;o.has(u)&&e.push(`Edge [${a}]: duplicate edge ${u}`),o.add(u)}}return{valid:e.length===0,errors:e}}export{qt as a,zt as b,Oe as c,qe as d,Yt as e,Qt as f,Xt as g,Zt as h,ze as i,Pe as j,Ye as k,tr as l,Qe as m,Ze as n,et as o,ve as p,tt as q,ur as r,cr as s,yr as t,br as u,Tr as v,Mr as w,vr as x,xr as y,wr as z,Lr as A,Cr as B,Ar as C,Sr as D,Fe as E,rt as F,Ge as G,nt as H,Be as I,Ir as J,Or as K,Pr as L,Dr as M,ot as N,at as O,st as P,jr as Q,Fr as R,Gr as S,$r as T,Ur as U,Kr as V,Vr as W};
|