@callbag-recharge/callbag-recharge 0.9.0 → 0.11.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.
Files changed (47) hide show
  1. package/dist/adapters/http.cjs +4 -4
  2. package/dist/adapters/http.d.cts +12 -29
  3. package/dist/adapters/http.d.ts +12 -29
  4. package/dist/adapters/http.js +1 -1
  5. package/dist/adapters/index.cjs +12 -12
  6. package/dist/adapters/index.d.cts +5 -4
  7. package/dist/adapters/index.d.ts +5 -4
  8. package/dist/adapters/index.js +1 -1
  9. package/dist/adapters/llm.cjs +5 -5
  10. package/dist/adapters/llm.d.cts +7 -7
  11. package/dist/adapters/llm.d.ts +7 -7
  12. package/dist/adapters/llm.js +1 -1
  13. package/dist/adapters/mcp.cjs +5 -5
  14. package/dist/adapters/mcp.d.cts +3 -3
  15. package/dist/adapters/mcp.d.ts +3 -3
  16. package/dist/adapters/mcp.js +1 -1
  17. package/dist/adapters/webhook.cjs +4 -4
  18. package/dist/adapters/webhook.d.cts +39 -33
  19. package/dist/adapters/webhook.d.ts +39 -33
  20. package/dist/adapters/webhook.js +1 -1
  21. package/dist/adapters/websocket.cjs +4 -4
  22. package/dist/adapters/websocket.d.cts +13 -33
  23. package/dist/adapters/websocket.d.ts +13 -33
  24. package/dist/adapters/websocket.js +1 -1
  25. package/dist/chunk-6M3P6NXX.js +1 -0
  26. package/dist/chunk-CXF5XC6M.js +1 -0
  27. package/dist/chunk-EEKTY7JA.js +1 -0
  28. package/dist/chunk-OHNEQFSD.js +1 -0
  29. package/dist/chunk-OXIEM5ZP.js +2 -0
  30. package/dist/chunk-RX5LWE4X.js +1 -0
  31. package/dist/chunk-W74KQTWL.js +2 -0
  32. package/dist/orchestrate/index.cjs +6 -4
  33. package/dist/orchestrate/index.d.cts +187 -10
  34. package/dist/orchestrate/index.d.ts +187 -10
  35. package/dist/orchestrate/index.js +3 -1
  36. package/dist/utils/index.cjs +4 -4
  37. package/dist/utils/index.d.cts +2 -42
  38. package/dist/utils/index.d.ts +2 -42
  39. package/dist/utils/index.js +1 -1
  40. package/dist/withStatus-BJI4TOZV.d.ts +44 -0
  41. package/dist/withStatus-BQCWdfrH.d.cts +44 -0
  42. package/package.json +1 -1
  43. package/dist/chunk-437ZAXJ7.js +0 -2
  44. package/dist/chunk-6DEMLAB5.js +0 -2
  45. package/dist/chunk-EHKXHATG.js +0 -1
  46. package/dist/chunk-KNWJHTOJ.js +0 -1
  47. package/dist/chunk-TATS3PIH.js +0 -1
