@ag-ui/client 0.0.40-alpha.6 → 0.0.40-alpha.8

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,8 @@
1
- var ut=Object.defineProperty,pt=Object.defineProperties;var dt=Object.getOwnPropertyDescriptors;var Y=Object.getOwnPropertySymbols;var mt=Object.prototype.hasOwnProperty,ft=Object.prototype.propertyIsEnumerable;var Q=(E,a,e)=>a in E?ut(E,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):E[a]=e,O=(E,a)=>{for(var e in a||(a={}))mt.call(a,e)&&Q(E,e,a[e]);if(Y)for(var e of Y(a))ft.call(a,e)&&Q(E,e,a[e]);return E},F=(E,a)=>pt(E,dt(a));import{EventType as M}from"@ag-ui/core";import{mergeAll as St,defaultIfEmpty as Tt,concatMap as At}from"rxjs/operators";import{of as vt,EMPTY as ht}from"rxjs";var h=E=>{if(typeof structuredClone=="function")return structuredClone(E);try{return JSON.parse(JSON.stringify(E))}catch(a){return O({},E)}};import{applyPatch as Mt}from"fast-json-patch";async function y(E,a,e,s){let t=a,n=e,i;for(let r of E)try{let l=await s(r,h(t),h(n));if(l===void 0)continue;if(l.messages!==void 0&&(t=l.messages),l.state!==void 0&&(n=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 O(O(O({},JSON.stringify(t)!==JSON.stringify(a)?{messages:t}:{}),JSON.stringify(n)!==JSON.stringify(e)?{state:n}:{}),i!==void 0?{stopPropagation:i}:{})}import yt from"untruncate-json";var z=(E,a,e,s)=>{let t=h(E.messages),n=h(E.state),i={},r=u=>{u.messages!==void 0&&(t=u.messages,i.messages=u.messages),u.state!==void 0&&(n=u.state,i.state=u.state)},l=()=>{let u=h(i);return i={},u.messages!==void 0||u.state!==void 0?vt(u):ht};return a.pipe(At(async u=>{var f,T;let S=await y(s,t,n,(o,g,m)=>{var p;return(p=o.onEvent)==null?void 0:p.call(o,{event:u,agent:e,input:E,messages:g,state:m})});if(r(S),S.stopPropagation===!0)return l();switch(u.type){case M.TEXT_MESSAGE_START:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onTextMessageStartEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E})});if(r(o),o.stopPropagation!==!0){let{messageId:g,role:m="assistant"}=u,p={id:g,role:m,content:""};t.push(p),r({messages:t})}return l()}case M.TEXT_MESSAGE_CONTENT:{let{messageId:o,delta:g}=u,m=t.find(c=>c.id===o);if(!m)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${o}'`),l();let p=await y(s,t,n,(c,C,x)=>{var w,H;return(H=c.onTextMessageContentEvent)==null?void 0:H.call(c,{event:u,messages:C,state:x,agent:e,input:E,textMessageBuffer:(w=m.content)!=null?w:""})});return r(p),p.stopPropagation!==!0&&(m.content=(m.content||"")+g,r({messages:t})),l()}case M.TEXT_MESSAGE_END:{let{messageId:o}=u,g=t.find(p=>p.id===o);if(!g)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${o}'`),l();let m=await y(s,t,n,(p,c,C)=>{var x,w;return(w=p.onTextMessageEndEvent)==null?void 0:w.call(p,{event:u,messages:c,state:C,agent:e,input:E,textMessageBuffer:(x=g.content)!=null?x:""})});return r(m),await Promise.all(s.map(p=>{var c;(c=p.onNewMessage)==null||c.call(p,{message:g,messages:t,state:n,agent:e,input:E})})),l()}case M.TOOL_CALL_START:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onToolCallStartEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E})});if(r(o),o.stopPropagation!==!0){let{toolCallId:g,toolCallName:m,parentMessageId:p}=u,c;p&&t.length>0&&t[t.length-1].id===p?c=t[t.length-1]:(c={id:p||g,role:"assistant",toolCalls:[]},t.push(c)),(f=c.toolCalls)!=null||(c.toolCalls=[]),c.toolCalls.push({id:g,type:"function",function:{name:m,arguments:""}}),r({messages:t})}return l()}case M.TOOL_CALL_ARGS:{let{toolCallId:o,delta:g}=u,m=t.find(C=>{var x;return(x=C.toolCalls)==null?void 0:x.some(w=>w.id===o)});if(!m)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${o}'`),l();let p=m.toolCalls.find(C=>C.id===o);if(!p)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${o}'`),l();let c=await y(s,t,n,(C,x,w)=>{var b;let H=p.function.arguments,k=p.function.name,G={};try{G=yt(H)}catch(ee){}return(b=C.onToolCallArgsEvent)==null?void 0:b.call(C,{event:u,messages:x,state:w,agent:e,input:E,toolCallBuffer:H,toolCallName:k,partialToolCallArgs:G})});return r(c),c.stopPropagation!==!0&&(p.function.arguments+=g,r({messages:t})),l()}case M.TOOL_CALL_END:{let{toolCallId:o}=u,g=t.find(c=>{var C;return(C=c.toolCalls)==null?void 0:C.some(x=>x.id===o)});if(!g)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${o}'`),l();let m=g.toolCalls.find(c=>c.id===o);if(!m)return console.warn(`TOOL_CALL_END: No tool call found with ID '${o}'`),l();let p=await y(s,t,n,(c,C,x)=>{var G;let w=m.function.arguments,H=m.function.name,k={};try{k=JSON.parse(w)}catch(b){}return(G=c.onToolCallEndEvent)==null?void 0:G.call(c,{event:u,messages:C,state:x,agent:e,input:E,toolCallName:H,toolCallArgs:k})});return r(p),await Promise.all(s.map(c=>{var C;(C=c.onNewToolCall)==null||C.call(c,{toolCall:m,messages:t,state:n,agent:e,input:E})})),l()}case M.TOOL_CALL_RESULT:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onToolCallResultEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E})});if(r(o),o.stopPropagation!==!0){let{messageId:g,toolCallId:m,content:p,role:c}=u,C={id:g,toolCallId:m,role:c||"tool",content:p};t.push(C),await Promise.all(s.map(x=>{var w;(w=x.onNewMessage)==null||w.call(x,{message:C,messages:t,state:n,agent:e,input:E})})),r({messages:t})}return l()}case M.STATE_SNAPSHOT:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onStateSnapshotEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E})});if(r(o),o.stopPropagation!==!0){let{snapshot:g}=u;n=g,r({state:n})}return l()}case M.STATE_DELTA:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onStateDeltaEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E})});if(r(o),o.stopPropagation!==!0){let{delta:g}=u;try{n=Mt(n,g,!0,!1).newDocument,r({state:n})}catch(m){let p=m instanceof Error?m.message:String(m);console.warn(`Failed to apply state patch:
1
+ var dt=Object.defineProperty,mt=Object.defineProperties;var ft=Object.getOwnPropertyDescriptors;var Q=Object.getOwnPropertySymbols;var Tt=Object.prototype.hasOwnProperty,St=Object.prototype.propertyIsEnumerable;var Z=(E,a,e)=>a in E?dt(E,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):E[a]=e,O=(E,a)=>{for(var e in a||(a={}))Tt.call(a,e)&&Z(E,e,a[e]);if(Q)for(var e of Q(a))St.call(a,e)&&Z(E,e,a[e]);return E},G=(E,a)=>mt(E,ft(a));import{EventType as R}from"@ag-ui/core";import{mergeAll as vt,defaultIfEmpty as ht,concatMap as yt}from"rxjs/operators";import{of as Mt,EMPTY as Ct}from"rxjs";import{v4 as At}from"uuid";var M=E=>{if(typeof structuredClone=="function")return structuredClone(E);try{return JSON.parse(JSON.stringify(E))}catch(a){return O({},E)}};function le(){return At()}import{applyPatch as tt}from"fast-json-patch";async function _(E,a,e,s){let t=a,n=e,r;for(let o of E)try{let i=await s(o,M(t),M(n));if(i===void 0)continue;if(i.messages!==void 0&&(t=i.messages),i.state!==void 0&&(n=i.state),r=i.stopPropagation,r===!0)break}catch(i){process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0||console.error("Subscriber error:",i);continue}return O(O(O({},JSON.stringify(t)!==JSON.stringify(a)?{messages:t}:{}),JSON.stringify(n)!==JSON.stringify(e)?{state:n}:{}),r!==void 0?{stopPropagation:r}:{})}import Rt from"untruncate-json";var J=(E,a,e,s)=>{let t=M(E.messages),n=M(E.state),r={},o=d=>{d.messages!==void 0&&(t=d.messages,r.messages=d.messages),d.state!==void 0&&(n=d.state,r.state=d.state)},i=()=>{let d=M(r);return r={},d.messages!==void 0||d.state!==void 0?Mt(d):Ct};return a.pipe(yt(async d=>{var T,v,g;let A=await _(s,t,n,(u,l,p)=>{var m;return(m=u.onEvent)==null?void 0:m.call(u,{event:d,agent:e,input:E,messages:l,state:p})});if(o(A),A.stopPropagation===!0)return i();switch(d.type){case R.TEXT_MESSAGE_START:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onTextMessageStartEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E})});if(o(u),u.stopPropagation!==!0){let{messageId:l,role:p="assistant"}=d,m={id:l,role:p,content:""};t.push(m),o({messages:t})}return i()}case R.TEXT_MESSAGE_CONTENT:{let{messageId:u,delta:l}=d,p=t.find(c=>c.id===u);if(!p)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${u}'`),i();let m=await _(s,t,n,(c,S,y)=>{var x;return(x=c.onTextMessageContentEvent)==null?void 0:x.call(c,{event:d,messages:S,state:y,agent:e,input:E,textMessageBuffer:typeof p.content=="string"?p.content:""})});if(o(m),m.stopPropagation!==!0){let c=typeof p.content=="string"?p.content:"";p.content=`${c}${l}`,o({messages:t})}return i()}case R.TEXT_MESSAGE_END:{let{messageId:u}=d,l=t.find(m=>m.id===u);if(!l)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${u}'`),i();let p=await _(s,t,n,(m,c,S)=>{var y;return(y=m.onTextMessageEndEvent)==null?void 0:y.call(m,{event:d,messages:c,state:S,agent:e,input:E,textMessageBuffer:typeof l.content=="string"?l.content:""})});return o(p),await Promise.all(s.map(m=>{var c;(c=m.onNewMessage)==null||c.call(m,{message:l,messages:t,state:n,agent:e,input:E})})),i()}case R.TOOL_CALL_START:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onToolCallStartEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E})});if(o(u),u.stopPropagation!==!0){let{toolCallId:l,toolCallName:p,parentMessageId:m}=d,c;m&&t.length>0&&t[t.length-1].id===m?c=t[t.length-1]:(c={id:m||l,role:"assistant",toolCalls:[]},t.push(c)),(T=c.toolCalls)!=null||(c.toolCalls=[]),c.toolCalls.push({id:l,type:"function",function:{name:p,arguments:""}}),o({messages:t})}return i()}case R.TOOL_CALL_ARGS:{let{toolCallId:u,delta:l}=d,p=t.find(S=>{var y;return(y=S.toolCalls)==null?void 0:y.some(x=>x.id===u)});if(!p)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${u}'`),i();let m=p.toolCalls.find(S=>S.id===u);if(!m)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${u}'`),i();let c=await _(s,t,n,(S,y,x)=>{var z;let D=m.function.arguments,K=m.function.name,U={};try{U=Rt(D)}catch(oe){}return(z=S.onToolCallArgsEvent)==null?void 0:z.call(S,{event:d,messages:y,state:x,agent:e,input:E,toolCallBuffer:D,toolCallName:K,partialToolCallArgs:U})});return o(c),c.stopPropagation!==!0&&(m.function.arguments+=l,o({messages:t})),i()}case R.TOOL_CALL_END:{let{toolCallId:u}=d,l=t.find(c=>{var S;return(S=c.toolCalls)==null?void 0:S.some(y=>y.id===u)});if(!l)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${u}'`),i();let p=l.toolCalls.find(c=>c.id===u);if(!p)return console.warn(`TOOL_CALL_END: No tool call found with ID '${u}'`),i();let m=await _(s,t,n,(c,S,y)=>{var U;let x=p.function.arguments,D=p.function.name,K={};try{K=JSON.parse(x)}catch(z){}return(U=c.onToolCallEndEvent)==null?void 0:U.call(c,{event:d,messages:S,state:y,agent:e,input:E,toolCallName:D,toolCallArgs:K})});return o(m),await Promise.all(s.map(c=>{var S;(S=c.onNewToolCall)==null||S.call(c,{toolCall:p,messages:t,state:n,agent:e,input:E})})),i()}case R.TOOL_CALL_RESULT:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onToolCallResultEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E})});if(o(u),u.stopPropagation!==!0){let{messageId:l,toolCallId:p,content:m,role:c}=d,S={id:l,toolCallId:p,role:c||"tool",content:m};t.push(S),await Promise.all(s.map(y=>{var x;(x=y.onNewMessage)==null||x.call(y,{message:S,messages:t,state:n,agent:e,input:E})})),o({messages:t})}return i()}case R.STATE_SNAPSHOT:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onStateSnapshotEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E})});if(o(u),u.stopPropagation!==!0){let{snapshot:l}=d;n=l,o({state:n})}return i()}case R.STATE_DELTA:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onStateDeltaEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E})});if(o(u),u.stopPropagation!==!0){let{delta:l}=d;try{n=tt(n,l,!0,!1).newDocument,o({state:n})}catch(p){let m=p instanceof Error?p.message:String(p);console.warn(`Failed to apply state patch:
2
2
  Current state: ${JSON.stringify(n,null,2)}
3
- Patch operations: ${JSON.stringify(g,null,2)}
4
- Error: ${p}`)}}return l()}case M.MESSAGES_SNAPSHOT:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onMessagesSnapshotEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E})});if(r(o),o.stopPropagation!==!0){let{messages:g}=u;t=g,r({messages:t})}return l()}case M.RAW:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onRawEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E})});return r(o),l()}case M.CUSTOM:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onCustomEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E})});return r(o),l()}case M.RUN_STARTED:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onRunStartedEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E})});if(r(o),o.stopPropagation!==!0){let g=u;if((T=g.input)!=null&&T.messages){for(let m of g.input.messages)t.find(c=>c.id===m.id)||t.push(m);r({messages:t})}}return l()}case M.RUN_FINISHED:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onRunFinishedEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E,result:u.result})});return r(o),l()}case M.RUN_ERROR:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onRunErrorEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E})});return r(o),l()}case M.STEP_STARTED:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onStepStartedEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E})});return r(o),l()}case M.STEP_FINISHED:{let o=await y(s,t,n,(g,m,p)=>{var c;return(c=g.onStepFinishedEvent)==null?void 0:c.call(g,{event:u,messages:m,state:p,agent:e,input:E})});return r(o),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 P=u.type;return l()}),St(),s.length>0?Tt({}):u=>u)};import{EventType as R,AGUIError as _}from"@ag-ui/core";import{throwError as N,of as I}from"rxjs";import{mergeMap as Ct}from"rxjs/operators";var U=E=>a=>{let e=new Map,s=new Map,t=!1,n=!1,i=!1,r=new Map,l=!1,u=!1,S=!1,P=()=>{e.clear(),s.clear(),r.clear(),l=!1,u=!1,t=!1,n=!1,S=!0};return a.pipe(Ct(f=>{let T=f.type;if(E&&console.debug("[VERIFY]:",JSON.stringify(f)),n)return N(()=>new _(`Cannot send event type '${T}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(t&&T!==R.RUN_ERROR&&T!==R.RUN_STARTED)return N(()=>new _(`Cannot send event type '${T}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(i){if(T===R.RUN_STARTED){if(S&&!t)return N(()=>new _("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));t&&P()}}else if(i=!0,T!==R.RUN_STARTED&&T!==R.RUN_ERROR)return N(()=>new _("First event must be 'RUN_STARTED'"));switch(T){case R.TEXT_MESSAGE_START:{let o=f.messageId;return e.has(o)?N(()=>new _(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${o}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(e.set(o,!0),I(f))}case R.TEXT_MESSAGE_CONTENT:{let o=f.messageId;return e.has(o)?I(f):N(()=>new _(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${o}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case R.TEXT_MESSAGE_END:{let o=f.messageId;return e.has(o)?(e.delete(o),I(f)):N(()=>new _(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${o}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case R.TOOL_CALL_START:{let o=f.toolCallId;return s.has(o)?N(()=>new _(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${o}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(s.set(o,!0),I(f))}case R.TOOL_CALL_ARGS:{let o=f.toolCallId;return s.has(o)?I(f):N(()=>new _(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${o}'. Start a tool call with 'TOOL_CALL_START' first.`))}case R.TOOL_CALL_END:{let o=f.toolCallId;return s.has(o)?(s.delete(o),I(f)):N(()=>new _(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${o}'. A 'TOOL_CALL_START' event must be sent first.`))}case R.STEP_STARTED:{let o=f.stepName;return r.has(o)?N(()=>new _(`Step "${o}" is already active for 'STEP_STARTED'`)):(r.set(o,!0),I(f))}case R.STEP_FINISHED:{let o=f.stepName;return r.has(o)?(r.delete(o),I(f)):N(()=>new _(`Cannot send 'STEP_FINISHED' for step "${o}" that was not started`))}case R.RUN_STARTED:return S=!0,I(f);case R.RUN_FINISHED:{if(r.size>0){let o=Array.from(r.keys()).join(", ");return N(()=>new _(`Cannot send 'RUN_FINISHED' while steps are still active: ${o}`))}if(e.size>0){let o=Array.from(e.keys()).join(", ");return N(()=>new _(`Cannot send 'RUN_FINISHED' while text messages are still active: ${o}`))}if(s.size>0){let o=Array.from(s.keys()).join(", ");return N(()=>new _(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${o}`))}return t=!0,I(f)}case R.RUN_ERROR:return n=!0,I(f);case R.CUSTOM:return I(f);case R.THINKING_TEXT_MESSAGE_START:return l?u?N(()=>new _("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(u=!0,I(f)):N(()=>new _("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case R.THINKING_TEXT_MESSAGE_CONTENT:return u?I(f):N(()=>new _("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case R.THINKING_TEXT_MESSAGE_END:return u?(u=!1,I(f)):N(()=>new _("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case R.THINKING_START:return l?N(()=>new _("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(l=!0,I(f));case R.THINKING_END:return l?(l=!1,I(f)):N(()=>new _("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return I(f)}}))};import{EventSchemas as Ot}from"@ag-ui/core";import{Subject as wt,ReplaySubject as Pt}from"rxjs";import{Observable as Rt,from as Z,defer as _t,throwError as tt}from"rxjs";import{mergeMap as Nt,switchMap as It}from"rxjs/operators";var j=(E,a)=>_t(()=>Z(fetch(E,a))).pipe(It(e=>{var n;if(!e.ok){let i=e.headers.get("content-type")||"";return Z(e.text()).pipe(Nt(r=>{let l=r;if(i.includes("application/json"))try{l=JSON.parse(r)}catch(S){}let u=new Error(`HTTP ${e.status}: ${typeof l=="string"?l:JSON.stringify(l)}`);return u.status=e.status,u.payload=l,tt(()=>u)}))}let s={type:"headers",status:e.status,headers:e.headers},t=(n=e.body)==null?void 0:n.getReader();return t?new Rt(i=>(i.next(s),(async()=>{try{for(;;){let{done:r,value:l}=await t.read();if(r)break;let u={type:"data",data:l};i.next(u)}i.complete()}catch(r){i.error(r)}})(),()=>{t.cancel()})):tt(()=>new Error("Failed to getReader() from response"))}));import{Subject as xt}from"rxjs";var J=E=>{let a=new xt,e=new TextDecoder("utf-8",{fatal:!1}),s="";E.subscribe({next:n=>{if(n.type!=="headers"&&n.type==="data"&&n.data){let i=e.decode(n.data,{stream:!0});s+=i;let r=s.split(/\n\n/);s=r.pop()||"";for(let l of r)t(l)}},error:n=>a.error(n),complete:()=>{s&&(s+=e.decode(),t(s)),a.complete()}});function t(n){let i=n.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
- `),u=JSON.parse(l);a.next(u)}catch(l){a.error(l)}}return a.asObservable()};import{Subject as Lt}from"rxjs";import*as et from"@ag-ui/proto";var $=E=>{let a=new Lt,e=new Uint8Array(0);E.subscribe({next:t=>{if(t.type!=="headers"&&t.type==="data"&&t.data){let n=new Uint8Array(e.length+t.data.length);n.set(e,0),n.set(t.data,e.length),e=n,s()}},error:t=>a.error(t),complete:()=>{if(e.length>0)try{s()}catch(t){console.warn("Incomplete or invalid protocol buffer data at stream end")}a.complete()}});function s(){for(;e.length>=4;){let i=4+new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1);if(e.length<i)break;try{let r=e.slice(4,i),l=et.decode(r);a.next(l),e=e.slice(i)}catch(r){let l=r instanceof Error?r.message:String(r);a.error(new Error(`Failed to decode protocol buffer message: ${l}`));return}}}return a.asObservable()};import*as nt from"@ag-ui/proto";var q=E=>{let a=new wt,e=new Pt,s=!1;return E.subscribe({next:t=>{e.next(t),t.type==="headers"&&!s?(s=!0,t.headers.get("content-type")===nt.AGUI_MEDIA_TYPE?$(e).subscribe({next:i=>a.next(i),error:i=>a.error(i),complete:()=>a.complete()}):J(e).subscribe({next:i=>{try{let r=Ot.parse(i);a.next(r)}catch(r){a.error(r)}},error:i=>a.error(i),complete:()=>a.complete()})):s||a.error(new Error("No headers event received before data events"))},error:t=>{e.error(t),a.error(t)},complete:()=>{e.complete()}}),a.asObservable()};import{mergeMap as jt}from"rxjs/operators";import{applyPatch as Jt}from"fast-json-patch";import{EventType as L}from"@ag-ui/core";import{z as d}from"zod";var v=d.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Dt=d.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Ht=d.object({type:d.literal(v.enum.TextMessageStart),messageId:d.string(),parentMessageId:d.string().optional(),role:d.string().optional()}),Gt=d.object({type:d.literal(v.enum.TextMessageContent),messageId:d.string(),content:d.string()}),Ft=d.object({type:d.literal(v.enum.TextMessageEnd),messageId:d.string()}),Ut=d.object({type:d.literal(v.enum.ActionExecutionStart),actionExecutionId:d.string(),actionName:d.string(),parentMessageId:d.string().optional()}),Xt=d.object({type:d.literal(v.enum.ActionExecutionArgs),actionExecutionId:d.string(),args:d.string()}),Bt=d.object({type:d.literal(v.enum.ActionExecutionEnd),actionExecutionId:d.string()}),kt=d.object({type:d.literal(v.enum.ActionExecutionResult),actionName:d.string(),actionExecutionId:d.string(),result:d.string()}),Kt=d.object({type:d.literal(v.enum.AgentStateMessage),threadId:d.string(),agentName:d.string(),nodeName:d.string(),runId:d.string(),active:d.boolean(),role:d.string(),state:d.string(),running:d.boolean()}),bt=d.object({type:d.literal(v.enum.MetaEvent),name:Dt,value:d.any()}),zt=d.object({type:d.literal(v.enum.RunError),message:d.string(),code:d.string().optional()}),Cn=d.discriminatedUnion("type",[Ht,Gt,Ft,Ut,Xt,Bt,kt,Kt,bt,zt]),Rn=d.object({id:d.string(),role:d.string(),content:d.string(),parentMessageId:d.string().optional()}),_n=d.object({id:d.string(),name:d.string(),arguments:d.any(),parentMessageId:d.string().optional()}),Nn=d.object({id:d.string(),result:d.any(),actionExecutionId:d.string(),actionName:d.string()});import $t from"untruncate-json";var W=(E,a,e)=>s=>{let t={},n=!0,i=!0,r="",l=null,u=null,S=[],P={},f=T=>{typeof T=="object"&&T!==null&&("messages"in T&&delete T.messages,t=T)};return s.pipe(jt(T=>{switch(T.type){case L.TEXT_MESSAGE_START:{let o=T;return[{type:v.enum.TextMessageStart,messageId:o.messageId,role:o.role}]}case L.TEXT_MESSAGE_CONTENT:{let o=T;return[{type:v.enum.TextMessageContent,messageId:o.messageId,content:o.delta}]}case L.TEXT_MESSAGE_END:{let o=T;return[{type:v.enum.TextMessageEnd,messageId:o.messageId}]}case L.TOOL_CALL_START:{let o=T;return S.push({id:o.toolCallId,type:"function",function:{name:o.toolCallName,arguments:""}}),i=!0,P[o.toolCallId]=o.toolCallName,[{type:v.enum.ActionExecutionStart,actionExecutionId:o.toolCallId,actionName:o.toolCallName,parentMessageId:o.parentMessageId}]}case L.TOOL_CALL_ARGS:{let o=T,g=S.find(p=>p.id===o.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${o.toolCallId}'`),[];g.function.arguments+=o.delta;let m=!1;if(u){let p=u.find(c=>c.tool==g.function.name);if(p)try{let c=JSON.parse($t(g.function.arguments));p.tool_argument&&p.tool_argument in c?(f(F(O({},t),{[p.state_key]:c[p.tool_argument]})),m=!0):p.tool_argument||(f(F(O({},t),{[p.state_key]:c})),m=!0)}catch(c){}}return[{type:v.enum.ActionExecutionArgs,actionExecutionId:o.toolCallId,args:o.delta},...m?[{type:v.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:r,runId:a,running:n,role:"assistant",state:JSON.stringify(t),active:i}]:[]]}case L.TOOL_CALL_END:{let o=T;return[{type:v.enum.ActionExecutionEnd,actionExecutionId:o.toolCallId}]}case L.TOOL_CALL_RESULT:{let o=T;return[{type:v.enum.ActionExecutionResult,actionExecutionId:o.toolCallId,result:o.content,actionName:P[o.toolCallId]||"unknown"}]}case L.RAW:return[];case L.CUSTOM:{let o=T;switch(o.name){case"Exit":n=!1;break;case"PredictState":u=o.value;break}return[{type:v.enum.MetaEvent,name:o.name,value:o.value}]}case L.STATE_SNAPSHOT:return f(T.snapshot),[{type:v.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:r,runId:a,running:n,role:"assistant",state:JSON.stringify(t),active:i}];case L.STATE_DELTA:{let g=Jt(t,T.delta,!0,!1);return g?(f(g.newDocument),[{type:v.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:r,runId:a,running:n,role:"assistant",state:JSON.stringify(t),active:i}]):[]}case L.MESSAGES_SNAPSHOT:return l=T.messages,[{type:v.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:r,runId:a,running:n,role:"assistant",state:JSON.stringify(O(O({},t),l?{messages:l}:{})),active:!0}];case L.RUN_STARTED:return[];case L.RUN_FINISHED:return l&&(t.messages=l),Object.keys(t).length===0?[]:[{type:v.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:r,runId:a,running:n,role:"assistant",state:JSON.stringify(O(O({},t),l?{messages:qt(l)}:{})),active:!1}];case L.RUN_ERROR:{let o=T;return[{type:v.enum.RunError,message:o.message,code:o.code}]}case L.STEP_STARTED:return r=T.stepName,S=[],u=null,[{type:v.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:r,runId:a,running:n,role:"assistant",state:JSON.stringify(t),active:!0}];case L.STEP_FINISHED:return S=[],u=null,[{type:v.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:r,runId:a,running:n,role:"assistant",state:JSON.stringify(t),active:!1}];default:return[]}}))};function qt(E){var e;let a=[];for(let s of E)if(s.role==="assistant"||s.role==="user"||s.role==="system"){if(s.content){let t={id:s.id,role:s.role,content:s.content};a.push(t)}if(s.role==="assistant"&&s.toolCalls&&s.toolCalls.length>0)for(let t of s.toolCalls){let n={id:t.id,name:t.function.name,arguments:JSON.parse(t.function.arguments),parentMessageId:s.id};a.push(n)}}else if(s.role==="tool"){let t="unknown";for(let i of E)if(i.role==="assistant"&&((e=i.toolCalls)!=null&&e.length)){for(let r of i.toolCalls)if(r.id===s.toolCallId){t=r.function.name;break}}let n={id:s.id,result:s.content,actionExecutionId:s.toolCallId,actionName:t};a.push(n)}return a}import{v4 as X}from"uuid";import{catchError as st,map as at,tap as Yt}from"rxjs/operators";import{finalize as ot}from"rxjs/operators";import{pipe as rt,from as Qt,of as it,EMPTY as Zt}from"rxjs";import{lastValueFrom as lt}from"rxjs";import{mergeMap as Wt,finalize as Vt}from"rxjs";import{EventType as A}from"@ag-ui/core";var K=E=>a=>{let e,s,t,n=()=>{if(!e||t!=="text")throw new Error("No text message to close");let l={type:A.TEXT_MESSAGE_END,messageId:e.messageId};return t=void 0,e=void 0,E&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(l)),l},i=()=>{if(!s||t!=="tool")throw new Error("No tool call to close");let l={type:A.TOOL_CALL_END,toolCallId:s.toolCallId};return t=void 0,s=void 0,E&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(l)),l},r=()=>t==="text"?[n()]:t==="tool"?[i()]:[];return a.pipe(Wt(l=>{switch(l.type){case A.TEXT_MESSAGE_START:case A.TEXT_MESSAGE_CONTENT:case A.TEXT_MESSAGE_END:case A.TOOL_CALL_START:case A.TOOL_CALL_ARGS:case A.TOOL_CALL_END:case A.TOOL_CALL_RESULT:case A.STATE_SNAPSHOT:case A.STATE_DELTA:case A.MESSAGES_SNAPSHOT:case A.CUSTOM:case A.RUN_STARTED:case A.RUN_FINISHED:case A.RUN_ERROR:case A.STEP_STARTED:case A.STEP_FINISHED:case A.THINKING_START:case A.THINKING_END:case A.THINKING_TEXT_MESSAGE_START:case A.THINKING_TEXT_MESSAGE_CONTENT:case A.THINKING_TEXT_MESSAGE_END:return[...r(),l];case A.RAW:return[l];case A.TEXT_MESSAGE_CHUNK:let S=l,P=[];if((t!=="text"||S.messageId!==void 0&&S.messageId!==(e==null?void 0:e.messageId))&&P.push(...r()),t!=="text"){if(S.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:S.messageId},t="text";let o={type:A.TEXT_MESSAGE_START,messageId:S.messageId,role:S.role||"assistant"};P.push(o),E&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(o))}if(S.delta!==void 0){let o={type:A.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:S.delta};P.push(o),E&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(o))}return P;case A.TOOL_CALL_CHUNK:let f=l,T=[];if((t!=="tool"||f.toolCallId!==void 0&&f.toolCallId!==(s==null?void 0:s.toolCallId))&&T.push(...r()),t!=="tool"){if(f.toolCallId===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallId");if(f.toolCallName===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallName");s={toolCallId:f.toolCallId,toolCallName:f.toolCallName,parentMessageId:f.parentMessageId},t="tool";let o={type:A.TOOL_CALL_START,toolCallId:f.toolCallId,toolCallName:f.toolCallName,parentMessageId:f.parentMessageId};T.push(o),E&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(o))}if(f.delta!==void 0){let o={type:A.TOOL_CALL_ARGS,toolCallId:s.toolCallId,delta:f.delta};T.push(o),E&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(o))}return T}let u=l.type}),Vt(()=>r()))};import{AGUIConnectNotImplementedError as gt}from"@ag-ui/core";var B=class{constructor({agentId:a,description:e,threadId:s,initialMessages:t,initialState:n,debug:i}={}){this.debug=!1;this.subscribers=[];this.isRunning=!1;this.agentId=a,this.description=e!=null?e:"",this.threadId=s!=null?s:X(),this.messages=h(t!=null?t:[]),this.state=h(n!=null?n:{}),this.debug=i!=null?i:!1}subscribe(a){return this.subscribers.push(a),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==a)}}}async runAgent(a,e){var s;try{this.isRunning=!0,this.agentId=(s=this.agentId)!=null?s:X();let t=this.prepareRunAgentInput(a),n,i=new Set(this.messages.map(S=>S.id)),r=[{onRunFinishedEvent:S=>{n=S.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,r);let l=rt(()=>this.run(t),K(this.debug),U(this.debug),S=>this.apply(t,S,r),S=>this.processApplyEvents(t,S,r),st(S=>(this.isRunning=!1,this.onError(t,S,r))),ot(()=>{this.isRunning=!1,this.onFinalize(t,r)}));await lt(l(it(null)));let u=h(this.messages).filter(S=>!i.has(S.id));return{result:n,newMessages:u}}finally{this.isRunning=!1}}connect(a){throw new gt}async connectAgent(a,e){var s;try{this.isRunning=!0,this.agentId=(s=this.agentId)!=null?s:X();let t=this.prepareRunAgentInput(a),n,i=new Set(this.messages.map(S=>S.id)),r=[{onRunFinishedEvent:S=>{n=S.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,r);let l=rt(()=>this.connect(t),K(this.debug),U(this.debug),S=>this.apply(t,S,r),S=>this.processApplyEvents(t,S,r),st(S=>(this.isRunning=!1,S instanceof gt?Zt:this.onError(t,S,r))),ot(()=>{this.isRunning=!1,this.onFinalize(t,r)}));await lt(l(it(null)));let u=h(this.messages).filter(S=>!i.has(S.id));return{result:n,newMessages:u}}finally{this.isRunning=!1}}abortRun(){}apply(a,e,s){return z(a,e,this,s)}processApplyEvents(a,e,s){return e.pipe(Yt(t=>{t.messages&&(this.messages=t.messages,s.forEach(n=>{var i;(i=n.onMessagesChanged)==null||i.call(n,{messages:this.messages,state:this.state,agent:this,input:a})})),t.state&&(this.state=t.state,s.forEach(n=>{var i;(i=n.onStateChanged)==null||i.call(n,{state:this.state,messages:this.messages,agent:this,input:a})}))}))}prepareRunAgentInput(a){var e,s,t;return{threadId:this.threadId,runId:(a==null?void 0:a.runId)||X(),tools:h((e=a==null?void 0:a.tools)!=null?e:[]),context:h((s=a==null?void 0:a.context)!=null?s:[]),forwardedProps:h((t=a==null?void 0:a.forwardedProps)!=null?t:{}),state:h(this.state),messages:h(this.messages)}}async onInitialize(a,e){let s=await y(e,this.messages,this.state,(t,n,i)=>{var r;return(r=t.onRunInitialized)==null?void 0:r.call(t,{messages:n,state:i,agent:this,input:a})});(s.messages!==void 0||s.state!==void 0)&&(s.messages&&(this.messages=s.messages,a.messages=s.messages,e.forEach(t=>{var n;(n=t.onMessagesChanged)==null||n.call(t,{messages:this.messages,state:this.state,agent:this,input:a})})),s.state&&(this.state=s.state,a.state=s.state,e.forEach(t=>{var n;(n=t.onStateChanged)==null||n.call(t,{state:this.state,messages:this.messages,agent:this,input:a})})))}onError(a,e,s){return Qt(y(s,this.messages,this.state,(t,n,i)=>{var r;return(r=t.onRunFailed)==null?void 0:r.call(t,{error:e,messages:n,state:i,agent:this,input:a})})).pipe(at(t=>{let n=t;if((n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,s.forEach(i=>{var r;(r=i.onMessagesChanged)==null||r.call(i,{messages:this.messages,state:this.state,agent:this,input:a})})),n.state!==void 0&&(this.state=n.state,s.forEach(i=>{var r;(r=i.onStateChanged)==null||r.call(i,{state:this.state,messages:this.messages,agent:this,input:a})}))),n.stopPropagation!==!0)throw console.error("Agent execution failed:",e),e;return{}}))}async onFinalize(a,e){let s=await y(e,this.messages,this.state,(t,n,i)=>{var r;return(r=t.onRunFinalized)==null?void 0:r.call(t,{messages:n,state:i,agent:this,input:a})});(s.messages!==void 0||s.state!==void 0)&&(s.messages!==void 0&&(this.messages=s.messages,e.forEach(t=>{var n;(n=t.onMessagesChanged)==null||n.call(t,{messages:this.messages,state:this.state,agent:this,input:a})})),s.state!==void 0&&(this.state=s.state,e.forEach(t=>{var n;(n=t.onStateChanged)==null||n.call(t,{state:this.state,messages:this.messages,agent:this,input:a})})))}clone(){let a=Object.create(Object.getPrototypeOf(this));return a.agentId=this.agentId,a.description=this.description,a.threadId=this.threadId,a.messages=h(this.messages),a.state=h(this.state),a.debug=this.debug,a.isRunning=this.isRunning,a.subscribers=[...this.subscribers],a}addMessage(a){this.messages.push(a),(async()=>{var e,s,t;for(let n of this.subscribers)await((e=n.onNewMessage)==null?void 0:e.call(n,{message:a,messages:this.messages,state:this.state,agent:this}));if(a.role==="assistant"&&a.toolCalls)for(let n of a.toolCalls)for(let i of this.subscribers)await((s=i.onNewToolCall)==null?void 0:s.call(i,{toolCall:n,messages:this.messages,state:this.state,agent:this}));for(let n of this.subscribers)await((t=n.onMessagesChanged)==null?void 0:t.call(n,{messages:this.messages,state:this.state,agent:this}))})()}addMessages(a){this.messages.push(...a),(async()=>{var e,s,t;for(let n of a){for(let i of this.subscribers)await((e=i.onNewMessage)==null?void 0:e.call(i,{message:n,messages:this.messages,state:this.state,agent:this}));if(n.role==="assistant"&&n.toolCalls)for(let i of n.toolCalls)for(let r of this.subscribers)await((s=r.onNewToolCall)==null?void 0:s.call(r,{toolCall:i,messages:this.messages,state:this.state,agent:this}))}for(let n of this.subscribers)await((t=n.onMessagesChanged)==null?void 0:t.call(n,{messages:this.messages,state:this.state,agent:this}))})()}setMessages(a){this.messages=h(a),(async()=>{var e;for(let s of this.subscribers)await((e=s.onMessagesChanged)==null?void 0:e.call(s,{messages:this.messages,state:this.state,agent:this}))})()}setState(a){this.state=h(a),(async()=>{var e;for(let s of this.subscribers)await((e=s.onStateChanged)==null?void 0:e.call(s,{messages:this.messages,state:this.state,agent:this}))})()}legacy_to_be_removed_runAgentBridged(a){var s;this.agentId=(s=this.agentId)!=null?s:X();let e=this.prepareRunAgentInput(a);return this.run(e).pipe(K(this.debug),U(this.debug),W(this.threadId,e.runId,this.agentId),t=>t.pipe(at(n=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(n)),n))))}};var V=class extends B{constructor(e){var s;super(e);this.abortController=new AbortController;this.url=e.url,this.headers=h((s=e.headers)!=null?s:{})}requestInit(e){return{method:"POST",headers:F(O({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e,s){var t;return this.abortController=(t=e==null?void 0:e.abortController)!=null?t:new AbortController,super.runAgent(e,s)}abortRun(){this.abortController.abort(),super.abortRun()}run(e){let s=j(this.url,this.requestInit(e));return q(s)}clone(){var n;let e=super.clone();e.url=this.url,e.headers=h((n=this.headers)!=null?n:{});let s=new AbortController,t=this.abortController.signal;return t.aborted&&s.abort(t.reason),e.abortController=s,e}};import{EventType as D}from"@ag-ui/core";function te(E){let a=[],e=new Map,s=new Map;for(let t of E)if(t.type===D.TEXT_MESSAGE_START){let n=t,i=n.messageId;e.has(i)||e.set(i,{contents:[],otherEvents:[]});let r=e.get(i);r.start=n}else if(t.type===D.TEXT_MESSAGE_CONTENT){let n=t,i=n.messageId;e.has(i)||e.set(i,{contents:[],otherEvents:[]}),e.get(i).contents.push(n)}else if(t.type===D.TEXT_MESSAGE_END){let n=t,i=n.messageId;e.has(i)||e.set(i,{contents:[],otherEvents:[]});let r=e.get(i);r.end=n,ct(i,r,a),e.delete(i)}else if(t.type===D.TOOL_CALL_START){let n=t,i=n.toolCallId;s.has(i)||s.set(i,{args:[],otherEvents:[]});let r=s.get(i);r.start=n}else if(t.type===D.TOOL_CALL_ARGS){let n=t,i=n.toolCallId;s.has(i)||s.set(i,{args:[],otherEvents:[]}),s.get(i).args.push(n)}else if(t.type===D.TOOL_CALL_END){let n=t,i=n.toolCallId;s.has(i)||s.set(i,{args:[],otherEvents:[]});let r=s.get(i);r.end=n,Et(i,r,a),s.delete(i)}else{let n=!1;for(let[i,r]of e)if(r.start&&!r.end){r.otherEvents.push(t),n=!0;break}if(!n){for(let[i,r]of s)if(r.start&&!r.end){r.otherEvents.push(t),n=!0;break}}n||a.push(t)}for(let[t,n]of e)ct(t,n,a);for(let[t,n]of s)Et(t,n,a);return a}function ct(E,a,e){if(a.start&&e.push(a.start),a.contents.length>0){let s=a.contents.map(n=>n.delta).join(""),t={type:D.TEXT_MESSAGE_CONTENT,messageId:E,delta:s};e.push(t)}a.end&&e.push(a.end);for(let s of a.otherEvents)e.push(s)}function Et(E,a,e){if(a.start&&e.push(a.start),a.args.length>0){let s=a.args.map(n=>n.delta).join(""),t={type:D.TOOL_CALL_ARGS,toolCallId:E,delta:s};e.push(t)}a.end&&e.push(a.end);for(let s of a.otherEvents)e.push(s)}export*from"@ag-ui/core";export{B as AbstractAgent,V as HttpAgent,te as compactEvents,W as convertToLegacyEvents,z as defaultApplyEvents,$ as parseProtoStream,J as parseSSEStream,j as runHttpRequest,q as transformHttpEventStream,U as verifyEvents};
3
+ Patch operations: ${JSON.stringify(l,null,2)}
4
+ Error: ${m}`)}}return i()}case R.MESSAGES_SNAPSHOT:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onMessagesSnapshotEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E})});if(o(u),u.stopPropagation!==!0){let{messages:l}=d;t=l,o({messages:t})}return i()}case R.ACTIVITY_SNAPSHOT:{let u=d,l=t.findIndex(S=>S.id===u.messageId),p=l>=0?t[l]:void 0,m=(p==null?void 0:p.role)==="activity"?p:void 0,c=await _(s,t,n,(S,y,x)=>{var D;return(D=S.onActivitySnapshotEvent)==null?void 0:D.call(S,{event:u,messages:y,state:x,agent:e,input:E,activityMessage:m,existingMessage:p})});if(o(c),c.stopPropagation!==!0){let S={id:u.messageId,role:"activity",activityType:u.activityType,content:M(u.content)},y;l===-1?(t.push(S),y=S):m?t[l]=G(O({},m),{activityType:u.activityType,content:M(u.content)}):(t[l]=S,y=S),o({messages:t}),y&&await Promise.all(s.map(x=>{var D;return(D=x.onNewMessage)==null?void 0:D.call(x,{message:y,messages:t,state:n,agent:e,input:E})}))}return i()}case R.ACTIVITY_DELTA:{let u=d,l=t.findIndex(S=>S.id===u.messageId);if(l===-1)return console.warn(`ACTIVITY_DELTA: No message found with ID '${u.messageId}' to apply patch`),i();let p=t[l];if(p.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${u.messageId}' is not an activity message`),i();let m=p,c=await _(s,t,n,(S,y,x)=>{var D;return(D=S.onActivityDeltaEvent)==null?void 0:D.call(S,{event:u,messages:y,state:x,agent:e,input:E,activityMessage:m})});if(o(c),c.stopPropagation!==!0)try{let S=M(m);S.activityType=u.activityType,(v=S.content)!=null||(S.content={});let x=tt(S,u.patch,!0,!1).newDocument;t[l]=G(O({},x),{id:m.id,role:"activity",activityType:u.activityType}),o({messages:t})}catch(S){let y=S instanceof Error?S.message:String(S);console.warn(`Failed to apply activity patch for '${u.messageId}': ${y}`)}return i()}case R.RAW:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onRawEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E})});return o(u),i()}case R.CUSTOM:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onCustomEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E})});return o(u),i()}case R.RUN_STARTED:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onRunStartedEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E})});if(o(u),u.stopPropagation!==!0){let l=d;if((g=l.input)!=null&&g.messages){for(let p of l.input.messages)t.find(c=>c.id===p.id)||t.push(p);o({messages:t})}}return i()}case R.RUN_FINISHED:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onRunFinishedEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E,result:d.result})});return o(u),i()}case R.RUN_ERROR:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onRunErrorEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E})});return o(u),i()}case R.STEP_STARTED:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onStepStartedEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E})});return o(u),i()}case R.STEP_FINISHED:{let u=await _(s,t,n,(l,p,m)=>{var c;return(c=l.onStepFinishedEvent)==null?void 0:c.call(l,{event:d,messages:p,state:m,agent:e,input:E})});return o(u),i()}case R.TEXT_MESSAGE_CHUNK:throw new Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case R.TOOL_CALL_CHUNK:throw new Error("TOOL_CALL_CHUNK must be tranformed before being applied");case R.THINKING_START:return i();case R.THINKING_END:return i();case R.THINKING_TEXT_MESSAGE_START:return i();case R.THINKING_TEXT_MESSAGE_CONTENT:return i();case R.THINKING_TEXT_MESSAGE_END:return i()}let H=d.type;return i()}),vt(),s.length>0?ht({}):d=>d)};import{EventType as I,AGUIError as N}from"@ag-ui/core";import{throwError as L,of as w}from"rxjs";import{mergeMap as _t}from"rxjs/operators";var X=E=>a=>{let e=new Map,s=new Map,t=!1,n=!1,r=!1,o=new Map,i=!1,d=!1,A=!1,H=()=>{e.clear(),s.clear(),o.clear(),i=!1,d=!1,t=!1,n=!1,A=!0};return a.pipe(_t(T=>{let v=T.type;if(E&&console.debug("[VERIFY]:",JSON.stringify(T)),n)return L(()=>new N(`Cannot send event type '${v}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(t&&v!==I.RUN_ERROR&&v!==I.RUN_STARTED)return L(()=>new N(`Cannot send event type '${v}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(r){if(v===I.RUN_STARTED){if(A&&!t)return L(()=>new N("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));t&&H()}}else if(r=!0,v!==I.RUN_STARTED&&v!==I.RUN_ERROR)return L(()=>new N("First event must be 'RUN_STARTED'"));switch(v){case I.TEXT_MESSAGE_START:{let g=T.messageId;return e.has(g)?L(()=>new N(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${g}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(e.set(g,!0),w(T))}case I.TEXT_MESSAGE_CONTENT:{let g=T.messageId;return e.has(g)?w(T):L(()=>new N(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${g}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case I.TEXT_MESSAGE_END:{let g=T.messageId;return e.has(g)?(e.delete(g),w(T)):L(()=>new N(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${g}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case I.TOOL_CALL_START:{let g=T.toolCallId;return s.has(g)?L(()=>new N(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${g}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(s.set(g,!0),w(T))}case I.TOOL_CALL_ARGS:{let g=T.toolCallId;return s.has(g)?w(T):L(()=>new N(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${g}'. Start a tool call with 'TOOL_CALL_START' first.`))}case I.TOOL_CALL_END:{let g=T.toolCallId;return s.has(g)?(s.delete(g),w(T)):L(()=>new N(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${g}'. A 'TOOL_CALL_START' event must be sent first.`))}case I.STEP_STARTED:{let g=T.stepName;return o.has(g)?L(()=>new N(`Step "${g}" is already active for 'STEP_STARTED'`)):(o.set(g,!0),w(T))}case I.STEP_FINISHED:{let g=T.stepName;return o.has(g)?(o.delete(g),w(T)):L(()=>new N(`Cannot send 'STEP_FINISHED' for step "${g}" that was not started`))}case I.RUN_STARTED:return A=!0,w(T);case I.RUN_FINISHED:{if(o.size>0){let g=Array.from(o.keys()).join(", ");return L(()=>new N(`Cannot send 'RUN_FINISHED' while steps are still active: ${g}`))}if(e.size>0){let g=Array.from(e.keys()).join(", ");return L(()=>new N(`Cannot send 'RUN_FINISHED' while text messages are still active: ${g}`))}if(s.size>0){let g=Array.from(s.keys()).join(", ");return L(()=>new N(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${g}`))}return t=!0,w(T)}case I.RUN_ERROR:return n=!0,w(T);case I.CUSTOM:return w(T);case I.THINKING_TEXT_MESSAGE_START:return i?d?L(()=>new N("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(d=!0,w(T)):L(()=>new N("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case I.THINKING_TEXT_MESSAGE_CONTENT:return d?w(T):L(()=>new N("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case I.THINKING_TEXT_MESSAGE_END:return d?(d=!1,w(T)):L(()=>new N("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case I.THINKING_START:return i?L(()=>new N("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(i=!0,w(T));case I.THINKING_END:return i?(i=!1,w(T)):L(()=>new N("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return w(T)}}))};import{EventSchemas as Pt}from"@ag-ui/core";import{Subject as Dt,ReplaySubject as Ht}from"rxjs";import{Observable as It,from as et,defer as xt,throwError as nt}from"rxjs";import{mergeMap as Nt,switchMap as Lt}from"rxjs/operators";var $=(E,a)=>xt(()=>et(fetch(E,a))).pipe(Lt(e=>{var n;if(!e.ok){let r=e.headers.get("content-type")||"";return et(e.text()).pipe(Nt(o=>{let i=o;if(r.includes("application/json"))try{i=JSON.parse(o)}catch(A){}let d=new Error(`HTTP ${e.status}: ${typeof i=="string"?i:JSON.stringify(i)}`);return d.status=e.status,d.payload=i,nt(()=>d)}))}let s={type:"headers",status:e.status,headers:e.headers},t=(n=e.body)==null?void 0:n.getReader();return t?new It(r=>(r.next(s),(async()=>{try{for(;;){let{done:o,value:i}=await t.read();if(o)break;let d={type:"data",data:i};r.next(d)}r.complete()}catch(o){r.error(o)}})(),()=>{t.cancel().catch(o=>{if((o==null?void 0:o.name)!=="AbortError")throw o})})):nt(()=>new Error("Failed to getReader() from response"))}));import{Subject as Ot}from"rxjs";var V=E=>{let a=new Ot,e=new TextDecoder("utf-8",{fatal:!1}),s="";E.subscribe({next:n=>{if(n.type!=="headers"&&n.type==="data"&&n.data){let r=e.decode(n.data,{stream:!0});s+=r;let o=s.split(/\n\n/);s=o.pop()||"";for(let i of o)t(i)}},error:n=>a.error(n),complete:()=>{s&&(s+=e.decode(),t(s)),a.complete()}});function t(n){let r=n.split(`
5
+ `),o=[];for(let i of r)i.startsWith("data: ")&&o.push(i.slice(6));if(o.length>0)try{let i=o.join(`
6
+ `),d=JSON.parse(i);a.next(d)}catch(i){a.error(i)}}return a.asObservable()};import{Subject as wt}from"rxjs";import*as st from"@ag-ui/proto";var b=E=>{let a=new wt,e=new Uint8Array(0);E.subscribe({next:t=>{if(t.type!=="headers"&&t.type==="data"&&t.data){let n=new Uint8Array(e.length+t.data.length);n.set(e,0),n.set(t.data,e.length),e=n,s()}},error:t=>a.error(t),complete:()=>{if(e.length>0)try{s()}catch(t){console.warn("Incomplete or invalid protocol buffer data at stream end")}a.complete()}});function s(){for(;e.length>=4;){let r=4+new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1);if(e.length<r)break;try{let o=e.slice(4,r),i=st.decode(o);a.next(i),e=e.slice(r)}catch(o){let i=o instanceof Error?o.message:String(o);a.error(new Error(`Failed to decode protocol buffer message: ${i}`));return}}}return a.asObservable()};import*as at from"@ag-ui/proto";import{EventType as Gt}from"@ag-ui/core";var Y=E=>{let a=new Dt,e=new Ht,s=!1;return E.subscribe({next:t=>{e.next(t),t.type==="headers"&&!s?(s=!0,t.headers.get("content-type")===at.AGUI_MEDIA_TYPE?b(e).subscribe({next:r=>a.next(r),error:r=>a.error(r),complete:()=>a.complete()}):V(e).subscribe({next:r=>{try{let o=Pt.parse(r);a.next(o)}catch(o){a.error(o)}},error:r=>{if((r==null?void 0:r.name)==="AbortError"){a.next({type:Gt.RUN_ERROR,rawEvent:r}),a.complete();return}return a.error(r)},complete:()=>a.complete()})):s||a.error(new Error("No headers event received before data events"))},error:t=>{e.error(t),a.error(t)},complete:()=>{e.complete()}}),a.asObservable()};import{mergeMap as bt}from"rxjs/operators";import{applyPatch as Yt}from"fast-json-patch";import{EventType as P}from"@ag-ui/core";import{z as f}from"zod";var C=f.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Ft=f.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Ut=f.object({type:f.literal(C.enum.TextMessageStart),messageId:f.string(),parentMessageId:f.string().optional(),role:f.string().optional()}),Xt=f.object({type:f.literal(C.enum.TextMessageContent),messageId:f.string(),content:f.string()}),Bt=f.object({type:f.literal(C.enum.TextMessageEnd),messageId:f.string()}),kt=f.object({type:f.literal(C.enum.ActionExecutionStart),actionExecutionId:f.string(),actionName:f.string(),parentMessageId:f.string().optional()}),Kt=f.object({type:f.literal(C.enum.ActionExecutionArgs),actionExecutionId:f.string(),args:f.string()}),jt=f.object({type:f.literal(C.enum.ActionExecutionEnd),actionExecutionId:f.string()}),zt=f.object({type:f.literal(C.enum.ActionExecutionResult),actionName:f.string(),actionExecutionId:f.string(),result:f.string()}),Jt=f.object({type:f.literal(C.enum.AgentStateMessage),threadId:f.string(),agentName:f.string(),nodeName:f.string(),runId:f.string(),active:f.boolean(),role:f.string(),state:f.string(),running:f.boolean()}),$t=f.object({type:f.literal(C.enum.MetaEvent),name:Ft,value:f.any()}),Vt=f.object({type:f.literal(C.enum.RunError),message:f.string(),code:f.string().optional()}),Hn=f.discriminatedUnion("type",[Ut,Xt,Bt,kt,Kt,jt,zt,Jt,$t,Vt]),Gn=f.object({id:f.string(),role:f.string(),content:f.string(),parentMessageId:f.string().optional()}),Fn=f.object({id:f.string(),name:f.string(),arguments:f.any(),parentMessageId:f.string().optional()}),Un=f.object({id:f.string(),result:f.any(),actionExecutionId:f.string(),actionName:f.string()});import Wt from"untruncate-json";var qt=E=>{if(typeof E=="string")return E;if(!Array.isArray(E))return;let a=E.filter(e=>e.type==="text").map(e=>e.text).filter(e=>e.length>0);if(a.length!==0)return a.join(`
7
+ `)},W=(E,a,e)=>s=>{let t={},n=!0,r=!0,o="",i=null,d=null,A=[],H={},T=v=>{typeof v=="object"&&v!==null&&("messages"in v&&delete v.messages,t=v)};return s.pipe(bt(v=>{switch(v.type){case P.TEXT_MESSAGE_START:{let g=v;return[{type:C.enum.TextMessageStart,messageId:g.messageId,role:g.role}]}case P.TEXT_MESSAGE_CONTENT:{let g=v;return[{type:C.enum.TextMessageContent,messageId:g.messageId,content:g.delta}]}case P.TEXT_MESSAGE_END:{let g=v;return[{type:C.enum.TextMessageEnd,messageId:g.messageId}]}case P.TOOL_CALL_START:{let g=v;return A.push({id:g.toolCallId,type:"function",function:{name:g.toolCallName,arguments:""}}),r=!0,H[g.toolCallId]=g.toolCallName,[{type:C.enum.ActionExecutionStart,actionExecutionId:g.toolCallId,actionName:g.toolCallName,parentMessageId:g.parentMessageId}]}case P.TOOL_CALL_ARGS:{let g=v,u=A.find(p=>p.id===g.toolCallId);if(!u)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${g.toolCallId}'`),[];u.function.arguments+=g.delta;let l=!1;if(d){let p=d.find(m=>m.tool==u.function.name);if(p)try{let m=JSON.parse(Wt(u.function.arguments));p.tool_argument&&p.tool_argument in m?(T(G(O({},t),{[p.state_key]:m[p.tool_argument]})),l=!0):p.tool_argument||(T(G(O({},t),{[p.state_key]:m})),l=!0)}catch(m){}}return[{type:C.enum.ActionExecutionArgs,actionExecutionId:g.toolCallId,args:g.delta},...l?[{type:C.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:o,runId:a,running:n,role:"assistant",state:JSON.stringify(t),active:r}]:[]]}case P.TOOL_CALL_END:{let g=v;return[{type:C.enum.ActionExecutionEnd,actionExecutionId:g.toolCallId}]}case P.TOOL_CALL_RESULT:{let g=v;return[{type:C.enum.ActionExecutionResult,actionExecutionId:g.toolCallId,result:g.content,actionName:H[g.toolCallId]||"unknown"}]}case P.RAW:return[];case P.CUSTOM:{let g=v;switch(g.name){case"Exit":n=!1;break;case"PredictState":d=g.value;break}return[{type:C.enum.MetaEvent,name:g.name,value:g.value}]}case P.STATE_SNAPSHOT:return T(v.snapshot),[{type:C.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:o,runId:a,running:n,role:"assistant",state:JSON.stringify(t),active:r}];case P.STATE_DELTA:{let u=Yt(t,v.delta,!0,!1);return u?(T(u.newDocument),[{type:C.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:o,runId:a,running:n,role:"assistant",state:JSON.stringify(t),active:r}]):[]}case P.MESSAGES_SNAPSHOT:return i=v.messages,[{type:C.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:o,runId:a,running:n,role:"assistant",state:JSON.stringify(O(O({},t),i?{messages:i}:{})),active:!0}];case P.RUN_STARTED:return[];case P.RUN_FINISHED:return i&&(t.messages=i),Object.keys(t).length===0?[]:[{type:C.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:o,runId:a,running:n,role:"assistant",state:JSON.stringify(O(O({},t),i?{messages:Qt(i)}:{})),active:!1}];case P.RUN_ERROR:{let g=v;return[{type:C.enum.RunError,message:g.message,code:g.code}]}case P.STEP_STARTED:return o=v.stepName,A=[],d=null,[{type:C.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:o,runId:a,running:n,role:"assistant",state:JSON.stringify(t),active:!0}];case P.STEP_FINISHED:return A=[],d=null,[{type:C.enum.AgentStateMessage,threadId:E,agentName:e,nodeName:o,runId:a,running:n,role:"assistant",state:JSON.stringify(t),active:!1}];default:return[]}}))};function Qt(E){var e;let a=[];for(let s of E)if(s.role==="assistant"||s.role==="user"||s.role==="system"){let t=qt(s.content);if(t){let n={id:s.id,role:s.role,content:t};a.push(n)}if(s.role==="assistant"&&s.toolCalls&&s.toolCalls.length>0)for(let n of s.toolCalls){let r={id:n.id,name:n.function.name,arguments:JSON.parse(n.function.arguments),parentMessageId:s.id};a.push(r)}}else if(s.role==="tool"){let t="unknown";for(let r of E)if(r.role==="assistant"&&((e=r.toolCalls)!=null&&e.length)){for(let o of r.toolCalls)if(o.id===s.toolCallId){t=o.function.name;break}}let n={id:s.id,result:s.content,actionExecutionId:s.toolCallId,actionName:t};a.push(n)}return a}import{v4 as B}from"uuid";import{catchError as ot,map as rt,tap as ee}from"rxjs/operators";import{finalize as it}from"rxjs/operators";import{pipe as lt,from as ne,of as gt,EMPTY as se}from"rxjs";import{lastValueFrom as ct}from"rxjs";import{mergeMap as Zt,finalize as te}from"rxjs";import{EventType as h}from"@ag-ui/core";var j=E=>a=>{let e,s,t,n=()=>{if(!e||t!=="text")throw new Error("No text message to close");let i={type:h.TEXT_MESSAGE_END,messageId:e.messageId};return t=void 0,e=void 0,E&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(i)),i},r=()=>{if(!s||t!=="tool")throw new Error("No tool call to close");let i={type:h.TOOL_CALL_END,toolCallId:s.toolCallId};return t=void 0,s=void 0,E&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(i)),i},o=()=>t==="text"?[n()]:t==="tool"?[r()]:[];return a.pipe(Zt(i=>{switch(i.type){case h.TEXT_MESSAGE_START:case h.TEXT_MESSAGE_CONTENT:case h.TEXT_MESSAGE_END:case h.TOOL_CALL_START:case h.TOOL_CALL_ARGS:case h.TOOL_CALL_END:case h.TOOL_CALL_RESULT:case h.STATE_SNAPSHOT:case h.STATE_DELTA:case h.MESSAGES_SNAPSHOT:case h.CUSTOM:case h.RUN_STARTED:case h.RUN_FINISHED:case h.RUN_ERROR:case h.STEP_STARTED:case h.STEP_FINISHED:case h.THINKING_START:case h.THINKING_END:case h.THINKING_TEXT_MESSAGE_START:case h.THINKING_TEXT_MESSAGE_CONTENT:case h.THINKING_TEXT_MESSAGE_END:return[...o(),i];case h.RAW:case h.ACTIVITY_SNAPSHOT:case h.ACTIVITY_DELTA:return[i];case h.TEXT_MESSAGE_CHUNK:let A=i,H=[];if((t!=="text"||A.messageId!==void 0&&A.messageId!==(e==null?void 0:e.messageId))&&H.push(...o()),t!=="text"){if(A.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:A.messageId},t="text";let g={type:h.TEXT_MESSAGE_START,messageId:A.messageId,role:A.role||"assistant"};H.push(g),E&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(g))}if(A.delta!==void 0){let g={type:h.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:A.delta};H.push(g),E&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(g))}return H;case h.TOOL_CALL_CHUNK:let T=i,v=[];if((t!=="tool"||T.toolCallId!==void 0&&T.toolCallId!==(s==null?void 0:s.toolCallId))&&v.push(...o()),t!=="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");s={toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId},t="tool";let g={type:h.TOOL_CALL_START,toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId};v.push(g),E&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(g))}if(T.delta!==void 0){let g={type:h.TOOL_CALL_ARGS,toolCallId:s.toolCallId,delta:T.delta};v.push(g),E&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(g))}return v}let d=i.type;return[]}),te(()=>{o()}))};import{AGUIConnectNotImplementedError as Et}from"@ag-ui/core";var k=class{constructor({agentId:a,description:e,threadId:s,initialMessages:t,initialState:n,debug:r}={}){this.debug=!1;this.subscribers=[];this.isRunning=!1;this.agentId=a,this.description=e!=null?e:"",this.threadId=s!=null?s:B(),this.messages=M(t!=null?t:[]),this.state=M(n!=null?n:{}),this.debug=r!=null?r:!1}subscribe(a){return this.subscribers.push(a),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==a)}}}async runAgent(a,e){var s;try{this.isRunning=!0,this.agentId=(s=this.agentId)!=null?s:B();let t=this.prepareRunAgentInput(a),n,r=new Set(this.messages.map(A=>A.id)),o=[{onRunFinishedEvent:A=>{n=A.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o);let i=lt(()=>this.run(t),j(this.debug),X(this.debug),A=>this.apply(t,A,o),A=>this.processApplyEvents(t,A,o),ot(A=>(this.isRunning=!1,this.onError(t,A,o))),it(()=>{this.isRunning=!1,this.onFinalize(t,o)}));await ct(i(gt(null)));let d=M(this.messages).filter(A=>!r.has(A.id));return{result:n,newMessages:d}}finally{this.isRunning=!1}}connect(a){throw new Et}async connectAgent(a,e){var s;try{this.isRunning=!0,this.agentId=(s=this.agentId)!=null?s:B();let t=this.prepareRunAgentInput(a),n,r=new Set(this.messages.map(A=>A.id)),o=[{onRunFinishedEvent:A=>{n=A.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o);let i=lt(()=>this.connect(t),j(this.debug),X(this.debug),A=>this.apply(t,A,o),A=>this.processApplyEvents(t,A,o),ot(A=>(this.isRunning=!1,A instanceof Et?se:this.onError(t,A,o))),it(()=>{this.isRunning=!1,this.onFinalize(t,o)}));await ct(i(gt(null)));let d=M(this.messages).filter(A=>!r.has(A.id));return{result:n,newMessages:d}}finally{this.isRunning=!1}}abortRun(){}apply(a,e,s){return J(a,e,this,s)}processApplyEvents(a,e,s){return e.pipe(ee(t=>{t.messages&&(this.messages=t.messages,s.forEach(n=>{var r;(r=n.onMessagesChanged)==null||r.call(n,{messages:this.messages,state:this.state,agent:this,input:a})})),t.state&&(this.state=t.state,s.forEach(n=>{var r;(r=n.onStateChanged)==null||r.call(n,{state:this.state,messages:this.messages,agent:this,input:a})}))}))}prepareRunAgentInput(a){var t,n,r;let s=M(this.messages).filter(o=>o.role!=="activity");return{threadId:this.threadId,runId:(a==null?void 0:a.runId)||B(),tools:M((t=a==null?void 0:a.tools)!=null?t:[]),context:M((n=a==null?void 0:a.context)!=null?n:[]),forwardedProps:M((r=a==null?void 0:a.forwardedProps)!=null?r:{}),state:M(this.state),messages:s}}async onInitialize(a,e){let s=await _(e,this.messages,this.state,(t,n,r)=>{var o;return(o=t.onRunInitialized)==null?void 0:o.call(t,{messages:n,state:r,agent:this,input:a})});(s.messages!==void 0||s.state!==void 0)&&(s.messages&&(this.messages=s.messages,a.messages=s.messages,e.forEach(t=>{var n;(n=t.onMessagesChanged)==null||n.call(t,{messages:this.messages,state:this.state,agent:this,input:a})})),s.state&&(this.state=s.state,a.state=s.state,e.forEach(t=>{var n;(n=t.onStateChanged)==null||n.call(t,{state:this.state,messages:this.messages,agent:this,input:a})})))}onError(a,e,s){return ne(_(s,this.messages,this.state,(t,n,r)=>{var o;return(o=t.onRunFailed)==null?void 0:o.call(t,{error:e,messages:n,state:r,agent:this,input:a})})).pipe(rt(t=>{let n=t;if((n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,s.forEach(r=>{var o;(o=r.onMessagesChanged)==null||o.call(r,{messages:this.messages,state:this.state,agent:this,input:a})})),n.state!==void 0&&(this.state=n.state,s.forEach(r=>{var o;(o=r.onStateChanged)==null||o.call(r,{state:this.state,messages:this.messages,agent:this,input:a})}))),n.stopPropagation!==!0)throw console.error("Agent execution failed:",e),e;return{}}))}async onFinalize(a,e){let s=await _(e,this.messages,this.state,(t,n,r)=>{var o;return(o=t.onRunFinalized)==null?void 0:o.call(t,{messages:n,state:r,agent:this,input:a})});(s.messages!==void 0||s.state!==void 0)&&(s.messages!==void 0&&(this.messages=s.messages,e.forEach(t=>{var n;(n=t.onMessagesChanged)==null||n.call(t,{messages:this.messages,state:this.state,agent:this,input:a})})),s.state!==void 0&&(this.state=s.state,e.forEach(t=>{var n;(n=t.onStateChanged)==null||n.call(t,{state:this.state,messages:this.messages,agent:this,input:a})})))}clone(){let a=Object.create(Object.getPrototypeOf(this));return a.agentId=this.agentId,a.description=this.description,a.threadId=this.threadId,a.messages=M(this.messages),a.state=M(this.state),a.debug=this.debug,a.isRunning=this.isRunning,a.subscribers=[...this.subscribers],a}addMessage(a){this.messages.push(a),(async()=>{var e,s,t;for(let n of this.subscribers)await((e=n.onNewMessage)==null?void 0:e.call(n,{message:a,messages:this.messages,state:this.state,agent:this}));if(a.role==="assistant"&&a.toolCalls)for(let n of a.toolCalls)for(let r of this.subscribers)await((s=r.onNewToolCall)==null?void 0:s.call(r,{toolCall:n,messages:this.messages,state:this.state,agent:this}));for(let n of this.subscribers)await((t=n.onMessagesChanged)==null?void 0:t.call(n,{messages:this.messages,state:this.state,agent:this}))})()}addMessages(a){this.messages.push(...a),(async()=>{var e,s,t;for(let n of a){for(let r of this.subscribers)await((e=r.onNewMessage)==null?void 0:e.call(r,{message:n,messages:this.messages,state:this.state,agent:this}));if(n.role==="assistant"&&n.toolCalls)for(let r of n.toolCalls)for(let o of this.subscribers)await((s=o.onNewToolCall)==null?void 0:s.call(o,{toolCall:r,messages:this.messages,state:this.state,agent:this}))}for(let n of this.subscribers)await((t=n.onMessagesChanged)==null?void 0:t.call(n,{messages:this.messages,state:this.state,agent:this}))})()}setMessages(a){this.messages=M(a),(async()=>{var e;for(let s of this.subscribers)await((e=s.onMessagesChanged)==null?void 0:e.call(s,{messages:this.messages,state:this.state,agent:this}))})()}setState(a){this.state=M(a),(async()=>{var e;for(let s of this.subscribers)await((e=s.onStateChanged)==null?void 0:e.call(s,{messages:this.messages,state:this.state,agent:this}))})()}legacy_to_be_removed_runAgentBridged(a){var s;this.agentId=(s=this.agentId)!=null?s:B();let e=this.prepareRunAgentInput(a);return this.run(e).pipe(j(this.debug),X(this.debug),W(this.threadId,e.runId,this.agentId),t=>t.pipe(rt(n=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(n)),n))))}};var q=class extends k{constructor(e){var s;super(e);this.abortController=new AbortController;this.url=e.url,this.headers=M((s=e.headers)!=null?s:{})}requestInit(e){return{method:"POST",headers:G(O({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e,s){var t;return this.abortController=(t=e==null?void 0:e.abortController)!=null?t:new AbortController,super.runAgent(e,s)}abortRun(){this.abortController.abort(),super.abortRun()}run(e){let s=$(this.url,this.requestInit(e));return Y(s)}clone(){var n;let e=super.clone();e.url=this.url,e.headers=M((n=this.headers)!=null?n:{});let s=new AbortController,t=this.abortController.signal;return t.aborted&&s.abort(t.reason),e.abortController=s,e}};import{EventType as F}from"@ag-ui/core";function ae(E){let a=[],e=new Map,s=new Map;for(let t of E)if(t.type===F.TEXT_MESSAGE_START){let n=t,r=n.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]});let o=e.get(r);o.start=n}else if(t.type===F.TEXT_MESSAGE_CONTENT){let n=t,r=n.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]}),e.get(r).contents.push(n)}else if(t.type===F.TEXT_MESSAGE_END){let n=t,r=n.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]});let o=e.get(r);o.end=n,ut(r,o,a),e.delete(r)}else if(t.type===F.TOOL_CALL_START){let n=t,r=n.toolCallId;s.has(r)||s.set(r,{args:[],otherEvents:[]});let o=s.get(r);o.start=n}else if(t.type===F.TOOL_CALL_ARGS){let n=t,r=n.toolCallId;s.has(r)||s.set(r,{args:[],otherEvents:[]}),s.get(r).args.push(n)}else if(t.type===F.TOOL_CALL_END){let n=t,r=n.toolCallId;s.has(r)||s.set(r,{args:[],otherEvents:[]});let o=s.get(r);o.end=n,pt(r,o,a),s.delete(r)}else{let n=!1;for(let[r,o]of e)if(o.start&&!o.end){o.otherEvents.push(t),n=!0;break}if(!n){for(let[r,o]of s)if(o.start&&!o.end){o.otherEvents.push(t),n=!0;break}}n||a.push(t)}for(let[t,n]of e)ut(t,n,a);for(let[t,n]of s)pt(t,n,a);return a}function ut(E,a,e){if(a.start&&e.push(a.start),a.contents.length>0){let s=a.contents.map(n=>n.delta).join(""),t={type:F.TEXT_MESSAGE_CONTENT,messageId:E,delta:s};e.push(t)}a.end&&e.push(a.end);for(let s of a.otherEvents)e.push(s)}function pt(E,a,e){if(a.start&&e.push(a.start),a.args.length>0){let s=a.args.map(n=>n.delta).join(""),t={type:F.TOOL_CALL_ARGS,toolCallId:E,delta:s};e.push(t)}a.end&&e.push(a.end);for(let s of a.otherEvents)e.push(s)}export*from"@ag-ui/core";export{k as AbstractAgent,q as HttpAgent,ae as compactEvents,W as convertToLegacyEvents,J as defaultApplyEvents,b as parseProtoStream,V as parseSSEStream,le as randomUUID,$ as runHttpRequest,M as structuredClone_,j as transformChunks,Y as transformHttpEventStream,X as verifyEvents};
7
8
  //# sourceMappingURL=index.mjs.map