@callbag-recharge/callbag-recharge 0.25.0 → 0.27.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 (57) hide show
  1. package/dist/ai/docIndex/index.cjs +1 -1
  2. package/dist/ai/docIndex/index.js +1 -1
  3. package/dist/ai/fromLLM.cjs +5 -5
  4. package/dist/ai/fromLLM.d.cts +60 -12
  5. package/dist/ai/fromLLM.d.ts +60 -12
  6. package/dist/ai/fromLLM.js +1 -1
  7. package/dist/ai/index.cjs +23 -20
  8. package/dist/ai/index.d.cts +110 -7
  9. package/dist/ai/index.d.ts +110 -7
  10. package/dist/ai/index.js +12 -9
  11. package/dist/ai/memoryStore/index.d.cts +2 -2
  12. package/dist/ai/memoryStore/index.d.ts +2 -2
  13. package/dist/ai/ragPipeline/index.d.cts +2 -2
  14. package/dist/ai/ragPipeline/index.d.ts +2 -2
  15. package/dist/{backoff-BXsH2Ago.d.cts → backoff-DTxCwT6Y.d.cts} +5 -1
  16. package/dist/{backoff-BXsH2Ago.d.ts → backoff-DTxCwT6Y.d.ts} +5 -1
  17. package/dist/chunk-D3D4V5KM.js +1 -0
  18. package/dist/chunk-DTTBQCH3.js +1 -0
  19. package/dist/chunk-QAHR7EMX.js +2 -0
  20. package/dist/chunk-RAMDA42C.js +1 -0
  21. package/dist/chunk-ULLWFMTO.js +1 -0
  22. package/dist/{circuitBreaker--CJqUJ4u.d.cts → circuitBreaker-D_6HSct4.d.cts} +7 -1
  23. package/dist/{circuitBreaker-eEj1lt8U.d.ts → circuitBreaker-Ne3hUw3t.d.ts} +7 -1
  24. package/dist/data/index.cjs +3 -3
  25. package/dist/data/index.d.cts +2 -2
  26. package/dist/data/index.d.ts +2 -2
  27. package/dist/data/index.js +1 -1
  28. package/dist/{executionLog-EPbLbbSd.d.ts → executionLog-CTa3GpdO.d.ts} +1 -1
  29. package/dist/{executionLog-BIdo4sqy.d.cts → executionLog-DTmkFVng.d.cts} +1 -1
  30. package/dist/memory/index.d.cts +3 -3
  31. package/dist/memory/index.d.ts +3 -3
  32. package/dist/messaging/index.cjs +9 -6
  33. package/dist/messaging/index.d.cts +260 -7
  34. package/dist/messaging/index.d.ts +260 -7
  35. package/dist/messaging/index.js +6 -3
  36. package/dist/orchestrate/executionLogAdapters.node.d.cts +2 -2
  37. package/dist/orchestrate/executionLogAdapters.node.d.ts +2 -2
  38. package/dist/orchestrate/index.cjs +6 -6
  39. package/dist/orchestrate/index.d.cts +131 -10
  40. package/dist/orchestrate/index.d.ts +131 -10
  41. package/dist/orchestrate/index.js +3 -3
  42. package/dist/{types-DbCdOVbw.d.cts → types-Ba0jr02y.d.cts} +1 -1
  43. package/dist/{types-ClmMSIr-.d.ts → types-ClFiOUXg.d.ts} +1 -1
  44. package/dist/{types-BRnNQbJn.d.cts → types-DYpaJ7gP.d.cts} +3 -1
  45. package/dist/{types-XRfOHCPC.d.cts → types-ibw_KZuI.d.cts} +9 -3
  46. package/dist/{types-n54oEEx_.d.ts → types-kbaGU2yR.d.ts} +3 -1
  47. package/dist/{types-CJKW4Ae9.d.ts → types-kdj4VxGp.d.ts} +9 -3
  48. package/dist/utils/index.cjs +9 -9
  49. package/dist/utils/index.d.cts +3 -3
  50. package/dist/utils/index.d.ts +3 -3
  51. package/dist/utils/index.js +6 -6
  52. package/package.json +6 -2
  53. package/dist/chunk-2HSHE2EI.js +0 -1
  54. package/dist/chunk-5UIA6BIQ.js +0 -1
  55. package/dist/chunk-IB56FLRE.js +0 -1
  56. package/dist/chunk-JWQFJJJB.js +0 -2
  57. package/dist/chunk-T5LUMTB7.js +0 -1
