@ag-ui/client 0.0.36-alpha.2 → 0.0.36

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