@@ -1,4 +1,4 @@
1
- "use strict";var U=Object.defineProperty;var gt=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var ht=Object.prototype.hasOwnProperty;var _t=(t,e)=>{for(var i in e)U(t,i,{get:e[i],enumerable:!0})},Tt=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of pt(e))!ht.call(t,s)&&s!==i&&U(t,s,{get:()=>e[s],enumerable:!(n=gt(e,s))||n.enumerable});return t};var St=t=>Tt(U({},"__esModule",{value:!0}),t);var xt={};_t(xt,{fromHTTP:()=>kt});module.exports=St(xt);var D=Symbol("DIRTY"),F=Symbol("RESOLVED"),Q=Symbol("SINGLE_DEP"),X=0,tt=1,et=2,nt=3,st=4,it=5,k=7,z=7<<k,mt=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function rt(t){return mt[(t&z)>>>k]}var x=0,m=1,h=2,y=3,M=0,j=[],G=!1;function ot(t){M++;try{return t()}finally{if(M--,M===0&&!G){G=!0;for(let e=0;e<j.length;e++)j[e]();j.length=0,G=!1}}}function K(){return M>0}function H(t){j.push(t)}var yt=0,vt=[];function at(t){yt>0?vt.push(t):t()}var $=class t{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(t._explicitEnabled!==null)return t._explicitEnabled;if(t._cachedDefault!==null)return t._cachedDefault;try{t._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{t._cachedDefault=!0}return t._cachedDefault}static set enabled(e){t._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let n=e.map(s=>t._names.get(s)??"?").join(",");return n.length>40?`${n.slice(0,37)}...`:n}static _resolveKey(e){let i=t._keys.get(e)??t._names.get(e);if(i)return i;let n=`anonymous_${t._nextId++}`;return t._keys.set(e,n),n}static register(e,i){if(!t.enabled)return;i?.name&&t._names.set(e,i.name),i?.kind&&t._kinds.set(e,i.kind);let n=t._nextId++,s=i?.name;if(!(s&&!t._usedKeys.has(s)))if(s){let r=t._depSuffix(i?.deps);s=r?`${s}(${r})`:`${s}_${n}`,t._usedKeys.has(s)&&(s=`${s}_${n}`)}else{let r=i?.kind??"store",o=t._depSuffix(i?.deps);s=o?`${r}(${o})`:`${r}_${n}`,t._usedKeys.has(s)&&(s=`${s}_${n}`)}t._usedKeys.add(s),t._keys.set(e,s),t._stores.add(new WeakRef(e))}static registerEdge(e,i){if(!t.enabled)return;let n=t._resolveKey(e),s=t._resolveKey(i),r=t._edges.get(n);r?r.includes(s)||r.push(s):t._edges.set(n,[s])}static getEdges(){return new Map(t._edges)}static getName(e){if(t.enabled)return t._names.get(e)}static getKind(e){return t._kinds.get(e)}static inspect(e){return{name:t._names.get(e),kind:t._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,i=new Set;for(let n of t._stores){let s=n.deref();if(!s){t._stores.delete(n);continue}let r=t._resolveKey(s);i.add(r),e.set(r,t.inspect(s))}for(let[n,s]of t._edges){if(!i.has(n)){t._edges.delete(n),t._usedKeys.delete(n);continue}let r=s.filter(o=>i.has(o));r.length===0?t._edges.delete(n):r.length!==s.length&&t._edges.set(n,r)}return e}static trace(e,i){let n=null,s=e.get();return e.source(x,(r,o)=>{if(r===x&&(n=o),r===h){n=null;return}if(r===1){let a=o;if(!Object.is(a,s)){let u=s;s=a,i(a,u)}}}),()=>n?.(h)}static dumpGraph(){let e=t.graph(),i=t.getEdges(),n=new Map;for(let[o,a]of i)for(let u of a){let f=n.get(u);f?f.includes(o)||f.push(o):n.set(u,[o])}let s=[];for(let[o,a]of e){let u=n.get(o),f=i.get(o),l=u?.length?` \u2190 [${u.join(", ")}]`:"",c=f?.length?` \u2192 [${f.join(", ")}]`:"";s.push(` ${o} (${a.kind}) = ${JSON.stringify(a.value)} [${a.status??"?"}]${l}${c}`)}return[`Store Graph (${e.size} nodes):`,...s].join(`
2
- `)}static _observe(e,i,n){let s=null,r=i??t.getName(e),o={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:r,dispose:()=>s?.(h)};return e.source(x,(a,u)=>{if(a===x){s=u;return}a===m?(o.values.push(u),o.events.push({type:"data",data:u}),n&&n(`[${r}] DATA:`,u)):a===y?(o.signals.push(u),o.events.push({type:"signal",data:u}),u===D?o.dirtyCount++:u===F&&o.resolvedCount++,n&&n(`[${r}] STATE:`,u)):a===h&&(o.ended=!0,o.endError=u,o.events.push({type:"end",data:u}),n&&n(`[${r}] END`,u!==void 0?u:""),s=null)}),o}static observe(e){return t._observe(e)}static tap(e,i){let n=i??`tap(${t.getName(e)??"anon"})`,s={get:()=>e.get(),source:e.source};return t.register(s,{name:n,kind:"tap"}),t.registerEdge(e,s),s}static spy(e,i){let n=i?.name??t.getName(e)??"spy",s=i?.log??console.log;return t._observe(e,n,s)}static snapshot(){let e=t.graph(),i=t.getEdges(),n=new Map;for(let o of t._stores){let a=o.deref();if(!a)continue;let u=t._annotations.get(a);u!==void 0&&n.set(t._resolveKey(a),u)}let s=[];for(let[o,a]of e){let u={name:o,kind:a.kind,value:a.value,status:a.status},f=n.get(o);f!==void 0&&(u.annotation=f),s.push(u)}let r=[];for(let[o,a]of i)for(let u of a)r.push({from:o,to:u});return{nodes:s,edges:r,trace:t.traceLog()}}static toMermaid(e){let i=e?.direction??"TD",n=t.snapshot(),s=[`graph ${i}`],r={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},o=new Map;function a(l){let c=l.replace(/[^a-zA-Z0-9_]/g,"_"),d=o.get(c);return d===void 0?(o.set(c,1),c):(o.set(c,d+1),`${c}__${d}`)}let u=new Map;function f(l){let c=JSON.stringify(l);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let l of n.nodes){let c=a(l.name);u.set(l.name,c);let d=`${l.name} (${l.kind}) = ${f(l.value)}`,p=r[l.status??""]??"";s.push(` ${c}["${d}"]${p}`)}for(let l of n.edges){let c=u.get(l.from)??a(l.from),d=u.get(l.to)??a(l.to);s.push(` ${c} --> ${d}`)}return s.push(""),s.push(" classDef settled fill:#d4edda,stroke:#28a745"),s.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),s.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),s.push(" classDef completed fill:#cce5ff,stroke:#007bff"),s.join(`
3
- `)}static toD2(e){let i=e?.direction??"down",n=t.snapshot(),s=[`direction: ${i}`,""],r={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},o=new Map;function a(l){let c=l.replace(/[^a-zA-Z0-9_]/g,"_"),d=o.get(c);return d===void 0?(o.set(c,1),c):(o.set(c,d+1),`${c}__${d}`)}let u=new Map;function f(l){let c=JSON.stringify(l);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let l of n.nodes){let c=a(l.name);u.set(l.name,c);let d=r[l.kind]??"rectangle",p=`${l.name} (${l.kind}) = ${f(l.value)}`,E=l.status?` [${l.status}]`:"";s.push(`${c}: "${p}${E}" { shape: ${d} }`)}n.edges.length>0&&s.push("");for(let l of n.edges){let c=u.get(l.from)??a(l.from),d=u.get(l.to)??a(l.to);s.push(`${c} -> ${d}`)}return s.join(`
4
- `)}static annotate(e,i){if(!t.enabled)return;t._annotations.set(e,i);let n={node:t._resolveKey(e),reason:i,timestamp:Date.now()},s=t.maxTraceEntries;s<=0||(t._traceLog.length<s?t._traceLog.push(n):(t._traceLog[t._traceHead]=n,t._traceFull=!0),t._traceHead=(t._traceHead+1)%s)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var Y=1,_=64,T=2,I=4,ut=8,lt=16,R=32,v=1024,g=z,P=tt<<k,A=et<<k,V=X<<k,Et=st<<k,bt=it<<k,Dt=nt<<k,L=class{_value;_output=null;_flags;get _status(){return rt(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(e,i){this._value=i?.initial,this._fn=e,this._eqFn=i?.equals,this._getterFn=i?.getter,this._initial=i?.initial;let n=0;i?.autoDirty!==!1&&(n|=I),i?.resetOnTeardown&&(n|=ut),i?.resubscribable&&(n|=lt),this._flags=n,this.source=this.source.bind(this),this.emit=this.emit.bind(this),i?._skipInspect||$.register(this,{kind:"producer",...i})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,i){let n=this._output;if(n)if(this._flags&_)for(let s of n)s(e,i);else n(e,i)}emit(e){this._flags&T||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(K()?this._flags&R||(this._flags|=R,this._flags&I&&(this._flags=this._flags&~g|P,this._dispatch(y,D)),H(()=>{this._flags&=~R,this._flags=this._flags&~g|A,this._dispatch(m,this._value)})):(this._flags&I&&!(this._flags&v)&&(this._flags=this._flags&~g|P,this._dispatch(y,D)),this._flags=this._flags&~g|A,this._dispatch(m,this._value))))}signal(e){this._flags&T||!this._output||(e===D?this._flags=this._flags&~g|P:e===F&&(this._flags=this._flags&~g|Dt),this._dispatch(y,e))}complete(){if(this._flags&T)return;this._flags=(this._flags|T)&~g|Et;let e=this._output,i=this._flags&_;if(this._output=null,this._flags&=~(_|v),this._singleDepCount=0,this._stop(),e)if(i)for(let n of e)n(h);else e(h)}error(e){if(this._flags&T)return;this._flags=(this._flags|T)&~g|bt;let i=this._output,n=this._flags&_;if(this._output=null,this._flags&=~(_|v),this._singleDepCount=0,this._stop(),i)if(n)for(let s of i)s(h,e);else i(h,e)}_start(){if(this._flags&Y||!this._fn)return;this._flags|=Y;let e=this._fn({emit:this.emit,signal:i=>this.signal(i),complete:()=>this.complete(),error:i=>this.error(i)});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&Y&&(this._flags&=~Y,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&ut&&(this._value=this._initial),this._flags&T||(this._flags=this._flags&~g|V))}source(e,i){if(e===x){let n=i;if(this._flags&T)if(this._flags&lt&&this._output===null)this._flags=this._flags&~(T|g)|V;else{n(x,r=>{}),n(h);return}if(this._output===null)this._output=n;else if(this._flags&_)this._output.add(n);else{let r=new Set;r.add(this._output),r.add(n),this._output=r,this._flags=(this._flags|_)&~v}let s=!1;n(x,(r,o)=>{if(r===m&&n(m,this._value),r===y&&o===Q&&!s&&(s=!0,this._singleDepCount++,this._flags&_||(this._flags|=v)),r===h){if(s&&(s=!1,this._singleDepCount--),this._output===null)return;if(this._flags&_){let a=this._output;a.delete(n),a.size===1?(this._output=a.values().next().value,this._flags&=~_,this._singleDepCount>0&&(this._flags|=v)):a.size===0&&(this._output=null,this._flags&=~(_|v),this._singleDepCount=0,this._flags=this._flags&~g|V,this._stop())}else this._output===n&&(this._output=null,this._flags&=~v,this._singleDepCount=0,this._flags=this._flags&~g|V,this._stop())}}),at(()=>this._start())}}};function ct(t,e){return new L(t,e)}var B=class extends L{constructor(e,i){super(void 0,{initial:e,autoDirty:!0,equals:i?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),$.register(this,{kind:"state",...i})}get(){return this._value}set(e){this._flags&T||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(K()?this._flags&R||(this._flags|=R,this._flags&I&&(this._flags=this._flags&~g|P,this._dispatch(y,D)),H(()=>{this._flags&=~R,this._flags=this._flags&~g|A,this._dispatch(m,this._value)})):(this._flags&I&&!(this._flags&v)&&(this._flags=this._flags&~g|P,this._dispatch(y,D)),this._flags=this._flags&~g|A,this._dispatch(m,this._value))))}update(e){this.set(e(this._value))}};function J(t,e){return new B(t,e)}function kt(t,e){let i=e?.name??"http",n=e?.method??"GET",s=e?.headers,r=e?.body,o=e?.poll??0,a=e?.transform??(w=>w.json()),u=e?.timeout??3e4,f=J("idle",{name:`${i}:status`,equals:()=>!1}),l=J(0,{name:`${i}:fetchCount`}),c=null,d=null,p=null,E=null,S=!1;async function W(){if(!S||!c)return;E=new AbortController;let w=[E.signal];e?.signal&&w.push(e.signal);let O=new AbortController;for(let b of w){if(b.aborted){O.abort(b.reason);break}b.addEventListener("abort",()=>O.abort(b.reason),{once:!0})}let C=setTimeout(()=>O.abort(new Error("Request timeout")),u);try{f.set("fetching");let b=r!==void 0?typeof r=="string"?r:JSON.stringify(r):void 0,N=await fetch(t,{method:n,headers:s,body:b,signal:O.signal});if(!S)return;if(!N.ok)throw new Error(`HTTP ${N.status}: ${N.statusText}`);let ft=await a(N);if(!S)return;ot(()=>{l.update(dt=>dt+1),f.set("success"),c?.(ft)})}catch(b){if(!S||b?.name==="AbortError")return;f.set("error"),d?.(b)}finally{clearTimeout(C),E=null}}function Z(){!S||o<=0||(p=setTimeout(()=>{p=null,W().then(()=>{S&&Z()}).catch(()=>{})},o))}let q=null;return{store:ct(({emit:w,error:O})=>(c=w,d=O,S=!0,q=()=>{W()},W().then(()=>{S&&Z()}),()=>{S=!1,c=null,d=null,q=null,E?.abort(),E=null,p!==null&&(clearTimeout(p),p=null);let C=f.get();C!=="error"&&C!=="success"&&f.set("idle")}),{name:i,kind:"http"}),status:f,fetchCount:l,refetch(){q?.()},stop(){S=!1,E?.abort(),E=null,p!==null&&(clearTimeout(p),p=null),f.get()==="fetching"&&f.set("idle")}}}0&&(module.exports={fromHTTP});
1
+ "use strict";var Q=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var Et=Object.prototype.hasOwnProperty;var Dt=(t,e)=>{for(var i in e)Q(t,i,{get:e[i],enumerable:!0})},kt=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of vt(e))!Et.call(t,s)&&s!==i&&Q(t,s,{get:()=>e[s],enumerable:!(n=yt(e,s))||n.enumerable});return t};var xt=t=>kt(Q({},"__esModule",{value:!0}),t);var At={};Dt(At,{fromHTTP:()=>$t});module.exports=xt(At);var k=Symbol("DIRTY"),Y=Symbol("RESOLVED"),st=Symbol("SINGLE_DEP"),it=0,rt=1,ot=2,at=3,ut=4,lt=5,x=7,tt=7<<x,Rt=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function ct(t){return Rt[(t&tt)>>>x]}var _=0,b=1,g=2,y=3,F=0,K=[],X=!1;function P(t){F++;try{return t()}finally{if(F--,F===0&&!X){X=!0;for(let e=0;e<K.length;e++)K[e]();K.length=0,X=!1}}}function V(){return F>0}function q(t){K.push(t)}var H=0,W=[];function ft(){H++}function dt(){if(H--,H===0){for(let t=0;t<W.length;t++)W[t]();W.length=0}}function pt(t){H>0?W.push(t):t()}var O=class t{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(t._explicitEnabled!==null)return t._explicitEnabled;if(t._cachedDefault!==null)return t._cachedDefault;try{t._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{t._cachedDefault=!0}return t._cachedDefault}static set enabled(e){t._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let n=e.map(s=>t._names.get(s)??"?").join(",");return n.length>40?`${n.slice(0,37)}...`:n}static _resolveKey(e){let i=t._keys.get(e)??t._names.get(e);if(i)return i;let n=`anonymous_${t._nextId++}`;return t._keys.set(e,n),n}static register(e,i){if(!t.enabled)return;i?.name&&t._names.set(e,i.name),i?.kind&&t._kinds.set(e,i.kind);let n=t._nextId++,s=i?.name;if(!(s&&!t._usedKeys.has(s)))if(s){let r=t._depSuffix(i?.deps);s=r?`${s}(${r})`:`${s}_${n}`,t._usedKeys.has(s)&&(s=`${s}_${n}`)}else{let r=i?.kind??"store",o=t._depSuffix(i?.deps);s=o?`${r}(${o})`:`${r}_${n}`,t._usedKeys.has(s)&&(s=`${s}_${n}`)}t._usedKeys.add(s),t._keys.set(e,s),t._stores.add(new WeakRef(e))}static registerEdge(e,i){if(!t.enabled)return;let n=t._resolveKey(e),s=t._resolveKey(i),r=t._edges.get(n);r?r.includes(s)||r.push(s):t._edges.set(n,[s])}static getEdges(){return new Map(t._edges)}static getName(e){if(t.enabled)return t._names.get(e)}static getKind(e){return t._kinds.get(e)}static inspect(e){return{name:t._names.get(e),kind:t._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,i=new Set;for(let n of t._stores){let s=n.deref();if(!s){t._stores.delete(n);continue}let r=t._resolveKey(s);i.add(r),e.set(r,t.inspect(s))}for(let[n,s]of t._edges){if(!i.has(n)){t._edges.delete(n),t._usedKeys.delete(n);continue}let r=s.filter(o=>i.has(o));r.length===0?t._edges.delete(n):r.length!==s.length&&t._edges.set(n,r)}return e}static trace(e,i){let n=null,s=e.get();return e.source(_,(r,o)=>{if(r===_&&(n=o),r===g){n=null;return}if(r===1){let u=o;if(!Object.is(u,s)){let l=s;s=u,i(u,l)}}}),()=>n?.(g)}static dumpGraph(){let e=t.graph(),i=t.getEdges(),n=new Map;for(let[o,u]of i)for(let l of u){let d=n.get(l);d?d.includes(o)||d.push(o):n.set(l,[o])}let s=[];for(let[o,u]of e){let l=n.get(o),d=i.get(o),a=l?.length?` \u2190 [${l.join(", ")}]`:"",c=d?.length?` \u2192 [${d.join(", ")}]`:"";s.push(` ${o} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${a}${c}`)}return[`Store Graph (${e.size} nodes):`,...s].join(`
2
+ `)}static _observe(e,i,n){let s=null,r=i??t.getName(e),o={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:r,dispose:()=>s?.(g)};return e.source(_,(u,l)=>{if(u===_){s=l;return}u===b?(o.values.push(l),o.events.push({type:"data",data:l}),n&&n(`[${r}] DATA:`,l)):u===y?(o.signals.push(l),o.events.push({type:"signal",data:l}),l===k?o.dirtyCount++:l===Y&&o.resolvedCount++,n&&n(`[${r}] STATE:`,l)):u===g&&(o.ended=!0,o.endError=l,o.events.push({type:"end",data:l}),n&&n(`[${r}] END`,l!==void 0?l:""),s=null)}),o}static observe(e){return t._observe(e)}static tap(e,i){let n=i??`tap(${t.getName(e)??"anon"})`,s={get:()=>e.get(),source:e.source};return t.register(s,{name:n,kind:"tap"}),t.registerEdge(e,s),s}static spy(e,i){let n=i?.name??t.getName(e)??"spy",s=i?.log??console.log;return t._observe(e,n,s)}static snapshot(){let e=t.graph(),i=t.getEdges(),n=new Map;for(let o of t._stores){let u=o.deref();if(!u)continue;let l=t._annotations.get(u);l!==void 0&&n.set(t._resolveKey(u),l)}let s=[];for(let[o,u]of e){let l={name:o,kind:u.kind,value:u.value,status:u.status},d=n.get(o);d!==void 0&&(l.annotation=d),s.push(l)}let r=[];for(let[o,u]of i)for(let l of u)r.push({from:o,to:l});return{nodes:s,edges:r,trace:t.traceLog()}}static toMermaid(e){let i=e?.direction??"TD",n=t.snapshot(),s=[`graph ${i}`],r={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},o=new Map;function u(a){let c=a.replace(/[^a-zA-Z0-9_]/g,"_"),f=o.get(c);return f===void 0?(o.set(c,1),c):(o.set(c,f+1),`${c}__${f}`)}let l=new Map;function d(a){let c=JSON.stringify(a);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let a of n.nodes){let c=u(a.name);l.set(a.name,c);let f=`${a.name} (${a.kind}) = ${d(a.value)}`,h=r[a.status??""]??"";s.push(` ${c}["${f}"]${h}`)}for(let a of n.edges){let c=l.get(a.from)??u(a.from),f=l.get(a.to)??u(a.to);s.push(` ${c} --> ${f}`)}return s.push(""),s.push(" classDef settled fill:#d4edda,stroke:#28a745"),s.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),s.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),s.push(" classDef completed fill:#cce5ff,stroke:#007bff"),s.join(`
3
+ `)}static toD2(e){let i=e?.direction??"down",n=t.snapshot(),s=[`direction: ${i}`,""],r={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},o=new Map;function u(a){let c=a.replace(/[^a-zA-Z0-9_]/g,"_"),f=o.get(c);return f===void 0?(o.set(c,1),c):(o.set(c,f+1),`${c}__${f}`)}let l=new Map;function d(a){let c=JSON.stringify(a);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let a of n.nodes){let c=u(a.name);l.set(a.name,c);let f=r[a.kind]??"rectangle",h=`${a.name} (${a.kind}) = ${d(a.value)}`,E=a.status?` [${a.status}]`:"";s.push(`${c}: "${h}${E}" { shape: ${f} }`)}n.edges.length>0&&s.push("");for(let a of n.edges){let c=l.get(a.from)??u(a.from),f=l.get(a.to)??u(a.to);s.push(`${c} -> ${f}`)}return s.join(`
4
+ `)}static annotate(e,i){if(!t.enabled)return;t._annotations.set(e,i);let n={node:t._resolveKey(e),reason:i,timestamp:Date.now()},s=t.maxTraceEntries;s<=0||(t._traceLog.length<s?t._traceLog.push(n):(t._traceLog[t._traceHead]=n,t._traceFull=!0),t._traceHead=(t._traceHead+1)%s)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var U=1,T=64,S=2,$=4,gt=8,ht=16,I=32,v=1024,p=tt,A=rt<<x,L=ot<<x,G=it<<x,wt=ut<<x,Ot=lt<<x,It=at<<x,N=class{_value;_output=null;_flags;get _status(){return ct(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(e,i){this._value=i?.initial,this._fn=e,this._eqFn=i?.equals,this._getterFn=i?.getter,this._initial=i?.initial;let n=0;i?.autoDirty!==!1&&(n|=$),i?.resetOnTeardown&&(n|=gt),i?.resubscribable&&(n|=ht),this._flags=n,this.source=this.source.bind(this),this.emit=this.emit.bind(this),i?._skipInspect||O.register(this,{kind:"producer",...i})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,i){let n=this._output;if(n)if(this._flags&T)for(let s of n)s(e,i);else n(e,i)}emit(e){this._flags&S||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(V()?this._flags&I||(this._flags|=I,this._flags&$&&(this._flags=this._flags&~p|A,this._dispatch(y,k)),q(()=>{this._flags&=~I,this._flags=this._flags&~p|L,this._dispatch(b,this._value)})):(this._flags&$&&!(this._flags&v)&&(this._flags=this._flags&~p|A,this._dispatch(y,k)),this._flags=this._flags&~p|L,this._dispatch(b,this._value))))}signal(e){this._flags&S||!this._output||(e===k?this._flags=this._flags&~p|A:e===Y&&(this._flags=this._flags&~p|It),this._dispatch(y,e))}complete(){if(this._flags&S)return;this._flags=(this._flags|S)&~p|wt;let e=this._output,i=this._flags&T;if(this._output=null,this._flags&=~(T|v),this._singleDepCount=0,this._stop(),e)if(i)for(let n of e)n(g);else e(g)}error(e){if(this._flags&S)return;this._flags=(this._flags|S)&~p|Ot;let i=this._output,n=this._flags&T;if(this._output=null,this._flags&=~(T|v),this._singleDepCount=0,this._stop(),i)if(n)for(let s of i)s(g,e);else i(g,e)}_start(){if(this._flags&U||!this._fn)return;this._flags|=U;let e=this._fn({emit:this.emit,signal:i=>this.signal(i),complete:()=>this.complete(),error:i=>this.error(i)});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&U&&(this._flags&=~U,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&gt&&(this._value=this._initial),this._flags&S||(this._flags=this._flags&~p|G))}source(e,i){if(e===_){let n=i;if(this._flags&S)if(this._flags&ht&&this._output===null)this._flags=this._flags&~(S|p)|G;else{n(_,r=>{}),n(g);return}if(this._output===null)this._output=n;else if(this._flags&T)this._output.add(n);else{let r=new Set;r.add(this._output),r.add(n),this._output=r,this._flags=(this._flags|T)&~v}let s=!1;n(_,(r,o)=>{if(r===b&&n(b,this._value),r===y&&o===st&&!s&&(s=!0,this._singleDepCount++,this._flags&T||(this._flags|=v)),r===g){if(s&&(s=!1,this._singleDepCount--),this._output===null)return;if(this._flags&T){let u=this._output;u.delete(n),u.size===1?(this._output=u.values().next().value,this._flags&=~T,this._singleDepCount>0&&(this._flags|=v)):u.size===0&&(this._output=null,this._flags&=~(T|v),this._singleDepCount=0,this._flags=this._flags&~p|G,this._stop())}else this._output===n&&(this._output=null,this._flags&=~v,this._singleDepCount=0,this._flags=this._flags&~p|G,this._stop())}}),pt(()=>this._start())}}};function z(t,e){return new N(t,e)}var et=class extends N{constructor(e,i){super(void 0,{initial:e,autoDirty:!0,equals:i?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),O.register(this,{kind:"state",...i})}get(){return this._value}set(e){this._flags&S||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(V()?this._flags&I||(this._flags|=I,this._flags&$&&(this._flags=this._flags&~p|A,this._dispatch(y,k)),q(()=>{this._flags&=~I,this._flags=this._flags&~p|L,this._dispatch(b,this._value)})):(this._flags&$&&!(this._flags&v)&&(this._flags=this._flags&~p|A,this._dispatch(y,k)),this._flags=this._flags&~p|L,this._dispatch(b,this._value))))}update(e){this.set(e(this._value))}};function C(t,e){return new et(t,e)}function _t(t,e,i){let n=null;ft(),t.source(_,(r,o)=>{if(r===_&&(n=o),r===g){n=null,i?.onEnd?.(o);return}if(r===1){let u=o,l=s;s=u,e(u,l)}});let s;try{s=t.get()}catch{}return dt(),()=>n?.(g)}function Tt(t,e){let i=e?.initialStatus??"pending",n=C(i,{name:"withStatus:status",equals:Object.is}),s=C(void 0,{name:"withStatus:error",equals:Object.is}),r=z(({emit:o,complete:u,error:l})=>{n.set(i),s.set(void 0);let d=_t(t,a=>{n.get()==="errored"?P(()=>{s.set(void 0),n.set("active")}):n.set("active"),o(a)},{onEnd:a=>{if(a!==void 0){let c=a instanceof Error?a:new Error(String(a));P(()=>{s.set(c),n.set("errored")}),l(a)}else n.set("completed"),u()}});return()=>{d()}},{initial:t.get(),resubscribable:!0});return O.register(r,{kind:"withStatus"}),{get:()=>t.get(),source:(o,u)=>r.source(o,u),status:n,error:s}}function $t(t,e){let i=e?.name??"http",n=e?.method??"GET",s=e?.headers,r=e?.body,o=e?.poll??0,u=e?.transform??(R=>R.json()),l=e?.timeout??3e4,d=C(0,{name:`${i}:fetchCount`}),a=null,c=null,f=null,h=null,E=null,m=!1;async function B(){if(!m||!a)return;E=new AbortController;let R=[E.signal];e?.signal&&R.push(e.signal);let w=new AbortController;for(let D of R){if(D.aborted){w.abort(D.reason);break}D.addEventListener("abort",()=>w.abort(D.reason),{once:!0})}let Z=setTimeout(()=>w.abort(new Error("Request timeout")),l);try{let D=r!==void 0?typeof r=="string"?r:JSON.stringify(r):void 0,j=await fetch(t,{method:n,headers:s,body:D,signal:w.signal});if(!m)return;if(!j.ok)throw new Error(`HTTP ${j.status}: ${j.statusText}`);let mt=await u(j);if(!m)return;P(()=>{d.update(bt=>bt+1),a?.(mt)})}catch(D){if(!m||D?.name==="AbortError")return;c?.(D)}finally{clearTimeout(Z),E=null}}function nt(){!m||o<=0||(h=setTimeout(()=>{h=null,B().then(()=>{m&&nt()}).catch(()=>{})},o))}let J=null,St=z(({emit:R,error:w,complete:Z})=>(a=R,c=w,f=Z,m=!0,J=()=>{B()},B().then(()=>{m&&nt()}),()=>{m=!1,a=null,c=null,f=null,J=null,E?.abort(),E=null,h!==null&&(clearTimeout(h),h=null)}),{name:i,kind:"http"}),M=Tt(St);return{get:()=>M.get(),source:(R,w)=>M.source(R,w),status:M.status,error:M.error,fetchCount:d,refetch(){J?.()},stop(){m=!1,E?.abort(),E=null,h!==null&&(clearTimeout(h),h=null),f?.()}}}0&&(module.exports={fromHTTP});
@@ -1,7 +1,7 @@
1
1
  import { S as Store } from '../types-BwU0Zcuz.cjs';
2
+ import { W as WithStatusStatus } from '../withStatus-BQCWdfrH.cjs';
2
3
  import '../protocol-BVxRx57r.cjs';
3
4
 
4
- type HTTPStatus = "idle" | "fetching" | "success" | "error";
5
5
  interface FromHTTPOptions {
6
6
  /** HTTP method. Default: "GET". */
7
7
  method?: string;
@@ -20,11 +20,11 @@ interface FromHTTPOptions {
20
20
  /** Timeout per request in ms. Default: 30000. */
21
21
  timeout?: number;
22
22
  }
23
- interface HTTPStore<T = unknown> {
24
- /** Reactive store emitting fetched values. */
25
- store: Store<T | undefined>;
26
- /** Fetch status store. */
27
- status: Store<HTTPStatus>;
23
+ interface HTTPStore<T = unknown> extends Store<T | undefined> {
24
+ /** Lifecycle status: pending active → completed/errored. */
25
+ status: Store<WithStatusStatus>;
26
+ /** Last error, if any. */
27
+ error: Store<Error | undefined>;
28
28
  /** Number of completed fetches. */
29
29
  fetchCount: Store<number>;
30
30
  /** Manually trigger a fetch (useful with polling disabled). */
@@ -38,44 +38,27 @@ interface HTTPStore<T = unknown> {
38
38
  * @param url - The URL to fetch.
39
39
  * @param opts - Optional configuration.
40
40
  *
41
- * @returns `HTTPStore<T>` — reactive store with status, fetch count, and manual refetch.
42
- *
43
- * @returnsTable store | Store\<T \| undefined\> | Reactive store emitting fetched values.
44
- * status | Store\<HTTPStatus\> | Fetch status: "idle", "fetching", "success", "error".
45
- * fetchCount | Store\<number\> | Number of completed fetches.
46
- * refetch() | () => void | Manually trigger a fetch.
47
- * stop() | () => void | Stop polling and cancel in-flight request.
41
+ * @returns `HTTPStore<T>` — reactive store with status, error, fetch count, and manual refetch.
48
42
  *
49
43
  * @remarks **Tier 2:** Cycle boundary — each fetch result starts a new reactive update cycle.
50
44
  * @remarks **Polling:** Set `poll` interval for periodic refetch. Omit for one-shot.
51
45
  * @remarks **Transform:** Default extracts JSON. Override with `transform` for text, blob, etc.
52
46
  * @remarks **Timeout:** Default 30s per request. Uses AbortController internally.
47
+ * @remarks **Status:** Uses withStatus() for lifecycle tracking (pending → active → completed/errored).
53
48
  *
54
49
  * @example
55
50
  * ```ts
56
- * import { fromHTTP } from 'callbag-recharge/adapters/http';
51
+ * import { fromHTTP } from 'callbag-recharge/adapters';
57
52
  * import { subscribe } from 'callbag-recharge';
58
53
  *
59
54
  * const api = fromHTTP("https://api.example.com/status", { poll: 5000 });
60
- * subscribe(api.store, data => console.log("status:", data));
61
- * // Fetches immediately, then every 5s
55
+ * subscribe(api, data => console.log("status:", data));
56
+ * subscribe(api.status, s => console.log("lifecycle:", s));
62
57
  * api.stop();
63
58
  * ```
64
59
  *
65
- * @example One-shot POST
66
- * ```ts
67
- * const result = fromHTTP("https://api.example.com/submit", {
68
- * method: "POST",
69
- * headers: { "Content-Type": "application/json" },
70
- * body: { name: "test" },
71
- * });
72
- * subscribe(result.store, v => console.log(v));
73
- * ```
74
- *
75
- * @seeAlso [fromWebhook](./webhook) — HTTP trigger (server-side), [fromWebSocket](./websocket) — WebSocket source
76
- *
77
60
  * @category adapters
78
61
  */
79
62
  declare function fromHTTP<T = unknown>(url: string, opts?: FromHTTPOptions): HTTPStore<T>;
80
63
 
81
- export { type FromHTTPOptions, type HTTPStatus, type HTTPStore, fromHTTP };
64
+ export { type FromHTTPOptions, type HTTPStore, fromHTTP };
@@ -1,7 +1,7 @@
1
1
  import { S as Store } from '../types-DGII6w5S.js';
2
+ import { W as WithStatusStatus } from '../withStatus-BJI4TOZV.js';
2
3
  import '../protocol-BVxRx57r.js';
3
4
 
4
- type HTTPStatus = "idle" | "fetching" | "success" | "error";
5
5
  interface FromHTTPOptions {
6
6
  /** HTTP method. Default: "GET". */
7
7
  method?: string;
@@ -20,11 +20,11 @@ interface FromHTTPOptions {
20
20
  /** Timeout per request in ms. Default: 30000. */
21
21
  timeout?: number;
22
22
  }
23
- interface HTTPStore<T = unknown> {
24
- /** Reactive store emitting fetched values. */
25
- store: Store<T | undefined>;
26
- /** Fetch status store. */
27
- status: Store<HTTPStatus>;
23
+ interface HTTPStore<T = unknown> extends Store<T | undefined> {
24
+ /** Lifecycle status: pending active → completed/errored. */
25
+ status: Store<WithStatusStatus>;
26
+ /** Last error, if any. */
27
+ error: Store<Error | undefined>;
28
28
  /** Number of completed fetches. */
29
29
  fetchCount: Store<number>;
30
30
  /** Manually trigger a fetch (useful with polling disabled). */
@@ -38,44 +38,27 @@ interface HTTPStore<T = unknown> {
38
38
  * @param url - The URL to fetch.
39
39
  * @param opts - Optional configuration.
40
40
  *
41
- * @returns `HTTPStore<T>` — reactive store with status, fetch count, and manual refetch.
42
- *
43
- * @returnsTable store | Store\<T \| undefined\> | Reactive store emitting fetched values.
44
- * status | Store\<HTTPStatus\> | Fetch status: "idle", "fetching", "success", "error".
45
- * fetchCount | Store\<number\> | Number of completed fetches.
46
- * refetch() | () => void | Manually trigger a fetch.
47
- * stop() | () => void | Stop polling and cancel in-flight request.
41
+ * @returns `HTTPStore<T>` — reactive store with status, error, fetch count, and manual refetch.
48
42
  *
49
43
  * @remarks **Tier 2:** Cycle boundary — each fetch result starts a new reactive update cycle.
50
44
  * @remarks **Polling:** Set `poll` interval for periodic refetch. Omit for one-shot.
51
45
  * @remarks **Transform:** Default extracts JSON. Override with `transform` for text, blob, etc.
52
46
  * @remarks **Timeout:** Default 30s per request. Uses AbortController internally.
47
+ * @remarks **Status:** Uses withStatus() for lifecycle tracking (pending → active → completed/errored).
53
48
  *
54
49
  * @example
55
50
  * ```ts
56
- * import { fromHTTP } from 'callbag-recharge/adapters/http';
51
+ * import { fromHTTP } from 'callbag-recharge/adapters';
57
52
  * import { subscribe } from 'callbag-recharge';
58
53
  *
59
54
  * const api = fromHTTP("https://api.example.com/status", { poll: 5000 });
60
- * subscribe(api.store, data => console.log("status:", data));
61
- * // Fetches immediately, then every 5s
55
+ * subscribe(api, data => console.log("status:", data));
56
+ * subscribe(api.status, s => console.log("lifecycle:", s));
62
57
  * api.stop();
63
58
  * ```
64
59
  *
65
- * @example One-shot POST
66
- * ```ts
67
- * const result = fromHTTP("https://api.example.com/submit", {
68
- * method: "POST",
69
- * headers: { "Content-Type": "application/json" },
70
- * body: { name: "test" },
71
- * });
72
- * subscribe(result.store, v => console.log(v));
73
- * ```
74
- *
75
- * @seeAlso [fromWebhook](./webhook) — HTTP trigger (server-side), [fromWebSocket](./websocket) — WebSocket source
76
- *
77
60
  * @category adapters
78
61
  */
79
62
  declare function fromHTTP<T = unknown>(url: string, opts?: FromHTTPOptions): HTTPStore<T>;
80
63
 
81
- export { type FromHTTPOptions, type HTTPStatus, type HTTPStore, fromHTTP };
64
+ export { type FromHTTPOptions, type HTTPStore, fromHTTP };
@@ -1 +1 @@
1
- import{a}from"../chunk-EHKXHATG.js";import"../chunk-P5MXN4AF.js";import"../chunk-YN4VWXAF.js";import"../chunk-M76W372U.js";import"../chunk-CWP55MPE.js";import"../chunk-I7AUKTXE.js";export{a as fromHTTP};
1
+ import{a}from"../chunk-EEKTY7JA.js";import"../chunk-RX5LWE4X.js";import"../chunk-YJXCVG35.js";import"../chunk-P5MXN4AF.js";import"../chunk-YN4VWXAF.js";import"../chunk-M76W372U.js";import"../chunk-CWP55MPE.js";import"../chunk-I7AUKTXE.js";export{a as fromHTTP};
@@ -1,16 +1,16 @@
1
- "use strict";var Ae=Object.create;var V=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var $e=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Ne=(e,t)=>{for(var n in t)V(e,n,{get:t[n],enumerable:!0})},fe=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Oe(t))!Ie.call(e,o)&&o!==n&&V(e,o,{get:()=>t[o],enumerable:!(r=Me(t,o))||r.enumerable});return e};var We=(e,t,n)=>(n=e!=null?Ae($e(e)):{},fe(t||!e||!e.__esModule?V(n,"default",{value:e,enumerable:!0}):n,e)),je=e=>fe(V({},"__esModule",{value:!0}),e);var Qe={};Ne(Qe,{fromHTTP:()=>we,fromLLM:()=>xe,fromMCP:()=>Pe,fromWebSocket:()=>Ce,fromWebhook:()=>Re,toSSE:()=>De,toWebSocket:()=>Le});module.exports=je(Qe);var I=Symbol("DIRTY"),Z=Symbol("RESOLVED"),de=Symbol("SINGLE_DEP"),pe=0,ge=1,me=2,he=3,Te=4,Se=5,N=7,se=7<<N,He=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function _e(e){return He[(e&se)>>>N]}var D=0,A=1,P=2,M=3,Y=0,G=[],oe=!1;function O(e){Y++;try{return e()}finally{if(Y--,Y===0&&!oe){oe=!0;for(let t=0;t<G.length;t++)G[t]();G.length=0,oe=!1}}}function X(){return Y>0}function ee(e){G.push(e)}var Q=0,J=[];function ye(){Q++}function be(){if(Q--,Q===0){for(let e=0;e<J.length;e++)J[e]();J.length=0}}function ke(e){Q>0?J.push(e):e()}var R=class e{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(e._explicitEnabled!==null)return e._explicitEnabled;if(e._cachedDefault!==null)return e._cachedDefault;try{e._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{e._cachedDefault=!0}return e._cachedDefault}static set enabled(t){e._explicitEnabled=t}static _depSuffix(t){if(!t?.length)return;let r=t.map(o=>e._names.get(o)??"?").join(",");return r.length>40?`${r.slice(0,37)}...`:r}static _resolveKey(t){let n=e._keys.get(t)??e._names.get(t);if(n)return n;let r=`anonymous_${e._nextId++}`;return e._keys.set(t,r),r}static register(t,n){if(!e.enabled)return;n?.name&&e._names.set(t,n.name),n?.kind&&e._kinds.set(t,n.kind);let r=e._nextId++,o=n?.name;if(!(o&&!e._usedKeys.has(o)))if(o){let l=e._depSuffix(n?.deps);o=l?`${o}(${l})`:`${o}_${r}`,e._usedKeys.has(o)&&(o=`${o}_${r}`)}else{let l=n?.kind??"store",i=e._depSuffix(n?.deps);o=i?`${l}(${i})`:`${l}_${r}`,e._usedKeys.has(o)&&(o=`${o}_${r}`)}e._usedKeys.add(o),e._keys.set(t,o),e._stores.add(new WeakRef(t))}static registerEdge(t,n){if(!e.enabled)return;let r=e._resolveKey(t),o=e._resolveKey(n),l=e._edges.get(r);l?l.includes(o)||l.push(o):e._edges.set(r,[o])}static getEdges(){return new Map(e._edges)}static getName(t){if(e.enabled)return e._names.get(t)}static getKind(t){return e._kinds.get(t)}static inspect(t){return{name:e._names.get(t),kind:e._kinds.get(t)??"unknown",value:typeof t.get=="function"?t.get():void 0,status:t._status}}static graph(){let t=new Map,n=new Set;for(let r of e._stores){let o=r.deref();if(!o){e._stores.delete(r);continue}let l=e._resolveKey(o);n.add(l),t.set(l,e.inspect(o))}for(let[r,o]of e._edges){if(!n.has(r)){e._edges.delete(r),e._usedKeys.delete(r);continue}let l=o.filter(i=>n.has(i));l.length===0?e._edges.delete(r):l.length!==o.length&&e._edges.set(r,l)}return t}static trace(t,n){let r=null,o=t.get();return t.source(D,(l,i)=>{if(l===D&&(r=i),l===P){r=null;return}if(l===1){let s=i;if(!Object.is(s,o)){let u=o;o=s,n(s,u)}}}),()=>r?.(P)}static dumpGraph(){let t=e.graph(),n=e.getEdges(),r=new Map;for(let[i,s]of n)for(let u of s){let c=r.get(u);c?c.includes(i)||c.push(i):r.set(u,[i])}let o=[];for(let[i,s]of t){let u=r.get(i),c=n.get(i),a=u?.length?` \u2190 [${u.join(", ")}]`:"",f=c?.length?` \u2192 [${c.join(", ")}]`:"";o.push(` ${i} (${s.kind}) = ${JSON.stringify(s.value)} [${s.status??"?"}]${a}${f}`)}return[`Store Graph (${t.size} nodes):`,...o].join(`
2
- `)}static _observe(t,n,r){let o=null,l=n??e.getName(t),i={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:l,dispose:()=>o?.(P)};return t.source(D,(s,u)=>{if(s===D){o=u;return}s===A?(i.values.push(u),i.events.push({type:"data",data:u}),r&&r(`[${l}] DATA:`,u)):s===M?(i.signals.push(u),i.events.push({type:"signal",data:u}),u===I?i.dirtyCount++:u===Z&&i.resolvedCount++,r&&r(`[${l}] STATE:`,u)):s===P&&(i.ended=!0,i.endError=u,i.events.push({type:"end",data:u}),r&&r(`[${l}] END`,u!==void 0?u:""),o=null)}),i}static observe(t){return e._observe(t)}static tap(t,n){let r=n??`tap(${e.getName(t)??"anon"})`,o={get:()=>t.get(),source:t.source};return e.register(o,{name:r,kind:"tap"}),e.registerEdge(t,o),o}static spy(t,n){let r=n?.name??e.getName(t)??"spy",o=n?.log??console.log;return e._observe(t,r,o)}static snapshot(){let t=e.graph(),n=e.getEdges(),r=new Map;for(let i of e._stores){let s=i.deref();if(!s)continue;let u=e._annotations.get(s);u!==void 0&&r.set(e._resolveKey(s),u)}let o=[];for(let[i,s]of t){let u={name:i,kind:s.kind,value:s.value,status:s.status},c=r.get(i);c!==void 0&&(u.annotation=c),o.push(u)}let l=[];for(let[i,s]of n)for(let u of s)l.push({from:i,to:u});return{nodes:o,edges:l,trace:e.traceLog()}}static toMermaid(t){let n=t?.direction??"TD",r=e.snapshot(),o=[`graph ${n}`],l={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},i=new Map;function s(a){let f=a.replace(/[^a-zA-Z0-9_]/g,"_"),m=i.get(f);return m===void 0?(i.set(f,1),f):(i.set(f,m+1),`${f}__${m}`)}let u=new Map;function c(a){let f=JSON.stringify(a);return f&&f.length>30?`${f.slice(0,27)}...`:f??"undefined"}for(let a of r.nodes){let f=s(a.name);u.set(a.name,f);let m=`${a.name} (${a.kind}) = ${c(a.value)}`,p=l[a.status??""]??"";o.push(` ${f}["${m}"]${p}`)}for(let a of r.edges){let f=u.get(a.from)??s(a.from),m=u.get(a.to)??s(a.to);o.push(` ${f} --> ${m}`)}return o.push(""),o.push(" classDef settled fill:#d4edda,stroke:#28a745"),o.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),o.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),o.push(" classDef completed fill:#cce5ff,stroke:#007bff"),o.join(`
3
- `)}static toD2(t){let n=t?.direction??"down",r=e.snapshot(),o=[`direction: ${n}`,""],l={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},i=new Map;function s(a){let f=a.replace(/[^a-zA-Z0-9_]/g,"_"),m=i.get(f);return m===void 0?(i.set(f,1),f):(i.set(f,m+1),`${f}__${m}`)}let u=new Map;function c(a){let f=JSON.stringify(a);return f&&f.length>30?`${f.slice(0,27)}...`:f??"undefined"}for(let a of r.nodes){let f=s(a.name);u.set(a.name,f);let m=l[a.kind]??"rectangle",p=`${a.name} (${a.kind}) = ${c(a.value)}`,h=a.status?` [${a.status}]`:"";o.push(`${f}: "${p}${h}" { shape: ${m} }`)}r.edges.length>0&&o.push("");for(let a of r.edges){let f=u.get(a.from)??s(a.from),m=u.get(a.to)??s(a.to);o.push(`${f} -> ${m}`)}return o.join(`
4
- `)}static annotate(t,n){if(!e.enabled)return;e._annotations.set(t,n);let r={node:e._resolveKey(t),reason:n,timestamp:Date.now()},o=e.maxTraceEntries;o<=0||(e._traceLog.length<o?e._traceLog.push(r):(e._traceLog[e._traceHead]=r,e._traceFull=!0),e._traceHead=(e._traceHead+1)%o)}static getAnnotation(t){return e._annotations.get(t)}static traceLog(){return e._traceFull?[...e._traceLog.slice(e._traceHead),...e._traceLog.slice(0,e._traceHead)]:e._traceLog.slice(0,e._traceHead||e._traceLog.length)}static clearTrace(){e._traceLog=[],e._traceHead=0,e._traceFull=!1}static _reset(){e._names=new WeakMap,e._kinds=new WeakMap,e._keys=new WeakMap,e._stores=new Set,e._edges=new Map,e._usedKeys=new Set,e._nextId=0,e._explicitEnabled=null,e._cachedDefault=null,e._annotations=new WeakMap,e._traceLog=[],e._traceHead=0,e._traceFull=!1,e.maxTraceEntries=1e3}};var te=1,C=64,L=2,F=4,ve=8,Ee=16,j=32,$=1024,w=se,B=ge<<N,U=me<<N,ne=pe<<N,Fe=Te<<N,Be=Se<<N,Ke=he<<N,z=class{_value;_output=null;_flags;get _status(){return _e(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(t,n){this._value=n?.initial,this._fn=t,this._eqFn=n?.equals,this._getterFn=n?.getter,this._initial=n?.initial;let r=0;n?.autoDirty!==!1&&(r|=F),n?.resetOnTeardown&&(r|=ve),n?.resubscribable&&(r|=Ee),this._flags=r,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||R.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(t,n){let r=this._output;if(r)if(this._flags&C)for(let o of r)o(t,n);else r(t,n)}emit(t){this._flags&L||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(X()?this._flags&j||(this._flags|=j,this._flags&F&&(this._flags=this._flags&~w|B,this._dispatch(M,I)),ee(()=>{this._flags&=~j,this._flags=this._flags&~w|U,this._dispatch(A,this._value)})):(this._flags&F&&!(this._flags&$)&&(this._flags=this._flags&~w|B,this._dispatch(M,I)),this._flags=this._flags&~w|U,this._dispatch(A,this._value))))}signal(t){this._flags&L||!this._output||(t===I?this._flags=this._flags&~w|B:t===Z&&(this._flags=this._flags&~w|Ke),this._dispatch(M,t))}complete(){if(this._flags&L)return;this._flags=(this._flags|L)&~w|Fe;let t=this._output,n=this._flags&C;if(this._output=null,this._flags&=~(C|$),this._singleDepCount=0,this._stop(),t)if(n)for(let r of t)r(P);else t(P)}error(t){if(this._flags&L)return;this._flags=(this._flags|L)&~w|Be;let n=this._output,r=this._flags&C;if(this._output=null,this._flags&=~(C|$),this._singleDepCount=0,this._stop(),n)if(r)for(let o of n)o(P,t);else n(P,t)}_start(){if(this._flags&te||!this._fn)return;this._flags|=te;let t=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n)});this._cleanup=typeof t=="function"?t:void 0}_stop(){this._flags&te&&(this._flags&=~te,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&ve&&(this._value=this._initial),this._flags&L||(this._flags=this._flags&~w|ne))}source(t,n){if(t===D){let r=n;if(this._flags&L)if(this._flags&Ee&&this._output===null)this._flags=this._flags&~(L|w)|ne;else{r(D,l=>{}),r(P);return}if(this._output===null)this._output=r;else if(this._flags&C)this._output.add(r);else{let l=new Set;l.add(this._output),l.add(r),this._output=l,this._flags=(this._flags|C)&~$}let o=!1;r(D,(l,i)=>{if(l===A&&r(A,this._value),l===M&&i===de&&!o&&(o=!0,this._singleDepCount++,this._flags&C||(this._flags|=$)),l===P){if(o&&(o=!1,this._singleDepCount--),this._output===null)return;if(this._flags&C){let s=this._output;s.delete(r),s.size===1?(this._output=s.values().next().value,this._flags&=~C,this._singleDepCount>0&&(this._flags|=$)):s.size===0&&(this._output=null,this._flags&=~(C|$),this._singleDepCount=0,this._flags=this._flags&~w|ne,this._stop())}else this._output===r&&(this._output=null,this._flags&=~$,this._singleDepCount=0,this._flags=this._flags&~w|ne,this._stop())}}),ke(()=>this._start())}}};function K(e,t){return new z(e,t)}var ie=class extends z{constructor(t,n){super(void 0,{initial:t,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),R.register(this,{kind:"state",...n})}get(){return this._value}set(t){this._flags&L||this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(X()?this._flags&j||(this._flags|=j,this._flags&F&&(this._flags=this._flags&~w|B,this._dispatch(M,I)),ee(()=>{this._flags&=~j,this._flags=this._flags&~w|U,this._dispatch(A,this._value)})):(this._flags&F&&!(this._flags&$)&&(this._flags=this._flags&~w|B,this._dispatch(M,I)),this._flags=this._flags&~w|U,this._dispatch(A,this._value))))}update(t){this.set(t(this._value))}};function k(e,t){return new ie(e,t)}function we(e,t){let n=t?.name??"http",r=t?.method??"GET",o=t?.headers,l=t?.body,i=t?.poll??0,s=t?.transform??(_=>_.json()),u=t?.timeout??3e4,c=k("idle",{name:`${n}:status`,equals:()=>!1}),a=k(0,{name:`${n}:fetchCount`}),f=null,m=null,p=null,h=null,g=!1;async function v(){if(!g||!f)return;h=new AbortController;let _=[h.signal];t?.signal&&_.push(t.signal);let y=new AbortController;for(let b of _){if(b.aborted){y.abort(b.reason);break}b.addEventListener("abort",()=>y.abort(b.reason),{once:!0})}let x=setTimeout(()=>y.abort(new Error("Request timeout")),u);try{c.set("fetching");let b=l!==void 0?typeof l=="string"?l:JSON.stringify(l):void 0,E=await fetch(e,{method:r,headers:o,body:b,signal:y.signal});if(!g)return;if(!E.ok)throw new Error(`HTTP ${E.status}: ${E.statusText}`);let H=await s(E);if(!g)return;O(()=>{a.update(W=>W+1),c.set("success"),f?.(H)})}catch(b){if(!g||b?.name==="AbortError")return;c.set("error"),m?.(b)}finally{clearTimeout(x),h=null}}function S(){!g||i<=0||(p=setTimeout(()=>{p=null,v().then(()=>{g&&S()}).catch(()=>{})},i))}let d=null;return{store:K(({emit:_,error:y})=>(f=_,m=y,g=!0,d=()=>{v()},v().then(()=>{g&&S()}),()=>{g=!1,f=null,m=null,d=null,h?.abort(),h=null,p!==null&&(clearTimeout(p),p=null);let x=c.get();x!=="error"&&x!=="success"&&c.set("idle")}),{name:n,kind:"http"}),status:c,fetchCount:a,refetch(){d?.()},stop(){g=!1,h?.abort(),h=null,p!==null&&(clearTimeout(p),p=null),c.get()==="fetching"&&c.set("idle")}}}function Ue(e){switch(e){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function ze(e,t){switch(e){case"openai":case"custom":return`${t}/chat/completions`;case"ollama":return`${t}/api/chat`;default:return`${t}/chat/completions`}}function qe(e,t,n,r){let o={model:t,messages:n,stream:!0};return r?.temperature!==void 0&&(o.temperature=r.temperature),r?.maxTokens!==void 0&&(e==="ollama"?o.options={num_predict:r.maxTokens}:o.max_tokens=r.maxTokens),r?.stop&&(o.stop=r.stop),o}function Ve(e,t){let n={"Content-Type":"application/json"};return t&&(n.Authorization=`Bearer ${t}`),n}function xe(e){let t=e.name??"llm",n=e.provider,r=e.baseURL??Ue(n),o=e.model??"",l=e.fetch??globalThis.fetch,i=k("",{name:`${t}.store`}),s=k({},{name:`${t}.tokens`}),u=k(!1,{name:`${t}.streaming`}),c=k(void 0,{name:`${t}.error`}),a=null;function f(){a&&(a.abort(),a=null),u.set(!1)}function m(h,g){f(),a=new AbortController;let v=g?.signal?Je(a.signal,g.signal):a.signal;O(()=>{i.set(""),s.set({}),c.set(void 0),u.set(!0)});let S=ze(n,r),d=qe(n,o,h,g),T=Ve(n,e.apiKey);p(S,T,d,v).catch(()=>{})}async function p(h,g,v,S){try{let d=await l(h,{method:"POST",headers:g,body:JSON.stringify(v),signal:S});if(!d.ok){let b=await d.text().catch(()=>"");throw new Error(`LLM API error ${d.status}: ${b}`)}let T=d.body?.getReader();if(!T)throw new Error("No response body");let _=new TextDecoder,y="",x="";for(;;){if(S.aborted)return;let{done:b,value:E}=await T.read();if(b)break;x+=_.decode(E,{stream:!0});let H=x.split(`
5
- `);x=H.pop()??"";for(let W of H){if(S.aborted)return;let q=W.trim();if(!q||q.startsWith(":")||!q.startsWith("data: "))continue;let ae=q.slice(6);if(ae!=="[DONE]")try{let le=JSON.parse(ae),ce=Ye(n,le);ce&&(y+=ce,i.set(y));let ue=Ge(n,le);ue&&s.set(ue)}catch{}}}if(_.decode(),S.aborted)return;u.set(!1),a=null}catch(d){if(S.aborted)return;O(()=>{c.set(d),u.set(!1)}),a=null}}return{store:i,tokens:s,streaming:u,error:c,generate:m,abort:f}}function Ye(e,t){return e==="ollama"?t?.message?.content:t?.choices?.[0]?.delta?.content}function Ge(e,t){let n=e==="ollama"?t:t?.usage;if(n){if(e==="ollama")return t.eval_count!==void 0||t.prompt_eval_count!==void 0?{promptTokens:t.prompt_eval_count,completionTokens:t.eval_count,totalTokens:(t.prompt_eval_count??0)+(t.eval_count??0)}:void 0;if(n.prompt_tokens!==void 0||n.completion_tokens!==void 0)return{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}}}function Je(e,t){let n=new AbortController,r=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o)},o=()=>{n.abort(),r()};return e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",o,{once:!0}),n._cleanup=r,n.signal}function Pe(e){let t=e.name??"mcp",n=e.client,r=k([],{name:`${t}.tools`}),o=k([],{name:`${t}.resources`}),l=k(void 0,{name:`${t}.refreshError`});function i(c){l.set(c);let a=e.onRefreshError;if(a==="warn")console.warn(`[${t}] refresh error:`,c);else{if(a==="error")throw c;typeof a=="function"&&a(c)}}async function s(){if(l.set(void 0),n.listTools)try{let c=await n.listTools();r.set(c.tools)}catch(c){i(c)}if(n.listResources)try{let c=await n.listResources();o.set(c.resources)}catch(c){i(c)}}function u(c){let a=`${t}:${c}`,f=k(void 0,{name:`${a}.result`}),m=k("idle",{name:`${a}.status`}),p=k(void 0,{name:`${a}.error`}),h=k(void 0,{name:`${a}.lastArgs`}),g=k(void 0,{name:`${a}.duration`}),v=!1;async function S(d){if(v)return;v=!0,O(()=>{h.set(d),p.set(void 0),m.set("calling")});let T=Date.now();try{let _=await n.callTool({name:c,arguments:d}),y=Date.now()-T;if(_.isError){let E=_.content.filter(W=>W.type==="text").map(W=>W.text??"").join(`
6
- `),H=new Error(E||"MCP tool returned error");O(()=>{g.set(y),p.set(H),m.set("errored")});return}let x=_.content.filter(E=>E.type==="text"),b;if(x.length===1){let E=x[0].text;if(E!==void 0)try{b=JSON.parse(E)}catch{b=E}}else x.length>1?b=x.map(E=>E.text??""):b=_.content;O(()=>{g.set(y),f.set(b),m.set("completed")})}catch(_){let y=Date.now()-T;O(()=>{g.set(y),p.set(_),m.set("errored")})}finally{v=!1}}return{store:f,status:m,error:p,call:S,lastArgs:h,duration:g}}return{tool:u,tools:r,resources:o,refresh:s,refreshError:l}}function re(e,t,n){let r=null;ye(),e.source(D,(l,i)=>{if(l===D&&(r=i),l===P){r=null,n?.onEnd?.(i);return}if(l===1){let s=i,u=o;o=s,t(s,u)}});let o;try{o=e.get()}catch{}return be(),()=>r?.(P)}function De(e,t){let n=t?.path??"/",r=t?.name??"sse",o=t?.hostname??"0.0.0.0",l=t?.serialize??JSON.stringify,i=t?.eventName??"message",s=t?.pingInterval??3e4,u=k(0,{name:`${r}:connections`}),c=new Set,a=new Map,f=null;function m(){f||(f=re(e,d=>{let T=l(d),_=`event: ${i}
7
- data: ${T}
1
+ "use strict";var Ae=Object.create;var Z=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var We=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty;var Ne=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},de=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of $e(t))!Ie.call(e,o)&&o!==n&&Z(e,o,{get:()=>t[o],enumerable:!(r=Me(t,o))||r.enumerable});return e};var je=(e,t,n)=>(n=e!=null?Ae(We(e)):{},de(t||!e||!e.__esModule?Z(n,"default",{value:e,enumerable:!0}):n,e)),He=e=>de(Z({},"__esModule",{value:!0}),e);var Ze={};Ne(Ze,{fromHTTP:()=>xe,fromLLM:()=>Re,fromMCP:()=>De,fromWebSocket:()=>Oe,fromWebhook:()=>Pe,toSSE:()=>Ce,toWebSocket:()=>Le});module.exports=He(Ze);var j=Symbol("DIRTY"),re=Symbol("RESOLVED"),pe=Symbol("SINGLE_DEP"),ge=0,me=1,he=2,Se=3,Te=4,be=5,H=7,ce=7<<H,Fe=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function ye(e){return Fe[(e&ce)>>>H]}var L=0,W=1,D=2,I=3,X=0,ee=[],ue=!1;function O(e){X++;try{return e()}finally{if(X--,X===0&&!ue){ue=!0;for(let t=0;t<ee.length;t++)ee[t]();ee.length=0,ue=!1}}}function oe(){return X>0}function se(e){ee.push(e)}var ne=0,te=[];function _e(){ne++}function ke(){if(ne--,ne===0){for(let e=0;e<te.length;e++)te[e]();te.length=0}}function ve(e){ne>0?te.push(e):e()}var C=class e{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(e._explicitEnabled!==null)return e._explicitEnabled;if(e._cachedDefault!==null)return e._cachedDefault;try{e._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{e._cachedDefault=!0}return e._cachedDefault}static set enabled(t){e._explicitEnabled=t}static _depSuffix(t){if(!t?.length)return;let r=t.map(o=>e._names.get(o)??"?").join(",");return r.length>40?`${r.slice(0,37)}...`:r}static _resolveKey(t){let n=e._keys.get(t)??e._names.get(t);if(n)return n;let r=`anonymous_${e._nextId++}`;return e._keys.set(t,r),r}static register(t,n){if(!e.enabled)return;n?.name&&e._names.set(t,n.name),n?.kind&&e._kinds.set(t,n.kind);let r=e._nextId++,o=n?.name;if(!(o&&!e._usedKeys.has(o)))if(o){let u=e._depSuffix(n?.deps);o=u?`${o}(${u})`:`${o}_${r}`,e._usedKeys.has(o)&&(o=`${o}_${r}`)}else{let u=n?.kind??"store",a=e._depSuffix(n?.deps);o=a?`${u}(${a})`:`${u}_${r}`,e._usedKeys.has(o)&&(o=`${o}_${r}`)}e._usedKeys.add(o),e._keys.set(t,o),e._stores.add(new WeakRef(t))}static registerEdge(t,n){if(!e.enabled)return;let r=e._resolveKey(t),o=e._resolveKey(n),u=e._edges.get(r);u?u.includes(o)||u.push(o):e._edges.set(r,[o])}static getEdges(){return new Map(e._edges)}static getName(t){if(e.enabled)return e._names.get(t)}static getKind(t){return e._kinds.get(t)}static inspect(t){return{name:e._names.get(t),kind:e._kinds.get(t)??"unknown",value:typeof t.get=="function"?t.get():void 0,status:t._status}}static graph(){let t=new Map,n=new Set;for(let r of e._stores){let o=r.deref();if(!o){e._stores.delete(r);continue}let u=e._resolveKey(o);n.add(u),t.set(u,e.inspect(o))}for(let[r,o]of e._edges){if(!n.has(r)){e._edges.delete(r),e._usedKeys.delete(r);continue}let u=o.filter(a=>n.has(a));u.length===0?e._edges.delete(r):u.length!==o.length&&e._edges.set(r,u)}return t}static trace(t,n){let r=null,o=t.get();return t.source(L,(u,a)=>{if(u===L&&(r=a),u===D){r=null;return}if(u===1){let i=a;if(!Object.is(i,o)){let l=o;o=i,n(i,l)}}}),()=>r?.(D)}static dumpGraph(){let t=e.graph(),n=e.getEdges(),r=new Map;for(let[a,i]of n)for(let l of i){let f=r.get(l);f?f.includes(a)||f.push(a):r.set(l,[a])}let o=[];for(let[a,i]of t){let l=r.get(a),f=n.get(a),s=l?.length?` \u2190 [${l.join(", ")}]`:"",c=f?.length?` \u2192 [${f.join(", ")}]`:"";o.push(` ${a} (${i.kind}) = ${JSON.stringify(i.value)} [${i.status??"?"}]${s}${c}`)}return[`Store Graph (${t.size} nodes):`,...o].join(`
2
+ `)}static _observe(t,n,r){let o=null,u=n??e.getName(t),a={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:u,dispose:()=>o?.(D)};return t.source(L,(i,l)=>{if(i===L){o=l;return}i===W?(a.values.push(l),a.events.push({type:"data",data:l}),r&&r(`[${u}] DATA:`,l)):i===I?(a.signals.push(l),a.events.push({type:"signal",data:l}),l===j?a.dirtyCount++:l===re&&a.resolvedCount++,r&&r(`[${u}] STATE:`,l)):i===D&&(a.ended=!0,a.endError=l,a.events.push({type:"end",data:l}),r&&r(`[${u}] END`,l!==void 0?l:""),o=null)}),a}static observe(t){return e._observe(t)}static tap(t,n){let r=n??`tap(${e.getName(t)??"anon"})`,o={get:()=>t.get(),source:t.source};return e.register(o,{name:r,kind:"tap"}),e.registerEdge(t,o),o}static spy(t,n){let r=n?.name??e.getName(t)??"spy",o=n?.log??console.log;return e._observe(t,r,o)}static snapshot(){let t=e.graph(),n=e.getEdges(),r=new Map;for(let a of e._stores){let i=a.deref();if(!i)continue;let l=e._annotations.get(i);l!==void 0&&r.set(e._resolveKey(i),l)}let o=[];for(let[a,i]of t){let l={name:a,kind:i.kind,value:i.value,status:i.status},f=r.get(a);f!==void 0&&(l.annotation=f),o.push(l)}let u=[];for(let[a,i]of n)for(let l of i)u.push({from:a,to:l});return{nodes:o,edges:u,trace:e.traceLog()}}static toMermaid(t){let n=t?.direction??"TD",r=e.snapshot(),o=[`graph ${n}`],u={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},a=new Map;function i(s){let c=s.replace(/[^a-zA-Z0-9_]/g,"_"),p=a.get(c);return p===void 0?(a.set(c,1),c):(a.set(c,p+1),`${c}__${p}`)}let l=new Map;function f(s){let c=JSON.stringify(s);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let s of r.nodes){let c=i(s.name);l.set(s.name,c);let p=`${s.name} (${s.kind}) = ${f(s.value)}`,y=u[s.status??""]??"";o.push(` ${c}["${p}"]${y}`)}for(let s of r.edges){let c=l.get(s.from)??i(s.from),p=l.get(s.to)??i(s.to);o.push(` ${c} --> ${p}`)}return o.push(""),o.push(" classDef settled fill:#d4edda,stroke:#28a745"),o.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),o.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),o.push(" classDef completed fill:#cce5ff,stroke:#007bff"),o.join(`
3
+ `)}static toD2(t){let n=t?.direction??"down",r=e.snapshot(),o=[`direction: ${n}`,""],u={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},a=new Map;function i(s){let c=s.replace(/[^a-zA-Z0-9_]/g,"_"),p=a.get(c);return p===void 0?(a.set(c,1),c):(a.set(c,p+1),`${c}__${p}`)}let l=new Map;function f(s){let c=JSON.stringify(s);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let s of r.nodes){let c=i(s.name);l.set(s.name,c);let p=u[s.kind]??"rectangle",y=`${s.name} (${s.kind}) = ${f(s.value)}`,_=s.status?` [${s.status}]`:"";o.push(`${c}: "${y}${_}" { shape: ${p} }`)}r.edges.length>0&&o.push("");for(let s of r.edges){let c=l.get(s.from)??i(s.from),p=l.get(s.to)??i(s.to);o.push(`${c} -> ${p}`)}return o.join(`
4
+ `)}static annotate(t,n){if(!e.enabled)return;e._annotations.set(t,n);let r={node:e._resolveKey(t),reason:n,timestamp:Date.now()},o=e.maxTraceEntries;o<=0||(e._traceLog.length<o?e._traceLog.push(r):(e._traceLog[e._traceHead]=r,e._traceFull=!0),e._traceHead=(e._traceHead+1)%o)}static getAnnotation(t){return e._annotations.get(t)}static traceLog(){return e._traceFull?[...e._traceLog.slice(e._traceHead),...e._traceLog.slice(0,e._traceHead)]:e._traceLog.slice(0,e._traceHead||e._traceLog.length)}static clearTrace(){e._traceLog=[],e._traceHead=0,e._traceFull=!1}static _reset(){e._names=new WeakMap,e._kinds=new WeakMap,e._keys=new WeakMap,e._stores=new Set,e._edges=new Map,e._usedKeys=new Set,e._nextId=0,e._explicitEnabled=null,e._cachedDefault=null,e._annotations=new WeakMap,e._traceLog=[],e._traceHead=0,e._traceFull=!1,e.maxTraceEntries=1e3}};var ie=1,M=64,$=2,K=4,we=8,Ee=16,q=32,N=1024,x=ce,U=me<<H,Y=he<<H,ae=ge<<H,qe=Te<<H,Be=be<<H,Ke=Se<<H,G=class{_value;_output=null;_flags;get _status(){return ye(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(t,n){this._value=n?.initial,this._fn=t,this._eqFn=n?.equals,this._getterFn=n?.getter,this._initial=n?.initial;let r=0;n?.autoDirty!==!1&&(r|=K),n?.resetOnTeardown&&(r|=we),n?.resubscribable&&(r|=Ee),this._flags=r,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||C.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(t,n){let r=this._output;if(r)if(this._flags&M)for(let o of r)o(t,n);else r(t,n)}emit(t){this._flags&$||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(oe()?this._flags&q||(this._flags|=q,this._flags&K&&(this._flags=this._flags&~x|U,this._dispatch(I,j)),se(()=>{this._flags&=~q,this._flags=this._flags&~x|Y,this._dispatch(W,this._value)})):(this._flags&K&&!(this._flags&N)&&(this._flags=this._flags&~x|U,this._dispatch(I,j)),this._flags=this._flags&~x|Y,this._dispatch(W,this._value))))}signal(t){this._flags&$||!this._output||(t===j?this._flags=this._flags&~x|U:t===re&&(this._flags=this._flags&~x|Ke),this._dispatch(I,t))}complete(){if(this._flags&$)return;this._flags=(this._flags|$)&~x|qe;let t=this._output,n=this._flags&M;if(this._output=null,this._flags&=~(M|N),this._singleDepCount=0,this._stop(),t)if(n)for(let r of t)r(D);else t(D)}error(t){if(this._flags&$)return;this._flags=(this._flags|$)&~x|Be;let n=this._output,r=this._flags&M;if(this._output=null,this._flags&=~(M|N),this._singleDepCount=0,this._stop(),n)if(r)for(let o of n)o(D,t);else n(D,t)}_start(){if(this._flags&ie||!this._fn)return;this._flags|=ie;let t=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n)});this._cleanup=typeof t=="function"?t:void 0}_stop(){this._flags&ie&&(this._flags&=~ie,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&we&&(this._value=this._initial),this._flags&$||(this._flags=this._flags&~x|ae))}source(t,n){if(t===L){let r=n;if(this._flags&$)if(this._flags&Ee&&this._output===null)this._flags=this._flags&~($|x)|ae;else{r(L,u=>{}),r(D);return}if(this._output===null)this._output=r;else if(this._flags&M)this._output.add(r);else{let u=new Set;u.add(this._output),u.add(r),this._output=u,this._flags=(this._flags|M)&~N}let o=!1;r(L,(u,a)=>{if(u===W&&r(W,this._value),u===I&&a===pe&&!o&&(o=!0,this._singleDepCount++,this._flags&M||(this._flags|=N)),u===D){if(o&&(o=!1,this._singleDepCount--),this._output===null)return;if(this._flags&M){let i=this._output;i.delete(r),i.size===1?(this._output=i.values().next().value,this._flags&=~M,this._singleDepCount>0&&(this._flags|=N)):i.size===0&&(this._output=null,this._flags&=~(M|N),this._singleDepCount=0,this._flags=this._flags&~x|ae,this._stop())}else this._output===r&&(this._output=null,this._flags&=~N,this._singleDepCount=0,this._flags=this._flags&~x|ae,this._stop())}}),ve(()=>this._start())}}};function F(e,t){return new G(e,t)}var le=class extends G{constructor(t,n){super(void 0,{initial:t,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),C.register(this,{kind:"state",...n})}get(){return this._value}set(t){this._flags&$||this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(oe()?this._flags&q||(this._flags|=q,this._flags&K&&(this._flags=this._flags&~x|U,this._dispatch(I,j)),se(()=>{this._flags&=~q,this._flags=this._flags&~x|Y,this._dispatch(W,this._value)})):(this._flags&K&&!(this._flags&N)&&(this._flags=this._flags&~x|U,this._dispatch(I,j)),this._flags=this._flags&~x|Y,this._dispatch(W,this._value))))}update(t){this.set(t(this._value))}};function v(e,t){return new le(e,t)}function z(e,t,n){let r=null;_e(),e.source(L,(u,a)=>{if(u===L&&(r=a),u===D){r=null,n?.onEnd?.(a);return}if(u===1){let i=a,l=o;o=i,t(i,l)}});let o;try{o=e.get()}catch{}return ke(),()=>r?.(D)}function V(e,t){let n=t?.initialStatus??"pending",r=v(n,{name:"withStatus:status",equals:Object.is}),o=v(void 0,{name:"withStatus:error",equals:Object.is}),u=F(({emit:a,complete:i,error:l})=>{r.set(n),o.set(void 0);let f=z(e,s=>{r.get()==="errored"?O(()=>{o.set(void 0),r.set("active")}):r.set("active"),a(s)},{onEnd:s=>{if(s!==void 0){let c=s instanceof Error?s:new Error(String(s));O(()=>{o.set(c),r.set("errored")}),l(s)}else r.set("completed"),i()}});return()=>{f()}},{initial:e.get(),resubscribable:!0});return C.register(u,{kind:"withStatus"}),{get:()=>e.get(),source:(a,i)=>u.source(a,i),status:r,error:o}}function xe(e,t){let n=t?.name??"http",r=t?.method??"GET",o=t?.headers,u=t?.body,a=t?.poll??0,i=t?.transform??(k=>k.json()),l=t?.timeout??3e4,f=v(0,{name:`${n}:fetchCount`}),s=null,c=null,p=null,y=null,_=null,h=!1;async function T(){if(!h||!s)return;_=new AbortController;let k=[_.signal];t?.signal&&k.push(t.signal);let E=new AbortController;for(let b of k){if(b.aborted){E.abort(b.reason);break}b.addEventListener("abort",()=>E.abort(b.reason),{once:!0})}let w=setTimeout(()=>E.abort(new Error("Request timeout")),l);try{let b=u!==void 0?typeof u=="string"?u:JSON.stringify(u):void 0,A=await fetch(e,{method:r,headers:o,body:b,signal:E.signal});if(!h)return;if(!A.ok)throw new Error(`HTTP ${A.status}: ${A.statusText}`);let P=await i(A);if(!h)return;O(()=>{f.update(R=>R+1),s?.(P)})}catch(b){if(!h||b?.name==="AbortError")return;c?.(b)}finally{clearTimeout(w),_=null}}function m(){!h||a<=0||(y=setTimeout(()=>{y=null,T().then(()=>{h&&m()}).catch(()=>{})},a))}let g=null,d=F(({emit:k,error:E,complete:w})=>(s=k,c=E,p=w,h=!0,g=()=>{T()},T().then(()=>{h&&m()}),()=>{h=!1,s=null,c=null,p=null,g=null,_?.abort(),_=null,y!==null&&(clearTimeout(y),y=null)}),{name:n,kind:"http"}),S=V(d);return{get:()=>S.get(),source:(k,E)=>S.source(k,E),status:S.status,error:S.error,fetchCount:f,refetch(){g?.()},stop(){h=!1,_?.abort(),_=null,y!==null&&(clearTimeout(y),y=null),p?.()}}}function Ue(e){switch(e){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function ze(e,t){switch(e){case"openai":case"custom":return`${t}/chat/completions`;case"ollama":return`${t}/api/chat`;default:return`${t}/chat/completions`}}function Ve(e,t,n,r){let o={model:t,messages:n,stream:!0};return r?.temperature!==void 0&&(o.temperature=r.temperature),r?.maxTokens!==void 0&&(e==="ollama"?o.options={num_predict:r.maxTokens}:o.max_tokens=r.maxTokens),r?.stop&&(o.stop=r.stop),o}function Ye(e,t){let n={"Content-Type":"application/json"};return t&&(n.Authorization=`Bearer ${t}`),n}function Re(e){let t=e.name??"llm",n=e.provider,r=e.baseURL??Ue(n),o=e.model??"",u=e.fetch??globalThis.fetch,a=v("",{name:`${t}.store`}),i=v({},{name:`${t}.tokens`}),l=v("pending",{name:`${t}.status`}),f=v(void 0,{name:`${t}.error`}),s=null;function c(){s&&(s.abort(),s=null),l.get()==="active"&&l.set("pending")}function p(_,h){c(),s=new AbortController;let T=h?.signal?Qe(s.signal,h.signal):s.signal;O(()=>{a.set(""),i.set({}),f.set(void 0),l.set("active")});let m=ze(n,r),g=Ve(n,o,_,h),d=Ye(n,e.apiKey);y(m,d,g,T).catch(()=>{})}async function y(_,h,T,m){try{let g=await u(_,{method:"POST",headers:h,body:JSON.stringify(T),signal:m});if(!g.ok){let w=await g.text().catch(()=>"");throw new Error(`LLM API error ${g.status}: ${w}`)}let d=g.body?.getReader();if(!d)throw new Error("No response body");let S=new TextDecoder,k="",E="";for(;;){if(m.aborted)return;let{done:w,value:b}=await d.read();if(w)break;E+=S.decode(b,{stream:!0});let A=E.split(`
5
+ `);E=A.pop()??"";for(let P of A){if(m.aborted)return;let R=P.trim();if(!R||R.startsWith(":")||!R.startsWith("data: "))continue;let J=R.slice(6);if(J!=="[DONE]")try{let B=JSON.parse(J),Q=Ge(n,B);Q&&(k+=Q,a.set(k));let fe=Je(n,B);fe&&i.set(fe)}catch{}}}if(S.decode(),m.aborted)return;l.set("completed"),s=null}catch(g){if(m.aborted)return;O(()=>{f.set(g),l.set("errored")}),s=null}finally{m._cleanup?.()}}return{store:a,tokens:i,status:l,error:f,generate:p,abort:c}}function Ge(e,t){return e==="ollama"?t?.message?.content:t?.choices?.[0]?.delta?.content}function Je(e,t){let n=e==="ollama"?t:t?.usage;if(n){if(e==="ollama")return t.eval_count!==void 0||t.prompt_eval_count!==void 0?{promptTokens:t.prompt_eval_count,completionTokens:t.eval_count,totalTokens:(t.prompt_eval_count??0)+(t.eval_count??0)}:void 0;if(n.prompt_tokens!==void 0||n.completion_tokens!==void 0)return{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}}}function Qe(e,t){let n=new AbortController,r=()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o)},o=()=>{n.abort(),r()};e.addEventListener("abort",o,{once:!0}),t.addEventListener("abort",o,{once:!0});let u=n.signal;return u._cleanup=r,u}function De(e){let t=e.name??"mcp",n=e.client,r=v([],{name:`${t}.tools`}),o=v([],{name:`${t}.resources`}),u=v(void 0,{name:`${t}.refreshError`});function a(f){u.set(f);let s=e.onRefreshError;if(s==="warn")console.warn(`[${t}] refresh error:`,f);else{if(s==="error")throw f;typeof s=="function"&&s(f)}}async function i(){if(u.set(void 0),n.listTools)try{let f=await n.listTools();r.set(f.tools)}catch(f){a(f)}if(n.listResources)try{let f=await n.listResources();o.set(f.resources)}catch(f){a(f)}}function l(f){let s=`${t}:${f}`,c=v(void 0,{name:`${s}.result`}),p=v("idle",{name:`${s}.status`}),y=v(void 0,{name:`${s}.error`}),_=v(void 0,{name:`${s}.lastArgs`}),h=v(void 0,{name:`${s}.duration`}),T=!1;async function m(g){if(T)return;T=!0,O(()=>{_.set(g),y.set(void 0),p.set("active")});let d=Date.now();try{let S=await n.callTool({name:f,arguments:g}),k=Date.now()-d;if(S.isError){let b=S.content.filter(P=>P.type==="text").map(P=>P.text??"").join(`
6
+ `),A=new Error(b||"MCP tool returned error");O(()=>{h.set(k),y.set(A),p.set("errored")});return}let E=S.content.filter(b=>b.type==="text"),w;if(E.length===1){let b=E[0].text;if(b!==void 0)try{w=JSON.parse(b)}catch{w=b}}else E.length>1?w=E.map(b=>b.text??""):w=S.content;O(()=>{h.set(k),c.set(w),p.set("completed")})}catch(S){let k=Date.now()-d;O(()=>{h.set(k),y.set(S),p.set("errored")})}finally{T=!1}}return{store:c,status:p,error:y,call:m,lastArgs:_,duration:h}}return{tool:l,tools:r,resources:o,refresh:i,refreshError:u}}function Ce(e,t){let n=t?.path??"/",r=t?.name??"sse",o=t?.hostname??"0.0.0.0",u=t?.serialize??JSON.stringify,a=t?.eventName??"message",i=t?.pingInterval??3e4,l=v(0,{name:`${r}:connections`}),f=new Set,s=new Map,c=null;function p(){c||(c=z(e,g=>{let d=u(g),S=`event: ${a}
7
+ data: ${d}
8
8
 
9
- `;for(let y of c)try{y.write(_)}catch{p(y)}}))}function p(d){c.delete(d);let T=a.get(d);T&&(clearInterval(T),a.delete(d)),u.set(c.size),c.size===0&&f&&(f(),f=null)}function h(d,T){let _=d.method?.toUpperCase();if((d.url??"/").split("?")[0]!==n){T.writeHead(404,{"Content-Type":"text/plain"}),T.end("Not found");return}if(_==="OPTIONS"){T.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"Cache-Control"}),T.end();return}if(_!=="GET"){T.writeHead(405,{"Content-Type":"text/plain"}),T.end("Method not allowed");return}T.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}),T.write(`:ok
9
+ `;for(let k of f)try{k.write(S)}catch{y(k)}}))}function y(g){f.delete(g);let d=s.get(g);d&&(clearInterval(d),s.delete(g)),l.set(f.size),f.size===0&&c&&(c(),c=null)}function _(g,d){let S=g.method?.toUpperCase();if((g.url??"/").split("?")[0]!==n){d.writeHead(404,{"Content-Type":"text/plain"}),d.end("Not found");return}if(S==="OPTIONS"){d.writeHead(204,{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Access-Control-Allow-Headers":"Cache-Control"}),d.end();return}if(S!=="GET"){d.writeHead(405,{"Content-Type":"text/plain"}),d.end("Method not allowed");return}d.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Access-Control-Allow-Origin":"*"}),d.write(`:ok
10
10
 
11
- `),c.add(T),u.set(c.size);try{let b=e.get();if(b!==void 0){let E=l(b);T.write(`event: ${i}
12
- data: ${E}
11
+ `),f.add(d),l.set(f.size);try{let w=e.get();if(w!==void 0){let b=u(w);d.write(`event: ${a}
12
+ data: ${b}
13
13
 
14
- `)}}catch{}if(s>0){let b=setInterval(()=>{try{T.write(`:ping
14
+ `)}}catch{}if(i>0){let w=setInterval(()=>{try{d.write(`:ping
15
15
 
16
- `)}catch{p(T)}},s);a.set(T,b)}d.on("close",()=>p(T)),m()}let g=null;async function v(){if(!t?.port)throw new Error("toSSE: port is required for listen()");if(g)throw new Error("toSSE: already listening. Call close() first.");let d=await import("http");return new Promise((T,_)=>{g=d.createServer(h),g.once("listening",()=>T()),g.once("error",y=>{g=null,_(y)}),g.listen(t.port,o)})}function S(){for(let d of c)try{d.end()}catch{}c.clear();for(let d of a.values())clearInterval(d);a.clear(),u.set(0),f?.(),f=null,g?.close(),g=null}return R.register(u,{kind:"sse"}),{connectionCount:u,handler:h,listen:v,close:S}}function Re(e){let t=e?.path??"/",n=e?.parse??JSON.parse,r=e?.name??"webhook",o=e?.hostname??"0.0.0.0",l=e?.maxBodySize??1024*1024,i=k(0,{name:`${r}:count`}),s=null,u=K(({emit:p})=>(s=p,()=>{s=null}),{name:r,kind:"webhook"});R.register(u,{kind:"webhook"});let c=null;function a(p,h){let g=p.method?.toUpperCase(),S=(p.url??"/").split("?")[0];if(g!=="POST"||S!==t){h.writeHead(404,{"Content-Type":"application/json"}),h.end(JSON.stringify({error:"Not found"}));return}let d=[],T=0,_=!1;p.on("error",()=>{_=!0,h.headersSent||(h.writeHead(400,{"Content-Type":"application/json"}),h.end(JSON.stringify({error:"Request aborted"})))}),p.on("data",y=>{if(!_){if(T+=y.length,T>l){_=!0,h.writeHead(413,{"Content-Type":"application/json"}),h.end(JSON.stringify({error:"Payload too large"})),p.destroy?.();return}d.push(y)}}),p.on("end",()=>{if(!_)try{let y=Buffer.concat(d).toString("utf-8"),x=y.length>0?n(y):void 0;i.update(b=>b+1),s?.(x),h.writeHead(200,{"Content-Type":"application/json"}),h.end(JSON.stringify({ok:!0}))}catch(y){h.writeHead(400,{"Content-Type":"application/json"}),h.end(JSON.stringify({error:y?.message??"Parse error"}))}})}function f(){return e?.port?c?Promise.reject(new Error("fromWebhook: already listening. Call close() first.")):new Promise((p,h)=>{try{c=require("http").createServer(a),c.once("listening",()=>p()),c.once("error",v=>{c=null,h(v)}),c.listen(e.port,o)}catch(g){h(g)}}):Promise.reject(new Error("fromWebhook: port is required for listen()"))}function m(){c?.close(),c=null}return{store:u,requestCount:i,handler:a,listen:f,close:m}}function Ce(e,t){let n=t?.name??"websocket",r=t?.parse??(S=>S),o=t?.reconnect??!1,l=t?.onParseError??"warn",i=k("connecting",{name:`${n}:status`,equals:()=>!1}),s=null,u=null,c=null,a=null,f=null,m=!1,p=[];function h(){for(;p.length>0&&s?.readyState===WebSocket.OPEN;)s.send(p.shift())}function g(){m=!1,i.set("connecting");try{s=new WebSocket(e,t?.protocols)}catch(S){i.set("closed"),c?.(S);return}s.onopen=()=>{i.set("open"),h()},s.onmessage=S=>{try{let d=r(S.data);u?.(d)}catch(d){l==="error"?c?.(d):l==="warn"&&console.warn(`[${n}] parse error:`,d)}},s.onerror=()=>{},s.onclose=()=>{i.set("closed"),s=null,!m&&o!==!1?f=setTimeout(()=>{f=null,u&&g()},o):a?.()}}let v=K(({emit:S,error:d,complete:T})=>(u=S,c=d,a=T,g(),()=>{u=null,c=null,a=null,m=!0,p.length=0,f!==null&&(clearTimeout(f),f=null),s&&(s.onopen=null,s.onmessage=null,s.onerror=null,s.onclose=null,s.close(),s=null),i.set("closed")}),{name:n,kind:"websocket"});return R.register(v,{kind:"websocket"}),{messages:v,status:i,send(S){s?.readyState===WebSocket.OPEN?s.send(S):p.push(S)},close(S,d){m=!0,p.length=0,f!==null&&(clearTimeout(f),f=null),s?.close(S,d)}}}function Le(e,t,n){let r=i=>typeof i=="string"?i:JSON.stringify(i),o=n?.serialize??r,l="send"in e&&typeof e.send=="function"?e.send.bind(e):null;if(!l)throw new Error("toWebSocket: invalid WebSocket target");return re(t,i=>{try{let s=o(i);l(s)}catch{}})}0&&(module.exports={fromHTTP,fromLLM,fromMCP,fromWebSocket,fromWebhook,toSSE,toWebSocket});
16
+ `)}catch{y(d)}},i);s.set(d,w)}g.on("close",()=>y(d)),p()}let h=null;async function T(){if(!t?.port)throw new Error("toSSE: port is required for listen()");if(h)throw new Error("toSSE: already listening. Call close() first.");let g=await import("http");return new Promise((d,S)=>{h=g.createServer(_),h.once("listening",()=>d()),h.once("error",k=>{h=null,S(k)}),h.listen(t.port,o)})}function m(){for(let g of f)try{g.end()}catch{}f.clear();for(let g of s.values())clearInterval(g);s.clear(),l.set(0),c?.(),c=null,h?.close(),h=null}return C.register(l,{kind:"sse"}),{connectionCount:l,handler:_,listen:T,close:m}}function Pe(e){let t=e?.path??"/",n=e?.parse??JSON.parse,r=e?.name??"webhook",o=e?.hostname??"0.0.0.0",u=e?.maxBodySize??1024*1024,a=e?.responseTimeout??3e4,i=v(0,{name:`${r}:count`}),l=null,f=F(({emit:T})=>(l=T,()=>{l=null}),{name:r,kind:"webhook"});C.register(f,{kind:"webhook"});let s=V(f),c=null,p=new Set;function y(T,m){let g=T.method?.toUpperCase(),S=(T.url??"/").split("?")[0];if(g!=="POST"||S!==t){m.writeHead(404,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:"Not found"}));return}let k=[],E=0,w=!1;T.on("error",()=>{w=!0,m.headersSent||(m.writeHead(400,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:"Request aborted"})))}),T.on("data",b=>{if(!w){if(E+=b.length,E>u){w=!0,m.writeHead(413,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:"Payload too large"})),T.destroy?.();return}k.push(b)}}),T.on("end",()=>{if(!w)try{let b=Buffer.concat(k).toString("utf-8"),A=b.length>0?n(b):void 0;i.update(B=>B+1);let P=!1,R=null,J={body:A,get responded(){return P},respond(B,Q=200){P||(P=!0,R!==null&&(clearTimeout(R),p.delete(R),R=null),m.writeHead(Q,{"Content-Type":"application/json"}),m.end(JSON.stringify(B)))}};R=setTimeout(()=>{p.delete(R),R=null,P||(P=!0,m.writeHead(504,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:"Response timeout"})))},a),p.add(R),l?.(J)}catch(b){m.writeHead(400,{"Content-Type":"application/json"}),m.end(JSON.stringify({error:b?.message??"Parse error"}))}})}function _(){return e?.port?c?Promise.reject(new Error("fromWebhook: already listening. Call close() first.")):new Promise((T,m)=>{try{c=require("http").createServer(y),c.once("listening",()=>T()),c.once("error",d=>{c=null,m(d)}),c.listen(e.port,o)}catch(g){m(g)}}):Promise.reject(new Error("fromWebhook: port is required for listen()"))}function h(){for(let T of p)clearTimeout(T);p.clear(),c?.close(),c=null}return{get:()=>s.get(),source:(T,m)=>s.source(T,m),status:s.status,error:s.error,requestCount:i,handler:y,listen:_,close:h}}function Oe(e,t){let n=t?.name??"websocket",r=t?.parse??(d=>d),o=t?.reconnect??!1,u=t?.onParseError??"warn",a=v("connecting",{name:`${n}:connectionState`,equals:()=>!1}),i=null,l=null,f=null,s=null,c=null,p=!1,y=null,_=[];function h(){for(;_.length>0&&i?.readyState===WebSocket.OPEN;)i.send(_.shift())}function T(){p=!1,a.set("connecting");try{i=new WebSocket(e,t?.protocols)}catch(d){a.set("closed"),f?.(d);return}i.onopen=()=>{a.set("open"),h()},i.onmessage=d=>{try{let S=r(d.data);l?.(S)}catch(S){u==="error"?f?.(S):u==="warn"&&console.warn(`[${n}] parse error:`,S)}},i.onerror=()=>{y=new Error(`WebSocket error on ${e}`)},i.onclose=()=>{a.set("closed"),i=null;let d=y;y=null,!p&&o!==!1?c=setTimeout(()=>{c=null,l&&T()},o):d&&!p?f?.(d):s?.()}}let m=F(({emit:d,error:S,complete:k})=>(l=d,f=S,s=k,T(),()=>{l=null,f=null,s=null,p=!0,_.length=0,c!==null&&(clearTimeout(c),c=null),i&&(i.onopen=null,i.onmessage=null,i.onerror=null,i.onclose=null,i.close(),i=null),a.set("closed")}),{name:n,kind:"websocket"});C.register(m,{kind:"websocket"});let g=V(m);return{get:()=>g.get(),source:(d,S)=>g.source(d,S),status:g.status,error:g.error,connectionState:a,send(d){i?.readyState===WebSocket.OPEN?i.send(d):_.push(d)},close(d,S){p=!0,_.length=0,c!==null&&(clearTimeout(c),c=null),i?.close(d,S)}}}function Le(e,t,n){let r=a=>typeof a=="string"?a:JSON.stringify(a),o=n?.serialize??r,u="send"in e&&typeof e.send=="function"?e.send.bind(e):null;if(!u)throw new Error("toWebSocket: invalid WebSocket target");return z(t,a=>{try{let i=o(a);u(i)}catch{}})}0&&(module.exports={fromHTTP,fromLLM,fromMCP,fromWebSocket,fromWebhook,toSSE,toWebSocket});
@@ -1,8 +1,9 @@
1
- export { FromHTTPOptions, HTTPStatus, HTTPStore, fromHTTP } from './http.cjs';
1
+ export { FromHTTPOptions, HTTPStore, fromHTTP } from './http.cjs';
2
2
  export { GenerateOptions, LLMMessage, LLMOptions, LLMStore, LLMTokenUsage, fromLLM } from './llm.cjs';
3
- export { MCPClientLike, MCPOptions, MCPResource, MCPResult, MCPToolInfo, MCPToolStatus, MCPToolStore, fromMCP } from './mcp.cjs';
3
+ export { MCPClientLike, MCPOptions, MCPResource, MCPResult, MCPToolInfo, MCPToolStore, fromMCP } from './mcp.cjs';
4
4
  export { SSEOptions, SSEStore, toSSE } from './sse.cjs';
5
- export { WebhookOptions, WebhookStore, fromWebhook } from './webhook.cjs';
6
- export { FromWebSocketOptions, ToWebSocketOptions, WebSocketStatus, WebSocketStore, fromWebSocket, toWebSocket } from './websocket.cjs';
5
+ export { WebhookOptions, WebhookRequest, WebhookStore, fromWebhook } from './webhook.cjs';
6
+ export { FromWebSocketOptions, ToWebSocketOptions, WebSocketConnectionState, WebSocketStore, fromWebSocket, toWebSocket } from './websocket.cjs';
7
7
  import '../types-BwU0Zcuz.cjs';
8
8
  import '../protocol-BVxRx57r.cjs';
9
+ import '../withStatus-BQCWdfrH.cjs';
@@ -1,8 +1,9 @@
1
- export { FromHTTPOptions, HTTPStatus, HTTPStore, fromHTTP } from './http.js';
1
+ export { FromHTTPOptions, HTTPStore, fromHTTP } from './http.js';
2
2
  export { GenerateOptions, LLMMessage, LLMOptions, LLMStore, LLMTokenUsage, fromLLM } from './llm.js';
3
- export { MCPClientLike, MCPOptions, MCPResource, MCPResult, MCPToolInfo, MCPToolStatus, MCPToolStore, fromMCP } from './mcp.js';
3
+ export { MCPClientLike, MCPOptions, MCPResource, MCPResult, MCPToolInfo, MCPToolStore, fromMCP } from './mcp.js';
4
4
  export { SSEOptions, SSEStore, toSSE } from './sse.js';
5
- export { WebhookOptions, WebhookStore, fromWebhook } from './webhook.js';
6
- export { FromWebSocketOptions, ToWebSocketOptions, WebSocketStatus, WebSocketStore, fromWebSocket, toWebSocket } from './websocket.js';
5
+ export { WebhookOptions, WebhookRequest, WebhookStore, fromWebhook } from './webhook.js';
6
+ export { FromWebSocketOptions, ToWebSocketOptions, WebSocketConnectionState, WebSocketStore, fromWebSocket, toWebSocket } from './websocket.js';
7
7
  import '../types-DGII6w5S.js';
8
8
  import '../protocol-BVxRx57r.js';
9
+ import '../withStatus-BJI4TOZV.js';
@@ -1 +1 @@
1
- import{a as o}from"../chunk-EHKXHATG.js";import{a as e}from"../chunk-437ZAXJ7.js";import{a as t}from"../chunk-6DEMLAB5.js";import{a as r}from"../chunk-X6RLUCXO.js";import{a as p}from"../chunk-KNWJHTOJ.js";import{a as m,b as S}from"../chunk-TATS3PIH.js";import"../chunk-YJXCVG35.js";import"../chunk-P5MXN4AF.js";import"../chunk-YN4VWXAF.js";import"../chunk-M76W372U.js";import"../chunk-CWP55MPE.js";import"../chunk-I7AUKTXE.js";export{o as fromHTTP,e as fromLLM,t as fromMCP,m as fromWebSocket,p as fromWebhook,r as toSSE,S as toWebSocket};
1
+ import{a as o}from"../chunk-EEKTY7JA.js";import{a as e}from"../chunk-OXIEM5ZP.js";import{a as t}from"../chunk-W74KQTWL.js";import{a as r}from"../chunk-X6RLUCXO.js";import{a as p}from"../chunk-6M3P6NXX.js";import{a as m,b as S}from"../chunk-OHNEQFSD.js";import"../chunk-RX5LWE4X.js";import"../chunk-YJXCVG35.js";import"../chunk-P5MXN4AF.js";import"../chunk-YN4VWXAF.js";import"../chunk-M76W372U.js";import"../chunk-CWP55MPE.js";import"../chunk-I7AUKTXE.js";export{o as fromHTTP,e as fromLLM,t as fromMCP,m as fromWebSocket,p as fromWebhook,r as toSSE,S as toWebSocket};
@@ -1,5 +1,5 @@
1
- "use strict";var q=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var vt=Object.prototype.hasOwnProperty;var bt=(t,e)=>{for(var n in e)q(t,n,{get:e[n],enumerable:!0})},yt=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of St(e))!vt.call(t,i)&&i!==n&&q(t,i,{get:()=>e[i],enumerable:!(s=mt(e,i))||s.enumerable});return t};var Et=t=>yt(q({},"__esModule",{value:!0}),t);var jt={};bt(jt,{fromLLM:()=>At});module.exports=Et(jt);var v=Symbol("DIRTY"),j=Symbol("RESOLVED"),rt=Symbol("SINGLE_DEP"),ot=0,at=1,ct=2,ut=3,lt=4,dt=5,b=7,B=7<<b,kt=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function ft(t){return kt[(t&B)>>>b]}var y=0,T=1,p=2,m=3,N=0,C=[],z=!1;function J(t){N++;try{return t()}finally{if(N--,N===0&&!z){z=!0;for(let e=0;e<C.length;e++)C[e]();C.length=0,z=!1}}}function K(){return N>0}function F(t){C.push(t)}var Dt=0,xt=[];function gt(t){Dt>0?xt.push(t):t()}var x=class t{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(t._explicitEnabled!==null)return t._explicitEnabled;if(t._cachedDefault!==null)return t._cachedDefault;try{t._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{t._cachedDefault=!0}return t._cachedDefault}static set enabled(e){t._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let s=e.map(i=>t._names.get(i)??"?").join(",");return s.length>40?`${s.slice(0,37)}...`:s}static _resolveKey(e){let n=t._keys.get(e)??t._names.get(e);if(n)return n;let s=`anonymous_${t._nextId++}`;return t._keys.set(e,s),s}static register(e,n){if(!t.enabled)return;n?.name&&t._names.set(e,n.name),n?.kind&&t._kinds.set(e,n.kind);let s=t._nextId++,i=n?.name;if(!(i&&!t._usedKeys.has(i)))if(i){let o=t._depSuffix(n?.deps);i=o?`${i}(${o})`:`${i}_${s}`,t._usedKeys.has(i)&&(i=`${i}_${s}`)}else{let o=n?.kind??"store",r=t._depSuffix(n?.deps);i=r?`${o}(${r})`:`${o}_${s}`,t._usedKeys.has(i)&&(i=`${i}_${s}`)}t._usedKeys.add(i),t._keys.set(e,i),t._stores.add(new WeakRef(e))}static registerEdge(e,n){if(!t.enabled)return;let s=t._resolveKey(e),i=t._resolveKey(n),o=t._edges.get(s);o?o.includes(i)||o.push(i):t._edges.set(s,[i])}static getEdges(){return new Map(t._edges)}static getName(e){if(t.enabled)return t._names.get(e)}static getKind(e){return t._kinds.get(e)}static inspect(e){return{name:t._names.get(e),kind:t._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,n=new Set;for(let s of t._stores){let i=s.deref();if(!i){t._stores.delete(s);continue}let o=t._resolveKey(i);n.add(o),e.set(o,t.inspect(i))}for(let[s,i]of t._edges){if(!n.has(s)){t._edges.delete(s),t._usedKeys.delete(s);continue}let o=i.filter(r=>n.has(r));o.length===0?t._edges.delete(s):o.length!==i.length&&t._edges.set(s,o)}return e}static trace(e,n){let s=null,i=e.get();return e.source(y,(o,r)=>{if(o===y&&(s=r),o===p){s=null;return}if(o===1){let u=r;if(!Object.is(u,i)){let c=i;i=u,n(u,c)}}}),()=>s?.(p)}static dumpGraph(){let e=t.graph(),n=t.getEdges(),s=new Map;for(let[r,u]of n)for(let c of u){let d=s.get(c);d?d.includes(r)||d.push(r):s.set(c,[r])}let i=[];for(let[r,u]of e){let c=s.get(r),d=n.get(r),a=c?.length?` \u2190 [${c.join(", ")}]`:"",l=d?.length?` \u2192 [${d.join(", ")}]`:"";i.push(` ${r} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${a}${l}`)}return[`Store Graph (${e.size} nodes):`,...i].join(`
2
- `)}static _observe(e,n,s){let i=null,o=n??t.getName(e),r={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:o,dispose:()=>i?.(p)};return e.source(y,(u,c)=>{if(u===y){i=c;return}u===T?(r.values.push(c),r.events.push({type:"data",data:c}),s&&s(`[${o}] DATA:`,c)):u===m?(r.signals.push(c),r.events.push({type:"signal",data:c}),c===v?r.dirtyCount++:c===j&&r.resolvedCount++,s&&s(`[${o}] STATE:`,c)):u===p&&(r.ended=!0,r.endError=c,r.events.push({type:"end",data:c}),s&&s(`[${o}] END`,c!==void 0?c:""),i=null)}),r}static observe(e){return t._observe(e)}static tap(e,n){let s=n??`tap(${t.getName(e)??"anon"})`,i={get:()=>e.get(),source:e.source};return t.register(i,{name:s,kind:"tap"}),t.registerEdge(e,i),i}static spy(e,n){let s=n?.name??t.getName(e)??"spy",i=n?.log??console.log;return t._observe(e,s,i)}static snapshot(){let e=t.graph(),n=t.getEdges(),s=new Map;for(let r of t._stores){let u=r.deref();if(!u)continue;let c=t._annotations.get(u);c!==void 0&&s.set(t._resolveKey(u),c)}let i=[];for(let[r,u]of e){let c={name:r,kind:u.kind,value:u.value,status:u.status},d=s.get(r);d!==void 0&&(c.annotation=d),i.push(c)}let o=[];for(let[r,u]of n)for(let c of u)o.push({from:r,to:c});return{nodes:i,edges:o,trace:t.traceLog()}}static toMermaid(e){let n=e?.direction??"TD",s=t.snapshot(),i=[`graph ${n}`],o={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},r=new Map;function u(a){let l=a.replace(/[^a-zA-Z0-9_]/g,"_"),f=r.get(l);return f===void 0?(r.set(l,1),l):(r.set(l,f+1),`${l}__${f}`)}let c=new Map;function d(a){let l=JSON.stringify(a);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let a of s.nodes){let l=u(a.name);c.set(a.name,l);let f=`${a.name} (${a.kind}) = ${d(a.value)}`,w=o[a.status??""]??"";i.push(` ${l}["${f}"]${w}`)}for(let a of s.edges){let l=c.get(a.from)??u(a.from),f=c.get(a.to)??u(a.to);i.push(` ${l} --> ${f}`)}return i.push(""),i.push(" classDef settled fill:#d4edda,stroke:#28a745"),i.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),i.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),i.push(" classDef completed fill:#cce5ff,stroke:#007bff"),i.join(`
3
- `)}static toD2(e){let n=e?.direction??"down",s=t.snapshot(),i=[`direction: ${n}`,""],o={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},r=new Map;function u(a){let l=a.replace(/[^a-zA-Z0-9_]/g,"_"),f=r.get(l);return f===void 0?(r.set(l,1),l):(r.set(l,f+1),`${l}__${f}`)}let c=new Map;function d(a){let l=JSON.stringify(a);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let a of s.nodes){let l=u(a.name);c.set(a.name,l);let f=o[a.kind]??"rectangle",w=`${a.name} (${a.kind}) = ${d(a.value)}`,$=a.status?` [${a.status}]`:"";i.push(`${l}: "${w}${$}" { shape: ${f} }`)}s.edges.length>0&&i.push("");for(let a of s.edges){let l=c.get(a.from)??u(a.from),f=c.get(a.to)??u(a.to);i.push(`${l} -> ${f}`)}return i.join(`
4
- `)}static annotate(e,n){if(!t.enabled)return;t._annotations.set(e,n);let s={node:t._resolveKey(e),reason:n,timestamp:Date.now()},i=t.maxTraceEntries;i<=0||(t._traceLog.length<i?t._traceLog.push(s):(t._traceLog[t._traceHead]=s,t._traceFull=!0),t._traceHead=(t._traceHead+1)%i)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var U=1,h=64,_=2,L=4,pt=8,ht=16,D=32,S=1024,g=B,R=at<<b,I=ct<<b,Y=ot<<b,Lt=lt<<b,Rt=dt<<b,wt=ut<<b,W=class{_value;_output=null;_flags;get _status(){return ft(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(e,n){this._value=n?.initial,this._fn=e,this._eqFn=n?.equals,this._getterFn=n?.getter,this._initial=n?.initial;let s=0;n?.autoDirty!==!1&&(s|=L),n?.resetOnTeardown&&(s|=pt),n?.resubscribable&&(s|=ht),this._flags=s,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||x.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,n){let s=this._output;if(s)if(this._flags&h)for(let i of s)i(e,n);else s(e,n)}emit(e){this._flags&_||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(K()?this._flags&D||(this._flags|=D,this._flags&L&&(this._flags=this._flags&~g|R,this._dispatch(m,v)),F(()=>{this._flags&=~D,this._flags=this._flags&~g|I,this._dispatch(T,this._value)})):(this._flags&L&&!(this._flags&S)&&(this._flags=this._flags&~g|R,this._dispatch(m,v)),this._flags=this._flags&~g|I,this._dispatch(T,this._value))))}signal(e){this._flags&_||!this._output||(e===v?this._flags=this._flags&~g|R:e===j&&(this._flags=this._flags&~g|wt),this._dispatch(m,e))}complete(){if(this._flags&_)return;this._flags=(this._flags|_)&~g|Lt;let e=this._output,n=this._flags&h;if(this._output=null,this._flags&=~(h|S),this._singleDepCount=0,this._stop(),e)if(n)for(let s of e)s(p);else e(p)}error(e){if(this._flags&_)return;this._flags=(this._flags|_)&~g|Rt;let n=this._output,s=this._flags&h;if(this._output=null,this._flags&=~(h|S),this._singleDepCount=0,this._stop(),n)if(s)for(let i of n)i(p,e);else n(p,e)}_start(){if(this._flags&U||!this._fn)return;this._flags|=U;let e=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n)});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&U&&(this._flags&=~U,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&pt&&(this._value=this._initial),this._flags&_||(this._flags=this._flags&~g|Y))}source(e,n){if(e===y){let s=n;if(this._flags&_)if(this._flags&ht&&this._output===null)this._flags=this._flags&~(_|g)|Y;else{s(y,o=>{}),s(p);return}if(this._output===null)this._output=s;else if(this._flags&h)this._output.add(s);else{let o=new Set;o.add(this._output),o.add(s),this._output=o,this._flags=(this._flags|h)&~S}let i=!1;s(y,(o,r)=>{if(o===T&&s(T,this._value),o===m&&r===rt&&!i&&(i=!0,this._singleDepCount++,this._flags&h||(this._flags|=S)),o===p){if(i&&(i=!1,this._singleDepCount--),this._output===null)return;if(this._flags&h){let u=this._output;u.delete(s),u.size===1?(this._output=u.values().next().value,this._flags&=~h,this._singleDepCount>0&&(this._flags|=S)):u.size===0&&(this._output=null,this._flags&=~(h|S),this._singleDepCount=0,this._flags=this._flags&~g|Y,this._stop())}else this._output===s&&(this._output=null,this._flags&=~S,this._singleDepCount=0,this._flags=this._flags&~g|Y,this._stop())}}),gt(()=>this._start())}}};var Z=class extends W{constructor(e,n){super(void 0,{initial:e,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),x.register(this,{kind:"state",...n})}get(){return this._value}set(e){this._flags&_||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(K()?this._flags&D||(this._flags|=D,this._flags&L&&(this._flags=this._flags&~g|R,this._dispatch(m,v)),F(()=>{this._flags&=~D,this._flags=this._flags&~g|I,this._dispatch(T,this._value)})):(this._flags&L&&!(this._flags&S)&&(this._flags=this._flags&~g|R,this._dispatch(m,v)),this._flags=this._flags&~g|I,this._dispatch(T,this._value))))}update(e){this.set(e(this._value))}};function O(t,e){return new Z(t,e)}function $t(t){switch(t){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function Mt(t,e){switch(t){case"openai":case"custom":return`${e}/chat/completions`;case"ollama":return`${e}/api/chat`;default:return`${e}/chat/completions`}}function It(t,e,n,s){let i={model:e,messages:n,stream:!0};return s?.temperature!==void 0&&(i.temperature=s.temperature),s?.maxTokens!==void 0&&(t==="ollama"?i.options={num_predict:s.maxTokens}:i.max_tokens=s.maxTokens),s?.stop&&(i.stop=s.stop),i}function Ot(t,e){let n={"Content-Type":"application/json"};return e&&(n.Authorization=`Bearer ${e}`),n}function At(t){let e=t.name??"llm",n=t.provider,s=t.baseURL??$t(n),i=t.model??"",o=t.fetch??globalThis.fetch,r=O("",{name:`${e}.store`}),u=O({},{name:`${e}.tokens`}),c=O(!1,{name:`${e}.streaming`}),d=O(void 0,{name:`${e}.error`}),a=null;function l(){a&&(a.abort(),a=null),c.set(!1)}function f($,M){l(),a=new AbortController;let V=M?.signal?Ct(a.signal,M.signal):a.signal;J(()=>{r.set(""),u.set({}),d.set(void 0),c.set(!0)});let k=Mt(n,s),E=It(n,i,$,M),A=Ot(n,t.apiKey);w(k,A,E,V).catch(()=>{})}async function w($,M,V,k){try{let E=await o($,{method:"POST",headers:M,body:JSON.stringify(V),signal:k});if(!E.ok){let H=await E.text().catch(()=>"");throw new Error(`LLM API error ${E.status}: ${H}`)}let A=E.body?.getReader();if(!A)throw new Error("No response body");let Q=new TextDecoder,X="",G="";for(;;){if(k.aborted)return;let{done:H,value:_t}=await A.read();if(H)break;G+=Q.decode(_t,{stream:!0});let tt=G.split(`
5
- `);G=tt.pop()??"";for(let Tt of tt){if(k.aborted)return;let P=Tt.trim();if(!P||P.startsWith(":")||!P.startsWith("data: "))continue;let et=P.slice(6);if(et!=="[DONE]")try{let nt=JSON.parse(et),st=Pt(n,nt);st&&(X+=st,r.set(X));let it=Nt(n,nt);it&&u.set(it)}catch{}}}if(Q.decode(),k.aborted)return;c.set(!1),a=null}catch(E){if(k.aborted)return;J(()=>{d.set(E),c.set(!1)}),a=null}}return{store:r,tokens:u,streaming:c,error:d,generate:f,abort:l}}function Pt(t,e){return t==="ollama"?e?.message?.content:e?.choices?.[0]?.delta?.content}function Nt(t,e){let n=t==="ollama"?e:e?.usage;if(n){if(t==="ollama")return e.eval_count!==void 0||e.prompt_eval_count!==void 0?{promptTokens:e.prompt_eval_count,completionTokens:e.eval_count,totalTokens:(e.prompt_eval_count??0)+(e.eval_count??0)}:void 0;if(n.prompt_tokens!==void 0||n.completion_tokens!==void 0)return{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}}}function Ct(t,e){let n=new AbortController,s=()=>{t.removeEventListener("abort",i),e.removeEventListener("abort",i)},i=()=>{n.abort(),s()};return t.addEventListener("abort",i,{once:!0}),e.addEventListener("abort",i,{once:!0}),n._cleanup=s,n.signal}0&&(module.exports={fromLLM});
1
+ "use strict";var q=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var vt=Object.prototype.hasOwnProperty;var yt=(t,e)=>{for(var n in e)q(t,n,{get:e[n],enumerable:!0})},bt=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of St(e))!vt.call(t,i)&&i!==n&&q(t,i,{get:()=>e[i],enumerable:!(s=mt(e,i))||s.enumerable});return t};var Et=t=>bt(q({},"__esModule",{value:!0}),t);var jt={};yt(jt,{fromLLM:()=>At});module.exports=Et(jt);var v=Symbol("DIRTY"),j=Symbol("RESOLVED"),rt=Symbol("SINGLE_DEP"),ot=0,at=1,ct=2,ut=3,lt=4,dt=5,y=7,B=7<<y,kt=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function ft(t){return kt[(t&B)>>>y]}var b=0,T=1,p=2,m=3,N=0,C=[],z=!1;function J(t){N++;try{return t()}finally{if(N--,N===0&&!z){z=!0;for(let e=0;e<C.length;e++)C[e]();C.length=0,z=!1}}}function K(){return N>0}function F(t){C.push(t)}var Dt=0,xt=[];function gt(t){Dt>0?xt.push(t):t()}var x=class t{static _names=new WeakMap;static _kinds=new WeakMap;static _keys=new WeakMap;static _stores=new Set;static _edges=new Map;static _nextId=0;static _usedKeys=new Set;static _explicitEnabled=null;static _cachedDefault=null;static _annotations=new WeakMap;static _traceLog=[];static _traceHead=0;static _traceFull=!1;static maxTraceEntries=1e3;static get enabled(){if(t._explicitEnabled!==null)return t._explicitEnabled;if(t._cachedDefault!==null)return t._cachedDefault;try{t._cachedDefault=globalThis.process?.env?.NODE_ENV!=="production"}catch{t._cachedDefault=!0}return t._cachedDefault}static set enabled(e){t._explicitEnabled=e}static _depSuffix(e){if(!e?.length)return;let s=e.map(i=>t._names.get(i)??"?").join(",");return s.length>40?`${s.slice(0,37)}...`:s}static _resolveKey(e){let n=t._keys.get(e)??t._names.get(e);if(n)return n;let s=`anonymous_${t._nextId++}`;return t._keys.set(e,s),s}static register(e,n){if(!t.enabled)return;n?.name&&t._names.set(e,n.name),n?.kind&&t._kinds.set(e,n.kind);let s=t._nextId++,i=n?.name;if(!(i&&!t._usedKeys.has(i)))if(i){let r=t._depSuffix(n?.deps);i=r?`${i}(${r})`:`${i}_${s}`,t._usedKeys.has(i)&&(i=`${i}_${s}`)}else{let r=n?.kind??"store",o=t._depSuffix(n?.deps);i=o?`${r}(${o})`:`${r}_${s}`,t._usedKeys.has(i)&&(i=`${i}_${s}`)}t._usedKeys.add(i),t._keys.set(e,i),t._stores.add(new WeakRef(e))}static registerEdge(e,n){if(!t.enabled)return;let s=t._resolveKey(e),i=t._resolveKey(n),r=t._edges.get(s);r?r.includes(i)||r.push(i):t._edges.set(s,[i])}static getEdges(){return new Map(t._edges)}static getName(e){if(t.enabled)return t._names.get(e)}static getKind(e){return t._kinds.get(e)}static inspect(e){return{name:t._names.get(e),kind:t._kinds.get(e)??"unknown",value:typeof e.get=="function"?e.get():void 0,status:e._status}}static graph(){let e=new Map,n=new Set;for(let s of t._stores){let i=s.deref();if(!i){t._stores.delete(s);continue}let r=t._resolveKey(i);n.add(r),e.set(r,t.inspect(i))}for(let[s,i]of t._edges){if(!n.has(s)){t._edges.delete(s),t._usedKeys.delete(s);continue}let r=i.filter(o=>n.has(o));r.length===0?t._edges.delete(s):r.length!==i.length&&t._edges.set(s,r)}return e}static trace(e,n){let s=null,i=e.get();return e.source(b,(r,o)=>{if(r===b&&(s=o),r===p){s=null;return}if(r===1){let u=o;if(!Object.is(u,i)){let a=i;i=u,n(u,a)}}}),()=>s?.(p)}static dumpGraph(){let e=t.graph(),n=t.getEdges(),s=new Map;for(let[o,u]of n)for(let a of u){let d=s.get(a);d?d.includes(o)||d.push(o):s.set(a,[o])}let i=[];for(let[o,u]of e){let a=s.get(o),d=n.get(o),c=a?.length?` \u2190 [${a.join(", ")}]`:"",l=d?.length?` \u2192 [${d.join(", ")}]`:"";i.push(` ${o} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${c}${l}`)}return[`Store Graph (${e.size} nodes):`,...i].join(`
2
+ `)}static _observe(e,n,s){let i=null,r=n??t.getName(e),o={values:[],signals:[],events:[],ended:!1,endError:void 0,dirtyCount:0,resolvedCount:0,name:r,dispose:()=>i?.(p)};return e.source(b,(u,a)=>{if(u===b){i=a;return}u===T?(o.values.push(a),o.events.push({type:"data",data:a}),s&&s(`[${r}] DATA:`,a)):u===m?(o.signals.push(a),o.events.push({type:"signal",data:a}),a===v?o.dirtyCount++:a===j&&o.resolvedCount++,s&&s(`[${r}] STATE:`,a)):u===p&&(o.ended=!0,o.endError=a,o.events.push({type:"end",data:a}),s&&s(`[${r}] END`,a!==void 0?a:""),i=null)}),o}static observe(e){return t._observe(e)}static tap(e,n){let s=n??`tap(${t.getName(e)??"anon"})`,i={get:()=>e.get(),source:e.source};return t.register(i,{name:s,kind:"tap"}),t.registerEdge(e,i),i}static spy(e,n){let s=n?.name??t.getName(e)??"spy",i=n?.log??console.log;return t._observe(e,s,i)}static snapshot(){let e=t.graph(),n=t.getEdges(),s=new Map;for(let o of t._stores){let u=o.deref();if(!u)continue;let a=t._annotations.get(u);a!==void 0&&s.set(t._resolveKey(u),a)}let i=[];for(let[o,u]of e){let a={name:o,kind:u.kind,value:u.value,status:u.status},d=s.get(o);d!==void 0&&(a.annotation=d),i.push(a)}let r=[];for(let[o,u]of n)for(let a of u)r.push({from:o,to:a});return{nodes:i,edges:r,trace:t.traceLog()}}static toMermaid(e){let n=e?.direction??"TD",s=t.snapshot(),i=[`graph ${n}`],r={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},o=new Map;function u(c){let l=c.replace(/[^a-zA-Z0-9_]/g,"_"),f=o.get(l);return f===void 0?(o.set(l,1),l):(o.set(l,f+1),`${l}__${f}`)}let a=new Map;function d(c){let l=JSON.stringify(c);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let c of s.nodes){let l=u(c.name);a.set(c.name,l);let f=`${c.name} (${c.kind}) = ${d(c.value)}`,w=r[c.status??""]??"";i.push(` ${l}["${f}"]${w}`)}for(let c of s.edges){let l=a.get(c.from)??u(c.from),f=a.get(c.to)??u(c.to);i.push(` ${l} --> ${f}`)}return i.push(""),i.push(" classDef settled fill:#d4edda,stroke:#28a745"),i.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),i.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),i.push(" classDef completed fill:#cce5ff,stroke:#007bff"),i.join(`
3
+ `)}static toD2(e){let n=e?.direction??"down",s=t.snapshot(),i=[`direction: ${n}`,""],r={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},o=new Map;function u(c){let l=c.replace(/[^a-zA-Z0-9_]/g,"_"),f=o.get(l);return f===void 0?(o.set(l,1),l):(o.set(l,f+1),`${l}__${f}`)}let a=new Map;function d(c){let l=JSON.stringify(c);return l&&l.length>30?`${l.slice(0,27)}...`:l??"undefined"}for(let c of s.nodes){let l=u(c.name);a.set(c.name,l);let f=r[c.kind]??"rectangle",w=`${c.name} (${c.kind}) = ${d(c.value)}`,$=c.status?` [${c.status}]`:"";i.push(`${l}: "${w}${$}" { shape: ${f} }`)}s.edges.length>0&&i.push("");for(let c of s.edges){let l=a.get(c.from)??u(c.from),f=a.get(c.to)??u(c.to);i.push(`${l} -> ${f}`)}return i.join(`
4
+ `)}static annotate(e,n){if(!t.enabled)return;t._annotations.set(e,n);let s={node:t._resolveKey(e),reason:n,timestamp:Date.now()},i=t.maxTraceEntries;i<=0||(t._traceLog.length<i?t._traceLog.push(s):(t._traceLog[t._traceHead]=s,t._traceFull=!0),t._traceHead=(t._traceHead+1)%i)}static getAnnotation(e){return t._annotations.get(e)}static traceLog(){return t._traceFull?[...t._traceLog.slice(t._traceHead),...t._traceLog.slice(0,t._traceHead)]:t._traceLog.slice(0,t._traceHead||t._traceLog.length)}static clearTrace(){t._traceLog=[],t._traceHead=0,t._traceFull=!1}static _reset(){t._names=new WeakMap,t._kinds=new WeakMap,t._keys=new WeakMap,t._stores=new Set,t._edges=new Map,t._usedKeys=new Set,t._nextId=0,t._explicitEnabled=null,t._cachedDefault=null,t._annotations=new WeakMap,t._traceLog=[],t._traceHead=0,t._traceFull=!1,t.maxTraceEntries=1e3}};var U=1,h=64,_=2,L=4,pt=8,ht=16,D=32,S=1024,g=B,R=at<<y,I=ct<<y,W=ot<<y,Lt=lt<<y,Rt=dt<<y,wt=ut<<y,Y=class{_value;_output=null;_flags;get _status(){return ft(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;constructor(e,n){this._value=n?.initial,this._fn=e,this._eqFn=n?.equals,this._getterFn=n?.getter,this._initial=n?.initial;let s=0;n?.autoDirty!==!1&&(s|=L),n?.resetOnTeardown&&(s|=pt),n?.resubscribable&&(s|=ht),this._flags=s,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||x.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(e,n){let s=this._output;if(s)if(this._flags&h)for(let i of s)i(e,n);else s(e,n)}emit(e){this._flags&_||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(K()?this._flags&D||(this._flags|=D,this._flags&L&&(this._flags=this._flags&~g|R,this._dispatch(m,v)),F(()=>{this._flags&=~D,this._flags=this._flags&~g|I,this._dispatch(T,this._value)})):(this._flags&L&&!(this._flags&S)&&(this._flags=this._flags&~g|R,this._dispatch(m,v)),this._flags=this._flags&~g|I,this._dispatch(T,this._value))))}signal(e){this._flags&_||!this._output||(e===v?this._flags=this._flags&~g|R:e===j&&(this._flags=this._flags&~g|wt),this._dispatch(m,e))}complete(){if(this._flags&_)return;this._flags=(this._flags|_)&~g|Lt;let e=this._output,n=this._flags&h;if(this._output=null,this._flags&=~(h|S),this._singleDepCount=0,this._stop(),e)if(n)for(let s of e)s(p);else e(p)}error(e){if(this._flags&_)return;this._flags=(this._flags|_)&~g|Rt;let n=this._output,s=this._flags&h;if(this._output=null,this._flags&=~(h|S),this._singleDepCount=0,this._stop(),n)if(s)for(let i of n)i(p,e);else n(p,e)}_start(){if(this._flags&U||!this._fn)return;this._flags|=U;let e=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n)});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&U&&(this._flags&=~U,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&pt&&(this._value=this._initial),this._flags&_||(this._flags=this._flags&~g|W))}source(e,n){if(e===b){let s=n;if(this._flags&_)if(this._flags&ht&&this._output===null)this._flags=this._flags&~(_|g)|W;else{s(b,r=>{}),s(p);return}if(this._output===null)this._output=s;else if(this._flags&h)this._output.add(s);else{let r=new Set;r.add(this._output),r.add(s),this._output=r,this._flags=(this._flags|h)&~S}let i=!1;s(b,(r,o)=>{if(r===T&&s(T,this._value),r===m&&o===rt&&!i&&(i=!0,this._singleDepCount++,this._flags&h||(this._flags|=S)),r===p){if(i&&(i=!1,this._singleDepCount--),this._output===null)return;if(this._flags&h){let u=this._output;u.delete(s),u.size===1?(this._output=u.values().next().value,this._flags&=~h,this._singleDepCount>0&&(this._flags|=S)):u.size===0&&(this._output=null,this._flags&=~(h|S),this._singleDepCount=0,this._flags=this._flags&~g|W,this._stop())}else this._output===s&&(this._output=null,this._flags&=~S,this._singleDepCount=0,this._flags=this._flags&~g|W,this._stop())}}),gt(()=>this._start())}}};var Z=class extends Y{constructor(e,n){super(void 0,{initial:e,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),x.register(this,{kind:"state",...n})}get(){return this._value}set(e){this._flags&_||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(K()?this._flags&D||(this._flags|=D,this._flags&L&&(this._flags=this._flags&~g|R,this._dispatch(m,v)),F(()=>{this._flags&=~D,this._flags=this._flags&~g|I,this._dispatch(T,this._value)})):(this._flags&L&&!(this._flags&S)&&(this._flags=this._flags&~g|R,this._dispatch(m,v)),this._flags=this._flags&~g|I,this._dispatch(T,this._value))))}update(e){this.set(e(this._value))}};function O(t,e){return new Z(t,e)}function $t(t){switch(t){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function Mt(t,e){switch(t){case"openai":case"custom":return`${e}/chat/completions`;case"ollama":return`${e}/api/chat`;default:return`${e}/chat/completions`}}function It(t,e,n,s){let i={model:e,messages:n,stream:!0};return s?.temperature!==void 0&&(i.temperature=s.temperature),s?.maxTokens!==void 0&&(t==="ollama"?i.options={num_predict:s.maxTokens}:i.max_tokens=s.maxTokens),s?.stop&&(i.stop=s.stop),i}function Ot(t,e){let n={"Content-Type":"application/json"};return e&&(n.Authorization=`Bearer ${e}`),n}function At(t){let e=t.name??"llm",n=t.provider,s=t.baseURL??$t(n),i=t.model??"",r=t.fetch??globalThis.fetch,o=O("",{name:`${e}.store`}),u=O({},{name:`${e}.tokens`}),a=O("pending",{name:`${e}.status`}),d=O(void 0,{name:`${e}.error`}),c=null;function l(){c&&(c.abort(),c=null),a.get()==="active"&&a.set("pending")}function f($,M){l(),c=new AbortController;let V=M?.signal?Ct(c.signal,M.signal):c.signal;J(()=>{o.set(""),u.set({}),d.set(void 0),a.set("active")});let E=Mt(n,s),k=It(n,i,$,M),A=Ot(n,t.apiKey);w(E,A,k,V).catch(()=>{})}async function w($,M,V,E){try{let k=await r($,{method:"POST",headers:M,body:JSON.stringify(V),signal:E});if(!k.ok){let H=await k.text().catch(()=>"");throw new Error(`LLM API error ${k.status}: ${H}`)}let A=k.body?.getReader();if(!A)throw new Error("No response body");let Q=new TextDecoder,X="",G="";for(;;){if(E.aborted)return;let{done:H,value:_t}=await A.read();if(H)break;G+=Q.decode(_t,{stream:!0});let tt=G.split(`
5
+ `);G=tt.pop()??"";for(let Tt of tt){if(E.aborted)return;let P=Tt.trim();if(!P||P.startsWith(":")||!P.startsWith("data: "))continue;let et=P.slice(6);if(et!=="[DONE]")try{let nt=JSON.parse(et),st=Pt(n,nt);st&&(X+=st,o.set(X));let it=Nt(n,nt);it&&u.set(it)}catch{}}}if(Q.decode(),E.aborted)return;a.set("completed"),c=null}catch(k){if(E.aborted)return;J(()=>{d.set(k),a.set("errored")}),c=null}finally{E._cleanup?.()}}return{store:o,tokens:u,status:a,error:d,generate:f,abort:l}}function Pt(t,e){return t==="ollama"?e?.message?.content:e?.choices?.[0]?.delta?.content}function Nt(t,e){let n=t==="ollama"?e:e?.usage;if(n){if(t==="ollama")return e.eval_count!==void 0||e.prompt_eval_count!==void 0?{promptTokens:e.prompt_eval_count,completionTokens:e.eval_count,totalTokens:(e.prompt_eval_count??0)+(e.eval_count??0)}:void 0;if(n.prompt_tokens!==void 0||n.completion_tokens!==void 0)return{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}}}function Ct(t,e){let n=new AbortController,s=()=>{t.removeEventListener("abort",i),e.removeEventListener("abort",i)},i=()=>{n.abort(),s()};t.addEventListener("abort",i,{once:!0}),e.addEventListener("abort",i,{once:!0});let r=n.signal;return r._cleanup=s,r}0&&(module.exports={fromLLM});