@@ -1,4 +1,4 @@
1
1
  "use strict";var ve=Object.create;var U=Object.defineProperty;var Ee=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var xe=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty;var Re=(e,t)=>{for(var i in t)U(e,i,{get:t[i],enumerable:!0})},re=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of De(t))!ke.call(e,n)&&n!==i&&U(e,n,{get:()=>t[n],enumerable:!(s=Ee(t,n))||s.enumerable});return e};var we=(e,t,i)=>(i=e!=null?ve(xe(e)):{},re(t||!e||!e.__esModule?U(i,"default",{value:e,enumerable:!0}):i,e)),Ie=e=>re(U({},"__esModule",{value:!0}),e);var Be={};Re(Be,{docIndex:()=>qe});module.exports=Ie(Be);var x=Symbol("DIRTY"),M=Symbol("RESOLVED"),oe=Symbol("SINGLE_DEP"),W=Symbol("RESET"),Oe=Symbol("PAUSE"),Ae=Symbol("RESUME"),te=Symbol("TEARDOWN");function ae(e){return e===W||e===Oe||e===Ae||e===te}var le=0,ue=1,ce=2,fe=3,de=4,ge=5,w=7,ne=7<<w,Le=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function pe(e){return Le[(e&ne)>>>w]}var T=0,m=1,p=2,v=3,V=0,Y=[],ee=!1;function I(e){V++;try{return e()}finally{if(V--,V===0&&!ee){ee=!0;for(let t=0;t<Y.length;t++)Y[t]();Y.length=0,ee=!1}}}function L(){return V>0}function H(e){Y.push(e)}var $e=0,Pe=[];function he(e){$e>0?Pe.push(e):e()}function G(e){let t=e;typeof t.complete=="function"?t.complete():typeof t._handleEnd=="function"&&t._handleEnd(void 0)}var P=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 s=t.map(n=>e._names.get(n)??"?").join(",");return s.length>40?`${s.slice(0,37)}...`:s}static _resolveKey(t){let i=e._keys.get(t)??e._names.get(t);if(i)return i;let s=`anonymous_${e._nextId++}`;return e._keys.set(t,s),s}static register(t,i){if(!e.enabled)return;i?.name&&e._names.set(t,i.name),i?.kind&&e._kinds.set(t,i.kind);let s=e._nextId++,n=i?.name;if(!(n&&!e._usedKeys.has(n)))if(n){let r=e._depSuffix(i?.deps);n=r?`${n}(${r})`:`${n}_${s}`,e._usedKeys.has(n)&&(n=`${n}_${s}`)}else{let r=i?.kind??"store",o=e._depSuffix(i?.deps);n=o?`${r}(${o})`:`${r}_${s}`,e._usedKeys.has(n)&&(n=`${n}_${s}`)}e._usedKeys.add(n),e._keys.set(t,n),e._stores.add(new WeakRef(t))}static registerEdge(t,i){if(!e.enabled)return;let s=e._resolveKey(t),n=e._resolveKey(i),r=e._edges.get(s);r?r.includes(n)||r.push(n):e._edges.set(s,[n])}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,i=new Set;for(let s of e._stores){let n=s.deref();if(!n){e._stores.delete(s);continue}let r=e._resolveKey(n);i.add(r),t.set(r,e.inspect(n))}for(let[s,n]of e._edges){if(!i.has(s)){e._edges.delete(s),e._usedKeys.delete(s);continue}let r=n.filter(o=>i.has(o));r.length===0?e._edges.delete(s):r.length!==n.length&&e._edges.set(s,r)}return t}static trace(t,i){let s=null,n=t.get();return t.source(T,(r,o)=>{if(r===T&&(s=o),r===p){s=null;return}if(r===1){let l=o;if(!Object.is(l,n)){let u=n;n=l,i(l,u)}}}),()=>s?.(p)}static dumpGraph(){let t=e.graph(),i=e.getEdges(),s=new Map;for(let[o,l]of i)for(let u of l){let f=s.get(u);f?f.includes(o)||f.push(o):s.set(u,[o])}let n=[];for(let[o,l]of t){let u=s.get(o),f=i.get(o),a=u?.length?` \u2190 [${u.join(", ")}]`:"",c=f?.length?` \u2192 [${f.join(", ")}]`:"";n.push(` ${o} (${l.kind}) = ${JSON.stringify(l.value)} [${l.status??"?"}]${a}${c}`)}return[`Store Graph (${t.size} nodes):`,...n].join(`
2
2
  `)}static _signalLabel(t){return t===x?"DIRTY":t===M?"RESOLVED":typeof t=="symbol"?t.description??String(t):String(t)}static _observe(t,i,s){let n=null,r=!1,o=i??e.getName(t),l=[],u={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return u.ended&&!r},get errored(){return u.ended&&r},dirtyCount:0,resolvedCount:0,name:o,get eventLog(){return l},dispose:()=>n?.(p),reconnect:()=>(n?.(p),e._observe(t,i,s))};return t.source(T,(f,a)=>{if(f===T){n=a;return}let c=L();f===m?(u.values.push(a),u.events.push({type:"data",data:a,inBatch:c}),l.push(a),s&&s(`[${o}] DATA:`,a)):f===v?(u.signals.push(a),u.events.push({type:"signal",data:a,inBatch:c}),l.push(e._signalLabel(a)),a===x?u.dirtyCount++:a===M&&u.resolvedCount++,s&&s(`[${o}] STATE:`,a)):f===p&&(u.ended=!0,u.endError=a,r=a!==void 0,u.events.push({type:"end",data:a,inBatch:c}),l.push(r?["END",a]:"END"),s&&s(`[${o}] END`,a!==void 0?a:""),n=null)}),u}static observe(t){return e._observe(t)}static activate(t){let i=null;return t.source(T,(s,n)=>{s===T&&(i=n),s===p&&(i=null)}),()=>i?.(p)}static tap(t,i){let s=i??`tap(${e.getName(t)??"anon"})`,n={get:()=>t.get(),source:t.source};return e.register(n,{name:s,kind:"tap"}),e.registerEdge(t,n),n}static spy(t,i){let s=i?.name??e.getName(t)??"spy",n=i?.log??console.log;return e._observe(t,s,n)}static snapshot(){let t=e.graph(),i=e.getEdges(),s=new Map;for(let o of e._stores){let l=o.deref();if(!l)continue;let u=e._annotations.get(l);u!==void 0&&s.set(e._resolveKey(l),u)}let n=[];for(let[o,l]of t){let u={name:o,kind:l.kind,value:l.value,status:l.status},f=s.get(o);f!==void 0&&(u.annotation=f),n.push(u)}let r=[];for(let[o,l]of i)for(let u of l)r.push({from:o,to:u});return{nodes:n,edges:r,trace:e.traceLog()}}static toMermaid(t){let i=t?.direction??"TD",s=e.snapshot(),n=[`graph ${i}`],r={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},o=new Map;function l(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 u=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=l(a.name);u.set(a.name,c);let d=`${a.name} (${a.kind}) = ${f(a.value)}`,y=r[a.status??""]??"";n.push(` ${c}["${d}"]${y}`)}for(let a of s.edges){let c=u.get(a.from)??l(a.from),d=u.get(a.to)??l(a.to);n.push(` ${c} --> ${d}`)}return n.push(""),n.push(" classDef settled fill:#d4edda,stroke:#28a745"),n.push(" classDef dirty fill:#fff3cd,stroke:#ffc107"),n.push(" classDef errored fill:#f8d7da,stroke:#dc3545"),n.push(" classDef completed fill:#cce5ff,stroke:#007bff"),n.join(`
3
3
  `)}static toD2(t){let i=t?.direction??"down",s=e.snapshot(),n=[`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 l(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 u=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=l(a.name);u.set(a.name,c);let d=r[a.kind]??"rectangle",y=`${a.name} (${a.kind}) = ${f(a.value)}`,_=a.status?` [${a.status}]`:"";n.push(`${c}: "${y}${_}" { shape: ${d} }`)}s.edges.length>0&&n.push("");for(let a of s.edges){let c=u.get(a.from)??l(a.from),d=u.get(a.to)??l(a.to);n.push(`${c} -> ${d}`)}return n.join(`
4
- `)}static annotate(t,i){if(!e.enabled)return;e._annotations.set(t,i);let s={node:e._resolveKey(t),reason:i,timestamp:Date.now()},n=e.maxTraceEntries;n<=0||(e._traceLog.length<n?e._traceLog.push(s):(e._traceLog[e._traceHead]=s,e._traceFull=!0),e._traceHead=(e._traceHead+1)%n)}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 timeline(t){let i=null,s=[];return t.source(T,(n,r)=>{if(n===T){i=r;return}let o={timestamp:Date.now(),type:n===m?"data":n===v?"signal":"end",data:r,inBatch:L()};s.push(o),n===p&&(i=null)}),{entries:s,dispose:()=>i?.(p)}}static observeDerived(t){let i=[],s=t,n=s._fn;if(typeof n!="function"||!Array.isArray(s._deps))return{...e.observe(t),evaluations:i};s._fn=()=>{let u=s._deps.map(a=>a.get()),f=n();return i.push({result:f,depValues:u,timestamp:Date.now()}),f};let r=e._observe(t),o=r.dispose;return{...r,evaluations:i,dispose:()=>{s._fn=n,o()},reconnect:()=>(s._fn=n,o(),e.observeDerived(t))}}static observeTaskState(t){let i=t.status.get(),s=[],n=null;return t.status.source(T,(r,o)=>{if(r===T){n=o;return}if(r===m){let l=o;if(l!==i){let u={from:i,to:l,timestamp:Date.now()};l==="error"&&(u.error=t.error.get()),s.push(u),i=l}}r===p&&(n=null)}),{transitions:s,get currentStatus(){return t.status.get()},dispose:()=>{n?.(p)}}}static causalityTrace(t){let i=[],s=t,n=s._fn;if(typeof n!="function"||!Array.isArray(s._deps))return{...e.observe(t),causality:i};let r=s._deps,o=r.map(a=>a.get());s._fn=()=>{let a=r.map(y=>y.get()),c=n(),d=-1;for(let y=0;y<r.length;y++)if(!Object.is(a[y],o[y])){d=y;break}return i.push({result:c,triggerDepIndex:d,triggerDepName:d>=0?e.getName(r[d]):void 0,depValues:a,timestamp:Date.now()}),o=a,c};let l=e._observe(t),u=l.dispose;return{...l,causality:i,dispose:()=>{s._fn=n,u()},reconnect:()=>(s._fn=n,u(),e.causalityTrace(t))}}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 z=1,E=64,S=2,C=4,Te=8,_e=16,A=32,k=1024,h=ne,N=ue<<w,F=ce<<w,J=le<<w,Ce=de<<w,Ne=ge<<w,Me=fe<<w,Z=class{_value;_output=null;_flags;get _status(){return pe(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(t,i){this._value=i?.initial,this._fn=t,this._eqFn=i?.equals,this._getterFn=i?.getter,this._initial=i?.initial;let s=0;i?.autoDirty!==!1&&(s|=C),i?.resetOnTeardown&&(s|=Te),i?.resubscribable&&(s|=_e),this._flags=s,this.source=this.source.bind(this),this.emit=this.emit.bind(this),i?._skipInspect||P.register(this,{kind:"producer",...i})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(t,i){let s=this._output;if(s)if(this._flags&E)for(let n of s)n(t,i);else s(t,i)}emit(t){this._flags&S||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(L()?this._flags&A||(this._flags|=A,this._flags&C&&(this._flags=this._flags&~h|N,this._dispatch(v,x)),H(()=>{this._flags&=~A,this._flags=this._flags&~h|F,this._dispatch(m,this._value)})):(this._flags&C&&!(this._flags&k)&&(this._flags=this._flags&~h|N,this._dispatch(v,x)),this._flags=this._flags&~h|F,this._dispatch(m,this._value))))}signal(t){this._flags&S||!this._output||(t===x?this._flags=this._flags&~h|N:t===M&&(this._flags=this._flags&~h|Me),this._dispatch(v,t))}complete(){if(this._flags&S)return;this._flags=(this._flags|S)&~h|Ce;let t=this._output,i=this._flags&E;if(this._output=null,this._flags&=~(E|k),this._singleDepCount=0,this._stop(),t)if(i)for(let s of t)s(p);else t(p)}error(t){if(this._flags&S)return;this._flags=(this._flags|S)&~h|Ne;let i=this._output,s=this._flags&E;if(this._output=null,this._flags&=~(E|k),this._singleDepCount=0,this._stop(),i)if(s)for(let n of i)n(p,t);else i(p,t)}_start(){if(this._flags&z||!this._fn)return;this._flags|=z,this._onLifecycleSignal=void 0;let t=this._fn({emit:this.emit,signal:i=>this.signal(i),complete:()=>this.complete(),error:i=>this.error(i),onSignal:i=>{this._onLifecycleSignal=i}});this._cleanup=typeof t=="function"?t:void 0}_stop(){this._flags&z&&(this._flags&=~z,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&Te&&(this._value=this._initial),this._flags&S||(this._flags=this._flags&~h|J))}_handleLifecycleSignal(t){if(!(this._flags&S)){if(t===te){this._onLifecycleSignal?.(t),this.complete();return}t===W&&(this._value=this._initial,this._flags&=~A),this._onLifecycleSignal?.(t),t===W&&this.emit(this._initial)}}source(t,i){if(t===T){let s=i;if(this._flags&S)if(this._flags&_e&&this._output===null)this._flags=this._flags&~(S|h)|J;else{s(T,r=>{}),s(p);return}if(this._output===null)this._output=s;else if(this._flags&E)this._output.add(s);else{let r=new Set;r.add(this._output),r.add(s),this._output=r,this._flags=(this._flags|E)&~k}let n=!1;s(T,(r,o)=>{if(r===m&&s(m,this._value),r===v){o===oe&&!n?(n=!0,this._singleDepCount++,this._flags&E||(this._flags|=k)):ae(o)&&this._handleLifecycleSignal(o);return}if(r===p){if(n&&(n=!1,this._singleDepCount--),this._output===null)return;if(this._flags&E){let l=this._output;l.delete(s),l.size===1?(this._output=l.values().next().value,this._flags&=~E,this._singleDepCount>0&&(this._flags|=k)):l.size===0&&(this._output=null,this._flags&=~(E|k),this._singleDepCount=0,this._flags=this._flags&~h|J,this._stop())}else this._output===s&&(this._output=null,this._flags&=~k,this._singleDepCount=0,this._flags=this._flags&~h|J,this._stop())}}),he(()=>this._start())}}};var se=class extends Z{constructor(t,i){super(void 0,{initial:t,autoDirty:!0,equals:i?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),P.register(this,{kind:"state",...i})}get(){return this._value}set(t){this._flags&S||this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(L()?this._flags&A||(this._flags|=A,this._flags&C&&(this._flags=this._flags&~h|N,this._dispatch(v,x)),H(()=>{this._flags&=~A,this._flags=this._flags&~h|F,this._dispatch(m,this._value)})):(this._flags&C&&!(this._flags&k)&&(this._flags=this._flags&~h|N,this._dispatch(v,x)),this._flags=this._flags&~h|F,this._dispatch(m,this._value))))}update(t){this.set(t(this._value))}};function Q(e,t){return new se(e,t)}function ye(e){return(t,i)=>{if(t!==0)return;let s=new AbortController,n=s.signal,r=!1,o,l;try{o=typeof e=="function"?e():e,l=o[Symbol.asyncIterator]()}catch(f){i(0,()=>{}),i(2,f);return}i(0,f=>{f===2&&!r&&(r=!0,s.abort(),Promise.resolve(l.return?.()).catch(()=>{}))});async function u(){try{for(;!r&&!n.aborted;){let f=await l.next();if(r||n.aborted)break;if(f.done){r=!0,i(2);return}i(1,f.value)}}catch(f){!r&&!n.aborted&&(r=!0,i(2,f))}}u()}}function me(e){return(t,i)=>{if(t!==0)return;let s=!1;i(0,n=>{n===2&&(s=!0)}),e.then(n=>{s||(i(1,n),s||i(2))},n=>{s||i(2,n)})}}function Fe(e){return e!=null&&typeof e.then=="function"}function je(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}function Ke(e){return e!=null&&typeof e[Symbol.iterator]=="function"}function j(e){return Fe(e)?me(e):je(e)?ye(e):typeof e!="string"&&Ke(e)?(t,i)=>{if(t!==0)return;let s=!1;i(0,n=>{n===2&&(s=!0)});for(let n of e){if(s)return;i(1,n)}s||i(2)}:(t,i)=>{if(t!==0)return;let s=!1;i(0,n=>{n===2&&(s=!0)}),s||i(1,e),s||i(2)}}function K(e,t,i){let s=null;return e(0,(n,r)=>{if(n===0){s=r;return}if(n===2){s=null,i?.onEnd?.(r);return}n===1&&t(r)}),{unsubscribe(){s?.(2),s=null}}}function qe(e){let t=typeof e.db=="string"?e.db:e.db.href,i=e.limit??10,s=e.fetch??globalThis.fetch,n=Q([],{name:e.name?`${e.name}.results`:void 0}),r=Q(!1,{name:e.name?`${e.name}.loaded`:void 0}),o=Q(void 0,{name:e.name?`${e.name}.error`:void 0}),l=null,u=null,f=!1;e._sqlite?(l=e._sqlite,a()):c();function a(){K(j(s(t)),_=>{if(!_.ok){f||I(()=>{r.set(!1),o.set(new Error(`Failed to fetch DB: ${_.status} ${_.statusText}`))});return}f||(u=l.open_v2("docs.db"),I(()=>{r.set(!0),o.set(void 0)}))},{onEnd:_=>{_!==void 0&&!f&&I(()=>{r.set(!1),o.set(_)})}})}function c(){let _=null,O=null,X=null,q=2,b=!1;function D(g){b||(b=!0,f||I(()=>{r.set(!1),o.set(g)}))}function B(){if(q--,q>0||b||f)return;let{SQLiteAPI:g}=_;l=g(O);let R=O.vfs;R&&typeof R.writeFile=="function"&&R.writeFile("docs.db",new Uint8Array(X)),u=l.open_v2("docs.db"),I(()=>{r.set(!0),o.set(void 0)})}K(j(import("@aspect-build/wa-sqlite")),g=>{_=g;let R=g.default??g;K(j(typeof R=="function"?R():R),$=>{O=$,B()},{onEnd:$=>{$!==void 0&&D($)}})},{onEnd:g=>{g!==void 0&&D(g)}}),K(j(s(t).then(g=>{if(!g.ok)throw new Error(`Failed to fetch DB: ${g.status} ${g.statusText}`);return g.arrayBuffer()})),g=>{X=g,B()},{onEnd:g=>{g!==void 0&&D(g)}})}function d(_){if(!l||u===null||f){n.set([]);return}if(!_.trim()){n.set([]);return}try{let O=[],q=`SELECT id, title, snippet(docs, 1, '<mark>', '</mark>', '\u2026', 32) as excerpt, rank, source, tags FROM docs WHERE docs MATCH '"${_.replace(/"/g,'""')}"' ORDER BY rank LIMIT ${i}`;l.exec(u,q,(b,D)=>{let B=D.indexOf("id"),g=D.indexOf("title"),R=D.indexOf("excerpt"),$=D.indexOf("rank"),Se=D.indexOf("source"),ie=D.indexOf("tags");O.push({id:String(b[B]??""),title:String(b[g]??""),excerpt:String(b[R]??""),score:Number(b[$]??0),source:String(b[Se]??""),tags:b[ie]?String(b[ie]).split(",").map(be=>be.trim()).filter(Boolean):[]})}),I(()=>{n.set(O),o.set(void 0)})}catch(O){I(()=>{n.set([]),o.set(O)})}}function y(){if(f=!0,l&&u!==null)try{l.close(u)}catch{}l=null,u=null,I(()=>{r.set(!1),n.set([]),o.set(void 0)}),G(n),G(r),G(o)}return{search:d,results:n,loaded:r,error:o,destroy:y}}0&&(module.exports={docIndex});
4
+ `)}static annotate(t,i){if(!e.enabled)return;e._annotations.set(t,i);let s={node:e._resolveKey(t),reason:i,timestamp:Date.now()},n=e.maxTraceEntries;n<=0||(e._traceLog.length<n?e._traceLog.push(s):(e._traceLog[e._traceHead]=s,e._traceFull=!0),e._traceHead=(e._traceHead+1)%n)}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 timeline(t){let i=null,s=[];return t.source(T,(n,r)=>{if(n===T){i=r;return}let o={timestamp:Date.now(),type:n===m?"data":n===v?"signal":"end",data:r,inBatch:L()};s.push(o),n===p&&(i=null)}),{entries:s,dispose:()=>i?.(p)}}static observeDerived(t){let i=[],s=t,n=s._fn;if(typeof n!="function"||!Array.isArray(s._deps))return{...e.observe(t),evaluations:i};s._fn=()=>{let u=s._deps.map(a=>a.get()),f=n();return i.push({result:f,depValues:u,timestamp:Date.now()}),f};let r=e._observe(t),o=r.dispose;return{...r,evaluations:i,dispose:()=>{s._fn=n,o()},reconnect:()=>(s._fn=n,o(),e.observeDerived(t))}}static observeTaskState(t){let i=t.status.get(),s=[],n=null;return t.status.source(T,(r,o)=>{if(r===T){n=o;return}if(r===m){let l=o;if(l!==i){let u={from:i,to:l,timestamp:Date.now()};l==="error"&&(u.error=t.error.get()),s.push(u),i=l}}r===p&&(n=null)}),{transitions:s,get currentStatus(){return t.status.get()},dispose:()=>{n?.(p)}}}static causalityTrace(t){let i=[],s=t,n=s._fn;if(typeof n!="function"||!Array.isArray(s._deps))return{...e.observe(t),causality:i};let r=s._deps,o=r.map(a=>a.get());s._fn=()=>{let a=r.map(y=>y.get()),c=n(),d=-1;for(let y=0;y<r.length;y++)if(!Object.is(a[y],o[y])){d=y;break}return i.push({result:c,triggerDepIndex:d,triggerDepName:d>=0?e.getName(r[d]):void 0,depValues:a,timestamp:Date.now()}),o=a,c};let l=e._observe(t),u=l.dispose;return{...l,causality:i,dispose:()=>{s._fn=n,u()},reconnect:()=>(s._fn=n,u(),e.causalityTrace(t))}}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 z=1,E=64,S=2,C=4,Te=8,_e=16,A=32,k=1024,h=ne,N=ue<<w,F=ce<<w,J=le<<w,Ce=de<<w,Ne=ge<<w,Me=fe<<w,Z=class{_value;_output=null;_flags;get _status(){return pe(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(t,i){this._value=i?.initial,this._fn=t,this._eqFn=i?.equals,this._getterFn=i?.getter,this._initial=i?.initial;let s=0;i?.autoDirty!==!1&&(s|=C),i?.resetOnTeardown&&(s|=Te),i?.resubscribable&&(s|=_e),this._flags=s,this.source=this.source.bind(this),this.emit=this.emit.bind(this),i?._skipInspect||P.register(this,{kind:"producer",...i})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(t,i){let s=this._output;if(s)if(this._flags&E)for(let n of s)n(t,i);else s(t,i)}emit(t){this._flags&S||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(L()?this._flags&A||(this._flags|=A,this._flags&C&&(this._flags=this._flags&~h|N,this._dispatch(v,x)),H(()=>{this._flags&=~A,this._flags=this._flags&~h|F,this._dispatch(m,this._value)})):(this._flags&C&&!(this._flags&k)&&(this._flags=this._flags&~h|N,this._dispatch(v,x)),this._flags=this._flags&~h|F,this._dispatch(m,this._value))))}signal(t){this._flags&S||!this._output||(t===x?this._flags=this._flags&~h|N:t===M&&(this._flags=this._flags&~h|Me),this._dispatch(v,t))}complete(){if(this._flags&S)return;this._flags=(this._flags|S)&~h|Ce;let t=this._output,i=this._flags&E;if(this._output=null,this._flags&=~(E|k),this._singleDepCount=0,this._stop(),t)if(i)for(let s of t)s(p);else t(p)}error(t){if(this._flags&S)return;this._flags=(this._flags|S)&~h|Ne;let i=this._output,s=this._flags&E;if(this._output=null,this._flags&=~(E|k),this._singleDepCount=0,this._stop(),i)if(s)for(let n of i)n(p,t);else i(p,t)}_start(){if(this._flags&z||!this._fn)return;this._flags|=z,this._onLifecycleSignal=void 0;let t=this._fn({emit:this.emit,signal:i=>this.signal(i),complete:()=>this.complete(),error:i=>this.error(i),onSignal:i=>{this._onLifecycleSignal=i}});this._cleanup=typeof t=="function"?t:void 0}_stop(){this._flags&z&&(this._flags&=~z,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&Te&&(this._value=this._initial),this._flags&S||(this._flags=this._flags&~h|J))}_handleLifecycleSignal(t){if(!(this._flags&S)){if(t===te){this._onLifecycleSignal?.(t),this.complete();return}t===W&&(this._value=this._initial,this._flags&=~A),this._onLifecycleSignal?.(t),t===W&&this.emit(this._initial)}}source(t,i){if(t===T){let s=i;if(this._flags&S)if(this._flags&_e&&this._output===null)this._flags=this._flags&~(S|h)|J;else{s(T,r=>{}),s(p);return}if(this._output===null)this._output=s;else if(this._flags&E)this._output.add(s);else{let r=new Set;r.add(this._output),r.add(s),this._output=r,this._flags=(this._flags|E)&~k}let n=!1;s(T,(r,o)=>{if(r===m&&s(m,this._value),r===v){o===oe&&!n?(n=!0,this._singleDepCount++,this._flags&E||(this._flags|=k)):ae(o)&&this._handleLifecycleSignal(o);return}if(r===p){if(n&&(n=!1,this._singleDepCount--),this._output===null)return;if(this._flags&E){let l=this._output;l.delete(s),l.size===1?(this._output=l.values().next().value,this._flags&=~E,this._singleDepCount>0&&(this._flags|=k)):l.size===0&&(this._output=null,this._flags&=~(E|k),this._singleDepCount=0,this._flags=this._flags&~h|J,this._stop())}else this._output===s&&(this._output=null,this._flags&=~k,this._singleDepCount=0,this._flags=this._flags&~h|J,this._stop())}}),he(()=>this._start())}}};var se=class extends Z{constructor(t,i){super(void 0,{initial:t,autoDirty:!0,equals:i?.equals??Object.is,_skipInspect:!0}),this.set=this.set.bind(this),P.register(this,{kind:"state",...i})}get(){return this._value}set(t){this._flags&S||this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(L()?this._flags&A||(this._flags|=A,this._flags&C&&(this._flags=this._flags&~h|N,this._dispatch(v,x)),H(()=>{this._flags&=~A,this._flags=this._flags&~h|F,this._dispatch(m,this._value)})):(this._flags&C&&!(this._flags&k)&&(this._flags=this._flags&~h|N,this._dispatch(v,x)),this._flags=this._flags&~h|F,this._dispatch(m,this._value))))}update(t){this.set(t(this._value))}};function Q(e,t){return new se(e,t)}function ye(e){return(t,i)=>{if(t!==0)return;let s=new AbortController,n=s.signal,r=!1,o,l;try{o=typeof e=="function"?e():e,l=o[Symbol.asyncIterator]()}catch(f){i(0,()=>{}),i(2,f);return}i(0,f=>{f===2&&!r&&(r=!0,s.abort(),Promise.resolve(l.return?.()).catch(()=>{}))});async function u(){try{for(;!r&&!n.aborted;){let f=await l.next();if(r||n.aborted)break;if(f.done){r=!0,i(2);return}i(1,f.value)}}catch(f){!r&&!n.aborted&&(r=!0,i(2,f))}}u()}}function me(e){return(t,i)=>{if(t!==0)return;let s=!1;i(0,n=>{n===2&&(s=!0)}),e.then(n=>{s||(i(1,n),s||i(2))},n=>{s||i(2,n)})}}function Fe(e){return e!=null&&typeof e.then=="function"}function je(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}function Ke(e){return e!=null&&typeof e[Symbol.iterator]=="function"}function j(e){return Fe(e)?me(e):je(e)?ye(e):typeof e!="string"&&Ke(e)?(t,i)=>{if(t!==0)return;let s=!1;i(0,n=>{n===2&&(s=!0)});for(let n of e){if(s)return;i(1,n)}s||i(2)}:(t,i)=>{if(t!==0)return;let s=!1;i(0,n=>{n===2&&(s=!0)}),s||i(1,e),s||i(2)}}function K(e,t,i){let s=null;return e(0,(n,r)=>{if(n===0){s=r;return}if(n===2){s=null,i?.onEnd?.(r);return}n===1&&t(r)}),{unsubscribe(){s?.(2),s=null}}}function qe(e){let t=typeof e.db=="string"?e.db:e.db.href,i=e.limit??10,s=e.fetch??globalThis.fetch,n=Q([],{name:e.name?`${e.name}.results`:void 0}),r=Q(!1,{name:e.name?`${e.name}.loaded`:void 0}),o=Q(void 0,{name:e.name?`${e.name}.error`:void 0}),l=null,u=null,f=!1;e._sqlite?(l=e._sqlite,a()):c();function a(){K(j(s(t)),_=>{if(!_.ok){f||I(()=>{r.set(!1),o.set(new Error(`Failed to fetch DB: ${_.status} ${_.statusText}`))});return}f||(u=l.open_v2("docs.db"),I(()=>{r.set(!0),o.set(void 0)}))},{onEnd:_=>{_!==void 0&&!f&&I(()=>{r.set(!1),o.set(_)})}})}function c(){let _=null,O=null,X=null,q=2,b=!1;function D(g){b||(b=!0,f||I(()=>{r.set(!1),o.set(g)}))}function B(){if(q--,q>0||b||f)return;let{SQLiteAPI:g}=_;l=g(O);let R=O.vfs;R&&typeof R.writeFile=="function"&&R.writeFile("docs.db",new Uint8Array(X)),u=l.open_v2("docs.db"),I(()=>{r.set(!0),o.set(void 0)})}K(j(import("@aspect-build/wa-sqlite")),g=>{_=g;let R=g.default??g;K(j(typeof R=="function"?R():R),$=>{O=$,B()},{onEnd:$=>{$!==void 0&&D($)}})},{onEnd:g=>{g!==void 0&&D(g)}}),K(j(s(t).then(g=>{if(!g.ok)throw new Error(`Failed to fetch DB: ${g.status} ${g.statusText}`);return g.arrayBuffer()})),g=>{X=g,B()},{onEnd:g=>{g!==void 0&&D(g)}})}function d(_){if(!l||u===null||f){n.set([]);return}if(!_.trim()){n.set([]);return}try{let O=[],q=`SELECT rowid as id, title, snippet(docs, 1, '<mark>', '</mark>', '\u2026', 32) as excerpt, rank, source, tags FROM docs WHERE docs MATCH '"${_.replace(/"/g,'""')}"' ORDER BY rank LIMIT ${i}`;l.exec(u,q,(b,D)=>{let B=D.indexOf("id"),g=D.indexOf("title"),R=D.indexOf("excerpt"),$=D.indexOf("rank"),Se=D.indexOf("source"),ie=D.indexOf("tags");O.push({id:String(b[B]??""),title:String(b[g]??""),excerpt:String(b[R]??""),score:Number(b[$]??0),source:String(b[Se]??""),tags:b[ie]?String(b[ie]).split(",").map(be=>be.trim()).filter(Boolean):[]})}),I(()=>{n.set(O),o.set(void 0)})}catch(O){I(()=>{n.set([]),o.set(O)})}}function y(){if(!f){if(f=!0,l&&u!==null)try{l.close(u)}catch{}l=null,u=null,I(()=>{r.set(!1),n.set([]),o.set(void 0)}),G(n),G(r),G(o)}}return{search:d,results:n,loaded:r,error:o,destroy:y}}0&&(module.exports={docIndex});
@@ -1 +1 @@
1
- import{a}from"../../chunk-T5LUMTB7.js";import"../../chunk-O2PONDZT.js";import"../../chunk-J2E7GAMR.js";import"../../chunk-4ILN4V4C.js";import"../../chunk-Q3HIBGHR.js";import"../../chunk-EAK2HKAD.js";import"../../chunk-2F6QWERG.js";import"../../chunk-2L6223KN.js";import"../../chunk-TUPD47IE.js";import"../../chunk-I7AUKTXE.js";export{a as docIndex};
1
+ import{a}from"../../chunk-DTTBQCH3.js";import"../../chunk-O2PONDZT.js";import"../../chunk-J2E7GAMR.js";import"../../chunk-4ILN4V4C.js";import"../../chunk-Q3HIBGHR.js";import"../../chunk-EAK2HKAD.js";import"../../chunk-2F6QWERG.js";import"../../chunk-2L6223KN.js";import"../../chunk-TUPD47IE.js";import"../../chunk-I7AUKTXE.js";export{a as docIndex};
@@ -1,5 +1,5 @@
1
- "use strict";var Z=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var De=Object.getOwnPropertyNames;var xe=Object.prototype.hasOwnProperty;var Le=(e,t)=>{for(var n in t)Z(e,n,{get:t[n],enumerable:!0})},Re=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of De(t))!xe.call(e,r)&&r!==n&&Z(e,r,{get:()=>t[r],enumerable:!(s=ke(t,r))||s.enumerable});return e};var we=e=>Re(Z({},"__esModule",{value:!0}),e);var ze={};Le(ze,{fromLLM:()=>Be});module.exports=we(ze);var v=Symbol("DIRTY"),C=Symbol("RESOLVED"),ce=Symbol("SINGLE_DEP"),W=Symbol("RESET"),Ae=Symbol("PAUSE"),Ie=Symbol("RESUME"),X=Symbol("TEARDOWN");function fe(e){return e===W||e===Ae||e===Ie||e===X}var de=0,pe=1,ge=2,he=3,me=4,Te=5,D=7,ee=7<<D,Oe=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function _e(e){return Oe[(e&ee)>>>D]}var m=0,_=1,p=2,b=3,U=0,K=[],Q=!1;function w(e){U++;try{return e()}finally{if(U--,U===0&&!Q){Q=!0;for(let t=0;t<K.length;t++)K[t]();K.length=0,Q=!1}}}function A(){return U>0}function V(e){K.push(e)}var $e=0,Me=[];function ye(e){$e>0?Me.push(e):e()}var O=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 s=t.map(r=>e._names.get(r)??"?").join(",");return s.length>40?`${s.slice(0,37)}...`:s}static _resolveKey(t){let n=e._keys.get(t)??e._names.get(t);if(n)return n;let s=`anonymous_${e._nextId++}`;return e._keys.set(t,s),s}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 s=e._nextId++,r=n?.name;if(!(r&&!e._usedKeys.has(r)))if(r){let i=e._depSuffix(n?.deps);r=i?`${r}(${i})`:`${r}_${s}`,e._usedKeys.has(r)&&(r=`${r}_${s}`)}else{let i=n?.kind??"store",a=e._depSuffix(n?.deps);r=a?`${i}(${a})`:`${i}_${s}`,e._usedKeys.has(r)&&(r=`${r}_${s}`)}e._usedKeys.add(r),e._keys.set(t,r),e._stores.add(new WeakRef(t))}static registerEdge(t,n){if(!e.enabled)return;let s=e._resolveKey(t),r=e._resolveKey(n),i=e._edges.get(s);i?i.includes(r)||i.push(r):e._edges.set(s,[r])}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 s of e._stores){let r=s.deref();if(!r){e._stores.delete(s);continue}let i=e._resolveKey(r);n.add(i),t.set(i,e.inspect(r))}for(let[s,r]of e._edges){if(!n.has(s)){e._edges.delete(s),e._usedKeys.delete(s);continue}let i=r.filter(a=>n.has(a));i.length===0?e._edges.delete(s):i.length!==r.length&&e._edges.set(s,i)}return t}static trace(t,n){let s=null,r=t.get();return t.source(m,(i,a)=>{if(i===m&&(s=a),i===p){s=null;return}if(i===1){let l=a;if(!Object.is(l,r)){let u=r;r=l,n(l,u)}}}),()=>s?.(p)}static dumpGraph(){let t=e.graph(),n=e.getEdges(),s=new Map;for(let[a,l]of n)for(let u of l){let f=s.get(u);f?f.includes(a)||f.push(a):s.set(u,[a])}let r=[];for(let[a,l]of t){let u=s.get(a),f=n.get(a),o=u?.length?` \u2190 [${u.join(", ")}]`:"",c=f?.length?` \u2192 [${f.join(", ")}]`:"";r.push(` ${a} (${l.kind}) = ${JSON.stringify(l.value)} [${l.status??"?"}]${o}${c}`)}return[`Store Graph (${t.size} nodes):`,...r].join(`
2
- `)}static _signalLabel(t){return t===v?"DIRTY":t===C?"RESOLVED":typeof t=="symbol"?t.description??String(t):String(t)}static _observe(t,n,s){let r=null,i=!1,a=n??e.getName(t),l=[],u={values:[],signals:[],events:[],ended:!1,endError:void 0,get completedCleanly(){return u.ended&&!i},get errored(){return u.ended&&i},dirtyCount:0,resolvedCount:0,name:a,get eventLog(){return l},dispose:()=>r?.(p),reconnect:()=>(r?.(p),e._observe(t,n,s))};return t.source(m,(f,o)=>{if(f===m){r=o;return}let c=A();f===_?(u.values.push(o),u.events.push({type:"data",data:o,inBatch:c}),l.push(o),s&&s(`[${a}] DATA:`,o)):f===b?(u.signals.push(o),u.events.push({type:"signal",data:o,inBatch:c}),l.push(e._signalLabel(o)),o===v?u.dirtyCount++:o===C&&u.resolvedCount++,s&&s(`[${a}] STATE:`,o)):f===p&&(u.ended=!0,u.endError=o,i=o!==void 0,u.events.push({type:"end",data:o,inBatch:c}),l.push(i?["END",o]:"END"),s&&s(`[${a}] END`,o!==void 0?o:""),r=null)}),u}static observe(t){return e._observe(t)}static activate(t){let n=null;return t.source(m,(s,r)=>{s===m&&(n=r),s===p&&(n=null)}),()=>n?.(p)}static tap(t,n){let s=n??`tap(${e.getName(t)??"anon"})`,r={get:()=>t.get(),source:t.source};return e.register(r,{name:s,kind:"tap"}),e.registerEdge(t,r),r}static spy(t,n){let s=n?.name??e.getName(t)??"spy",r=n?.log??console.log;return e._observe(t,s,r)}static snapshot(){let t=e.graph(),n=e.getEdges(),s=new Map;for(let a of e._stores){let l=a.deref();if(!l)continue;let u=e._annotations.get(l);u!==void 0&&s.set(e._resolveKey(l),u)}let r=[];for(let[a,l]of t){let u={name:a,kind:l.kind,value:l.value,status:l.status},f=s.get(a);f!==void 0&&(u.annotation=f),r.push(u)}let i=[];for(let[a,l]of n)for(let u of l)i.push({from:a,to:u});return{nodes:r,edges:i,trace:e.traceLog()}}static toMermaid(t){let n=t?.direction??"TD",s=e.snapshot(),r=[`graph ${n}`],i={SETTLED:":::settled",DIRTY:":::dirty",ERRORED:":::errored",COMPLETED:":::completed"},a=new Map;function l(o){let c=o.replace(/[^a-zA-Z0-9_]/g,"_"),d=a.get(c);return d===void 0?(a.set(c,1),c):(a.set(c,d+1),`${c}__${d}`)}let u=new Map;function f(o){let c=JSON.stringify(o);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let o of s.nodes){let c=l(o.name);u.set(o.name,c);let d=`${o.name} (${o.kind}) = ${f(o.value)}`,T=i[o.status??""]??"";r.push(` ${c}["${d}"]${T}`)}for(let o of s.edges){let c=u.get(o.from)??l(o.from),d=u.get(o.to)??l(o.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(t){let n=t?.direction??"down",s=e.snapshot(),r=[`direction: ${n}`,""],i={state:"rectangle",derived:"hexagon",effect:"oval",producer:"rectangle",operator:"parallelogram","pipeline-step":"rectangle","pipeline-status":"diamond",checkpoint:"cylinder"},a=new Map;function l(o){let c=o.replace(/[^a-zA-Z0-9_]/g,"_"),d=a.get(c);return d===void 0?(a.set(c,1),c):(a.set(c,d+1),`${c}__${d}`)}let u=new Map;function f(o){let c=JSON.stringify(o);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let o of s.nodes){let c=l(o.name);u.set(o.name,c);let d=i[o.kind]??"rectangle",T=`${o.name} (${o.kind}) = ${f(o.value)}`,L=o.status?` [${o.status}]`:"";r.push(`${c}: "${T}${L}" { shape: ${d} }`)}s.edges.length>0&&r.push("");for(let o of s.edges){let c=u.get(o.from)??l(o.from),d=u.get(o.to)??l(o.to);r.push(`${c} -> ${d}`)}return r.join(`
4
- `)}static annotate(t,n){if(!e.enabled)return;e._annotations.set(t,n);let s={node:e._resolveKey(t),reason:n,timestamp:Date.now()},r=e.maxTraceEntries;r<=0||(e._traceLog.length<r?e._traceLog.push(s):(e._traceLog[e._traceHead]=s,e._traceFull=!0),e._traceHead=(e._traceHead+1)%r)}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 timeline(t){let n=null,s=[];return t.source(m,(r,i)=>{if(r===m){n=i;return}let a={timestamp:Date.now(),type:r===_?"data":r===b?"signal":"end",data:i,inBatch:A()};s.push(a),r===p&&(n=null)}),{entries:s,dispose:()=>n?.(p)}}static observeDerived(t){let n=[],s=t,r=s._fn;if(typeof r!="function"||!Array.isArray(s._deps))return{...e.observe(t),evaluations:n};s._fn=()=>{let u=s._deps.map(o=>o.get()),f=r();return n.push({result:f,depValues:u,timestamp:Date.now()}),f};let i=e._observe(t),a=i.dispose;return{...i,evaluations:n,dispose:()=>{s._fn=r,a()},reconnect:()=>(s._fn=r,a(),e.observeDerived(t))}}static observeTaskState(t){let n=t.status.get(),s=[],r=null;return t.status.source(m,(i,a)=>{if(i===m){r=a;return}if(i===_){let l=a;if(l!==n){let u={from:n,to:l,timestamp:Date.now()};l==="error"&&(u.error=t.error.get()),s.push(u),n=l}}i===p&&(r=null)}),{transitions:s,get currentStatus(){return t.status.get()},dispose:()=>{r?.(p)}}}static causalityTrace(t){let n=[],s=t,r=s._fn;if(typeof r!="function"||!Array.isArray(s._deps))return{...e.observe(t),causality:n};let i=s._deps,a=i.map(o=>o.get());s._fn=()=>{let o=i.map(T=>T.get()),c=r(),d=-1;for(let T=0;T<i.length;T++)if(!Object.is(o[T],a[T])){d=T;break}return n.push({result:c,triggerDepIndex:d,triggerDepName:d>=0?e.getName(i[d]):void 0,depValues:o,timestamp:Date.now()}),a=o,c};let l=e._observe(t),u=l.dispose;return{...l,causality:n,dispose:()=>{s._fn=r,u()},reconnect:()=>(s._fn=r,u(),e.causalityTrace(t))}}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 Y=1,S=64,y=2,$=4,be=8,Se=16,x=32,E=1024,g=ee,M=pe<<D,N=ge<<D,B=de<<D,Pe=me<<D,Ce=Te<<D,Ne=he<<D,G=class{_value;_output=null;_flags;get _status(){return _e(this._flags)}_cleanup;_fn;_eqFn;_getterFn;_initial;_singleDepCount=0;_onLifecycleSignal;constructor(t,n){this._value=n?.initial,this._fn=t,this._eqFn=n?.equals,this._getterFn=n?.getter,this._initial=n?.initial;let s=0;n?.autoDirty!==!1&&(s|=$),n?.resetOnTeardown&&(s|=be),n?.resubscribable&&(s|=Se),this._flags=s,this.source=this.source.bind(this),this.emit=this.emit.bind(this),n?._skipInspect||O.register(this,{kind:"producer",...n})}get(){return this._getterFn?this._getterFn(this._value):this._value}_dispatch(t,n){let s=this._output;if(s)if(this._flags&S)for(let r of s)r(t,n);else s(t,n)}emit(t){this._flags&y||this._eqFn&&this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(A()?this._flags&x||(this._flags|=x,this._flags&$&&(this._flags=this._flags&~g|M,this._dispatch(b,v)),V(()=>{this._flags&=~x,this._flags=this._flags&~g|N,this._dispatch(_,this._value)})):(this._flags&$&&!(this._flags&E)&&(this._flags=this._flags&~g|M,this._dispatch(b,v)),this._flags=this._flags&~g|N,this._dispatch(_,this._value))))}signal(t){this._flags&y||!this._output||(t===v?this._flags=this._flags&~g|M:t===C&&(this._flags=this._flags&~g|Ne),this._dispatch(b,t))}complete(){if(this._flags&y)return;this._flags=(this._flags|y)&~g|Pe;let t=this._output,n=this._flags&S;if(this._output=null,this._flags&=~(S|E),this._singleDepCount=0,this._stop(),t)if(n)for(let s of t)s(p);else t(p)}error(t){if(this._flags&y)return;this._flags=(this._flags|y)&~g|Ce;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(p,t);else n(p,t)}_start(){if(this._flags&Y||!this._fn)return;this._flags|=Y,this._onLifecycleSignal=void 0;let t=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 t=="function"?t:void 0}_stop(){this._flags&Y&&(this._flags&=~Y,this._onLifecycleSignal=void 0,this._cleanup&&this._cleanup(),this._cleanup=void 0,this._flags&be&&(this._value=this._initial),this._flags&y||(this._flags=this._flags&~g|B))}_handleLifecycleSignal(t){if(!(this._flags&y)){if(t===X){this._onLifecycleSignal?.(t),this.complete();return}t===W&&(this._value=this._initial,this._flags&=~x),this._onLifecycleSignal?.(t),t===W&&this.emit(this._initial)}}source(t,n){if(t===m){let s=n;if(this._flags&y)if(this._flags&Se&&this._output===null)this._flags=this._flags&~(y|g)|B;else{s(m,i=>{}),s(p);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,a)=>{if(i===_&&s(_,this._value),i===b){a===ce&&!r?(r=!0,this._singleDepCount++,this._flags&S||(this._flags|=E)):fe(a)&&this._handleLifecycleSignal(a);return}if(i===p){if(r&&(r=!1,this._singleDepCount--),this._output===null)return;if(this._flags&S){let l=this._output;l.delete(s),l.size===1?(this._output=l.values().next().value,this._flags&=~S,this._singleDepCount>0&&(this._flags|=E)):l.size===0&&(this._output=null,this._flags&=~(S|E),this._singleDepCount=0,this._flags=this._flags&~g|B,this._stop())}else this._output===s&&(this._output=null,this._flags&=~E,this._singleDepCount=0,this._flags=this._flags&~g|B,this._stop())}}),ye(()=>this._start())}}};var te=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),O.register(this,{kind:"state",...n})}get(){return this._value}set(t){this._flags&y||this._value!==void 0&&this._eqFn(this._value,t)||(this._value=t,this._output&&(A()?this._flags&x||(this._flags|=x,this._flags&$&&(this._flags=this._flags&~g|M,this._dispatch(b,v)),V(()=>{this._flags&=~x,this._flags=this._flags&~g|N,this._dispatch(_,this._value)})):(this._flags&$&&!(this._flags&E)&&(this._flags=this._flags&~g|M,this._dispatch(b,v)),this._flags=this._flags&~g|N,this._dispatch(_,this._value))))}update(t){this.set(t(this._value))}};function j(e,t){return new te(e,t)}function H(e){return(t,n)=>{if(t!==0)return;let s=new AbortController,r=s.signal,i=!1,a,l;try{a=typeof e=="function"?e():e,l=a[Symbol.asyncIterator]()}catch(f){n(0,()=>{}),n(2,f);return}n(0,f=>{f===2&&!i&&(i=!0,s.abort(),Promise.resolve(l.return?.()).catch(()=>{}))});async function u(){try{for(;!i&&!r.aborted;){let f=await l.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))}}u()}}function ve(e){return(t,n)=>{if(t!==0)return;let s=!1;n(0,r=>{r===2&&(s=!0)}),e.then(r=>{s||(n(1,r),s||n(2))},r=>{s||n(2,r)})}}function je(e){return e!=null&&typeof e.then=="function"}function Fe(e){return e!=null&&typeof e[Symbol.asyncIterator]=="function"}function Ue(e){return e!=null&&typeof e[Symbol.iterator]=="function"}function ne(e){return je(e)?ve(e):Fe(e)?H(e):typeof e!="string"&&Ue(e)?(t,n)=>{if(t!==0)return;let s=!1;n(0,r=>{r===2&&(s=!0)});for(let r of e){if(s)return;n(1,r)}s||n(2)}:(t,n)=>{if(t!==0)return;let s=!1;n(0,r=>{r===2&&(s=!0)}),s||n(1,e),s||n(2)}}function q(e,t,n){let s=null;return e(0,(r,i)=>{if(r===0){s=i;return}if(r===2){s=null,n?.onEnd?.(i);return}r===1&&t(i)}),{unsubscribe(){s?.(2),s=null}}}function Ke(e){switch(e){case"openai":return"https://api.openai.com/v1";case"ollama":return"http://localhost:11434";default:return""}}function We(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,s){let r={model:t,messages:n,stream:!0};return s?.temperature!==void 0&&(r.temperature=s.temperature),s?.maxTokens!==void 0&&(e==="ollama"?r.options={num_predict:s.maxTokens}:r.max_tokens=s.maxTokens),s?.stop&&(r.stop=s.stop),r}function Ye(e,t){let n={"Content-Type":"application/json"};return t&&(n.Authorization=`Bearer ${t}`),n}function Be(e){let t=e.name??"llm",n=e.provider,s=e.baseURL??Ke(n),r=e.model??"",i=e.fetch??globalThis.fetch,a=j("",{name:`${t}.store`}),l=j({},{name:`${t}.tokens`}),u=j("pending",{name:`${t}.status`}),f=j(void 0,{name:`${t}.error`}),o=null;function c(){o&&(o.abort(),o=null),u.get()==="active"&&w(()=>{a.set(""),u.set("pending")})}function d(L,R){c(),o=new AbortController;let z=R?.signal?qe(o.signal,R.signal):o.signal;w(()=>{a.set(""),l.set({}),f.set(void 0),u.set("active")});let h=We(n,s),k=Ve(n,r,L,R),P=Ye(n,e.apiKey);T(h,P,k,z)}function T(L,R,z,h){q(ne(i(L,{method:"POST",headers:R,body:JSON.stringify(z),signal:h})),k=>{if(!k.ok){q(ne(k.text().catch(()=>"")),I=>{h.aborted||(w(()=>{f.set(new Error(`LLM API error ${k.status}: ${I}`)),u.set("errored")}),o=null,h._cleanup?.())});return}let P=k.body?.getReader();if(!P){if(h.aborted)return;w(()=>{f.set(new Error("No response body")),u.set("errored")}),o=null,h._cleanup?.();return}let se=new TextDecoder,re="",J="";q(H({[Symbol.asyncIterator](){return{next(){return P.read()},return(){return P.cancel(),Promise.resolve({done:!0,value:void 0})}}}}),I=>{if(h.aborted)return;J+=se.decode(I,{stream:!0});let ie=J.split(`
5
- `);J=ie.pop()??"";for(let Ee of ie){if(h.aborted)return;let F=Ee.trim();if(!F||F.startsWith(":")||!F.startsWith("data: "))continue;let oe=F.slice(6);if(oe!=="[DONE]")try{let ae=JSON.parse(oe),ue=Ge(n,ae);ue&&(re+=ue,a.set(re));let le=He(n,ae);le&&l.set(le)}catch{}}},{onEnd:I=>{if(se.decode(),h.aborted){h._cleanup?.();return}I!==void 0?w(()=>{f.set(I),u.set("errored")}):u.set("completed"),o=null,h._cleanup?.()}})},{onEnd:k=>{if(k!==void 0){if(h.aborted){h._cleanup?.();return}w(()=>{f.set(k),u.set("errored")}),o=null,h._cleanup?.()}}})}return{get:()=>a.get(),source:(L,R)=>a.source(L,R),tokens:l,status:u,error:f,generate:d,abort:c}}function Ge(e,t){return e==="ollama"?t?.message?.content:t?.choices?.[0]?.delta?.content}function He(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,s=()=>{e.removeEventListener("abort",r),t.removeEventListener("abort",r)},r=()=>{n.abort(),s()};e.addEventListener("abort",r,{once:!0}),t.addEventListener("abort",r,{once:!0});let i=n.signal;return i._cleanup=s,i}0&&(module.exports={fromLLM});
1
+ "use strict";var ce=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Ne=Object.prototype.hasOwnProperty;var je=(t,e)=>{for(var n in e)ce(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&&ce(t,r,{get:()=>e[r],enumerable:!(s=$e(e,r))||s.enumerable});return t};var Ue=t=>Fe(ce({},"__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"),te=Symbol("RESET"),Ke=Symbol("PAUSE"),We=Symbol("RESUME"),de=Symbol("TEARDOWN");function _e(t){return t===te||t===Ke||t===We||t===de}var ye=0,be=1,Se=2,ve=3,Ee=4,ke=5,D=7,ge=7<<D,Ve=["DISCONNECTED","DIRTY","SETTLED","RESOLVED","COMPLETED","ERRORED"];function De(t){return Ve[(t&ge)>>>D]}var h=0,_=1,g=2,b=3,X=0,ee=[],fe=!1;function L(t){X++;try{return t()}finally{if(X--,X===0&&!fe){fe=!0;for(let e=0;e<ee.length;e++)ee[e]();ee.length=0,fe=!1}}}function A(){return X>0}function ne(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",a=t._depSuffix(n?.deps);r=a?`${i}(${a})`:`${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(a=>n.has(a));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(h,(i,a)=>{if(i===h&&(s=a),i===g){s=null;return}if(i===1){let u=a;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[a,u]of n)for(let l of u){let f=s.get(l);f?f.includes(a)||f.push(a):s.set(l,[a])}let r=[];for(let[a,u]of e){let l=s.get(a),f=n.get(a),o=l?.length?` \u2190 [${l.join(", ")}]`:"",c=f?.length?` \u2192 [${f.join(", ")}]`:"";r.push(` ${a} (${u.kind}) = ${JSON.stringify(u.value)} [${u.status??"?"}]${o}${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,a=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:a,get eventLog(){return u},dispose:()=>r?.(g),reconnect:()=>(r?.(g),t._observe(e,n,s))};return e.source(h,(f,o)=>{if(f===h){r=o;return}let c=A();f===_?(l.values.push(o),l.events.push({type:"data",data:o,inBatch:c}),u.push(o),s&&s(`[${a}] DATA:`,o)):f===b?(l.signals.push(o),l.events.push({type:"signal",data:o,inBatch:c}),u.push(t._signalLabel(o)),o===v?l.dirtyCount++:o===G&&l.resolvedCount++,s&&s(`[${a}] STATE:`,o)):f===g&&(l.ended=!0,l.endError=o,i=o!==void 0,l.events.push({type:"end",data:o,inBatch:c}),u.push(i?["END",o]:"END"),s&&s(`[${a}] END`,o!==void 0?o:""),r=null)}),l}static observe(e){return t._observe(e)}static activate(e){let n=null;return e.source(h,(s,r)=>{s===h&&(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 a of t._stores){let u=a.deref();if(!u)continue;let l=t._annotations.get(u);l!==void 0&&s.set(t._resolveKey(u),l)}let r=[];for(let[a,u]of e){let l={name:a,kind:u.kind,value:u.value,status:u.status},f=s.get(a);f!==void 0&&(l.annotation=f),r.push(l)}let i=[];for(let[a,u]of n)for(let l of u)i.push({from:a,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"},a=new Map;function u(o){let c=o.replace(/[^a-zA-Z0-9_]/g,"_"),d=a.get(c);return d===void 0?(a.set(c,1),c):(a.set(c,d+1),`${c}__${d}`)}let l=new Map;function f(o){let c=JSON.stringify(o);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let o of s.nodes){let c=u(o.name);l.set(o.name,c);let d=`${o.name} (${o.kind}) = ${f(o.value)}`,T=i[o.status??""]??"";r.push(` ${c}["${d}"]${T}`)}for(let o of s.edges){let c=l.get(o.from)??u(o.from),d=l.get(o.to)??u(o.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"},a=new Map;function u(o){let c=o.replace(/[^a-zA-Z0-9_]/g,"_"),d=a.get(c);return d===void 0?(a.set(c,1),c):(a.set(c,d+1),`${c}__${d}`)}let l=new Map;function f(o){let c=JSON.stringify(o);return c&&c.length>30?`${c.slice(0,27)}...`:c??"undefined"}for(let o of s.nodes){let c=u(o.name);l.set(o.name,c);let d=i[o.kind]??"rectangle",T=`${o.name} (${o.kind}) = ${f(o.value)}`,q=o.status?` [${o.status}]`:"";r.push(`${c}: "${T}${q}" { shape: ${d} }`)}s.edges.length>0&&r.push("");for(let o of s.edges){let c=l.get(o.from)??u(o.from),d=l.get(o.to)??u(o.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(h,(r,i)=>{if(r===h){n=i;return}let a={timestamp:Date.now(),type:r===_?"data":r===b?"signal":"end",data:i,inBatch:A()};s.push(a),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(o=>o.get()),f=r();return n.push({result:f,depValues:l,timestamp:Date.now()}),f};let i=t._observe(e),a=i.dispose;return{...i,evaluations:n,dispose:()=>{s._fn=r,a()},reconnect:()=>(s._fn=r,a(),t.observeDerived(e))}}static observeTaskState(e){let n=e.status.get(),s=[],r=null;return e.status.source(h,(i,a)=>{if(i===h){r=a;return}if(i===_){let u=a;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,a=i.map(o=>o.get());s._fn=()=>{let o=i.map(T=>T.get()),c=r(),d=-1;for(let T=0;T<i.length;T++)if(!Object.is(o[T],a[T])){d=T;break}return n.push({result:c,triggerDepIndex:d,triggerDepName:d>=0?t.getName(i[d]):void 0,depValues:o,timestamp:Date.now()}),a=o,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 se=1,S=64,y=2,j=4,xe=8,Re=16,x=32,E=1024,m=ge,F=be<<D,H=Se<<D,re=ye<<D,Ge=Ee<<D,He=ke<<D,qe=ve<<D,ie=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&x||(this._flags|=x,this._flags&j&&(this._flags=this._flags&~m|F,this._dispatch(b,v)),ne(()=>{this._flags&=~x,this._flags=this._flags&~m|H,this._dispatch(_,this._value)})):(this._flags&j&&!(this._flags&E)&&(this._flags=this._flags&~m|F,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|F:e===G&&(this._flags=this._flags&~m|qe),this._dispatch(b,e))}complete(){if(this._flags&y)return;this._flags=(this._flags|y)&~m|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)&~m|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&se||!this._fn)return;this._flags|=se,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&se&&(this._flags&=~se,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&~m|re))}_handleLifecycleSignal(e){if(!(this._flags&y)){if(e===de){this._onLifecycleSignal?.(e),this.complete();return}e===te&&(this._value=this._initial,this._flags&=~x),this._onLifecycleSignal?.(e),e===te&&this.emit(this._initial)}}source(e,n){if(e===h){let s=n;if(this._flags&y)if(this._flags&Re&&this._output===null)this._flags=this._flags&~(y|m)|re;else{s(h,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(h,(i,a)=>{if(i===_&&s(_,this._value),i===b){a===Te&&!r?(r=!0,this._singleDepCount++,this._flags&S||(this._flags|=E)):_e(a)&&this._handleLifecycleSignal(a);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|re,this._stop())}else this._output===s&&(this._output=null,this._flags&=~E,this._singleDepCount=0,this._flags=this._flags&~m|re,this._stop())}}),Le(()=>this._start())}}};var pe=class extends ie{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&x||(this._flags|=x,this._flags&j&&(this._flags=this._flags&~m|F,this._dispatch(b,v)),ne(()=>{this._flags&=~x,this._flags=this._flags&~m|H,this._dispatch(_,this._value)})):(this._flags&j&&!(this._flags&E)&&(this._flags=this._flags&~m|F,this._dispatch(b,v)),this._flags=this._flags&~m|H,this._dispatch(_,this._value))))}update(e){this.set(e(this._value))}};function U(t,e){return new pe(t,e)}function oe(t){return(e,n)=>{if(e!==0)return;let s=new AbortController,r=s.signal,i=!1,a,u;try{a=typeof t=="function"?t():t,u=a[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 me(t){return ze(t)?we(t):Je(t)?oe(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 ae(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,a=U("",{name:`${e}.store`}),u=U({},{name:`${e}.tokens`}),l=U("pending",{name:`${e}.status`}),f=U(void 0,{name:`${e}.error`}),o=U([],{name:`${e}.toolCalls`}),c=null,d=0,T=0;function q(){c&&(c.abort(),c=null),l.get()==="active"&&L(()=>{a.set(""),o.set([]),l.set("pending")})}function Ce(K,R){q(),c=new AbortController;let z=R?.signal?it(c.signal,R.signal):c.signal;L(()=>{a.set(""),u.set({}),f.set(void 0),o.set([]),l.set("active")});let p=++d;try{let W=et(n,s),I=tt(n,r,K,R),k=st(n,t.apiKey);Oe(W,k,I,z,p)}catch(W){L(()=>{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)};ae(me(i(K,{method:"POST",headers:R,body:JSON.stringify(z),signal:p})),k=>{if(!k.ok){ae(me(k.text().catch(()=>"")),C=>{p.aborted||(L(()=>{f.set(new Error(`LLM API error ${k.status}: ${C}`)),l.set("errored")}),I(),p._cleanup?.())});return}let le=k.body?.getReader();if(!le){if(p.aborted){p._cleanup?.();return}L(()=>{f.set(new Error("No response body")),l.set("errored")}),I(),p._cleanup?.();return}let he=new TextDecoder,J="",M="",Z=new Map;ae(oe({[Symbol.asyncIterator](){return{next(){return le.read()},return(){return le.cancel(),Promise.resolve({done:!0,value:void 0})}}}}),C=>{if(p.aborted)return;M+=he.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,a.set(J)),Ie(n,$,Z,()=>`call_${T++}`)){let P=[];for(let[,ue]of Z)P.push({id:ue.id,name:ue.name,arguments:ue.arguments});o.set(P)}let B=Me(n,$);B&&u.set(B)}catch{}}},{onEnd:C=>{let V=he.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+=$,a.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});o.set(B)}let Y=Me(n,O);Y&&u.set(Y)}catch{}}}if(p.aborted){p._cleanup?.();return}C!==void 0?L(()=>{f.set(C),l.set("errored")}):l.set("completed"),I(),p._cleanup?.()}})},{onEnd:k=>{if(k!==void 0){if(p.aborted){p._cleanup?.();return}L(()=>{f.set(k),l.set("errored")}),I()}p._cleanup?.()}})}return{get:()=>a.get(),source:(K,R)=>a.source(K,R),tokens:u,status:l,error:f,toolCalls:o,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 a=e?.message?.tool_calls;if(!Array.isArray(a))return!1;let u=!1;for(let l=0;l<a.length;l++){let o=a[l]?.function;o&&(n.set(l,{id:s?s():`call_${l}`,name:o.name??"",arguments:typeof o.arguments=="string"?o.arguments:JSON.stringify(o.arguments??{})}),u=!0)}return u}let r=e?.choices?.[0]?.delta?.tool_calls;if(!Array.isArray(r))return!1;let i=!1;for(let a of r){let u=a.index??0,l=n.get(u);l||(l={id:"",name:"",arguments:""},n.set(u,l)),a.id&&(l.id=a.id,i=!0),a.function?.name&&(l.name=a.function.name,i=!0),a.function?.arguments&&(l.arguments+=a.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});
@@ -2,15 +2,42 @@ import { S as Store } from '../types-BohB8jJr.cjs';
2
2
  import { W as WithStatusStatus } from '../withStatus-ByT_R2Rz.cjs';
3
3
  import '../protocol-fwiQ1TAS.cjs';
4
4
 
5
+ /** Role for LLM messages. */
6
+ type LLMRole = "user" | "assistant" | "system" | "tool";
7
+ /** A tool call emitted by the LLM (from assistant message). */
8
+ interface LLMToolCall {
9
+ /** Tool call ID assigned by the LLM (for matching tool results). */
10
+ id: string;
11
+ /** Tool/function name. */
12
+ name: string;
13
+ /** Raw JSON string of arguments. Call JSON.parse() to get structured args. */
14
+ arguments: string;
15
+ }
16
+ /** An LLM message. Supports text content and/or tool calls. */
5
17
  interface LLMMessage {
6
- role: "user" | "assistant" | "system";
7
- content: string;
18
+ role: LLMRole;
19
+ /** Text content. May be empty/null for pure tool-call messages. */
20
+ content: string | null;
21
+ /** Tool calls requested by the assistant (only on role="assistant"). */
22
+ tool_calls?: LLMToolCall[];
23
+ /** Tool call ID this message responds to (only on role="tool"). */
24
+ tool_call_id?: string;
8
25
  }
26
+ /** Token usage metadata from the LLM response. */
9
27
  interface LLMTokenUsage {
10
28
  promptTokens?: number;
11
29
  completionTokens?: number;
12
30
  totalTokens?: number;
13
31
  }
32
+ /** Tool definition in OpenAI function-calling format. */
33
+ interface LLMToolDefinition {
34
+ type: "function";
35
+ function: {
36
+ name: string;
37
+ description: string;
38
+ parameters?: Record<string, unknown>;
39
+ };
40
+ }
14
41
  interface LLMOptions {
15
42
  /** Provider type. Determines URL patterns and response format. */
16
43
  provider: "openai" | "ollama" | "custom";
@@ -34,6 +61,8 @@ interface GenerateOptions {
34
61
  stop?: string[];
35
62
  /** AbortSignal for cancellation. */
36
63
  signal?: AbortSignal;
64
+ /** Tool definitions for function calling. Pass `registry.definitions()` from toolRegistry. */
65
+ tools?: LLMToolDefinition[];
37
66
  }
38
67
  interface LLMStore extends Store<string> {
39
68
  /** Token usage from the last generation (reactive, populated on completion). */
@@ -42,43 +71,62 @@ interface LLMStore extends Store<string> {
42
71
  status: Store<WithStatusStatus>;
43
72
  /** Last error, if any (reactive). */
44
73
  error: Store<unknown | undefined>;
74
+ /** Tool calls parsed from the last generation (reactive). Empty array when no tool calls. */
75
+ toolCalls: Store<LLMToolCall[]>;
45
76
  /** Start a generation. Aborts any in-progress generation. */
46
77
  generate: (messages: LLMMessage[], opts?: GenerateOptions) => void;
47
78
  /** Abort the current generation. */
48
79
  abort: () => void;
49
80
  }
81
+ /**
82
+ * Convert `LLMToolCall[]` from fromLLM into `ToolCallRequest[]` for toolRegistry.
83
+ * Convenience bridge between the two primitives.
84
+ *
85
+ * Safe to call on partial tool calls mid-stream: malformed JSON arguments
86
+ * are passed through as the raw string rather than throwing.
87
+ */
88
+ declare function toToolCallRequests(calls: LLMToolCall[]): Array<{
89
+ id: string;
90
+ tool: string;
91
+ args: unknown;
92
+ }>;
50
93
  /**
51
94
  * Creates a unified reactive source for LLM inference via any OpenAI-compatible endpoint.
52
95
  *
53
96
  * @param opts - Provider configuration (provider, baseURL, apiKey, model).
54
97
  *
55
- * @returns `LLMStore` — `Store<string>` with `status`, `error`, `tokens` companion stores, plus `generate()` and `abort()`.
98
+ * @returns `LLMStore` — `Store<string>` with `status`, `error`, `tokens`, `toolCalls` companion stores, plus `generate()` and `abort()`.
56
99
  *
57
100
  * @remarks **Provider-agnostic:** Works with OpenAI, Ollama, Anthropic (via proxy), Vercel AI SDK, or any OpenAI-compatible endpoint.
58
101
  * @remarks **No hard deps:** Uses fetch + SSE line parsing. No SDK imports required.
59
102
  * @remarks **Auto-cancel:** Calling `generate()` while streaming aborts the previous generation.
103
+ * @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()`.
60
104
  * @remarks **Token tracking:** `tokens` store populated on stream completion (when usage data is available).
61
105
  * @remarks **Status:** Uses WithStatusStatus enum (pending → active → completed/errored) for consistent lifecycle tracking.
62
106
  * @remarks **Persistent source:** This is a long-lived store backed by `state()`. It does not send callbag END — lifecycle is managed imperatively via `generate()`/`abort()`, not via stream completion. Do not wrap with `withStatus()` or `retry()` — use the built-in `.status` and `.error` companions instead.
63
107
  *
64
108
  * @example
65
109
  * ```ts
66
- * import { fromLLM } from 'callbag-recharge/ai';
110
+ * import { fromLLM, toToolCallRequests } from 'callbag-recharge/ai';
67
111
  * import { effect } from 'callbag-recharge';
68
112
  *
69
- * const llm = fromLLM({ provider: 'ollama', model: 'llama4' });
70
- *
71
- * effect([llm], () => {
72
- * console.log(llm.get()); // accumulating response...
73
- * });
113
+ * const llm = fromLLM({ provider: 'openai', apiKey: 'sk-...', model: 'gpt-4o' });
74
114
  *
115
+ * // Text generation
75
116
  * llm.generate([{ role: 'user', content: 'What is TypeScript?' }]);
76
- * // llm.status.get() → "active"
77
- * // llm.get() → "TypeScript is..."
117
+ *
118
+ * // Tool calling
119
+ * llm.generate(messages, { tools: registry.definitions() });
120
+ * effect([llm.toolCalls], () => {
121
+ * const calls = llm.toolCalls.get();
122
+ * if (calls.length > 0) {
123
+ * registry.execute(toToolCallRequests(calls));
124
+ * }
125
+ * });
78
126
  * ```
79
127
  *
80
128
  * @category ai
81
129
  */
82
130
  declare function fromLLM(opts: LLMOptions): LLMStore;
83
131
 
84
- export { type GenerateOptions, type LLMMessage, type LLMOptions, type LLMStore, type LLMTokenUsage, fromLLM };
132
+ export { type GenerateOptions, type LLMMessage, type LLMOptions, type LLMRole, type LLMStore, type LLMTokenUsage, type LLMToolCall, type LLMToolDefinition, fromLLM, toToolCallRequests };
@@ -2,15 +2,42 @@ import { S as Store } from '../types-CB1htCM8.js';
2
2
  import { W as WithStatusStatus } from '../withStatus---CFNir7.js';
3
3
  import '../protocol-fwiQ1TAS.js';
4
4
 
5
+ /** Role for LLM messages. */
6
+ type LLMRole = "user" | "assistant" | "system" | "tool";
7
+ /** A tool call emitted by the LLM (from assistant message). */
8
+ interface LLMToolCall {
9
+ /** Tool call ID assigned by the LLM (for matching tool results). */
10
+ id: string;
11
+ /** Tool/function name. */
12
+ name: string;
13
+ /** Raw JSON string of arguments. Call JSON.parse() to get structured args. */
14
+ arguments: string;
15
+ }
16
+ /** An LLM message. Supports text content and/or tool calls. */
5
17
  interface LLMMessage {
6
- role: "user" | "assistant" | "system";
7
- content: string;
18
+ role: LLMRole;
19
+ /** Text content. May be empty/null for pure tool-call messages. */
20
+ content: string | null;
21
+ /** Tool calls requested by the assistant (only on role="assistant"). */
22
+ tool_calls?: LLMToolCall[];
23
+ /** Tool call ID this message responds to (only on role="tool"). */
24
+ tool_call_id?: string;
8
25
  }
26
+ /** Token usage metadata from the LLM response. */
9
27
  interface LLMTokenUsage {
10
28
  promptTokens?: number;
11
29
  completionTokens?: number;
12
30
  totalTokens?: number;
13
31
  }
32
+ /** Tool definition in OpenAI function-calling format. */
33
+ interface LLMToolDefinition {
34
+ type: "function";
35
+ function: {
36
+ name: string;
37
+ description: string;
38
+ parameters?: Record<string, unknown>;
39
+ };
40
+ }
14
41
  interface LLMOptions {
15
42
  /** Provider type. Determines URL patterns and response format. */
16
43
  provider: "openai" | "ollama" | "custom";
@@ -34,6 +61,8 @@ interface GenerateOptions {
34
61
  stop?: string[];
35
62
  /** AbortSignal for cancellation. */
36
63
  signal?: AbortSignal;
64
+ /** Tool definitions for function calling. Pass `registry.definitions()` from toolRegistry. */
65
+ tools?: LLMToolDefinition[];
37
66
  }
38
67
  interface LLMStore extends Store<string> {
39
68
  /** Token usage from the last generation (reactive, populated on completion). */
@@ -42,43 +71,62 @@ interface LLMStore extends Store<string> {
42
71
  status: Store<WithStatusStatus>;
43
72
  /** Last error, if any (reactive). */
44
73
  error: Store<unknown | undefined>;
74
+ /** Tool calls parsed from the last generation (reactive). Empty array when no tool calls. */
75
+ toolCalls: Store<LLMToolCall[]>;
45
76
  /** Start a generation. Aborts any in-progress generation. */
46
77
  generate: (messages: LLMMessage[], opts?: GenerateOptions) => void;
47
78
  /** Abort the current generation. */
48
79
  abort: () => void;
49
80
  }
81
+ /**
82
+ * Convert `LLMToolCall[]` from fromLLM into `ToolCallRequest[]` for toolRegistry.
83
+ * Convenience bridge between the two primitives.
84
+ *
85
+ * Safe to call on partial tool calls mid-stream: malformed JSON arguments
86
+ * are passed through as the raw string rather than throwing.
87
+ */
88
+ declare function toToolCallRequests(calls: LLMToolCall[]): Array<{
89
+ id: string;
90
+ tool: string;
91
+ args: unknown;
92
+ }>;
50
93
  /**
51
94
  * Creates a unified reactive source for LLM inference via any OpenAI-compatible endpoint.
52
95
  *
53
96
  * @param opts - Provider configuration (provider, baseURL, apiKey, model).
54
97
  *
55
- * @returns `LLMStore` — `Store<string>` with `status`, `error`, `tokens` companion stores, plus `generate()` and `abort()`.
98
+ * @returns `LLMStore` — `Store<string>` with `status`, `error`, `tokens`, `toolCalls` companion stores, plus `generate()` and `abort()`.
56
99
  *
57
100
  * @remarks **Provider-agnostic:** Works with OpenAI, Ollama, Anthropic (via proxy), Vercel AI SDK, or any OpenAI-compatible endpoint.
58
101
  * @remarks **No hard deps:** Uses fetch + SSE line parsing. No SDK imports required.
59
102
  * @remarks **Auto-cancel:** Calling `generate()` while streaming aborts the previous generation.
103
+ * @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()`.
60
104
  * @remarks **Token tracking:** `tokens` store populated on stream completion (when usage data is available).
61
105
  * @remarks **Status:** Uses WithStatusStatus enum (pending → active → completed/errored) for consistent lifecycle tracking.
62
106
  * @remarks **Persistent source:** This is a long-lived store backed by `state()`. It does not send callbag END — lifecycle is managed imperatively via `generate()`/`abort()`, not via stream completion. Do not wrap with `withStatus()` or `retry()` — use the built-in `.status` and `.error` companions instead.
63
107
  *
64
108
  * @example
65
109
  * ```ts
66
- * import { fromLLM } from 'callbag-recharge/ai';
110
+ * import { fromLLM, toToolCallRequests } from 'callbag-recharge/ai';
67
111
  * import { effect } from 'callbag-recharge';
68
112
  *
69
- * const llm = fromLLM({ provider: 'ollama', model: 'llama4' });
70
- *
71
- * effect([llm], () => {
72
- * console.log(llm.get()); // accumulating response...
73
- * });
113
+ * const llm = fromLLM({ provider: 'openai', apiKey: 'sk-...', model: 'gpt-4o' });
74
114
  *
115
+ * // Text generation
75
116
  * llm.generate([{ role: 'user', content: 'What is TypeScript?' }]);
76
- * // llm.status.get() → "active"
77
- * // llm.get() → "TypeScript is..."
117
+ *
118
+ * // Tool calling
119
+ * llm.generate(messages, { tools: registry.definitions() });
120
+ * effect([llm.toolCalls], () => {
121
+ * const calls = llm.toolCalls.get();
122
+ * if (calls.length > 0) {
123
+ * registry.execute(toToolCallRequests(calls));
124
+ * }
125
+ * });
78
126
  * ```
79
127
  *
80
128
  * @category ai
81
129
  */
82
130
  declare function fromLLM(opts: LLMOptions): LLMStore;
83
131
 
84
- export { type GenerateOptions, type LLMMessage, type LLMOptions, type LLMStore, type LLMTokenUsage, fromLLM };
132
+ export { type GenerateOptions, type LLMMessage, type LLMOptions, type LLMRole, type LLMStore, type LLMTokenUsage, type LLMToolCall, type LLMToolDefinition, fromLLM, toToolCallRequests };
@@ -1 +1 @@
1
- import{a}from"../chunk-JWQFJJJB.js";import"../chunk-O2PONDZT.js";import"../chunk-J2E7GAMR.js";import"../chunk-4ILN4V4C.js";import"../chunk-Q3HIBGHR.js";import"../chunk-EAK2HKAD.js";import"../chunk-2F6QWERG.js";import"../chunk-2L6223KN.js";import"../chunk-TUPD47IE.js";import"../chunk-I7AUKTXE.js";export{a as fromLLM};
1
+ import{a,b}from"../chunk-QAHR7EMX.js";import"../chunk-O2PONDZT.js";import"../chunk-J2E7GAMR.js";import"../chunk-4ILN4V4C.js";import"../chunk-Q3HIBGHR.js";import"../chunk-EAK2HKAD.js";import"../chunk-2F6QWERG.js";import"../chunk-2L6223KN.js";import"../chunk-TUPD47IE.js";import"../chunk-I7AUKTXE.js";export{b as fromLLM,a as toToolCallRequests};