@callbag-recharge/callbag-recharge 0.28.0 → 0.30.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 (48) hide show
  1. package/README.md +8 -0
  2. package/dist/ai/fromLLM.cjs +5 -5
  3. package/dist/ai/fromLLM.d.cts +4 -1
  4. package/dist/ai/fromLLM.d.ts +4 -1
  5. package/dist/ai/fromLLM.js +1 -1
  6. package/dist/ai/index.cjs +44 -22
  7. package/dist/ai/index.d.cts +297 -33
  8. package/dist/ai/index.d.ts +297 -33
  9. package/dist/ai/index.js +37 -15
  10. package/dist/ai/memoryStore/index.cjs +4 -4
  11. package/dist/ai/memoryStore/index.d.cts +1 -1
  12. package/dist/ai/memoryStore/index.d.ts +1 -1
  13. package/dist/ai/memoryStore/index.js +1 -1
  14. package/dist/ai/ragPipeline/index.d.cts +1 -1
  15. package/dist/ai/ragPipeline/index.d.ts +1 -1
  16. package/dist/chunk-57OAI7Y6.js +1 -0
  17. package/dist/chunk-DIC2IVQO.js +1 -0
  18. package/dist/chunk-DXM2IC4C.js +2 -0
  19. package/dist/chunk-F4TK5JZI.js +1 -0
  20. package/dist/chunk-PS42SVSV.js +1 -0
  21. package/dist/{chunk-CSMHDOAR.js → chunk-Z2ND66W4.js} +1 -1
  22. package/dist/compat/react/index.cjs +1 -1
  23. package/dist/compat/react/index.d.cts +18 -2
  24. package/dist/compat/react/index.d.ts +18 -2
  25. package/dist/compat/react/index.js +1 -1
  26. package/dist/memory/index.cjs +4 -4
  27. package/dist/memory/index.d.cts +5 -3
  28. package/dist/memory/index.d.ts +5 -3
  29. package/dist/memory/index.js +1 -1
  30. package/dist/messaging/index.cjs +9 -9
  31. package/dist/messaging/index.d.cts +7 -131
  32. package/dist/messaging/index.d.ts +7 -131
  33. package/dist/messaging/index.js +6 -6
  34. package/dist/orchestrate/index.cjs +4 -4
  35. package/dist/orchestrate/index.d.cts +1 -1
  36. package/dist/orchestrate/index.d.ts +1 -1
  37. package/dist/orchestrate/index.js +3 -3
  38. package/dist/{types-BH6fI4xa.d.cts → topicBridge-B8_71CY5.d.cts} +164 -4
  39. package/dist/{types-DpplCkXF.d.ts → topicBridge-BDS_cqVj.d.ts} +164 -4
  40. package/dist/{types-CxUiO1ko.d.cts → types-2zgL7QtP.d.cts} +25 -1
  41. package/dist/{types-vpHq4g8l.d.ts → types-BPee8DL6.d.ts} +25 -1
  42. package/dist/utils/index.cjs +8 -8
  43. package/dist/utils/index.js +6 -6
  44. package/package.json +1 -1
  45. package/dist/chunk-ECHFG6CV.js +0 -1
  46. package/dist/chunk-IHAQFWGK.js +0 -1
  47. package/dist/chunk-QO3UGDBL.js +0 -1
  48. package/dist/chunk-YLOA2CAG.js +0 -2
package/README.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # callbag-recharge
2
2
 
