@ag-ui/client 0.0.36 → 0.0.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- var ee=Object.defineProperty,te=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var q=Object.getOwnPropertySymbols;var ae=Object.prototype.hasOwnProperty,se=Object.prototype.propertyIsEnumerable;var V=(p,o,t)=>o in p?ee(p,o,{enumerable:!0,configurable:!0,writable:!0,value:t}):p[o]=t,I=(p,o)=>{for(var t in o||(o={}))ae.call(o,t)&&V(p,t,o[t]);if(q)for(var t of q(o))se.call(o,t)&&V(p,t,o[t]);return p},G=(p,o)=>te(p,ne(o));import{EventType as M}from"@ag-ui/core";import{mergeAll as oe,defaultIfEmpty as re,concatMap as ie}from"rxjs/operators";import{of as le,EMPTY as ge}from"rxjs";var R=p=>{if(typeof structuredClone=="function")return structuredClone(p);try{return JSON.parse(JSON.stringify(p))}catch(o){return I({},p)}};import{applyPatch as Ee}from"fast-json-patch";async function C(p,o,t,n){let e=o,s=t,i;for(let r of p)try{let l=await n(r,R(e),R(s));if(l===void 0)continue;if(l.messages!==void 0&&(e=l.messages),l.state!==void 0&&(s=l.state),i=l.stopPropagation,i===!0)break}catch(l){process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0||console.error("Subscriber error:",l);continue}return I(I(I({},JSON.stringify(e)!==JSON.stringify(o)?{messages:e}:{}),JSON.stringify(s)!==JSON.stringify(t)?{state:s}:{}),i!==void 0?{stopPropagation:i}:{})}import ce from"untruncate-json";var K=(p,o,t,n)=>{let e=R(p.messages),s=R(p.state),i={},r=c=>{c.messages!==void 0&&(e=c.messages,i.messages=c.messages),c.state!==void 0&&(s=c.state,i.state=c.state)},l=()=>{let c=R(i);return i={},c.messages!==void 0||c.state!==void 0?le(c):ge};return o.pipe(ie(async c=>{var T;let d=await C(n,e,s,(u,a,E)=>{var S;return(S=u.onEvent)==null?void 0:S.call(u,{event:c,agent:t,input:p,messages:a,state:E})});if(r(d),d.stopPropagation===!0)return l();switch(c.type){case M.TEXT_MESSAGE_START:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onTextMessageStartEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p})});if(r(u),u.stopPropagation!==!0){let{messageId:a,role:E}=c,S={id:a,role:E,content:""};e.push(S),r({messages:e})}return l()}case M.TEXT_MESSAGE_CONTENT:{let u=await C(n,e,s,(a,E,S)=>{var g,N;return(N=a.onTextMessageContentEvent)==null?void 0:N.call(a,{event:c,messages:E,state:S,agent:t,input:p,textMessageBuffer:(g=E[E.length-1].content)!=null?g:""})});if(r(u),u.stopPropagation!==!0){let{delta:a}=c,E=e[e.length-1];E.content=E.content+a,r({messages:e})}return l()}case M.TEXT_MESSAGE_END:{let u=await C(n,e,s,(a,E,S)=>{var g,N;return(N=a.onTextMessageEndEvent)==null?void 0:N.call(a,{event:c,messages:E,state:S,agent:t,input:p,textMessageBuffer:(g=E[E.length-1].content)!=null?g:""})});return r(u),await Promise.all(n.map(a=>{var E;(E=a.onNewMessage)==null||E.call(a,{message:e[e.length-1],messages:e,state:s,agent:t,input:p})})),l()}case M.TOOL_CALL_START:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onToolCallStartEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p})});if(r(u),u.stopPropagation!==!0){let{toolCallId:a,toolCallName:E,parentMessageId:S}=c,g;S&&e.length>0&&e[e.length-1].id===S?g=e[e.length-1]:(g={id:S||a,role:"assistant",toolCalls:[]},e.push(g)),(T=g.toolCalls)!=null||(g.toolCalls=[]),g.toolCalls.push({id:a,type:"function",function:{name:E,arguments:""}}),r({messages:e})}return l()}case M.TOOL_CALL_ARGS:{let u=await C(n,e,s,(a,E,S)=>{var P,D,H;let g=(D=(P=E[E.length-1])==null?void 0:P.toolCalls)!=null?D:[],N=g.length>0?g[g.length-1].function.arguments:"",w=g.length>0?g[g.length-1].function.name:"",O={};try{O=ce(N)}catch(Z){}return(H=a.onToolCallArgsEvent)==null?void 0:H.call(a,{event:c,messages:E,state:S,agent:t,input:p,toolCallBuffer:N,toolCallName:w,partialToolCallArgs:O})});if(r(u),u.stopPropagation!==!0){let{delta:a}=c,E=e[e.length-1],S=E.toolCalls[E.toolCalls.length-1];S.function.arguments+=a,r({messages:e})}return l()}case M.TOOL_CALL_END:{let u=await C(n,e,s,(a,E,S)=>{var P,D,H;let g=(D=(P=E[E.length-1])==null?void 0:P.toolCalls)!=null?D:[],N=g.length>0?g[g.length-1].function.arguments:"",w=g.length>0?g[g.length-1].function.name:"",O={};try{O=JSON.parse(N)}catch(Z){}return(H=a.onToolCallEndEvent)==null?void 0:H.call(a,{event:c,messages:E,state:S,agent:t,input:p,toolCallName:w,toolCallArgs:O})});return r(u),await Promise.all(n.map(a=>{var E;(E=a.onNewToolCall)==null||E.call(a,{toolCall:e[e.length-1].toolCalls[e[e.length-1].toolCalls.length-1],messages:e,state:s,agent:t,input:p})})),l()}case M.TOOL_CALL_RESULT:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onToolCallResultEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p})});if(r(u),u.stopPropagation!==!0){let{messageId:a,toolCallId:E,content:S,role:g}=c,N={id:a,toolCallId:E,role:g||"tool",content:S};e.push(N),await Promise.all(n.map(w=>{var O;(O=w.onNewMessage)==null||O.call(w,{message:N,messages:e,state:s,agent:t,input:p})})),r({messages:e})}return l()}case M.STATE_SNAPSHOT:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onStateSnapshotEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p})});if(r(u),u.stopPropagation!==!0){let{snapshot:a}=c;s=a,r({state:s})}return l()}case M.STATE_DELTA:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onStateDeltaEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p})});if(r(u),u.stopPropagation!==!0){let{delta:a}=c;try{s=Ee(s,a,!0,!1).newDocument,r({state:s})}catch(E){let S=E instanceof Error?E.message:String(E);console.warn(`Failed to apply state patch:
1
+ var ee=Object.defineProperty,te=Object.defineProperties;var ne=Object.getOwnPropertyDescriptors;var b=Object.getOwnPropertySymbols;var ae=Object.prototype.hasOwnProperty,se=Object.prototype.propertyIsEnumerable;var V=(u,o,n)=>o in u?ee(u,o,{enumerable:!0,configurable:!0,writable:!0,value:n}):u[o]=n,L=(u,o)=>{for(var n in o||(o={}))ae.call(o,n)&&V(u,n,o[n]);if(b)for(var n of b(o))se.call(o,n)&&V(u,n,o[n]);return u},H=(u,o)=>te(u,ne(o));import{EventType as v}from"@ag-ui/core";import{mergeAll as oe,defaultIfEmpty as re,concatMap as ie}from"rxjs/operators";import{of as le,EMPTY as ge}from"rxjs";var C=u=>{if(typeof structuredClone=="function")return structuredClone(u);try{return JSON.parse(JSON.stringify(u))}catch(o){return L({},u)}};import{applyPatch as ce}from"fast-json-patch";async function h(u,o,n,a){let e=o,s=n,g;for(let r of u)try{let l=await a(r,C(e),C(s));if(l===void 0)continue;if(l.messages!==void 0&&(e=l.messages),l.state!==void 0&&(s=l.state),g=l.stopPropagation,g===!0)break}catch(l){process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0||console.error("Subscriber error:",l);continue}return L(L(L({},JSON.stringify(e)!==JSON.stringify(o)?{messages:e}:{}),JSON.stringify(s)!==JSON.stringify(n)?{state:s}:{}),g!==void 0?{stopPropagation:g}:{})}import Ee from"untruncate-json";var k=(u,o,n,a)=>{let e=C(u.messages),s=C(u.state),g={},r=E=>{E.messages!==void 0&&(e=E.messages,g.messages=E.messages),E.state!==void 0&&(s=E.state,g.state=E.state)},l=()=>{let E=C(g);return g={},E.messages!==void 0||E.state!==void 0?le(E):ge};return o.pipe(ie(async E=>{var d;let M=await h(a,e,s,(i,t,S)=>{var m;return(m=i.onEvent)==null?void 0:m.call(i,{event:E,agent:n,input:u,messages:t,state:S})});if(r(M),M.stopPropagation===!0)return l();switch(E.type){case v.TEXT_MESSAGE_START:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onTextMessageStartEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});if(r(i),i.stopPropagation!==!0){let{messageId:t,role:S="assistant"}=E,m={id:t,role:S,content:""};e.push(m),r({messages:e})}return l()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:i,delta:t}=E,S=e.find(c=>c.id===i);if(!S)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${i}'`),l();let m=await h(a,e,s,(c,T,x)=>{var O,P;return(P=c.onTextMessageContentEvent)==null?void 0:P.call(c,{event:E,messages:T,state:x,agent:n,input:u,textMessageBuffer:(O=S.content)!=null?O:""})});return r(m),m.stopPropagation!==!0&&(S.content=(S.content||"")+t,r({messages:e})),l()}case v.TEXT_MESSAGE_END:{let{messageId:i}=E,t=e.find(m=>m.id===i);if(!t)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${i}'`),l();let S=await h(a,e,s,(m,c,T)=>{var x,O;return(O=m.onTextMessageEndEvent)==null?void 0:O.call(m,{event:E,messages:c,state:T,agent:n,input:u,textMessageBuffer:(x=t.content)!=null?x:""})});return r(S),await Promise.all(a.map(m=>{var c;(c=m.onNewMessage)==null||c.call(m,{message:t,messages:e,state:s,agent:n,input:u})})),l()}case v.TOOL_CALL_START:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onToolCallStartEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});if(r(i),i.stopPropagation!==!0){let{toolCallId:t,toolCallName:S,parentMessageId:m}=E,c;m&&e.length>0&&e[e.length-1].id===m?c=e[e.length-1]:(c={id:m||t,role:"assistant",toolCalls:[]},e.push(c)),(d=c.toolCalls)!=null||(c.toolCalls=[]),c.toolCalls.push({id:t,type:"function",function:{name:S,arguments:""}}),r({messages:e})}return l()}case v.TOOL_CALL_ARGS:{let{toolCallId:i,delta:t}=E,S=e.find(T=>{var x;return(x=T.toolCalls)==null?void 0:x.some(O=>O.id===i)});if(!S)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${i}'`),l();let m=S.toolCalls.find(T=>T.id===i);if(!m)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${i}'`),l();let c=await h(a,e,s,(T,x,O)=>{var K;let P=m.function.arguments,F=m.function.name,D={};try{D=Ee(P)}catch(qe){}return(K=T.onToolCallArgsEvent)==null?void 0:K.call(T,{event:E,messages:x,state:O,agent:n,input:u,toolCallBuffer:P,toolCallName:F,partialToolCallArgs:D})});return r(c),c.stopPropagation!==!0&&(m.function.arguments+=t,r({messages:e})),l()}case v.TOOL_CALL_END:{let{toolCallId:i}=E,t=e.find(c=>{var T;return(T=c.toolCalls)==null?void 0:T.some(x=>x.id===i)});if(!t)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${i}'`),l();let S=t.toolCalls.find(c=>c.id===i);if(!S)return console.warn(`TOOL_CALL_END: No tool call found with ID '${i}'`),l();let m=await h(a,e,s,(c,T,x)=>{var D;let O=S.function.arguments,P=S.function.name,F={};try{F=JSON.parse(O)}catch(K){}return(D=c.onToolCallEndEvent)==null?void 0:D.call(c,{event:E,messages:T,state:x,agent:n,input:u,toolCallName:P,toolCallArgs:F})});return r(m),await Promise.all(a.map(c=>{var T;(T=c.onNewToolCall)==null||T.call(c,{toolCall:S,messages:e,state:s,agent:n,input:u})})),l()}case v.TOOL_CALL_RESULT:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onToolCallResultEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});if(r(i),i.stopPropagation!==!0){let{messageId:t,toolCallId:S,content:m,role:c}=E,T={id:t,toolCallId:S,role:c||"tool",content:m};e.push(T),await Promise.all(a.map(x=>{var O;(O=x.onNewMessage)==null||O.call(x,{message:T,messages:e,state:s,agent:n,input:u})})),r({messages:e})}return l()}case v.STATE_SNAPSHOT:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onStateSnapshotEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});if(r(i),i.stopPropagation!==!0){let{snapshot:t}=E;s=t,r({state:s})}return l()}case v.STATE_DELTA:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onStateDeltaEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});if(r(i),i.stopPropagation!==!0){let{delta:t}=E;try{s=ce(s,t,!0,!1).newDocument,r({state:s})}catch(S){let m=S instanceof Error?S.message:String(S);console.warn(`Failed to apply state patch:
2
2
  Current state: ${JSON.stringify(s,null,2)}
3
- Patch operations: ${JSON.stringify(a,null,2)}
4
- Error: ${S}`)}}return l()}case M.MESSAGES_SNAPSHOT:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onMessagesSnapshotEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p})});if(r(u),u.stopPropagation!==!0){let{messages:a}=c;e=a,r({messages:e})}return l()}case M.RAW:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onRawEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p})});return r(u),l()}case M.CUSTOM:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onCustomEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p})});return r(u),l()}case M.RUN_STARTED:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onRunStartedEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p})});return r(u),l()}case M.RUN_FINISHED:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onRunFinishedEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p,result:c.result})});return r(u),l()}case M.RUN_ERROR:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onRunErrorEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p})});return r(u),l()}case M.STEP_STARTED:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onStepStartedEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p})});return r(u),l()}case M.STEP_FINISHED:{let u=await C(n,e,s,(a,E,S)=>{var g;return(g=a.onStepFinishedEvent)==null?void 0:g.call(a,{event:c,messages:E,state:S,agent:t,input:p})});return r(u),l()}case M.TEXT_MESSAGE_CHUNK:throw new Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case M.TOOL_CALL_CHUNK:throw new Error("TOOL_CALL_CHUNK must be tranformed before being applied");case M.THINKING_START:return l();case M.THINKING_END:return l();case M.THINKING_TEXT_MESSAGE_START:return l();case M.THINKING_TEXT_MESSAGE_CONTENT:return l();case M.THINKING_TEXT_MESSAGE_END:return l()}let _=c.type;return l()}),oe(),n.length>0?re({}):c=>c)};import{EventType as A,AGUIError as h}from"@ag-ui/core";import{throwError as y,of as x}from"rxjs";import{mergeMap as ue}from"rxjs/operators";var X=p=>o=>{let t,n,e=!1,s=!1,i=!1,r=new Map,l=!1,c=!1;return o.pipe(ue(d=>{let _=d.type;if(p&&console.debug("[VERIFY]:",JSON.stringify(d)),s)return y(()=>new h(`Cannot send event type '${_}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(e&&_!==A.RUN_ERROR)return y(()=>new h(`Cannot send event type '${_}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(t!==void 0&&![A.TEXT_MESSAGE_CONTENT,A.TEXT_MESSAGE_END,A.RAW].includes(_))return y(()=>new h(`Cannot send event type '${_}' after 'TEXT_MESSAGE_START': Send 'TEXT_MESSAGE_END' first.`));if(n!==void 0&&![A.TOOL_CALL_ARGS,A.TOOL_CALL_END,A.RAW].includes(_))return _===A.TOOL_CALL_START?y(()=>new h("Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.")):y(()=>new h(`Cannot send event type '${_}' after 'TOOL_CALL_START': Send 'TOOL_CALL_END' first.`));if(i){if(_===A.RUN_STARTED)return y(()=>new h("Cannot send multiple 'RUN_STARTED' events: A 'RUN_STARTED' event was already sent. Each run must have exactly one 'RUN_STARTED' event at the beginning."))}else if(i=!0,_!==A.RUN_STARTED&&_!==A.RUN_ERROR)return y(()=>new h("First event must be 'RUN_STARTED'"));switch(_){case A.TEXT_MESSAGE_START:return t!==void 0?y(()=>new h("Cannot send 'TEXT_MESSAGE_START' event: A text message is already in progress. Complete it with 'TEXT_MESSAGE_END' first.")):(t=d.messageId,x(d));case A.TEXT_MESSAGE_CONTENT:return t===void 0?y(()=>new h("Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found. Start a text message with 'TEXT_MESSAGE_START' first.")):d.messageId!==t?y(()=>new h(`Cannot send 'TEXT_MESSAGE_CONTENT' event: Message ID mismatch. The ID '${d.messageId}' doesn't match the active message ID '${t}'.`)):x(d);case A.TEXT_MESSAGE_END:return t===void 0?y(()=>new h("Cannot send 'TEXT_MESSAGE_END' event: No active text message found. A 'TEXT_MESSAGE_START' event must be sent first.")):d.messageId!==t?y(()=>new h(`Cannot send 'TEXT_MESSAGE_END' event: Message ID mismatch. The ID '${d.messageId}' doesn't match the active message ID '${t}'.`)):(t=void 0,x(d));case A.TOOL_CALL_START:return n!==void 0?y(()=>new h("Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.")):(n=d.toolCallId,x(d));case A.TOOL_CALL_ARGS:return n===void 0?y(()=>new h("Cannot send 'TOOL_CALL_ARGS' event: No active tool call found. Start a tool call with 'TOOL_CALL_START' first.")):d.toolCallId!==n?y(()=>new h(`Cannot send 'TOOL_CALL_ARGS' event: Tool call ID mismatch. The ID '${d.toolCallId}' doesn't match the active tool call ID '${n}'.`)):x(d);case A.TOOL_CALL_END:return n===void 0?y(()=>new h("Cannot send 'TOOL_CALL_END' event: No active tool call found. A 'TOOL_CALL_START' event must be sent first.")):d.toolCallId!==n?y(()=>new h(`Cannot send 'TOOL_CALL_END' event: Tool call ID mismatch. The ID '${d.toolCallId}' doesn't match the active tool call ID '${n}'.`)):(n=void 0,x(d));case A.STEP_STARTED:{let T=d.stepName;return r.has(T)?y(()=>new h(`Step "${T}" is already active for 'STEP_STARTED'`)):(r.set(T,!0),x(d))}case A.STEP_FINISHED:{let T=d.stepName;return r.has(T)?(r.delete(T),x(d)):y(()=>new h(`Cannot send 'STEP_FINISHED' for step "${T}" that was not started`))}case A.RUN_STARTED:return x(d);case A.RUN_FINISHED:{if(r.size>0){let T=Array.from(r.keys()).join(", ");return y(()=>new h(`Cannot send 'RUN_FINISHED' while steps are still active: ${T}`))}return e=!0,x(d)}case A.RUN_ERROR:return s=!0,x(d);case A.CUSTOM:return x(d);case A.THINKING_TEXT_MESSAGE_START:return l?c?y(()=>new h("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(c=!0,x(d)):y(()=>new h("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case A.THINKING_TEXT_MESSAGE_CONTENT:return c?x(d):y(()=>new h("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case A.THINKING_TEXT_MESSAGE_END:return c?(c=!1,x(d)):y(()=>new h("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case A.THINKING_START:return l?y(()=>new h("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(l=!0,x(d));case A.THINKING_END:return l?(l=!1,x(d)):y(()=>new h("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return x(d)}}))};import{EventSchemas as ve}from"@ag-ui/core";import{Subject as he,ReplaySubject as ye}from"rxjs";import{Observable as pe,from as me,defer as Se,throwError as de}from"rxjs";import{switchMap as Te}from"rxjs/operators";var k=(p,o)=>Se(()=>me(fetch(p,o))).pipe(Te(t=>{var s;let n={type:"headers",status:t.status,headers:t.headers},e=(s=t.body)==null?void 0:s.getReader();return e?new pe(i=>(i.next(n),(async()=>{try{for(;;){let{done:r,value:l}=await e.read();if(r)break;let c={type:"data",data:l};i.next(c)}i.complete()}catch(r){i.error(r)}})(),()=>{e.cancel()})):de(()=>new Error("Failed to getReader() from response"))}));import{Subject as fe}from"rxjs";var B=p=>{let o=new fe,t=new TextDecoder("utf-8",{fatal:!1}),n="";p.subscribe({next:s=>{if(s.type!=="headers"&&s.type==="data"&&s.data){let i=t.decode(s.data,{stream:!0});n+=i;let r=n.split(/\n\n/);n=r.pop()||"";for(let l of r)e(l)}},error:s=>o.error(s),complete:()=>{n&&(n+=t.decode(),e(n)),o.complete()}});function e(s){let i=s.split(`
5
- `),r=[];for(let l of i)l.startsWith("data: ")&&r.push(l.slice(6));if(r.length>0)try{let l=r.join(`
6
- `),c=JSON.parse(l);o.next(c)}catch(l){o.error(l)}}return o.asObservable()};import{Subject as Ae}from"rxjs";import*as b from"@ag-ui/proto";var z=p=>{let o=new Ae,t=new Uint8Array(0);p.subscribe({next:e=>{if(e.type!=="headers"&&e.type==="data"&&e.data){let s=new Uint8Array(t.length+e.data.length);s.set(t,0),s.set(e.data,t.length),t=s,n()}},error:e=>o.error(e),complete:()=>{if(t.length>0)try{n()}catch(e){console.warn("Incomplete or invalid protocol buffer data at stream end")}o.complete()}});function n(){for(;t.length>=4;){let i=4+new DataView(t.buffer,t.byteOffset,4).getUint32(0,!1);if(t.length<i)break;try{let r=t.slice(4,i),l=b.decode(r);o.next(l),t=t.slice(i)}catch(r){let l=r instanceof Error?r.message:String(r);o.error(new Error(`Failed to decode protocol buffer message: ${l}`));return}}}return o.asObservable()};import*as Y from"@ag-ui/proto";var J=p=>{let o=new he,t=new ye,n=!1;return p.subscribe({next:e=>{t.next(e),e.type==="headers"&&!n?(n=!0,e.headers.get("content-type")===Y.AGUI_MEDIA_TYPE?z(t).subscribe({next:i=>o.next(i),error:i=>o.error(i),complete:()=>o.complete()}):B(t).subscribe({next:i=>{try{let r=ve.parse(i);o.next(r)}catch(r){o.error(r)}},error:i=>o.error(i),complete:()=>o.complete()})):n||o.error(new Error("No headers event received before data events"))},error:e=>{t.error(e),o.error(e)},complete:()=>{t.complete()}}),o.asObservable()};import{mergeMap as De}from"rxjs/operators";import{applyPatch as He}from"fast-json-patch";import{EventType as L}from"@ag-ui/core";import{z as m}from"zod";var v=m.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Me=m.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Ce=m.object({type:m.literal(v.enum.TextMessageStart),messageId:m.string(),parentMessageId:m.string().optional()}),_e=m.object({type:m.literal(v.enum.TextMessageContent),messageId:m.string(),content:m.string()}),Re=m.object({type:m.literal(v.enum.TextMessageEnd),messageId:m.string()}),Ne=m.object({type:m.literal(v.enum.ActionExecutionStart),actionExecutionId:m.string(),actionName:m.string(),parentMessageId:m.string().optional()}),xe=m.object({type:m.literal(v.enum.ActionExecutionArgs),actionExecutionId:m.string(),args:m.string()}),Le=m.object({type:m.literal(v.enum.ActionExecutionEnd),actionExecutionId:m.string()}),Ie=m.object({type:m.literal(v.enum.ActionExecutionResult),actionName:m.string(),actionExecutionId:m.string(),result:m.string()}),Oe=m.object({type:m.literal(v.enum.AgentStateMessage),threadId:m.string(),agentName:m.string(),nodeName:m.string(),runId:m.string(),active:m.boolean(),role:m.string(),state:m.string(),running:m.boolean()}),we=m.object({type:m.literal(v.enum.MetaEvent),name:Me,value:m.any()}),Pe=m.object({type:m.literal(v.enum.RunError),message:m.string(),code:m.string().optional()}),un=m.discriminatedUnion("type",[Ce,_e,Re,Ne,xe,Le,Ie,Oe,we,Pe]),pn=m.object({id:m.string(),role:m.string(),content:m.string(),parentMessageId:m.string().optional()}),mn=m.object({id:m.string(),name:m.string(),arguments:m.any(),parentMessageId:m.string().optional()}),Sn=m.object({id:m.string(),result:m.any(),actionExecutionId:m.string(),actionName:m.string()});import Ge from"untruncate-json";var j=(p,o,t)=>n=>{let e={},s=!0,i=!0,r="",l=null,c=null,d=[],_={},T=u=>{typeof u=="object"&&u!==null&&("messages"in u&&delete u.messages,e=u)};return n.pipe(De(u=>{switch(u.type){case L.TEXT_MESSAGE_START:{let a=u;return[{type:v.enum.TextMessageStart,messageId:a.messageId}]}case L.TEXT_MESSAGE_CONTENT:{let a=u;return[{type:v.enum.TextMessageContent,messageId:a.messageId,content:a.delta}]}case L.TEXT_MESSAGE_END:{let a=u;return[{type:v.enum.TextMessageEnd,messageId:a.messageId}]}case L.TOOL_CALL_START:{let a=u;return d.push({id:a.toolCallId,type:"function",function:{name:a.toolCallName,arguments:""}}),i=!0,_[a.toolCallId]=a.toolCallName,[{type:v.enum.ActionExecutionStart,actionExecutionId:a.toolCallId,actionName:a.toolCallName,parentMessageId:a.parentMessageId}]}case L.TOOL_CALL_ARGS:{let a=u,E=d[d.length-1];E.function.arguments+=a.delta;let S=!1;if(c){let g=c.find(N=>N.tool==E.function.name);if(g)try{let N=JSON.parse(Ge(E.function.arguments));g.tool_argument&&g.tool_argument in N?(T(G(I({},e),{[g.state_key]:N[g.tool_argument]})),S=!0):g.tool_argument||(T(G(I({},e),{[g.state_key]:N})),S=!0)}catch(N){}}return[{type:v.enum.ActionExecutionArgs,actionExecutionId:a.toolCallId,args:a.delta},...S?[{type:v.enum.AgentStateMessage,threadId:p,agentName:t,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:i}]:[]]}case L.TOOL_CALL_END:{let a=u;return[{type:v.enum.ActionExecutionEnd,actionExecutionId:a.toolCallId}]}case L.TOOL_CALL_RESULT:{let a=u;return[{type:v.enum.ActionExecutionResult,actionExecutionId:a.toolCallId,result:a.content,actionName:_[a.toolCallId]||"unknown"}]}case L.RAW:return[];case L.CUSTOM:{let a=u;switch(a.name){case"Exit":s=!1;break;case"PredictState":c=a.value;break}return[{type:v.enum.MetaEvent,name:a.name,value:a.value}]}case L.STATE_SNAPSHOT:return T(u.snapshot),[{type:v.enum.AgentStateMessage,threadId:p,agentName:t,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:i}];case L.STATE_DELTA:{let E=He(e,u.delta,!0,!1);return E?(T(E.newDocument),[{type:v.enum.AgentStateMessage,threadId:p,agentName:t,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:i}]):[]}case L.MESSAGES_SNAPSHOT:return l=u.messages,[{type:v.enum.AgentStateMessage,threadId:p,agentName:t,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(I(I({},e),l?{messages:l}:{})),active:!0}];case L.RUN_STARTED:return[];case L.RUN_FINISHED:return l&&(e.messages=l),[{type:v.enum.AgentStateMessage,threadId:p,agentName:t,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(I(I({},e),l?{messages:Fe(l)}:{})),active:!1}];case L.RUN_ERROR:{let a=u;return[{type:v.enum.RunError,message:a.message,code:a.code}]}case L.STEP_STARTED:return r=u.stepName,d=[],c=null,[{type:v.enum.AgentStateMessage,threadId:p,agentName:t,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:!0}];case L.STEP_FINISHED:return d=[],c=null,[{type:v.enum.AgentStateMessage,threadId:p,agentName:t,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:!1}];default:return[]}}))};function Fe(p){var t;let o=[];for(let n of p)if(n.role==="assistant"||n.role==="user"||n.role==="system"){if(n.content){let e={id:n.id,role:n.role,content:n.content};o.push(e)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let e of n.toolCalls){let s={id:e.id,name:e.function.name,arguments:JSON.parse(e.function.arguments),parentMessageId:n.id};o.push(s)}}else if(n.role==="tool"){let e="unknown";for(let i of p)if(i.role==="assistant"&&((t=i.toolCalls)!=null&&t.length)){for(let r of i.toolCalls)if(r.id===n.toolCallId){e=r.function.name;break}}let s={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:e};o.push(s)}return o}import{v4 as U}from"uuid";import{catchError as Ke,map as Q,tap as ke}from"rxjs/operators";import{finalize as Be}from"rxjs/operators";import{pipe as ze,from as Je,of as je}from"rxjs";import{lastValueFrom as $e}from"rxjs";import{mergeMap as Xe,finalize as Ue}from"rxjs";import{EventType as f}from"@ag-ui/core";var $=p=>o=>{let t,n,e,s=()=>{if(!t||e!=="text")throw new Error("No text message to close");let l={type:f.TEXT_MESSAGE_END,messageId:t.messageId};return e=void 0,t=void 0,p&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(l)),l},i=()=>{if(!n||e!=="tool")throw new Error("No tool call to close");let l={type:f.TOOL_CALL_END,toolCallId:n.toolCallId};return e=void 0,n=void 0,p&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(l)),l},r=()=>e==="text"?[s()]:e==="tool"?[i()]:[];return o.pipe(Xe(l=>{switch(l.type){case f.TEXT_MESSAGE_START:case f.TEXT_MESSAGE_CONTENT:case f.TEXT_MESSAGE_END:case f.TOOL_CALL_START:case f.TOOL_CALL_ARGS:case f.TOOL_CALL_END:case f.TOOL_CALL_RESULT:case f.STATE_SNAPSHOT:case f.STATE_DELTA:case f.MESSAGES_SNAPSHOT:case f.CUSTOM:case f.RUN_STARTED:case f.RUN_FINISHED:case f.RUN_ERROR:case f.STEP_STARTED:case f.STEP_FINISHED:case f.THINKING_START:case f.THINKING_END:case f.THINKING_TEXT_MESSAGE_START:case f.THINKING_TEXT_MESSAGE_CONTENT:case f.THINKING_TEXT_MESSAGE_END:return[...r(),l];case f.RAW:return[l];case f.TEXT_MESSAGE_CHUNK:let d=l,_=[];if((e!=="text"||d.messageId!==void 0&&d.messageId!==(t==null?void 0:t.messageId))&&_.push(...r()),e!=="text"){if(d.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");t={messageId:d.messageId},e="text";let a={type:f.TEXT_MESSAGE_START,messageId:d.messageId,role:"assistant"};_.push(a),p&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(a))}if(d.delta!==void 0){let a={type:f.TEXT_MESSAGE_CONTENT,messageId:t.messageId,delta:d.delta};_.push(a),p&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(a))}return _;case f.TOOL_CALL_CHUNK:let T=l,u=[];if((e!=="tool"||T.toolCallId!==void 0&&T.toolCallId!==(n==null?void 0:n.toolCallId))&&u.push(...r()),e!=="tool"){if(T.toolCallId===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallId");if(T.toolCallName===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallName");n={toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId},e="tool";let a={type:f.TOOL_CALL_START,toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId};u.push(a),p&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(a))}if(T.delta!==void 0){let a={type:f.TOOL_CALL_ARGS,toolCallId:n.toolCallId,delta:T.delta};u.push(a),p&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(a))}return u}let c=l.type}),Ue(()=>r()))};var F=class{constructor({agentId:o,description:t,threadId:n,initialMessages:e,initialState:s,debug:i}={}){this.debug=!1;this.subscribers=[];this.agentId=o,this.description=t!=null?t:"",this.threadId=n!=null?n:U(),this.messages=R(e!=null?e:[]),this.state=R(s!=null?s:{}),this.debug=i!=null?i:!1}subscribe(o){return this.subscribers.push(o),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==o)}}}async runAgent(o,t){var l;this.agentId=(l=this.agentId)!=null?l:U();let n=this.prepareRunAgentInput(o),e,s=new Set(this.messages.map(c=>c.id)),i=[{onRunFinishedEvent:c=>{e=c.result}},...this.subscribers,t!=null?t:{}];await this.onInitialize(n,i);let r=ze(()=>this.run(n),$(this.debug),X(this.debug),c=>this.apply(n,c,i),c=>this.processApplyEvents(n,c,i),Ke(c=>this.onError(n,c,i)),Be(()=>{this.onFinalize(n,i)}));return $e(r(je(null))).then(()=>{let c=R(this.messages).filter(d=>!s.has(d.id));return{result:e,newMessages:c}})}abortRun(){}apply(o,t,n){return K(o,t,this,n)}processApplyEvents(o,t,n){return t.pipe(ke(e=>{e.messages&&(this.messages=e.messages,n.forEach(s=>{var i;(i=s.onMessagesChanged)==null||i.call(s,{messages:this.messages,state:this.state,agent:this,input:o})})),e.state&&(this.state=e.state,n.forEach(s=>{var i;(i=s.onStateChanged)==null||i.call(s,{state:this.state,messages:this.messages,agent:this,input:o})}))}))}prepareRunAgentInput(o){var t,n,e;return{threadId:this.threadId,runId:(o==null?void 0:o.runId)||U(),tools:R((t=o==null?void 0:o.tools)!=null?t:[]),context:R((n=o==null?void 0:o.context)!=null?n:[]),forwardedProps:R((e=o==null?void 0:o.forwardedProps)!=null?e:{}),state:R(this.state),messages:R(this.messages)}}async onInitialize(o,t){let n=await C(t,this.messages,this.state,(e,s,i)=>{var r;return(r=e.onRunInitialized)==null?void 0:r.call(e,{messages:s,state:i,agent:this,input:o})});(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,o.messages=n.messages,t.forEach(e=>{var s;(s=e.onMessagesChanged)==null||s.call(e,{messages:this.messages,state:this.state,agent:this,input:o})})),n.state&&(this.state=n.state,o.state=n.state,t.forEach(e=>{var s;(s=e.onStateChanged)==null||s.call(e,{state:this.state,messages:this.messages,agent:this,input:o})})))}onError(o,t,n){return Je(C(n,this.messages,this.state,(e,s,i)=>{var r;return(r=e.onRunFailed)==null?void 0:r.call(e,{error:t,messages:s,state:i,agent:this,input:o})})).pipe(Q(e=>{let s=e;if((s.messages!==void 0||s.state!==void 0)&&(s.messages!==void 0&&(this.messages=s.messages,n.forEach(i=>{var r;(r=i.onMessagesChanged)==null||r.call(i,{messages:this.messages,state:this.state,agent:this,input:o})})),s.state!==void 0&&(this.state=s.state,n.forEach(i=>{var r;(r=i.onStateChanged)==null||r.call(i,{state:this.state,messages:this.messages,agent:this,input:o})}))),s.stopPropagation!==!0)throw console.error("Agent execution failed:",t),t;return{}}))}async onFinalize(o,t){let n=await C(t,this.messages,this.state,(e,s,i)=>{var r;return(r=e.onRunFinalized)==null?void 0:r.call(e,{messages:s,state:i,agent:this,input:o})});(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,t.forEach(e=>{var s;(s=e.onMessagesChanged)==null||s.call(e,{messages:this.messages,state:this.state,agent:this,input:o})})),n.state!==void 0&&(this.state=n.state,t.forEach(e=>{var s;(s=e.onStateChanged)==null||s.call(e,{state:this.state,messages:this.messages,agent:this,input:o})})))}clone(){let o=Object.create(Object.getPrototypeOf(this));for(let t of Object.getOwnPropertyNames(this)){let n=this[t];typeof n!="function"&&(o[t]=R(n))}return o}addMessage(o){this.messages.push(o),(async()=>{var t,n,e;for(let s of this.subscribers)await((t=s.onNewMessage)==null?void 0:t.call(s,{message:o,messages:this.messages,state:this.state,agent:this}));if(o.role==="assistant"&&o.toolCalls)for(let s of o.toolCalls)for(let i of this.subscribers)await((n=i.onNewToolCall)==null?void 0:n.call(i,{toolCall:s,messages:this.messages,state:this.state,agent:this}));for(let s of this.subscribers)await((e=s.onMessagesChanged)==null?void 0:e.call(s,{messages:this.messages,state:this.state,agent:this}))})()}addMessages(o){this.messages.push(...o),(async()=>{var t,n,e;for(let s of o){for(let i of this.subscribers)await((t=i.onNewMessage)==null?void 0:t.call(i,{message:s,messages:this.messages,state:this.state,agent:this}));if(s.role==="assistant"&&s.toolCalls)for(let i of s.toolCalls)for(let r of this.subscribers)await((n=r.onNewToolCall)==null?void 0:n.call(r,{toolCall:i,messages:this.messages,state:this.state,agent:this}))}for(let s of this.subscribers)await((e=s.onMessagesChanged)==null?void 0:e.call(s,{messages:this.messages,state:this.state,agent:this}))})()}setMessages(o){this.messages=R(o),(async()=>{var t;for(let n of this.subscribers)await((t=n.onMessagesChanged)==null?void 0:t.call(n,{messages:this.messages,state:this.state,agent:this}))})()}setState(o){this.state=R(o),(async()=>{var t;for(let n of this.subscribers)await((t=n.onStateChanged)==null?void 0:t.call(n,{messages:this.messages,state:this.state,agent:this}))})()}legacy_to_be_removed_runAgentBridged(o){var n;this.agentId=(n=this.agentId)!=null?n:U();let t=this.prepareRunAgentInput(o);return this.run(t).pipe($(this.debug),X(this.debug),j(this.threadId,t.runId,this.agentId),e=>e.pipe(Q(s=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(s)),s))))}};var W=class extends F{constructor(t){var n;super(t);this.abortController=new AbortController;this.url=t.url,this.headers=R((n=t.headers)!=null?n:{})}requestInit(t){return{method:"POST",headers:G(I({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(t),signal:this.abortController.signal}}runAgent(t,n){var e;return this.abortController=(e=t==null?void 0:t.abortController)!=null?e:new AbortController,super.runAgent(t,n)}abortRun(){this.abortController.abort(),super.abortRun()}run(t){let n=k(this.url,this.requestInit(t));return J(n)}};export*from"@ag-ui/core";export{F as AbstractAgent,W as HttpAgent,j as convertToLegacyEvents,K as defaultApplyEvents,z as parseProtoStream,B as parseSSEStream,k as runHttpRequest,J as transformHttpEventStream,X as verifyEvents};
3
+ Patch operations: ${JSON.stringify(t,null,2)}
4
+ Error: ${m}`)}}return l()}case v.MESSAGES_SNAPSHOT:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onMessagesSnapshotEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});if(r(i),i.stopPropagation!==!0){let{messages:t}=E;e=t,r({messages:e})}return l()}case v.RAW:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onRawEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});return r(i),l()}case v.CUSTOM:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onCustomEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});return r(i),l()}case v.RUN_STARTED:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onRunStartedEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});return r(i),l()}case v.RUN_FINISHED:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onRunFinishedEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u,result:E.result})});return r(i),l()}case v.RUN_ERROR:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onRunErrorEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});return r(i),l()}case v.STEP_STARTED:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onStepStartedEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});return r(i),l()}case v.STEP_FINISHED:{let i=await h(a,e,s,(t,S,m)=>{var c;return(c=t.onStepFinishedEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});return r(i),l()}case v.TEXT_MESSAGE_CHUNK:throw new Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case v.TOOL_CALL_CHUNK:throw new Error("TOOL_CALL_CHUNK must be tranformed before being applied");case v.THINKING_START:return l();case v.THINKING_END:return l();case v.THINKING_TEXT_MESSAGE_START:return l();case v.THINKING_TEXT_MESSAGE_CONTENT:return l();case v.THINKING_TEXT_MESSAGE_END:return l()}let w=E.type;return l()}),oe(),a.length>0?re({}):E=>E)};import{EventType as y,AGUIError as R}from"@ag-ui/core";import{throwError as _,of as N}from"rxjs";import{mergeMap as ue}from"rxjs/operators";var U=u=>o=>{let n=new Map,a=new Map,e=!1,s=!1,g=!1,r=new Map,l=!1,E=!1,M=!1,w=()=>{n.clear(),a.clear(),r.clear(),l=!1,E=!1,e=!1,s=!1,M=!0};return o.pipe(ue(d=>{let i=d.type;if(u&&console.debug("[VERIFY]:",JSON.stringify(d)),s)return _(()=>new R(`Cannot send event type '${i}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(e&&i!==y.RUN_ERROR&&i!==y.RUN_STARTED)return _(()=>new R(`Cannot send event type '${i}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(g){if(i===y.RUN_STARTED){if(M&&!e)return _(()=>new R("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));e&&w()}}else if(g=!0,i!==y.RUN_STARTED&&i!==y.RUN_ERROR)return _(()=>new R("First event must be 'RUN_STARTED'"));switch(i){case y.TEXT_MESSAGE_START:{let t=d.messageId;return n.has(t)?_(()=>new R(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${t}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(n.set(t,!0),N(d))}case y.TEXT_MESSAGE_CONTENT:{let t=d.messageId;return n.has(t)?N(d):_(()=>new R(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${t}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case y.TEXT_MESSAGE_END:{let t=d.messageId;return n.has(t)?(n.delete(t),N(d)):_(()=>new R(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${t}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case y.TOOL_CALL_START:{let t=d.toolCallId;return a.has(t)?_(()=>new R(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${t}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(a.set(t,!0),N(d))}case y.TOOL_CALL_ARGS:{let t=d.toolCallId;return a.has(t)?N(d):_(()=>new R(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${t}'. Start a tool call with 'TOOL_CALL_START' first.`))}case y.TOOL_CALL_END:{let t=d.toolCallId;return a.has(t)?(a.delete(t),N(d)):_(()=>new R(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${t}'. A 'TOOL_CALL_START' event must be sent first.`))}case y.STEP_STARTED:{let t=d.stepName;return r.has(t)?_(()=>new R(`Step "${t}" is already active for 'STEP_STARTED'`)):(r.set(t,!0),N(d))}case y.STEP_FINISHED:{let t=d.stepName;return r.has(t)?(r.delete(t),N(d)):_(()=>new R(`Cannot send 'STEP_FINISHED' for step "${t}" that was not started`))}case y.RUN_STARTED:return M=!0,N(d);case y.RUN_FINISHED:{if(r.size>0){let t=Array.from(r.keys()).join(", ");return _(()=>new R(`Cannot send 'RUN_FINISHED' while steps are still active: ${t}`))}if(n.size>0){let t=Array.from(n.keys()).join(", ");return _(()=>new R(`Cannot send 'RUN_FINISHED' while text messages are still active: ${t}`))}if(a.size>0){let t=Array.from(a.keys()).join(", ");return _(()=>new R(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${t}`))}return e=!0,N(d)}case y.RUN_ERROR:return s=!0,N(d);case y.CUSTOM:return N(d);case y.THINKING_TEXT_MESSAGE_START:return l?E?_(()=>new R("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(E=!0,N(d)):_(()=>new R("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case y.THINKING_TEXT_MESSAGE_CONTENT:return E?N(d):_(()=>new R("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case y.THINKING_TEXT_MESSAGE_END:return E?(E=!1,N(d)):_(()=>new R("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case y.THINKING_START:return l?_(()=>new R("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(l=!0,N(d));case y.THINKING_END:return l?(l=!1,N(d)):_(()=>new R("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return N(d)}}))};import{EventSchemas as ve}from"@ag-ui/core";import{Subject as he,ReplaySubject as Me}from"rxjs";import{Observable as pe,from as me,defer as Se,throwError as de}from"rxjs";import{switchMap as fe}from"rxjs/operators";var z=(u,o)=>Se(()=>me(fetch(u,o))).pipe(fe(n=>{var s;let a={type:"headers",status:n.status,headers:n.headers},e=(s=n.body)==null?void 0:s.getReader();return e?new pe(g=>(g.next(a),(async()=>{try{for(;;){let{done:r,value:l}=await e.read();if(r)break;let E={type:"data",data:l};g.next(E)}g.complete()}catch(r){g.error(r)}})(),()=>{e.cancel()})):de(()=>new Error("Failed to getReader() from response"))}));import{Subject as Te}from"rxjs";var B=u=>{let o=new Te,n=new TextDecoder("utf-8",{fatal:!1}),a="";u.subscribe({next:s=>{if(s.type!=="headers"&&s.type==="data"&&s.data){let g=n.decode(s.data,{stream:!0});a+=g;let r=a.split(/\n\n/);a=r.pop()||"";for(let l of r)e(l)}},error:s=>o.error(s),complete:()=>{a&&(a+=n.decode(),e(a)),o.complete()}});function e(s){let g=s.split(`
5
+ `),r=[];for(let l of g)l.startsWith("data: ")&&r.push(l.slice(6));if(r.length>0)try{let l=r.join(`
6
+ `),E=JSON.parse(l);o.next(E)}catch(l){o.error(l)}}return o.asObservable()};import{Subject as Ae}from"rxjs";import*as Y from"@ag-ui/proto";var j=u=>{let o=new Ae,n=new Uint8Array(0);u.subscribe({next:e=>{if(e.type!=="headers"&&e.type==="data"&&e.data){let s=new Uint8Array(n.length+e.data.length);s.set(n,0),s.set(e.data,n.length),n=s,a()}},error:e=>o.error(e),complete:()=>{if(n.length>0)try{a()}catch(e){console.warn("Incomplete or invalid protocol buffer data at stream end")}o.complete()}});function a(){for(;n.length>=4;){let g=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<g)break;try{let r=n.slice(4,g),l=Y.decode(r);o.next(l),n=n.slice(g)}catch(r){let l=r instanceof Error?r.message:String(r);o.error(new Error(`Failed to decode protocol buffer message: ${l}`));return}}}return o.asObservable()};import*as Q from"@ag-ui/proto";var J=u=>{let o=new he,n=new Me,a=!1;return u.subscribe({next:e=>{n.next(e),e.type==="headers"&&!a?(a=!0,e.headers.get("content-type")===Q.AGUI_MEDIA_TYPE?j(n).subscribe({next:g=>o.next(g),error:g=>o.error(g),complete:()=>o.complete()}):B(n).subscribe({next:g=>{try{let r=ve.parse(g);o.next(r)}catch(r){o.error(r)}},error:g=>o.error(g),complete:()=>o.complete()})):a||o.error(new Error("No headers event received before data events"))},error:e=>{n.error(e),o.error(e)},complete:()=>{n.complete()}}),o.asObservable()};import{mergeMap as De}from"rxjs/operators";import{applyPatch as He}from"fast-json-patch";import{EventType as I}from"@ag-ui/core";import{z as p}from"zod";var A=p.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),ye=p.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Ce=p.object({type:p.literal(A.enum.TextMessageStart),messageId:p.string(),parentMessageId:p.string().optional(),role:p.string().optional()}),Re=p.object({type:p.literal(A.enum.TextMessageContent),messageId:p.string(),content:p.string()}),_e=p.object({type:p.literal(A.enum.TextMessageEnd),messageId:p.string()}),Ne=p.object({type:p.literal(A.enum.ActionExecutionStart),actionExecutionId:p.string(),actionName:p.string(),parentMessageId:p.string().optional()}),xe=p.object({type:p.literal(A.enum.ActionExecutionArgs),actionExecutionId:p.string(),args:p.string()}),Ie=p.object({type:p.literal(A.enum.ActionExecutionEnd),actionExecutionId:p.string()}),Le=p.object({type:p.literal(A.enum.ActionExecutionResult),actionName:p.string(),actionExecutionId:p.string(),result:p.string()}),Oe=p.object({type:p.literal(A.enum.AgentStateMessage),threadId:p.string(),agentName:p.string(),nodeName:p.string(),runId:p.string(),active:p.boolean(),role:p.string(),state:p.string(),running:p.boolean()}),we=p.object({type:p.literal(A.enum.MetaEvent),name:ye,value:p.any()}),Pe=p.object({type:p.literal(A.enum.RunError),message:p.string(),code:p.string().optional()}),dn=p.discriminatedUnion("type",[Ce,Re,_e,Ne,xe,Ie,Le,Oe,we,Pe]),fn=p.object({id:p.string(),role:p.string(),content:p.string(),parentMessageId:p.string().optional()}),Tn=p.object({id:p.string(),name:p.string(),arguments:p.any(),parentMessageId:p.string().optional()}),An=p.object({id:p.string(),result:p.any(),actionExecutionId:p.string(),actionName:p.string()});import Ge from"untruncate-json";var $=(u,o,n)=>a=>{let e={},s=!0,g=!0,r="",l=null,E=null,M=[],w={},d=i=>{typeof i=="object"&&i!==null&&("messages"in i&&delete i.messages,e=i)};return a.pipe(De(i=>{switch(i.type){case I.TEXT_MESSAGE_START:{let t=i;return[{type:A.enum.TextMessageStart,messageId:t.messageId,role:t.role}]}case I.TEXT_MESSAGE_CONTENT:{let t=i;return[{type:A.enum.TextMessageContent,messageId:t.messageId,content:t.delta}]}case I.TEXT_MESSAGE_END:{let t=i;return[{type:A.enum.TextMessageEnd,messageId:t.messageId}]}case I.TOOL_CALL_START:{let t=i;return M.push({id:t.toolCallId,type:"function",function:{name:t.toolCallName,arguments:""}}),g=!0,w[t.toolCallId]=t.toolCallName,[{type:A.enum.ActionExecutionStart,actionExecutionId:t.toolCallId,actionName:t.toolCallName,parentMessageId:t.parentMessageId}]}case I.TOOL_CALL_ARGS:{let t=i,S=M.find(c=>c.id===t.toolCallId);if(!S)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${t.toolCallId}'`),[];S.function.arguments+=t.delta;let m=!1;if(E){let c=E.find(T=>T.tool==S.function.name);if(c)try{let T=JSON.parse(Ge(S.function.arguments));c.tool_argument&&c.tool_argument in T?(d(H(L({},e),{[c.state_key]:T[c.tool_argument]})),m=!0):c.tool_argument||(d(H(L({},e),{[c.state_key]:T})),m=!0)}catch(T){}}return[{type:A.enum.ActionExecutionArgs,actionExecutionId:t.toolCallId,args:t.delta},...m?[{type:A.enum.AgentStateMessage,threadId:u,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:g}]:[]]}case I.TOOL_CALL_END:{let t=i;return[{type:A.enum.ActionExecutionEnd,actionExecutionId:t.toolCallId}]}case I.TOOL_CALL_RESULT:{let t=i;return[{type:A.enum.ActionExecutionResult,actionExecutionId:t.toolCallId,result:t.content,actionName:w[t.toolCallId]||"unknown"}]}case I.RAW:return[];case I.CUSTOM:{let t=i;switch(t.name){case"Exit":s=!1;break;case"PredictState":E=t.value;break}return[{type:A.enum.MetaEvent,name:t.name,value:t.value}]}case I.STATE_SNAPSHOT:return d(i.snapshot),[{type:A.enum.AgentStateMessage,threadId:u,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:g}];case I.STATE_DELTA:{let S=He(e,i.delta,!0,!1);return S?(d(S.newDocument),[{type:A.enum.AgentStateMessage,threadId:u,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:g}]):[]}case I.MESSAGES_SNAPSHOT:return l=i.messages,[{type:A.enum.AgentStateMessage,threadId:u,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(L(L({},e),l?{messages:l}:{})),active:!0}];case I.RUN_STARTED:return[];case I.RUN_FINISHED:return l&&(e.messages=l),[{type:A.enum.AgentStateMessage,threadId:u,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(L(L({},e),l?{messages:Fe(l)}:{})),active:!1}];case I.RUN_ERROR:{let t=i;return[{type:A.enum.RunError,message:t.message,code:t.code}]}case I.STEP_STARTED:return r=i.stepName,M=[],E=null,[{type:A.enum.AgentStateMessage,threadId:u,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:!0}];case I.STEP_FINISHED:return M=[],E=null,[{type:A.enum.AgentStateMessage,threadId:u,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:!1}];default:return[]}}))};function Fe(u){var n;let o=[];for(let a of u)if(a.role==="assistant"||a.role==="user"||a.role==="system"){if(a.content){let e={id:a.id,role:a.role,content:a.content};o.push(e)}if(a.role==="assistant"&&a.toolCalls&&a.toolCalls.length>0)for(let e of a.toolCalls){let s={id:e.id,name:e.function.name,arguments:JSON.parse(e.function.arguments),parentMessageId:a.id};o.push(s)}}else if(a.role==="tool"){let e="unknown";for(let g of u)if(g.role==="assistant"&&((n=g.toolCalls)!=null&&n.length)){for(let r of g.toolCalls)if(r.id===a.toolCallId){e=r.function.name;break}}let s={id:a.id,result:a.content,actionExecutionId:a.toolCallId,actionName:e};o.push(s)}return o}import{v4 as X}from"uuid";import{catchError as Ke,map as Z,tap as ke}from"rxjs/operators";import{finalize as ze}from"rxjs/operators";import{pipe as Be,from as je,of as Je}from"rxjs";import{lastValueFrom as $e}from"rxjs";import{mergeMap as Ue,finalize as Xe}from"rxjs";import{EventType as f}from"@ag-ui/core";var q=u=>o=>{let n,a,e,s=()=>{if(!n||e!=="text")throw new Error("No text message to close");let l={type:f.TEXT_MESSAGE_END,messageId:n.messageId};return e=void 0,n=void 0,u&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(l)),l},g=()=>{if(!a||e!=="tool")throw new Error("No tool call to close");let l={type:f.TOOL_CALL_END,toolCallId:a.toolCallId};return e=void 0,a=void 0,u&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(l)),l},r=()=>e==="text"?[s()]:e==="tool"?[g()]:[];return o.pipe(Ue(l=>{switch(l.type){case f.TEXT_MESSAGE_START:case f.TEXT_MESSAGE_CONTENT:case f.TEXT_MESSAGE_END:case f.TOOL_CALL_START:case f.TOOL_CALL_ARGS:case f.TOOL_CALL_END:case f.TOOL_CALL_RESULT:case f.STATE_SNAPSHOT:case f.STATE_DELTA:case f.MESSAGES_SNAPSHOT:case f.CUSTOM:case f.RUN_STARTED:case f.RUN_FINISHED:case f.RUN_ERROR:case f.STEP_STARTED:case f.STEP_FINISHED:case f.THINKING_START:case f.THINKING_END:case f.THINKING_TEXT_MESSAGE_START:case f.THINKING_TEXT_MESSAGE_CONTENT:case f.THINKING_TEXT_MESSAGE_END:return[...r(),l];case f.RAW:return[l];case f.TEXT_MESSAGE_CHUNK:let M=l,w=[];if((e!=="text"||M.messageId!==void 0&&M.messageId!==(n==null?void 0:n.messageId))&&w.push(...r()),e!=="text"){if(M.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");n={messageId:M.messageId},e="text";let t={type:f.TEXT_MESSAGE_START,messageId:M.messageId,role:M.role||"assistant"};w.push(t),u&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(t))}if(M.delta!==void 0){let t={type:f.TEXT_MESSAGE_CONTENT,messageId:n.messageId,delta:M.delta};w.push(t),u&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(t))}return w;case f.TOOL_CALL_CHUNK:let d=l,i=[];if((e!=="tool"||d.toolCallId!==void 0&&d.toolCallId!==(a==null?void 0:a.toolCallId))&&i.push(...r()),e!=="tool"){if(d.toolCallId===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallId");if(d.toolCallName===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallName");a={toolCallId:d.toolCallId,toolCallName:d.toolCallName,parentMessageId:d.parentMessageId},e="tool";let t={type:f.TOOL_CALL_START,toolCallId:d.toolCallId,toolCallName:d.toolCallName,parentMessageId:d.parentMessageId};i.push(t),u&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(t))}if(d.delta!==void 0){let t={type:f.TOOL_CALL_ARGS,toolCallId:a.toolCallId,delta:d.delta};i.push(t),u&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(t))}return i}let E=l.type}),Xe(()=>r()))};var G=class{constructor({agentId:o,description:n,threadId:a,initialMessages:e,initialState:s,debug:g}={}){this.debug=!1;this.subscribers=[];this.agentId=o,this.description=n!=null?n:"",this.threadId=a!=null?a:X(),this.messages=C(e!=null?e:[]),this.state=C(s!=null?s:{}),this.debug=g!=null?g:!1}subscribe(o){return this.subscribers.push(o),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(n=>n!==o)}}}async runAgent(o,n){var l;this.agentId=(l=this.agentId)!=null?l:X();let a=this.prepareRunAgentInput(o),e,s=new Set(this.messages.map(E=>E.id)),g=[{onRunFinishedEvent:E=>{e=E.result}},...this.subscribers,n!=null?n:{}];await this.onInitialize(a,g);let r=Be(()=>this.run(a),q(this.debug),U(this.debug),E=>this.apply(a,E,g),E=>this.processApplyEvents(a,E,g),Ke(E=>this.onError(a,E,g)),ze(()=>{this.onFinalize(a,g)}));return $e(r(Je(null))).then(()=>{let E=C(this.messages).filter(M=>!s.has(M.id));return{result:e,newMessages:E}})}abortRun(){}apply(o,n,a){return k(o,n,this,a)}processApplyEvents(o,n,a){return n.pipe(ke(e=>{e.messages&&(this.messages=e.messages,a.forEach(s=>{var g;(g=s.onMessagesChanged)==null||g.call(s,{messages:this.messages,state:this.state,agent:this,input:o})})),e.state&&(this.state=e.state,a.forEach(s=>{var g;(g=s.onStateChanged)==null||g.call(s,{state:this.state,messages:this.messages,agent:this,input:o})}))}))}prepareRunAgentInput(o){var n,a,e;return{threadId:this.threadId,runId:(o==null?void 0:o.runId)||X(),tools:C((n=o==null?void 0:o.tools)!=null?n:[]),context:C((a=o==null?void 0:o.context)!=null?a:[]),forwardedProps:C((e=o==null?void 0:o.forwardedProps)!=null?e:{}),state:C(this.state),messages:C(this.messages)}}async onInitialize(o,n){let a=await h(n,this.messages,this.state,(e,s,g)=>{var r;return(r=e.onRunInitialized)==null?void 0:r.call(e,{messages:s,state:g,agent:this,input:o})});(a.messages!==void 0||a.state!==void 0)&&(a.messages&&(this.messages=a.messages,o.messages=a.messages,n.forEach(e=>{var s;(s=e.onMessagesChanged)==null||s.call(e,{messages:this.messages,state:this.state,agent:this,input:o})})),a.state&&(this.state=a.state,o.state=a.state,n.forEach(e=>{var s;(s=e.onStateChanged)==null||s.call(e,{state:this.state,messages:this.messages,agent:this,input:o})})))}onError(o,n,a){return je(h(a,this.messages,this.state,(e,s,g)=>{var r;return(r=e.onRunFailed)==null?void 0:r.call(e,{error:n,messages:s,state:g,agent:this,input:o})})).pipe(Z(e=>{let s=e;if((s.messages!==void 0||s.state!==void 0)&&(s.messages!==void 0&&(this.messages=s.messages,a.forEach(g=>{var r;(r=g.onMessagesChanged)==null||r.call(g,{messages:this.messages,state:this.state,agent:this,input:o})})),s.state!==void 0&&(this.state=s.state,a.forEach(g=>{var r;(r=g.onStateChanged)==null||r.call(g,{state:this.state,messages:this.messages,agent:this,input:o})}))),s.stopPropagation!==!0)throw console.error("Agent execution failed:",n),n;return{}}))}async onFinalize(o,n){let a=await h(n,this.messages,this.state,(e,s,g)=>{var r;return(r=e.onRunFinalized)==null?void 0:r.call(e,{messages:s,state:g,agent:this,input:o})});(a.messages!==void 0||a.state!==void 0)&&(a.messages!==void 0&&(this.messages=a.messages,n.forEach(e=>{var s;(s=e.onMessagesChanged)==null||s.call(e,{messages:this.messages,state:this.state,agent:this,input:o})})),a.state!==void 0&&(this.state=a.state,n.forEach(e=>{var s;(s=e.onStateChanged)==null||s.call(e,{state:this.state,messages:this.messages,agent:this,input:o})})))}clone(){let o=Object.create(Object.getPrototypeOf(this));for(let n of Object.getOwnPropertyNames(this)){let a=this[n];typeof a!="function"&&(o[n]=C(a))}return o}addMessage(o){this.messages.push(o),(async()=>{var n,a,e;for(let s of this.subscribers)await((n=s.onNewMessage)==null?void 0:n.call(s,{message:o,messages:this.messages,state:this.state,agent:this}));if(o.role==="assistant"&&o.toolCalls)for(let s of o.toolCalls)for(let g of this.subscribers)await((a=g.onNewToolCall)==null?void 0:a.call(g,{toolCall:s,messages:this.messages,state:this.state,agent:this}));for(let s of this.subscribers)await((e=s.onMessagesChanged)==null?void 0:e.call(s,{messages:this.messages,state:this.state,agent:this}))})()}addMessages(o){this.messages.push(...o),(async()=>{var n,a,e;for(let s of o){for(let g of this.subscribers)await((n=g.onNewMessage)==null?void 0:n.call(g,{message:s,messages:this.messages,state:this.state,agent:this}));if(s.role==="assistant"&&s.toolCalls)for(let g of s.toolCalls)for(let r of this.subscribers)await((a=r.onNewToolCall)==null?void 0:a.call(r,{toolCall:g,messages:this.messages,state:this.state,agent:this}))}for(let s of this.subscribers)await((e=s.onMessagesChanged)==null?void 0:e.call(s,{messages:this.messages,state:this.state,agent:this}))})()}setMessages(o){this.messages=C(o),(async()=>{var n;for(let a of this.subscribers)await((n=a.onMessagesChanged)==null?void 0:n.call(a,{messages:this.messages,state:this.state,agent:this}))})()}setState(o){this.state=C(o),(async()=>{var n;for(let a of this.subscribers)await((n=a.onStateChanged)==null?void 0:n.call(a,{messages:this.messages,state:this.state,agent:this}))})()}legacy_to_be_removed_runAgentBridged(o){var a;this.agentId=(a=this.agentId)!=null?a:X();let n=this.prepareRunAgentInput(o);return this.run(n).pipe(q(this.debug),U(this.debug),$(this.threadId,n.runId,this.agentId),e=>e.pipe(Z(s=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(s)),s))))}};var W=class extends G{constructor(n){var a;super(n);this.abortController=new AbortController;this.url=n.url,this.headers=C((a=n.headers)!=null?a:{})}requestInit(n){return{method:"POST",headers:H(L({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(n),signal:this.abortController.signal}}runAgent(n,a){var e;return this.abortController=(e=n==null?void 0:n.abortController)!=null?e:new AbortController,super.runAgent(n,a)}abortRun(){this.abortController.abort(),super.abortRun()}run(n){let a=z(this.url,this.requestInit(n));return J(a)}};export*from"@ag-ui/core";export{G as AbstractAgent,W as HttpAgent,$ as convertToLegacyEvents,k as defaultApplyEvents,j as parseProtoStream,B as parseSSEStream,z as runHttpRequest,J as transformHttpEventStream,U as verifyEvents};
7
7
  //# sourceMappingURL=index.mjs.map