3
+ > **This project has been succeeded by [GraphReFly](https://github.com/graphrefly/graphrefly-ts).** New development, bug fixes, and documentation happen there. See the [migration guide](https://graphrefly.dev/recipes/from-callbag-recharge/) or jump straight to [graphrefly.dev](https://graphrefly.dev).
4
+ >
5
+ > ```bash
6
+ > npm install @graphrefly/graphrefly
7
+ > ```
8
+
9
+ ---
10
+
3
11
  **State that flows.** Reactive state management for TypeScript — from simple atoms to streaming pipelines, in one library.
4
12
 
5
13
  - **6 primitives** — `state`, `derived`, `dynamicDerived`, `effect`, `producer`, `operator`
@@ -1,5 +1,5 @@
1
- "use strict";var ue=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Ne=Object.prototype.hasOwnProperty;var je=(t,e)=>{for(var n in e)ue(t,n,{get:e[n],enumerable:!0})},Fe=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Pe(e))!Ne.call(t,r)&&r!==n&&ue(t,r,{get:()=>e[r],enumerable:!(s=$e(e,r))||s.enumerable});return t};var Ue=t=>Fe(ue({},"__esModule",{value:!0}),t);var ot={};je(ot,{fromLLM:()=>rt,toToolCallRequests:()=>Qe});module.exports=Ue(ot);var v=Symbol("DIRTY"),G=Symbol("RESOLVED"),Te=Symbol("SINGLE_DEP"),fe=Symbol("RESET"),Ke=Symbol("PAUSE"),We=Symbol("RESUME"),de=Symbol("TEARDOWN");function _e(t){return t===fe||t===Ke||t===We||t===de}var ye=0,be=1,Se=2,ve=3,Ee=4,ke=5,L=7,ge=7<<L,Ve=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function De(t){return Ve[(t&ge)>>>L]}var m=0,_=1,g=2,b=3,X=0,ee=[],ce=!1;function x(t){X++;let e,n,s=!1;try{e=t()}catch(i){n=i,s=!0}X--;let r;if(X===0&&!ce){ce=!0;try{for(let i=0;i<ee.length;i++)try{ee[i]()}catch(o){r??=o}}finally{ee.length=0,ce=!1}}if(s)throw n;if(r)throw r;return e}function A(){return X>0}function te(t){ee.push(t)}var Ye=0,Be=[];function Le(t){Ye>0?Be.push(t):t()}var N=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(r=>t._names.get(r)??"?").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++,r=n?.name;if(!(r&&!t._usedKeys.has(r)))if(r){let i=t._depSuffix(n?.deps);r=i?`${r}(${i})`:`${r}_${s}`,t._usedKeys.has(r)&&(r=`${r}_${s}`)}else{let i=n?.kind??"store",o=t._depSuffix(n?.deps);r=o?`${i}(${o})`:`${i}_${s}`,t._usedKeys.has(r)&&(r=`${r}_${s}`)}t._usedKeys.add(r),t._keys.set(e,r),t._stores.add(new WeakRef(e))}static registerEdge(e,n){if(!t.enabled)return;let s=t._resolveKey(e),r=t._resolveKey(n),i=t._edges.get(s);i?i.includes(r)||i.push(r):t._edges.set(s,[r])}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 r=s.deref();if(!r){t._stores.delete(s);continue}let i=t._resolveKey(r);n.add(i),e.set(i,t.inspect(r))}for(let[s,r]of t._edges){if(!n.has(s)){t._edges.delete(s),t._usedKeys.delete(s);continue}let i=r.filter(o=>n.has(o));i.length===0?t._edges.delete(s):i.length!==r.length&&t._edges.set(s,i)}return e}static trace(e,n){let s=null,r=e.get();return e.source(m,(i,o)=>{if(i===m&&(s=o),i===g){s=null;return}if(i===1){let u=o;if(!Object.is(u,r)){let l=r;r=u,n(u,l)}}}),()=>s?.(g)}static dumpGraph(){let e=t.graph(),n=t.getEdges(),s=new Map;for(let[o,u]of n)for(let l of u){let f=s.get(l);f?f.includes(o)||f.push(o):s.set(l,[o])}let r=[];for(let[o,u]of e){let l=s.get(o),f=n.get(o),a=l?.length?` \u2190 [${l.join(", ")}]`:"",c=f?.length?` \u2192 [${f.join(", ")}]`:"";r.push(` ${o} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${a}${c}`)}return[`Store Graph (${e.size} nodes):`,...r].join(`
2
- `)}static _signalLabel(e){return e===v?"DIRTY":e===G?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,n,s){let r=null,i=!1,o=n??t.getName(e),u=[],l={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return l.ended&&!i},get errored(){return l.ended&&i},dirtyCount:0,resolvedCount:0,name:o,get eventLog(){return u},dispose:()=>r?.(g),reconnect:()=>(r?.(g),t._observe(e,n,s))};return e.source(m,(f,a)=>{if(f===m){r=a;return}let c=A();f===_?(l.values.push(a),l.events.push({type:"data",data:a,inBatch:c}),u.push(a),s&&s(`[${o}] DATA:`,a)):f===b?(l.signals.push(a),l.events.push({type:"signal",data:a,inBatch:c}),u.push(t._signalLabel(a)),a===v?l.dirtyCount++:a===G&&l.resolvedCount++,s&&s(`[${o}] STATE:`,a)):f===g&&(l.ended=!0,l.endError=a,i=a!==void 0,l.events.push({type:"end",data:a,inBatch:c}),u.push(i?["END",a]:"END"),s&&s(`[${o}] END`,a!==void 0?a:""),r=null)}),l}static observe(e){return t._observe(e)}static activate(e){let n=null;return e.source(m,(s,r)=>{s===m&&(n=r),s===g&&(n=null)}),()=>n?.(g)}static tap(e,n){let s=n??`tap(${t.getName(e)??"anon"})`,r={get:()=>e.get(),source:e.source};return t.register(r,{name:s,kind:"tap"}),t.registerEdge(e,r),r}static spy(e,n){let s=n?.name??t.getName(e)??"spy",r=n?.log??console.log;return t._observe(e,s,r)}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 l=t._annotations.get(u);l!==void 0&&s.set(t._resolveKey(u),l)}let r=[];for(let[o,u]of e){let l={name:o,kind:u.kind,value:u.value,status:u.status},f=s.get(o);f!==void 0&&(l.annotation=f),r.push(l)}let i=[];for(let[o,u]of n)for(let l of u)i.push({from:o,to:l});return{nodes:r,edges:i,trace:t.traceLog()}}static toMermaid(e){let n=e?.direction??"TD",s=t.snapshot(),r=[`graph ${n}`],i={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},o=new Map;function u(a){let c=a.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 l=new Map;function f(a){let c=JSON.stringify(a);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let a of s.nodes){let c=u(a.name);l.set(a.name,c);let d=`${a.name} (${a.kind}) = ${f(a.value)}`,T=i[a.status??""]??"";r.push(` ${c}["${d}"]${T}`)}for(let a of s.edges){let c=l.get(a.from)??u(a.from),d=l.get(a.to)??u(a.to);r.push(` ${c} --> ${d}`)}return r.push(""),r.push(" classDef settled fill:#d4edda,stroke:#28a745"),r.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),r.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),r.push(" classDef completed fill:#cce5ff,stroke:#007bff"),r.join(`
3
- `)}static toD2(e){let n=e?.direction??"down",s=t.snapshot(),r=[`direction: ${n}`,""],i={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,"_"),d=o.get(c);return d===void 0?(o.set(c,1),c):(o.set(c,d+1),`${c}__${d}`)}let l=new Map;function f(a){let c=JSON.stringify(a);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let a of s.nodes){let c=u(a.name);l.set(a.name,c);let d=i[a.kind]??"rectangle",T=`${a.name} (${a.kind}) = ${f(a.value)}`,q=a.status?` [${a.status}]`:"";r.push(`${c}: "${T}${q}" { shape: ${d} }`)}s.edges.length>0&&r.push("");for(let a of s.edges){let c=l.get(a.from)??u(a.from),d=l.get(a.to)??u(a.to);r.push(`${c} -> ${d}`)}return r.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()},r=t.maxTraceEntries;r<=0||(t._traceLog.length<r?t._traceLog.push(s):(t._traceLog[t._traceHead]=s,t._traceFull=!0),t._traceHead=(t._traceHead+1)%r)}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 timeline(e){let n=null,s=[];return e.source(m,(r,i)=>{if(r===m){n=i;return}let o={timestamp:Date.now(),type:r===_?"data":r===b?"signal":"end",data:i,inBatch:A()};s.push(o),r===g&&(n=null)}),{entries:s,dispose:()=>n?.(g)}}static observeDerived(e){let n=[],s=e,r=s._fn;if(typeof r!="function"||!Array.isArray(s._deps))return{...t.observe(e),evaluations:n};s._fn=()=>{let l=s._deps.map(a=>a.get()),f=r();return n.push({result:f,depValues:l,timestamp:Date.now()}),f};let i=t._observe(e),o=i.dispose;return{...i,evaluations:n,dispose:()=>{s._fn=r,o()},reconnect:()=>(s._fn=r,o(),t.observeDerived(e))}}static observeTaskState(e){let n=e.status.get(),s=[],r=null;return e.status.source(m,(i,o)=>{if(i===m){r=o;return}if(i===_){let u=o;if(u!==n){let l={from:n,to:u,timestamp:Date.now()};u==="error"&&(l.error=e.error.get()),s.push(l),n=u}}i===g&&(r=null)}),{transitions:s,get currentStatus(){return e.status.get()},dispose:()=>{r?.(g)}}}static causalityTrace(e){let n=[],s=e,r=s._fn;if(typeof r!="function"||!Array.isArray(s._deps))return{...t.observe(e),causality:n};let i=s._deps,o=i.map(a=>a.get());s._fn=()=>{let a=i.map(T=>T.get()),c=r(),d=-1;for(let T=0;T<i.length;T++)if(!Object.is(a[T],o[T])){d=T;break}return n.push({result:c,triggerDepIndex:d,triggerDepName:d>=0?t.getName(i[d]):void 0,depValues:a,timestamp:Date.now()}),o=a,c};let u=t._observe(e),l=u.dispose;return{...u,causality:n,dispose:()=>{s._fn=r,l()},reconnect:()=>(s._fn=r,l(),t.causalityTrace(e))}}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 ne=1,S=64,y=2,j=4,xe=8,Re=16,k=32,E=1024,h=ge,F=be<<L,H=Se<<L,se=ye<<L,Ge=Ee<<L,He=ke<<L,qe=ve<<L,re=class{_value;_output=null;_flags;get _status(){return De(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;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|=j),n?.resetOnTeardown&&(s|=xe),n?.resubscribable&&(s|=Re),this._flags=s,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||N.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&S)for(let r of s)r(e,n);else s(e,n)}emit(e){this._flags&y||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(A()?this._flags&k||(this._flags|=k,this._flags&j&&(this._flags=this._flags&~h|F,this._dispatch(b,v)),te(()=>{this._flags&k&&(this._flags&=~k,this._flags=this._flags&~h|H,this._dispatch(_,this._value))})):(this._flags&j&&!(this._flags&E)&&(this._flags=this._flags&~h|F,this._dispatch(b,v)),this._flags=this._flags&~h|H,this._dispatch(_,this._value))))}signal(e){this._flags&y||!this._output||(e===v?this._flags=this._flags&~h|F:e===G&&(this._flags=this._flags&~h|qe),this._dispatch(b,e))}complete(){if(this._flags&y)return;this._flags=(this._flags|y)&~h|Ge;let e=this._output,n=this._flags&S;if(this._output=null,this._flags&=~(S|E),this._singleDepCount=0,this._stop(),e)if(n)for(let s of e)s(g);else e(g)}error(e){if(this._flags&y)return;this._flags=(this._flags|y)&~h|He;let n=this._output,s=this._flags&S;if(this._output=null,this._flags&=~(S|E),this._singleDepCount=0,this._stop(),n)if(s)for(let r of n)r(g,e);else n(g,e)}_start(){if(this._flags&ne||!this._fn)return;this._flags|=ne,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n),onSignal:n=>{this._onLifecycleSignal=n}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&ne&&(this._flags&=~ne,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&xe&&(this._value=this._initial),this._flags&y||(this._flags=this._flags&~h|se))}_handleLifecycleSignal(e){if(!(this._flags&y)){if(e===de){this._onLifecycleSignal?.(e),this.complete();return}e===fe&&(this._value=this._initial,this._flags&=~k),this._onLifecycleSignal?.(e)}}source(e,n){if(e===m){let s=n;if(this._flags&y)if(this._flags&Re&&this._output===null)this._flags=this._flags&~(y|h)|se;else{s(m,i=>{}),s(g);return}if(this._output===null)this._output=s;else if(this._flags&S)this._output.add(s);else{let i=new Set;i.add(this._output),i.add(s),this._output=i,this._flags=(this._flags|S)&~E}let r=!1;s(m,(i,o)=>{if(i===_&&s(_,this._value),i===b){o===Te&&!r?(r=!0,this._singleDepCount++,this._flags&S||(this._flags|=E)):_e(o)&&this._handleLifecycleSignal(o);return}if(i===g){if(r&&(r=!1,this._singleDepCount--),this._output===null)return;if(this._flags&S){let u=this._output;u.delete(s),u.size===1?(this._output=u.values().next().value,this._flags&=~S,this._singleDepCount>0&&(this._flags|=E)):u.size===0&&(this._output=null,this._flags&=~(S|E),this._singleDepCount=0,this._flags=this._flags&~h|se,this._stop())}else this._output===s&&(this._output=null,this._flags&=~E,this._singleDepCount=0,this._flags=this._flags&~h|se,this._stop())}}),Le(()=>this._start())}}};var pe=class extends re{constructor(e,n){super(void 0,{initial:e,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),N.register(this,{kind:"state",...n})}get(){return this._value}set(e){this._flags&y||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(A()?this._flags&k||(this._flags|=k,this._flags&j&&(this._flags=this._flags&~h|F,this._dispatch(b,v)),te(()=>{this._flags&k&&(this._flags&=~k,this._flags=this._flags&~h|H,this._dispatch(_,this._value))})):(this._flags&j&&!(this._flags&E)&&(this._flags=this._flags&~h|F,this._dispatch(b,v)),this._flags=this._flags&~h|H,this._dispatch(_,this._value))))}update(e){this.set(e(this._value))}};function U(t,e){return new pe(t,e)}function ie(t){return(e,n)=>{if(e!==0)return;let s=new AbortController,r=s.signal,i=!1,o,u;try{o=typeof t=="function"?t():t,u=o[Symbol.asyncIterator]()}catch(f){n(0,()=>{}),n(2,f);return}n(0,f=>{f===2&&!i&&(i=!0,s.abort(),Promise.resolve(u.return?.()).catch(()=>{}))});async function l(){try{for(;!i&&!r.aborted;){let f=await u.next();if(i||r.aborted)break;if(f.done){i=!0,n(2);return}n(1,f.value)}}catch(f){!i&&!r.aborted&&(i=!0,n(2,f))}}l()}}function we(t){return(e,n)=>{if(e!==0)return;let s=!1;n(0,r=>{r===2&&(s=!0)}),t.then(r=>{s||(n(1,r),s||n(2))},r=>{s||n(2,r)})}}function ze(t){return t!=null&&typeof t.then=="function"}function Je(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}function Ze(t){return t!=null&&typeof t[Symbol.iterator]=="function"}function he(t){return ze(t)?we(t):Je(t)?ie(t):typeof t!="string"&&Ze(t)?(e,n)=>{if(e!==0)return;let s=!1;n(0,r=>{r===2&&(s=!0)});for(let r of t){if(s)return;n(1,r)}s||n(2)}:(e,n)=>{if(e!==0)return;let s=!1;n(0,r=>{r===2&&(s=!0)}),s||n(1,t),s||n(2)}}function oe(t,e,n){let s=null;return t(0,(r,i)=>{if(r===0){s=i;return}if(r===2){s=null,n?.onEnd?.(i);return}r===1&&e(i)}),{unsubscribe(){s?.(2),s=null}}}function Qe(t){return t.map(e=>{let n;try{n=JSON.parse(e.arguments)}catch{n=e.arguments}return{id:e.id,tool:e.name,args:n}})}function Xe(t){switch(t){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function et(t,e){switch(t){case"openai":case"custom":return`${e}/chat/completions`;case"ollama":return`${e}/api/chat`;default:return`${e}/chat/completions`}}function tt(t,e,n,s){let r={model:e,messages:n.map(i=>nt(t,i)),stream:!0};return s?.temperature!==void 0&&(r.temperature=s.temperature),s?.maxTokens!==void 0&&(t==="ollama"?r.options={num_predict:s.maxTokens}:r.max_tokens=s.maxTokens),s?.stop&&(r.stop=s.stop),s?.tools&&s.tools.length>0&&(r.tools=s.tools),r}function nt(t,e){let n={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(t==="ollama"?n.tool_calls=e.tool_calls.map(s=>{let r;try{r=JSON.parse(s.arguments)}catch{r={}}return{function:{name:s.name,arguments:r}}}):n.tool_calls=e.tool_calls.map(s=>({id:s.id,type:"function",function:{name:s.name,arguments:s.arguments}}))),e.tool_call_id&&(n.tool_call_id=e.tool_call_id),n}function st(t,e){let n={"Content-Type":"application/json"};return e&&(n.Authorization=`Bearer ${e}`),n}function rt(t){let e=t.name??"llm",n=t.provider,s=t.baseURL??Xe(n),r=t.model??"",i=t.fetch??globalThis.fetch,o=U("",{name:`${e}.store`}),u=U({},{name:`${e}.tokens`}),l=U("pending",{name:`${e}.status`}),f=U(void 0,{name:`${e}.error`}),a=U([],{name:`${e}.toolCalls`}),c=null,d=0,T=0;function q(){c&&(c.abort(),c=null),l.get()==="active"&&x(()=>{o.set(""),a.set([]),l.set("pending")})}function Ce(K,R){q(),c=new AbortController;let z=R?.signal?it(c.signal,R.signal):c.signal;x(()=>{o.set(""),u.set({}),f.set(void 0),a.set([]),l.set("active")});let p=++d;try{let W=et(n,s),I=tt(n,r,K,R),D=st(n,t.apiKey);Oe(W,D,I,z,p)}catch(W){x(()=>{f.set(W),l.set("errored")}),d===p&&(c=null),z._cleanup?.()}}function Oe(K,R,z,p,W){let I=()=>{d===W&&(c=null)};oe(he(i(K,{method:"POST",headers:R,body:JSON.stringify(z),signal:p})),D=>{if(!D.ok){oe(he(D.text().catch(()=>"")),C=>{p.aborted||(x(()=>{f.set(new Error(`LLM API error ${D.status}: ${C}`)),l.set("errored")}),I(),p._cleanup?.())});return}let ae=D.body?.getReader();if(!ae){if(p.aborted){p._cleanup?.();return}x(()=>{f.set(new Error("No response body")),l.set("errored")}),I(),p._cleanup?.();return}let me=new TextDecoder,J="",M="",Z=new Map;oe(ie({[Symbol.asyncIterator](){return{next(){return ae.read()},return(){return ae.cancel(),Promise.resolve({done:!0,value:void 0})}}}}),C=>{if(p.aborted)return;M+=me.decode(C,{stream:!0});let V=M.split(`
5
- `);M=V.pop()??"";for(let Q of V){if(p.aborted)return;let w=Q.trim();if(!w||w.startsWith(":")||!w.startsWith("data: "))continue;let O=w.slice(6);if(O!=="[DONE]")try{let $=JSON.parse(O),Y=Ae(n,$);if(Y&&(J+=Y,o.set(J)),Ie(n,$,Z,()=>`call_${T++}`)){let P=[];for(let[,le]of Z)P.push({id:le.id,name:le.name,arguments:le.arguments});a.set(P)}let B=Me(n,$);B&&u.set(B)}catch{}}},{onEnd:C=>{let V=me.decode();if(V&&(M+=V),M.trim()){let Q=M.trim();if(Q.startsWith("data: ")){let w=Q.slice(6);if(w!=="[DONE]")try{let O=JSON.parse(w),$=Ae(n,O);if($&&(J+=$,o.set(J)),Ie(n,O,Z,()=>`call_${T++}`)){let B=[];for(let[,P]of Z)B.push({id:P.id,name:P.name,arguments:P.arguments});a.set(B)}let Y=Me(n,O);Y&&u.set(Y)}catch{}}}if(p.aborted){p._cleanup?.();return}C!==void 0?x(()=>{f.set(C),l.set("errored")}):l.set("completed"),I(),p._cleanup?.()}})},{onEnd:D=>{if(D!==void 0){if(p.aborted){p._cleanup?.();return}x(()=>{f.set(D),l.set("errored")}),I()}p._cleanup?.()}})}return{get:()=>o.get(),source:(K,R)=>o.source(K,R),tokens:u,status:l,error:f,toolCalls:a,generate:Ce,abort:q}}function Ae(t,e){return t==="ollama"?e?.message?.content:e?.choices?.[0]?.delta?.content}function Ie(t,e,n,s){if(t==="ollama"){let o=e?.message?.tool_calls;if(!Array.isArray(o))return!1;let u=!1;for(let l=0;l<o.length;l++){let a=o[l]?.function;a&&(n.set(l,{id:s?s():`call_${l}`,name:a.name??"",arguments:typeof a.arguments=="string"?a.arguments:JSON.stringify(a.arguments??{})}),u=!0)}return u}let r=e?.choices?.[0]?.delta?.tool_calls;if(!Array.isArray(r))return!1;let i=!1;for(let o of r){let u=o.index??0,l=n.get(u);l||(l={id:"",name:"",arguments:""},n.set(u,l)),o.id&&(l.id=o.id,i=!0),o.function?.name&&(l.name=o.function.name,i=!0),o.function?.arguments&&(l.arguments+=o.function.arguments,i=!0)}return i}function Me(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 it(t,e){let n=new AbortController,s=n.signal;if(t.aborted||e.aborted)return n.abort(),s._cleanup=()=>{},s;let r=()=>{t.removeEventListener("abort",i),e.removeEventListener("abort",i)},i=()=>{n.abort(),r()};return t.addEventListener("abort",i,{once:!0}),e.addEventListener("abort",i,{once:!0}),s._cleanup=r,s}0&&(module.exports={fromLLM,toToolCallRequests});
1
+ "use strict";var ue=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var Fe=(t,e)=>{for(var n in e)ue(t,n,{get:e[n],enumerable:!0})},Ue=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ne(e))!je.call(t,r)&&r!==n&&ue(t,r,{get:()=>e[r],enumerable:!(s=Pe(e,r))||s.enumerable});return t};var Ke=t=>Ue(ue({},"__esModule",{value:!0}),t);var at={};Fe(at,{fromLLM:()=>it,toToolCallRequests:()=>Xe});module.exports=Ke(at);var v=Symbol("DIRTY"),G=Symbol("RESOLVED"),_e=Symbol("SINGLE_DEP"),fe=Symbol("RESET"),We=Symbol("PAUSE"),Ve=Symbol("RESUME"),de=Symbol("TEARDOWN");function ye(t){return t===fe||t===We||t===Ve||t===de}var be=0,Se=1,ve=2,Ee=3,ke=4,De=5,L=7,ge=7<<L,Ye=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function Le(t){return Ye[(t&ge)>>>L]}var T=0,_=1,g=2,b=3,X=0,ee=[],ce=!1;function x(t){X++;let e,n,s=!1;try{e=t()}catch(i){n=i,s=!0}X--;let r;if(X===0&&!ce){ce=!0;try{for(let i=0;i<ee.length;i++)try{ee[i]()}catch(o){r??=o}}finally{ee.length=0,ce=!1}}if(s)throw n;if(r)throw r;return e}function A(){return X>0}function te(t){ee.push(t)}var Be=0,Ge=[];function xe(t){Be>0?Ge.push(t):t()}var j=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(r=>t._names.get(r)??"?").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++,r=n?.name;if(!(r&&!t._usedKeys.has(r)))if(r){let i=t._depSuffix(n?.deps);r=i?`${r}(${i})`:`${r}_${s}`,t._usedKeys.has(r)&&(r=`${r}_${s}`)}else{let i=n?.kind??"store",o=t._depSuffix(n?.deps);r=o?`${i}(${o})`:`${i}_${s}`,t._usedKeys.has(r)&&(r=`${r}_${s}`)}t._usedKeys.add(r),t._keys.set(e,r),t._stores.add(new WeakRef(e))}static registerEdge(e,n){if(!t.enabled)return;let s=t._resolveKey(e),r=t._resolveKey(n),i=t._edges.get(s);i?i.includes(r)||i.push(r):t._edges.set(s,[r])}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 r=s.deref();if(!r){t._stores.delete(s);continue}let i=t._resolveKey(r);n.add(i),e.set(i,t.inspect(r))}for(let[s,r]of t._edges){if(!n.has(s)){t._edges.delete(s),t._usedKeys.delete(s);continue}let i=r.filter(o=>n.has(o));i.length===0?t._edges.delete(s):i.length!==r.length&&t._edges.set(s,i)}return e}static trace(e,n){let s=null,r=e.get();return e.source(T,(i,o)=>{if(i===T&&(s=o),i===g){s=null;return}if(i===1){let u=o;if(!Object.is(u,r)){let l=r;r=u,n(u,l)}}}),()=>s?.(g)}static dumpGraph(){let e=t.graph(),n=t.getEdges(),s=new Map;for(let[o,u]of n)for(let l of u){let f=s.get(l);f?f.includes(o)||f.push(o):s.set(l,[o])}let r=[];for(let[o,u]of e){let l=s.get(o),f=n.get(o),a=l?.length?` \u2190 [${l.join(", ")}]`:"",c=f?.length?` \u2192 [${f.join(", ")}]`:"";r.push(` ${o} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${a}${c}`)}return[`Store Graph (${e.size} nodes):`,...r].join(`
2
+ `)}static _signalLabel(e){return e===v?"DIRTY":e===G?"RESOLVED":typeof e=="symbol"?e.description??String(e):String(e)}static _observe(e,n,s){let r=null,i=!1,o=n??t.getName(e),u=[],l={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return l.ended&&!i},get errored(){return l.ended&&i},dirtyCount:0,resolvedCount:0,name:o,get eventLog(){return u},dispose:()=>r?.(g),reconnect:()=>(r?.(g),t._observe(e,n,s))};return e.source(T,(f,a)=>{if(f===T){r=a;return}let c=A();f===_?(l.values.push(a),l.events.push({type:"data",data:a,inBatch:c}),u.push(a),s&&s(`[${o}] DATA:`,a)):f===b?(l.signals.push(a),l.events.push({type:"signal",data:a,inBatch:c}),u.push(t._signalLabel(a)),a===v?l.dirtyCount++:a===G&&l.resolvedCount++,s&&s(`[${o}] STATE:`,a)):f===g&&(l.ended=!0,l.endError=a,i=a!==void 0,l.events.push({type:"end",data:a,inBatch:c}),u.push(i?["END",a]:"END"),s&&s(`[${o}] END`,a!==void 0?a:""),r=null)}),l}static observe(e){return t._observe(e)}static activate(e){let n=null;return e.source(T,(s,r)=>{s===T&&(n=r),s===g&&(n=null)}),()=>n?.(g)}static tap(e,n){let s=n??`tap(${t.getName(e)??"anon"})`,r={get:()=>e.get(),source:e.source};return t.register(r,{name:s,kind:"tap"}),t.registerEdge(e,r),r}static spy(e,n){let s=n?.name??t.getName(e)??"spy",r=n?.log??console.log;return t._observe(e,s,r)}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 l=t._annotations.get(u);l!==void 0&&s.set(t._resolveKey(u),l)}let r=[];for(let[o,u]of e){let l={name:o,kind:u.kind,value:u.value,status:u.status},f=s.get(o);f!==void 0&&(l.annotation=f),r.push(l)}let i=[];for(let[o,u]of n)for(let l of u)i.push({from:o,to:l});return{nodes:r,edges:i,trace:t.traceLog()}}static toMermaid(e){let n=e?.direction??"TD",s=t.snapshot(),r=[`graph ${n}`],i={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},o=new Map;function u(a){let c=a.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 l=new Map;function f(a){let c=JSON.stringify(a);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let a of s.nodes){let c=u(a.name);l.set(a.name,c);let d=`${a.name} (${a.kind}) = ${f(a.value)}`,h=i[a.status??""]??"";r.push(` ${c}["${d}"]${h}`)}for(let a of s.edges){let c=l.get(a.from)??u(a.from),d=l.get(a.to)??u(a.to);r.push(` ${c} --> ${d}`)}return r.push(""),r.push(" classDef settled fill:#d4edda,stroke:#28a745"),r.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),r.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),r.push(" classDef completed fill:#cce5ff,stroke:#007bff"),r.join(`
3
+ `)}static toD2(e){let n=e?.direction??"down",s=t.snapshot(),r=[`direction: ${n}`,""],i={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,"_"),d=o.get(c);return d===void 0?(o.set(c,1),c):(o.set(c,d+1),`${c}__${d}`)}let l=new Map;function f(a){let c=JSON.stringify(a);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let a of s.nodes){let c=u(a.name);l.set(a.name,c);let d=i[a.kind]??"rectangle",h=`${a.name} (${a.kind}) = ${f(a.value)}`,q=a.status?` [${a.status}]`:"";r.push(`${c}: "${h}${q}" { shape: ${d} }`)}s.edges.length>0&&r.push("");for(let a of s.edges){let c=l.get(a.from)??u(a.from),d=l.get(a.to)??u(a.to);r.push(`${c} -> ${d}`)}return r.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()},r=t.maxTraceEntries;r<=0||(t._traceLog.length<r?t._traceLog.push(s):(t._traceLog[t._traceHead]=s,t._traceFull=!0),t._traceHead=(t._traceHead+1)%r)}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 timeline(e){let n=null,s=[];return e.source(T,(r,i)=>{if(r===T){n=i;return}let o={timestamp:Date.now(),type:r===_?"data":r===b?"signal":"end",data:i,inBatch:A()};s.push(o),r===g&&(n=null)}),{entries:s,dispose:()=>n?.(g)}}static observeDerived(e){let n=[],s=e,r=s._fn;if(typeof r!="function"||!Array.isArray(s._deps))return{...t.observe(e),evaluations:n};s._fn=()=>{let l=s._deps.map(a=>a.get()),f=r();return n.push({result:f,depValues:l,timestamp:Date.now()}),f};let i=t._observe(e),o=i.dispose;return{...i,evaluations:n,dispose:()=>{s._fn=r,o()},reconnect:()=>(s._fn=r,o(),t.observeDerived(e))}}static observeTaskState(e){let n=e.status.get(),s=[],r=null;return e.status.source(T,(i,o)=>{if(i===T){r=o;return}if(i===_){let u=o;if(u!==n){let l={from:n,to:u,timestamp:Date.now()};u==="error"&&(l.error=e.error.get()),s.push(l),n=u}}i===g&&(r=null)}),{transitions:s,get currentStatus(){return e.status.get()},dispose:()=>{r?.(g)}}}static causalityTrace(e){let n=[],s=e,r=s._fn;if(typeof r!="function"||!Array.isArray(s._deps))return{...t.observe(e),causality:n};let i=s._deps,o=i.map(a=>a.get());s._fn=()=>{let a=i.map(h=>h.get()),c=r(),d=-1;for(let h=0;h<i.length;h++)if(!Object.is(a[h],o[h])){d=h;break}return n.push({result:c,triggerDepIndex:d,triggerDepName:d>=0?t.getName(i[d]):void 0,depValues:a,timestamp:Date.now()}),o=a,c};let u=t._observe(e),l=u.dispose;return{...u,causality:n,dispose:()=>{s._fn=r,l()},reconnect:()=>(s._fn=r,l(),t.causalityTrace(e))}}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 ne=1,S=64,y=2,F=4,Re=8,we=16,k=32,E=1024,m=ge,U=Se<<L,H=ve<<L,se=be<<L,He=ke<<L,qe=De<<L,ze=Ee<<L,re=class{_value;_output=null;_flags;get _status(){return Le(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;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|=F),n?.resetOnTeardown&&(s|=Re),n?.resubscribable&&(s|=we),this._flags=s,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||j.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&S)for(let r of s)r(e,n);else s(e,n)}emit(e){this._flags&y||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(A()?this._flags&k||(this._flags|=k,this._flags&F&&(this._flags=this._flags&~m|U,this._dispatch(b,v)),te(()=>{this._flags&k&&(this._flags&=~k,this._flags=this._flags&~m|H,this._dispatch(_,this._value))})):(this._flags&F&&!(this._flags&E)&&(this._flags=this._flags&~m|U,this._dispatch(b,v)),this._flags=this._flags&~m|H,this._dispatch(_,this._value))))}signal(e){this._flags&y||!this._output||(e===v?this._flags=this._flags&~m|U:e===G&&(this._flags=this._flags&~m|ze),this._dispatch(b,e))}complete(){if(this._flags&y)return;this._flags=(this._flags|y)&~m|He;let e=this._output,n=this._flags&S;if(this._output=null,this._flags&=~(S|E),this._singleDepCount=0,this._stop(),e)if(n)for(let s of e)s(g);else e(g)}error(e){if(this._flags&y)return;this._flags=(this._flags|y)&~m|qe;let n=this._output,s=this._flags&S;if(this._output=null,this._flags&=~(S|E),this._singleDepCount=0,this._stop(),n)if(s)for(let r of n)r(g,e);else n(g,e)}_start(){if(this._flags&ne||!this._fn)return;this._flags|=ne,this._onLifecycleSignal=void 0;let e=this._fn({emit:this.emit,signal:n=>this.signal(n),complete:()=>this.complete(),error:n=>this.error(n),onSignal:n=>{this._onLifecycleSignal=n}});this._cleanup=typeof e=="function"?e:void 0}_stop(){this._flags&ne&&(this._flags&=~ne,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&Re&&(this._value=this._initial),this._flags&y||(this._flags=this._flags&~m|se))}_handleLifecycleSignal(e){if(!(this._flags&y)){if(e===de){this._onLifecycleSignal?.(e),this.complete();return}e===fe&&(this._value=this._initial,this._flags&=~k),this._onLifecycleSignal?.(e)}}source(e,n){if(e===T){let s=n;if(this._flags&y)if(this._flags&we&&this._output===null)this._flags=this._flags&~(y|m)|se;else{s(T,i=>{}),s(g);return}if(this._output===null)this._output=s;else if(this._flags&S)this._output.add(s);else{let i=new Set;i.add(this._output),i.add(s),this._output=i,this._flags=(this._flags|S)&~E}let r=!1;s(T,(i,o)=>{if(i===_&&s(_,this._value),i===b){o===_e&&!r?(r=!0,this._singleDepCount++,this._flags&S||(this._flags|=E)):ye(o)&&this._handleLifecycleSignal(o);return}if(i===g){if(r&&(r=!1,this._singleDepCount--),this._output===null)return;if(this._flags&S){let u=this._output;u.delete(s),u.size===1?(this._output=u.values().next().value,this._flags&=~S,this._singleDepCount>0&&(this._flags|=E)):u.size===0&&(this._output=null,this._flags&=~(S|E),this._singleDepCount=0,this._flags=this._flags&~m|se,this._stop())}else this._output===s&&(this._output=null,this._flags&=~E,this._singleDepCount=0,this._flags=this._flags&~m|se,this._stop())}}),xe(()=>this._start())}}};var pe=class extends re{constructor(e,n){super(void 0,{initial:e,autoDirty:!0,equals:n?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),j.register(this,{kind:"state",...n})}get(){return this._value}set(e){this._flags&y||this._value!==void 0&&this._eqFn(this._value,e)||(this._value=e,this._output&&(A()?this._flags&k||(this._flags|=k,this._flags&F&&(this._flags=this._flags&~m|U,this._dispatch(b,v)),te(()=>{this._flags&k&&(this._flags&=~k,this._flags=this._flags&~m|H,this._dispatch(_,this._value))})):(this._flags&F&&!(this._flags&E)&&(this._flags=this._flags&~m|U,this._dispatch(b,v)),this._flags=this._flags&~m|H,this._dispatch(_,this._value))))}update(e){this.set(e(this._value))}};function I(t,e){return new pe(t,e)}function ie(t){return(e,n)=>{if(e!==0)return;let s=new AbortController,r=s.signal,i=!1,o,u;try{o=typeof t=="function"?t():t,u=o[Symbol.asyncIterator]()}catch(f){n(0,()=>{}),n(2,f);return}n(0,f=>{f===2&&!i&&(i=!0,s.abort(),Promise.resolve(u.return?.()).catch(()=>{}))});async function l(){try{for(;!i&&!r.aborted;){let f=await u.next();if(i||r.aborted)break;if(f.done){i=!0,n(2);return}n(1,f.value)}}catch(f){!i&&!r.aborted&&(i=!0,n(2,f))}}l()}}function Ae(t){return(e,n)=>{if(e!==0)return;let s=!1;n(0,r=>{r===2&&(s=!0)}),t.then(r=>{s||(n(1,r),s||n(2))},r=>{s||n(2,r)})}}function Je(t){return t!=null&&typeof t.then=="function"}function Ze(t){return t!=null&&typeof t[Symbol.asyncIterator]=="function"}function Qe(t){return t!=null&&typeof t[Symbol.iterator]=="function"}function me(t){return Je(t)?Ae(t):Ze(t)?ie(t):typeof t!="string"&&Qe(t)?(e,n)=>{if(e!==0)return;let s=!1;n(0,r=>{r===2&&(s=!0)});for(let r of t){if(s)return;n(1,r)}s||n(2)}:(e,n)=>{if(e!==0)return;let s=!1;n(0,r=>{r===2&&(s=!0)}),s||n(1,t),s||n(2)}}function oe(t,e,n){let s=null;return t(0,(r,i)=>{if(r===0){s=i;return}if(r===2){s=null,n?.onEnd?.(i);return}r===1&&e(i)}),{unsubscribe(){s?.(2),s=null}}}function Xe(t){return t.map(e=>{let n;try{n=JSON.parse(e.arguments)}catch{n=e.arguments}return{id:e.id,tool:e.name,args:n}})}function et(t){switch(t){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function tt(t,e){switch(t){case"openai":case"custom":return`${e}/chat/completions`;case"ollama":return`${e}/api/chat`;default:return`${e}/chat/completions`}}function nt(t,e,n,s){let r={model:e,messages:n.map(i=>st(t,i)),stream:!0};return s?.temperature!==void 0&&(r.temperature=s.temperature),s?.maxTokens!==void 0&&(t==="ollama"?r.options={num_predict:s.maxTokens}:r.max_tokens=s.maxTokens),s?.stop&&(r.stop=s.stop),s?.tools&&s.tools.length>0&&(r.tools=s.tools),r}function st(t,e){let n={role:e.role,content:e.content};return e.tool_calls&&e.tool_calls.length>0&&(t==="ollama"?n.tool_calls=e.tool_calls.map(s=>{let r;try{r=JSON.parse(s.arguments)}catch{r={}}return{function:{name:s.name,arguments:r}}}):n.tool_calls=e.tool_calls.map(s=>({id:s.id,type:"function",function:{name:s.name,arguments:s.arguments}}))),e.tool_call_id&&(n.tool_call_id=e.tool_call_id),n}function rt(t,e){let n={"Content-Type":"application/json"};return e&&(n.Authorization=`Bearer ${e}`),n}function it(t){let e=t.name??"llm",n=t.provider,s=t.baseURL??et(n),r=t.model??"",i=t.fetch??globalThis.fetch,o=I("",{name:`${e}.store`}),u=I({},{name:`${e}.tokens`}),l=I("pending",{name:`${e}.status`}),f=I(void 0,{name:`${e}.error`}),a=I([],{name:`${e}.toolCalls`}),c=I(0,{name:`${e}.generationId`}),d=null,h=0,q=0;function he(){d&&(d.abort(),d=null),l.get()==="active"&&x(()=>{o.set(""),a.set([]),l.set("pending")})}function Oe(K,R){he(),d=new AbortController;let z=R?.signal?ot(d.signal,R.signal):d.signal,p=++h;x(()=>{o.set(""),u.set({}),f.set(void 0),a.set([]),c.set(p),l.set("active")});try{let W=tt(n,s),M=nt(n,r,K,R),D=rt(n,t.apiKey);$e(W,D,M,z,p)}catch(W){x(()=>{f.set(W),l.set("errored")}),h===p&&(d=null),z._cleanup?.()}}function $e(K,R,z,p,W){let M=()=>{h===W&&(d=null)};oe(me(i(K,{method:"POST",headers:R,body:JSON.stringify(z),signal:p})),D=>{if(!D.ok){oe(me(D.text().catch(()=>"")),O=>{p.aborted||(x(()=>{f.set(new Error(`LLM API error ${D.status}: ${O}`)),l.set("errored")}),M(),p._cleanup?.())});return}let ae=D.body?.getReader();if(!ae){if(p.aborted){p._cleanup?.();return}x(()=>{f.set(new Error("No response body")),l.set("errored")}),M(),p._cleanup?.();return}let Te=new TextDecoder,J="",C="",Z=new Map;oe(ie({[Symbol.asyncIterator](){return{next(){return ae.read()},return(){return ae.cancel(),Promise.resolve({done:!0,value:void 0})}}}}),O=>{if(p.aborted)return;C+=Te.decode(O,{stream:!0});let V=C.split(`
5
+ `);C=V.pop()??"";for(let Q of V){if(p.aborted)return;let w=Q.trim();if(!w||w.startsWith(":")||!w.startsWith("data: "))continue;let $=w.slice(6);if($!=="[DONE]")try{let P=JSON.parse($),Y=Ie(n,P);if(Y&&(J+=Y,o.set(J)),Me(n,P,Z,()=>`call_${q++}`)){let N=[];for(let[,le]of Z)N.push({id:le.id,name:le.name,arguments:le.arguments});a.set(N)}let B=Ce(n,P);B&&u.set(B)}catch{}}},{onEnd:O=>{let V=Te.decode();if(V&&(C+=V),C.trim()){let Q=C.trim();if(Q.startsWith("data: ")){let w=Q.slice(6);if(w!=="[DONE]")try{let $=JSON.parse(w),P=Ie(n,$);if(P&&(J+=P,o.set(J)),Me(n,$,Z,()=>`call_${q++}`)){let B=[];for(let[,N]of Z)B.push({id:N.id,name:N.name,arguments:N.arguments});a.set(B)}let Y=Ce(n,$);Y&&u.set(Y)}catch{}}}if(p.aborted){p._cleanup?.();return}O!==void 0?x(()=>{f.set(O),l.set("errored")}):l.set("completed"),M(),p._cleanup?.()}})},{onEnd:D=>{if(D!==void 0){if(p.aborted){p._cleanup?.();return}x(()=>{f.set(D),l.set("errored")}),M()}p._cleanup?.()}})}return{get:()=>o.get(),source:(K,R)=>o.source(K,R),tokens:u,status:l,error:f,toolCalls:a,generationId:c,generate:Oe,abort:he}}function Ie(t,e){return t==="ollama"?e?.message?.content:e?.choices?.[0]?.delta?.content}function Me(t,e,n,s){if(t==="ollama"){let o=e?.message?.tool_calls;if(!Array.isArray(o))return!1;let u=!1;for(let l=0;l<o.length;l++){let a=o[l]?.function;a&&(n.set(l,{id:s?s():`call_${l}`,name:a.name??"",arguments:typeof a.arguments=="string"?a.arguments:JSON.stringify(a.arguments??{})}),u=!0)}return u}let r=e?.choices?.[0]?.delta?.tool_calls;if(!Array.isArray(r))return!1;let i=!1;for(let o of r){let u=o.index??0,l=n.get(u);l||(l={id:"",name:"",arguments:""},n.set(u,l)),o.id&&(l.id=o.id,i=!0),o.function?.name&&(l.name=o.function.name,i=!0),o.function?.arguments&&(l.arguments+=o.function.arguments,i=!0)}return i}function Ce(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 ot(t,e){let n=new AbortController,s=n.signal;if(t.aborted||e.aborted)return n.abort(),s._cleanup=()=>{},s;let r=()=>{t.removeEventListener("abort",i),e.removeEventListener("abort",i)},i=()=>{n.abort(),r()};return t.addEventListener("abort",i,{once:!0}),e.addEventListener("abort",i,{once:!0}),s._cleanup=r,s}0&&(module.exports={fromLLM,toToolCallRequests});
@@ -73,6 +73,8 @@ interface LLMStore extends Store<string> {
73
73
  error: Store<unknown | undefined>;
74
74
  /** Tool calls parsed from the last generation (reactive). Empty array when no tool calls. */
75
75
  toolCalls: Store<LLMToolCall[]>;
76
+ /** Monotonically increasing generation nonce. Incremented on each generate() call. */
77
+ generationId: Store<number>;
76
78
  /** Start a generation. Aborts any in-progress generation. */
77
79
  generate: (messages: LLMMessage[], opts?: GenerateOptions) => void;
78
80
  /** Abort the current generation. */
@@ -95,11 +97,12 @@ declare function toToolCallRequests(calls: LLMToolCall[]): Array<{
95
97
  *
96
98
  * @param opts - Provider configuration (provider, baseURL, apiKey, model).
97
99
  *
98
- * @returns `LLMStore` — `Store<string>` with `status`, `error`, `tokens`, `toolCalls` companion stores, plus `generate()` and `abort()`.
100
+ * @returns `LLMStore` — `Store<string>` with `status`, `error`, `tokens`, `toolCalls`, `generationId` companion stores, plus `generate()` and `abort()`.
99
101
  *
100
102
  * @remarks **Provider-agnostic:** Works with OpenAI, Ollama, Anthropic (via proxy), Vercel AI SDK, or any OpenAI-compatible endpoint.
101
103
  * @remarks **No hard deps:** Uses fetch + SSE line parsing. No SDK imports required.
102
104
  * @remarks **Auto-cancel:** Calling `generate()` while streaming aborts the previous generation.
105
+ * @remarks **Generation nonce:** `generationId` is a monotonically increasing `Store<number>` incremented on each `generate()` call. Use it to distinguish stale status emissions from previous generations when subscribing to `status`.
103
106
  * @remarks **Tool calling:** Pass `tools` in `GenerateOptions` to enable function calling. Parsed tool calls accumulate in the `toolCalls` store. Use `toToolCallRequests()` to convert to `ToolCallRequest[]` for `toolRegistry.execute()`.
104
107
  * @remarks **Token tracking:** `tokens` store populated on stream completion (when usage data is available).
105
108
  * @remarks **Status:** Uses WithStatusStatus enum (pending → active → completed/errored) for consistent lifecycle tracking.
@@ -73,6 +73,8 @@ interface LLMStore extends Store<string> {
73
73
  error: Store<unknown | undefined>;
74
74
  /** Tool calls parsed from the last generation (reactive). Empty array when no tool calls. */
75
75
  toolCalls: Store<LLMToolCall[]>;
76
+ /** Monotonically increasing generation nonce. Incremented on each generate() call. */
77
+ generationId: Store<number>;
76
78
  /** Start a generation. Aborts any in-progress generation. */
77
79
  generate: (messages: LLMMessage[], opts?: GenerateOptions) => void;
78
80
  /** Abort the current generation. */
@@ -95,11 +97,12 @@ declare function toToolCallRequests(calls: LLMToolCall[]): Array<{
95
97
  *
96
98
  * @param opts - Provider configuration (provider, baseURL, apiKey, model).
97
99
  *
98
- * @returns `LLMStore` — `Store<string>` with `status`, `error`, `tokens`, `toolCalls` companion stores, plus `generate()` and `abort()`.
100
+ * @returns `LLMStore` — `Store<string>` with `status`, `error`, `tokens`, `toolCalls`, `generationId` companion stores, plus `generate()` and `abort()`.
99
101
  *
100
102
  * @remarks **Provider-agnostic:** Works with OpenAI, Ollama, Anthropic (via proxy), Vercel AI SDK, or any OpenAI-compatible endpoint.
101
103
  * @remarks **No hard deps:** Uses fetch + SSE line parsing. No SDK imports required.
102
104
  * @remarks **Auto-cancel:** Calling `generate()` while streaming aborts the previous generation.
105
+ * @remarks **Generation nonce:** `generationId` is a monotonically increasing `Store<number>` incremented on each `generate()` call. Use it to distinguish stale status emissions from previous generations when subscribing to `status`.
103
106
  * @remarks **Tool calling:** Pass `tools` in `GenerateOptions` to enable function calling. Parsed tool calls accumulate in the `toolCalls` store. Use `toToolCallRequests()` to convert to `ToolCallRequest[]` for `toolRegistry.execute()`.
104
107
  * @remarks **Token tracking:** `tokens` store populated on stream completion (when usage data is available).
105
108
  * @remarks **Status:** Uses WithStatusStatus enum (pending → active → completed/errored) for consistent lifecycle tracking.
@@ -1 +1 @@
1
- import{a,b}from"../chunk-YLOA2CAG.js";import"../chunk-O2PONDZT.js";import"../chunk-J2E7GAMR.js";import"../chunk-4ILN4V4C.js";import"../chunk-Q3HIBGHR.js";import"../chunk-FFYLM7DC.js";import"../chunk-RUSKMKKL.js";import"../chunk-HKNYRLNU.js";import"../chunk-JNSWP6KQ.js";import"../chunk-I7AUKTXE.js";export{b as fromLLM,a as toToolCallRequests};
1
+ import{a,b}from"../chunk-DXM2IC4C.js";import"../chunk-O2PONDZT.js";import"../chunk-J2E7GAMR.js";import"../chunk-4ILN4V4C.js";import"../chunk-Q3HIBGHR.js";import"../chunk-FFYLM7DC.js";import"../chunk-RUSKMKKL.js";import"../chunk-HKNYRLNU.js";import"../chunk-JNSWP6KQ.js";import"../chunk-I7AUKTXE.js";export{b as fromLLM,a as toToolCallRequests};