@ag-ui/client 0.0.44 → 0.0.45

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,8 +1,5 @@
1
- var It=Object.defineProperty,_t=Object.defineProperties;var Nt=Object.getOwnPropertyDescriptors;var Y=Object.getOwnPropertySymbols;var it=Object.prototype.hasOwnProperty,lt=Object.prototype.propertyIsEnumerable;var rt=(g,a,e)=>a in g?It(g,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):g[a]=e,N=(g,a)=>{for(var e in a||(a={}))it.call(a,e)&&rt(g,e,a[e]);if(Y)for(var e of Y(a))lt.call(a,e)&&rt(g,e,a[e]);return g},G=(g,a)=>_t(g,Nt(a));var gt=(g,a)=>{var e={};for(var n in g)it.call(g,n)&&a.indexOf(n)<0&&(e[n]=g[n]);if(g!=null&&Y)for(var n of Y(g))a.indexOf(n)<0&&lt.call(g,n)&&(e[n]=g[n]);return e};import{EventType as R}from"@ag-ui/core";import{mergeAll as Lt,defaultIfEmpty as Ot,concatMap as Pt}from"rxjs/operators";import{of as Dt,EMPTY as Ht}from"rxjs";import{v4 as wt}from"uuid";var y=g=>{if(typeof structuredClone=="function")return structuredClone(g);try{return JSON.parse(JSON.stringify(g))}catch(a){return N({},g)}};function Re(){return wt()}import{applyPatch as ct}from"fast-json-patch";async function I(g,a,e,n){let t=a,s=e,r;for(let o of g)try{let i=await n(o,y(t),y(s));if(i===void 0)continue;if(i.messages!==void 0&&(t=i.messages),i.state!==void 0&&(s=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 N(N(N({},JSON.stringify(t)!==JSON.stringify(a)?{messages:t}:{}),JSON.stringify(s)!==JSON.stringify(e)?{state:s}:{}),r!==void 0?{stopPropagation:r}:{})}import Gt from"untruncate-json";var $=(g,a,e,n)=>{let t=y(e.messages),s=y(g.state),r={},o=d=>{d.messages!==void 0&&(t=d.messages,r.messages=d.messages),d.state!==void 0&&(s=d.state,r.state=d.state)},i=()=>{let d=y(r);return r={},d.messages!==void 0||d.state!==void 0?Dt(d):Ht};return a.pipe(Pt(async d=>{var T,v,c,b,U;let x=await I(n,t,s,(E,l,p)=>{var m;return(m=E.onEvent)==null?void 0:m.call(E,{event:d,agent:e,input:g,messages:l,state:p})});if(o(x),x.stopPropagation===!0)return i();switch(d.type){case R.TEXT_MESSAGE_START:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onTextMessageStartEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let{messageId:l,role:p="assistant"}=d;if(!t.find(u=>u.id===l)){let u={id:l,role:p,content:""};t.push(u),o({messages:t})}}return i()}case R.TEXT_MESSAGE_CONTENT:{let{messageId:E,delta:l}=d,p=t.find(u=>u.id===E);if(!p)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${E}'`),i();let m=await I(n,t,s,(u,A,h)=>{var _;return(_=u.onTextMessageContentEvent)==null?void 0:_.call(u,{event:d,messages:A,state:h,agent:e,input:g,textMessageBuffer:typeof p.content=="string"?p.content:""})});if(o(m),m.stopPropagation!==!0){let u=typeof p.content=="string"?p.content:"";p.content=`${u}${l}`,o({messages:t})}return i()}case R.TEXT_MESSAGE_END:{let{messageId:E}=d,l=t.find(m=>m.id===E);if(!l)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${E}'`),i();let p=await I(n,t,s,(m,u,A)=>{var h;return(h=m.onTextMessageEndEvent)==null?void 0:h.call(m,{event:d,messages:u,state:A,agent:e,input:g,textMessageBuffer:typeof l.content=="string"?l.content:""})});return o(p),await Promise.all(n.map(m=>{var u;(u=m.onNewMessage)==null||u.call(m,{message:l,messages:t,state:s,agent:e,input:g})})),i()}case R.TOOL_CALL_START:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onToolCallStartEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let{toolCallId:l,toolCallName:p,parentMessageId:m}=d,u;m&&t.length>0&&t[t.length-1].id===m?u=t[t.length-1]:(u={id:m||l,role:"assistant",toolCalls:[]},t.push(u)),(T=u.toolCalls)!=null||(u.toolCalls=[]),u.toolCalls.push({id:l,type:"function",function:{name:p,arguments:""}}),o({messages:t})}return i()}case R.TOOL_CALL_ARGS:{let{toolCallId:E,delta:l}=d,p=t.find(A=>{var h;return(h=A.toolCalls)==null?void 0:h.some(_=>_.id===E)});if(!p)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${E}'`),i();let m=p.toolCalls.find(A=>A.id===E);if(!m)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${E}'`),i();let u=await I(n,t,s,(A,h,_)=>{var Z;let H=m.function.arguments,F=m.function.name,X={};try{X=Gt(H)}catch(ye){}return(Z=A.onToolCallArgsEvent)==null?void 0:Z.call(A,{event:d,messages:h,state:_,agent:e,input:g,toolCallBuffer:H,toolCallName:F,partialToolCallArgs:X})});return o(u),u.stopPropagation!==!0&&(m.function.arguments+=l,o({messages:t})),i()}case R.TOOL_CALL_END:{let{toolCallId:E}=d,l=t.find(u=>{var A;return(A=u.toolCalls)==null?void 0:A.some(h=>h.id===E)});if(!l)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${E}'`),i();let p=l.toolCalls.find(u=>u.id===E);if(!p)return console.warn(`TOOL_CALL_END: No tool call found with ID '${E}'`),i();let m=await I(n,t,s,(u,A,h)=>{var X;let _=p.function.arguments,H=p.function.name,F={};try{F=JSON.parse(_)}catch(Z){}return(X=u.onToolCallEndEvent)==null?void 0:X.call(u,{event:d,messages:A,state:h,agent:e,input:g,toolCallName:H,toolCallArgs:F})});return o(m),await Promise.all(n.map(u=>{var A;(A=u.onNewToolCall)==null||A.call(u,{toolCall:p,messages:t,state:s,agent:e,input:g})})),i()}case R.TOOL_CALL_RESULT:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onToolCallResultEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let{messageId:l,toolCallId:p,content:m,role:u}=d,A={id:l,toolCallId:p,role:u||"tool",content:m};t.push(A),await Promise.all(n.map(h=>{var _;(_=h.onNewMessage)==null||_.call(h,{message:A,messages:t,state:s,agent:e,input:g})})),o({messages:t})}return i()}case R.STATE_SNAPSHOT:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onStateSnapshotEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let{snapshot:l}=d;s=l,o({state:s})}return i()}case R.STATE_DELTA:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onStateDeltaEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let{delta:l}=d;try{s=ct(s,l,!0,!1).newDocument,o({state:s})}catch(p){let m=p instanceof Error?p.message:String(p);console.warn(`Failed to apply state patch:
2
- Current state: ${JSON.stringify(s,null,2)}
3
- Patch operations: ${JSON.stringify(l,null,2)}
4
- Error: ${m}`)}}return i()}case R.MESSAGES_SNAPSHOT:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onMessagesSnapshotEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let{messages:l}=d;t=l,o({messages:t})}return i()}case R.ACTIVITY_SNAPSHOT:{let E=d,l=t.findIndex(h=>h.id===E.messageId),p=l>=0?t[l]:void 0,m=(p==null?void 0:p.role)==="activity"?p:void 0,u=(v=E.replace)!=null?v:!0,A=await I(n,t,s,(h,_,H)=>{var F;return(F=h.onActivitySnapshotEvent)==null?void 0:F.call(h,{event:E,messages:_,state:H,agent:e,input:g,activityMessage:m,existingMessage:p})});if(o(A),A.stopPropagation!==!0){let h={id:E.messageId,role:"activity",activityType:E.activityType,content:y(E.content)},_;l===-1?(t.push(h),_=h):m?u&&(t[l]=G(N({},m),{activityType:E.activityType,content:y(E.content)})):u&&(t[l]=h,_=h),o({messages:t}),_&&await Promise.all(n.map(H=>{var F;return(F=H.onNewMessage)==null?void 0:F.call(H,{message:_,messages:t,state:s,agent:e,input:g})}))}return i()}case R.ACTIVITY_DELTA:{let E=d,l=t.findIndex(A=>A.id===E.messageId);if(l===-1)return console.warn(`ACTIVITY_DELTA: No message found with ID '${E.messageId}' to apply patch`),i();let p=t[l];if(p.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${E.messageId}' is not an activity message`),i();let m=p,u=await I(n,t,s,(A,h,_)=>{var H;return(H=A.onActivityDeltaEvent)==null?void 0:H.call(A,{event:E,messages:h,state:_,agent:e,input:g,activityMessage:m})});if(o(u),u.stopPropagation!==!0)try{let A=y((c=m.content)!=null?c:{}),_=ct(A,(b=E.patch)!=null?b:[],!0,!1).newDocument;t[l]=G(N({},m),{content:y(_),activityType:E.activityType}),o({messages:t})}catch(A){let h=A instanceof Error?A.message:String(A);console.warn(`Failed to apply activity patch for '${E.messageId}': ${h}`)}return i()}case R.RAW:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onRawEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g})});return o(E),i()}case R.CUSTOM:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onCustomEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g})});return o(E),i()}case R.RUN_STARTED:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onRunStartedEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let l=d;if((U=l.input)!=null&&U.messages){for(let p of l.input.messages)t.find(u=>u.id===p.id)||t.push(p);o({messages:t})}}return i()}case R.RUN_FINISHED:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onRunFinishedEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g,result:d.result})});return o(E),i()}case R.RUN_ERROR:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onRunErrorEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g})});return o(E),i()}case R.STEP_STARTED:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onStepStartedEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g})});return o(E),i()}case R.STEP_FINISHED:{let E=await I(n,t,s,(l,p,m)=>{var u;return(u=l.onStepFinishedEvent)==null?void 0:u.call(l,{event:d,messages:p,state:m,agent:e,input:g})});return o(E),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 S=d.type;return i()}),Lt(),n.length>0?Ot({}):d=>d)};import{EventType as w,AGUIError as L}from"@ag-ui/core";import{throwError as O,of as P}from"rxjs";import{mergeMap as bt}from"rxjs/operators";var z=g=>a=>{let e=new Map,n=new Map,t=!1,s=!1,r=!1,o=new Map,i=!1,d=!1,x=!1,S=()=>{e.clear(),n.clear(),o.clear(),i=!1,d=!1,t=!1,s=!1,x=!0};return a.pipe(bt(T=>{let v=T.type;if(g&&console.debug("[VERIFY]:",JSON.stringify(T)),s)return O(()=>new L(`Cannot send event type '${v}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(t&&v!==w.RUN_ERROR&&v!==w.RUN_STARTED)return O(()=>new L(`Cannot send event type '${v}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(r){if(v===w.RUN_STARTED){if(x&&!t)return O(()=>new L("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&&S()}}else if(r=!0,v!==w.RUN_STARTED&&v!==w.RUN_ERROR)return O(()=>new L("First event must be 'RUN_STARTED'"));switch(v){case w.TEXT_MESSAGE_START:{let c=T.messageId;return e.has(c)?O(()=>new L(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${c}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(e.set(c,!0),P(T))}case w.TEXT_MESSAGE_CONTENT:{let c=T.messageId;return e.has(c)?P(T):O(()=>new L(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${c}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case w.TEXT_MESSAGE_END:{let c=T.messageId;return e.has(c)?(e.delete(c),P(T)):O(()=>new L(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${c}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case w.TOOL_CALL_START:{let c=T.toolCallId;return n.has(c)?O(()=>new L(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${c}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(n.set(c,!0),P(T))}case w.TOOL_CALL_ARGS:{let c=T.toolCallId;return n.has(c)?P(T):O(()=>new L(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${c}'. Start a tool call with 'TOOL_CALL_START' first.`))}case w.TOOL_CALL_END:{let c=T.toolCallId;return n.has(c)?(n.delete(c),P(T)):O(()=>new L(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${c}'. A 'TOOL_CALL_START' event must be sent first.`))}case w.STEP_STARTED:{let c=T.stepName;return o.has(c)?O(()=>new L(`Step "${c}" is already active for 'STEP_STARTED'`)):(o.set(c,!0),P(T))}case w.STEP_FINISHED:{let c=T.stepName;return o.has(c)?(o.delete(c),P(T)):O(()=>new L(`Cannot send 'STEP_FINISHED' for step "${c}" that was not started`))}case w.RUN_STARTED:return x=!0,P(T);case w.RUN_FINISHED:{if(o.size>0){let c=Array.from(o.keys()).join(", ");return O(()=>new L(`Cannot send 'RUN_FINISHED' while steps are still active: ${c}`))}if(e.size>0){let c=Array.from(e.keys()).join(", ");return O(()=>new L(`Cannot send 'RUN_FINISHED' while text messages are still active: ${c}`))}if(n.size>0){let c=Array.from(n.keys()).join(", ");return O(()=>new L(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${c}`))}return t=!0,P(T)}case w.RUN_ERROR:return s=!0,P(T);case w.CUSTOM:return P(T);case w.THINKING_TEXT_MESSAGE_START:return i?d?O(()=>new L("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(d=!0,P(T)):O(()=>new L("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case w.THINKING_TEXT_MESSAGE_CONTENT:return d?P(T):O(()=>new L("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case w.THINKING_TEXT_MESSAGE_END:return d?(d=!1,P(T)):O(()=>new L("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case w.THINKING_START:return i?O(()=>new L("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(i=!0,P(T));case w.THINKING_END:return i?(i=!1,P(T)):O(()=>new L("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return P(T)}}))};import{EventSchemas as $t}from"@ag-ui/core";import{Subject as zt,ReplaySubject as Kt}from"rxjs";import{Observable as Ft,from as ut,defer as kt,throwError as Et}from"rxjs";import{mergeMap as Bt,switchMap as Ut}from"rxjs/operators";var tt=(g,a)=>kt(()=>ut(fetch(g,a))).pipe(Ut(e=>{var s;if(!e.ok){let r=e.headers.get("content-type")||"";return ut(e.text()).pipe(Bt(o=>{let i=o;if(r.includes("application/json"))try{i=JSON.parse(o)}catch(x){}let d=new Error(`HTTP ${e.status}: ${typeof i=="string"?i:JSON.stringify(i)}`);return d.status=e.status,d.payload=i,Et(()=>d)}))}let n={type:"headers",status:e.status,headers:e.headers},t=(s=e.body)==null?void 0:s.getReader();return t?new Ft(r=>(r.next(n),(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})})):Et(()=>new Error("Failed to getReader() from response"))}));import{Subject as jt}from"rxjs";var et=g=>{let a=new jt,e=new TextDecoder("utf-8",{fatal:!1}),n="";g.subscribe({next:s=>{if(s.type!=="headers"&&s.type==="data"&&s.data){let r=e.decode(s.data,{stream:!0});n+=r;let o=n.split(/\n\n/);n=o.pop()||"";for(let i of o)t(i)}},error:s=>a.error(s),complete:()=>{n&&(n+=e.decode(),t(n)),a.complete()}});function t(s){let r=s.split(`
5
- `),o=[];for(let i of r)i.startsWith("data:")&&o.push(i.slice(5).replace(/^ /,""));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 Xt}from"rxjs";import*as dt from"@ag-ui/proto";var nt=g=>{let a=new Xt,e=new Uint8Array(0);g.subscribe({next:t=>{if(t.type!=="headers"&&t.type==="data"&&t.data){let s=new Uint8Array(e.length+t.data.length);s.set(e,0),s.set(t.data,e.length),e=s,n()}},error:t=>a.error(t),complete:()=>{if(e.length>0)try{n()}catch(t){console.warn("Incomplete or invalid protocol buffer data at stream end")}a.complete()}});function n(){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=dt.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 pt from"@ag-ui/proto";import{EventType as Jt}from"@ag-ui/core";var st=g=>{let a=new zt,e=new Kt,n=!1;return g.subscribe({next:t=>{e.next(t),t.type==="headers"&&!n?(n=!0,t.headers.get("content-type")===pt.AGUI_MEDIA_TYPE?nt(e).subscribe({next:r=>a.next(r),error:r=>a.error(r),complete:()=>a.complete()}):et(e).subscribe({next:r=>{try{let o=$t.parse(r);a.next(o)}catch(o){a.error(o)}},error:r=>{if((r==null?void 0:r.name)==="AbortError"){a.next({type:Jt.RUN_ERROR,message:r.message||"Request aborted",code:"abort",rawEvent:r}),a.complete();return}return a.error(r)},complete:()=>a.complete()})):n||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 oe}from"rxjs/operators";import{applyPatch as re}from"fast-json-patch";import{EventType as D}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"]),Vt=f.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Wt=f.object({type:f.literal(C.enum.TextMessageStart),messageId:f.string(),parentMessageId:f.string().optional(),role:f.string().optional()}),Yt=f.object({type:f.literal(C.enum.TextMessageContent),messageId:f.string(),content:f.string()}),qt=f.object({type:f.literal(C.enum.TextMessageEnd),messageId:f.string()}),Qt=f.object({type:f.literal(C.enum.ActionExecutionStart),actionExecutionId:f.string(),actionName:f.string(),parentMessageId:f.string().optional()}),Zt=f.object({type:f.literal(C.enum.ActionExecutionArgs),actionExecutionId:f.string(),args:f.string()}),te=f.object({type:f.literal(C.enum.ActionExecutionEnd),actionExecutionId:f.string()}),ee=f.object({type:f.literal(C.enum.ActionExecutionResult),actionName:f.string(),actionExecutionId:f.string(),result:f.string()}),ne=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()}),se=f.object({type:f.literal(C.enum.MetaEvent),name:Vt,value:f.any()}),ae=f.object({type:f.literal(C.enum.RunError),message:f.string(),code:f.string().optional()}),Qn=f.discriminatedUnion("type",[Wt,Yt,qt,Qt,Zt,te,ee,ne,se,ae]),Zn=f.object({id:f.string(),role:f.string(),content:f.string(),parentMessageId:f.string().optional()}),ts=f.object({id:f.string(),name:f.string(),arguments:f.any(),parentMessageId:f.string().optional()}),es=f.object({id:f.string(),result:f.any(),actionExecutionId:f.string(),actionName:f.string()});import ie from"untruncate-json";var le=g=>{if(typeof g=="string")return g;if(!Array.isArray(g))return;let a=g.filter(e=>e.type==="text").map(e=>e.text).filter(e=>e.length>0);if(a.length!==0)return a.join(`
7
- `)},at=(g,a,e)=>n=>{let t={},s=!0,r=!0,o="",i=null,d=null,x=[],S={},T=v=>{typeof v=="object"&&v!==null&&("messages"in v&&delete v.messages,t=v)};return n.pipe(oe(v=>{switch(v.type){case D.TEXT_MESSAGE_START:{let c=v;return[{type:C.enum.TextMessageStart,messageId:c.messageId,role:c.role}]}case D.TEXT_MESSAGE_CONTENT:{let c=v;return[{type:C.enum.TextMessageContent,messageId:c.messageId,content:c.delta}]}case D.TEXT_MESSAGE_END:{let c=v;return[{type:C.enum.TextMessageEnd,messageId:c.messageId}]}case D.TOOL_CALL_START:{let c=v;return x.push({id:c.toolCallId,type:"function",function:{name:c.toolCallName,arguments:""}}),r=!0,S[c.toolCallId]=c.toolCallName,[{type:C.enum.ActionExecutionStart,actionExecutionId:c.toolCallId,actionName:c.toolCallName,parentMessageId:c.parentMessageId}]}case D.TOOL_CALL_ARGS:{let c=v,b=x.find(E=>E.id===c.toolCallId);if(!b)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c.toolCallId}'`),[];b.function.arguments+=c.delta;let U=!1;if(d){let E=d.find(l=>l.tool==b.function.name);if(E)try{let l=JSON.parse(ie(b.function.arguments));E.tool_argument&&E.tool_argument in l?(T(G(N({},t),{[E.state_key]:l[E.tool_argument]})),U=!0):E.tool_argument||(T(G(N({},t),{[E.state_key]:l})),U=!0)}catch(l){}}return[{type:C.enum.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...U?[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}]:[]]}case D.TOOL_CALL_END:{let c=v;return[{type:C.enum.ActionExecutionEnd,actionExecutionId:c.toolCallId}]}case D.TOOL_CALL_RESULT:{let c=v;return[{type:C.enum.ActionExecutionResult,actionExecutionId:c.toolCallId,result:c.content,actionName:S[c.toolCallId]||"unknown"}]}case D.RAW:return[];case D.CUSTOM:{let c=v;switch(c.name){case"Exit":s=!1;break;case"PredictState":d=c.value;break}return[{type:C.enum.MetaEvent,name:c.name,value:c.value}]}case D.STATE_SNAPSHOT:return T(v.snapshot),[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}];case D.STATE_DELTA:{let b=re(t,v.delta,!0,!1);return b?(T(b.newDocument),[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}]):[]}case D.MESSAGES_SNAPSHOT:return i=v.messages,[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(N(N({},t),i?{messages:i}:{})),active:!0}];case D.RUN_STARTED:return[];case D.RUN_FINISHED:return i&&(t.messages=i),Object.keys(t).length===0?[]:[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(N(N({},t),i?{messages:ge(i)}:{})),active:!1}];case D.RUN_ERROR:{let c=v;return[{type:C.enum.RunError,message:c.message,code:c.code}]}case D.STEP_STARTED:return o=v.stepName,x=[],d=null,[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!0}];case D.STEP_FINISHED:return x=[],d=null,[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!1}];default:return[]}}))};function ge(g){var e;let a=[];for(let n of g)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let t=le(n.content);if(t){let s={id:n.id,role:n.role,content:t};a.push(s)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let s of n.toolCalls){let r={id:s.id,name:s.function.name,arguments:JSON.parse(s.function.arguments),parentMessageId:n.id};a.push(r)}}else if(n.role==="tool"){let t="unknown";for(let r of g)if(r.role==="assistant"&&((e=r.toolCalls)!=null&&e.length)){for(let o of r.toolCalls)if(o.id===n.toolCallId){t=o.function.name;break}}let s={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:t};a.push(s)}return a}import{v4 as V}from"uuid";import{compareVersions as Te}from"compare-versions";import{catchError as ft,map as Tt,tap as Se}from"rxjs/operators";import{finalize as St}from"rxjs/operators";import{takeUntil as vt}from"rxjs/operators";import{pipe as At,from as ve,of as ht,EMPTY as Ae,Subject as yt}from"rxjs";import{lastValueFrom as Mt}from"rxjs";import{mergeMap as ce,finalize as ue}from"rxjs";import{EventType as M}from"@ag-ui/core";var j=g=>a=>{let e,n,t,s=()=>{if(!e||t!=="text")throw new Error("No text message to close");let i={type:M.TEXT_MESSAGE_END,messageId:e.messageId};return t=void 0,e=void 0,g&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(i)),i},r=()=>{if(!n||t!=="tool")throw new Error("No tool call to close");let i={type:M.TOOL_CALL_END,toolCallId:n.toolCallId};return t=void 0,n=void 0,g&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(i)),i},o=()=>t==="text"?[s()]:t==="tool"?[r()]:[];return a.pipe(ce(i=>{switch(i.type){case M.TEXT_MESSAGE_START:case M.TEXT_MESSAGE_CONTENT:case M.TEXT_MESSAGE_END:case M.TOOL_CALL_START:case M.TOOL_CALL_ARGS:case M.TOOL_CALL_END:case M.TOOL_CALL_RESULT:case M.STATE_SNAPSHOT:case M.STATE_DELTA:case M.MESSAGES_SNAPSHOT:case M.CUSTOM:case M.RUN_STARTED:case M.RUN_FINISHED:case M.RUN_ERROR:case M.STEP_STARTED:case M.STEP_FINISHED:case M.THINKING_START:case M.THINKING_END:case M.THINKING_TEXT_MESSAGE_START:case M.THINKING_TEXT_MESSAGE_CONTENT:case M.THINKING_TEXT_MESSAGE_END:return[...o(),i];case M.RAW:case M.ACTIVITY_SNAPSHOT:case M.ACTIVITY_DELTA:return[i];case M.TEXT_MESSAGE_CHUNK:let x=i,S=[];if((t!=="text"||x.messageId!==void 0&&x.messageId!==(e==null?void 0:e.messageId))&&S.push(...o()),t!=="text"){if(x.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:x.messageId},t="text";let c={type:M.TEXT_MESSAGE_START,messageId:x.messageId,role:x.role||"assistant"};S.push(c),g&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(c))}if(x.delta!==void 0){let c={type:M.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:x.delta};S.push(c),g&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(c))}return S;case M.TOOL_CALL_CHUNK:let T=i,v=[];if((t!=="tool"||T.toolCallId!==void 0&&T.toolCallId!==(n==null?void 0:n.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");n={toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId},t="tool";let c={type:M.TOOL_CALL_START,toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId};v.push(c),g&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(c))}if(T.delta!==void 0){let c={type:M.TOOL_CALL_ARGS,toolCallId:n.toolCallId,delta:T.delta};v.push(c),g&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(c))}return v}let d=i.type;return[]}),ue(()=>{o()}))};import{AGUIConnectNotImplementedError as Ct}from"@ag-ui/core";import{ReplaySubject as Ee}from"rxjs";import{concatMap as de}from"rxjs/operators";var k=class{runNext(a,e){return e.run(a).pipe(j(!1))}runNextWithState(a,e){let n=y(a.messages||[]),t=y(a.state||{}),s=new Ee;return $(a,s,e,[]).subscribe(o=>{o.messages!==void 0&&(n=o.messages),o.state!==void 0&&(t=o.state)}),this.runNext(a,e).pipe(de(async o=>(s.next(o),await new Promise(i=>setTimeout(i,0)),{event:o,messages:y(n),state:y(t)})))}},K=class extends k{constructor(e){super();this.fn=e}run(e,n){return this.fn(e,n)}};import{EventType as q}from"@ag-ui/core";import{filter as pe}from"rxjs/operators";var Q=class extends k{constructor(e){super();this.blockedToolCallIds=new Set;if(e.allowedToolCalls&&e.disallowedToolCalls)throw new Error("Cannot specify both allowedToolCalls and disallowedToolCalls");if(!e.allowedToolCalls&&!e.disallowedToolCalls)throw new Error("Must specify either allowedToolCalls or disallowedToolCalls");e.allowedToolCalls?this.allowedTools=new Set(e.allowedToolCalls):e.disallowedToolCalls&&(this.disallowedTools=new Set(e.disallowedToolCalls))}run(e,n){return this.runNext(e,n).pipe(pe(t=>{if(t.type===q.TOOL_CALL_START){let s=t;return this.shouldFilterTool(s.toolCallName)?(this.blockedToolCallIds.add(s.toolCallId),!1):!0}if(t.type===q.TOOL_CALL_ARGS){let s=t;return!this.blockedToolCallIds.has(s.toolCallId)}if(t.type===q.TOOL_CALL_END){let s=t;return!this.blockedToolCallIds.has(s.toolCallId)}if(t.type===q.TOOL_CALL_RESULT){let s=t;return this.blockedToolCallIds.has(s.toolCallId)?(this.blockedToolCallIds.delete(s.toolCallId),!1):!0}return!0}))}shouldFilterTool(e){return this.allowedTools?!this.allowedTools.has(e):this.disallowedTools?this.disallowedTools.has(e):!1}};function me(g){let a=g.content;if(Array.isArray(a)){let e=a.filter(n=>typeof n=="object"&&n!==null&&"type"in n&&n.type==="text"&&typeof n.text=="string").map(n=>n.text).join("");return G(N({},g),{content:e})}return typeof a=="string"?g:G(N({},g),{content:""})}var J=class extends k{run(a,e){let r=a,{parentRunId:n}=r,t=gt(r,["parentRunId"]),s=G(N({},t),{messages:t.messages.map(me)});return this.runNext(s,e)}};var mt={name:"@ag-ui/client",author:"Markus Ecker <markus.ecker@gmail.com>",version:"0.0.44",private:!1,publishConfig:{access:"public"},main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",sideEffects:!1,files:["dist/**","README.md"],scripts:{build:"tsup",dev:"tsup --watch",clean:"rm -rf dist .turbo node_modules",typecheck:"tsc --noEmit",test:"jest","link:global":"pnpm link --global","unlink:global":"pnpm unlink --global"},dependencies:{"@ag-ui/core":"workspace:*","@ag-ui/encoder":"workspace:*","@ag-ui/proto":"workspace:*","@types/uuid":"^10.0.0","compare-versions":"^6.1.1","fast-json-patch":"^3.1.1",rxjs:"7.8.1","untruncate-json":"^0.0.1",uuid:"^11.1.0",zod:"^3.22.4"},devDependencies:{"@types/jest":"^29.5.14","@types/node":"^20.11.19",jest:"^29.7.0","ts-jest":"^29.1.2",tsup:"^8.0.2",typescript:"^5.3.3"}};var W=class{constructor({agentId:a,description:e,threadId:n,initialMessages:t,initialState:s,debug:r}={}){this.debug=!1;this.subscribers=[];this.isRunning=!1;this.middlewares=[];this.agentId=a,this.description=e!=null?e:"",this.threadId=n!=null?n:V(),this.messages=y(t!=null?t:[]),this.state=y(s!=null?s:{}),this.debug=r!=null?r:!1,Te(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new J)}get maxVersion(){return mt.version}subscribe(a){return this.subscribers.push(a),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==a)}}}use(...a){let e=a.map(n=>typeof n=="function"?new K(n):n);return this.middlewares.push(...e),this}async runAgent(a,e){var n;try{this.isRunning=!0,this.agentId=(n=this.agentId)!=null?n:V();let t=this.prepareRunAgentInput(a),s,r=new Set(this.messages.map(S=>S.id)),o=[{onRunFinishedEvent:S=>{s=S.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o),this.activeRunDetach$=new yt;let i;this.activeRunCompletionPromise=new Promise(S=>{i=S});let d=At(()=>this.middlewares.length===0?this.run(t):this.middlewares.reduceRight((T,v)=>({run:c=>v.run(c,T)}),this).run(t),j(this.debug),z(this.debug),S=>S.pipe(vt(this.activeRunDetach$)),S=>this.apply(t,S,o),S=>this.processApplyEvents(t,S,o),ft(S=>(this.isRunning=!1,this.onError(t,S,o))),St(()=>{this.isRunning=!1,this.onFinalize(t,o),i==null||i(),i=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}));await Mt(d(ht(null)));let x=y(this.messages).filter(S=>!r.has(S.id));return{result:s,newMessages:x}}finally{this.isRunning=!1}}connect(a){throw new Ct}async connectAgent(a,e){var n;try{this.isRunning=!0,this.agentId=(n=this.agentId)!=null?n:V();let t=this.prepareRunAgentInput(a),s,r=new Set(this.messages.map(S=>S.id)),o=[{onRunFinishedEvent:S=>{s=S.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o),this.activeRunDetach$=new yt;let i;this.activeRunCompletionPromise=new Promise(S=>{i=S});let d=At(()=>this.connect(t),j(this.debug),z(this.debug),S=>S.pipe(vt(this.activeRunDetach$)),S=>this.apply(t,S,o),S=>this.processApplyEvents(t,S,o),ft(S=>(this.isRunning=!1,S instanceof Ct?Ae:this.onError(t,S,o))),St(()=>{this.isRunning=!1,this.onFinalize(t,o),i==null||i(),i=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}));await Mt(d(ht(null)));let x=y(this.messages).filter(S=>!r.has(S.id));return{result:s,newMessages:x}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){var e,n;if(!this.activeRunDetach$)return;let a=(e=this.activeRunCompletionPromise)!=null?e:Promise.resolve();this.activeRunDetach$.next(),(n=this.activeRunDetach$)==null||n.complete(),await a}apply(a,e,n){return $(a,e,this,n)}processApplyEvents(a,e,n){return e.pipe(Se(t=>{t.messages&&(this.messages=t.messages,n.forEach(s=>{var r;(r=s.onMessagesChanged)==null||r.call(s,{messages:this.messages,state:this.state,agent:this,input:a})})),t.state&&(this.state=t.state,n.forEach(s=>{var r;(r=s.onStateChanged)==null||r.call(s,{state:this.state,messages:this.messages,agent:this,input:a})}))}))}prepareRunAgentInput(a){var t,s,r;let n=y(this.messages).filter(o=>o.role!=="activity");return{threadId:this.threadId,runId:(a==null?void 0:a.runId)||V(),tools:y((t=a==null?void 0:a.tools)!=null?t:[]),context:y((s=a==null?void 0:a.context)!=null?s:[]),forwardedProps:y((r=a==null?void 0:a.forwardedProps)!=null?r:{}),state:y(this.state),messages:n}}async onInitialize(a,e){let n=await I(e,this.messages,this.state,(t,s,r)=>{var o;return(o=t.onRunInitialized)==null?void 0:o.call(t,{messages:s,state:r,agent:this,input:a})});(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,a.messages=n.messages,e.forEach(t=>{var s;(s=t.onMessagesChanged)==null||s.call(t,{messages:this.messages,state:this.state,agent:this,input:a})})),n.state&&(this.state=n.state,a.state=n.state,e.forEach(t=>{var s;(s=t.onStateChanged)==null||s.call(t,{state:this.state,messages:this.messages,agent:this,input:a})})))}onError(a,e,n){return ve(I(n,this.messages,this.state,(t,s,r)=>{var o;return(o=t.onRunFailed)==null?void 0:o.call(t,{error:e,messages:s,state:r,agent:this,input:a})})).pipe(Tt(t=>{let s=t;if((s.messages!==void 0||s.state!==void 0)&&(s.messages!==void 0&&(this.messages=s.messages,n.forEach(r=>{var o;(o=r.onMessagesChanged)==null||o.call(r,{messages:this.messages,state:this.state,agent:this,input:a})})),s.state!==void 0&&(this.state=s.state,n.forEach(r=>{var o;(o=r.onStateChanged)==null||o.call(r,{state:this.state,messages:this.messages,agent:this,input:a})}))),s.stopPropagation!==!0)throw console.error("Agent execution failed:",e),e;return{}}))}async onFinalize(a,e){let n=await I(e,this.messages,this.state,(t,s,r)=>{var o;return(o=t.onRunFinalized)==null?void 0:o.call(t,{messages:s,state:r,agent:this,input:a})});(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(t=>{var s;(s=t.onMessagesChanged)==null||s.call(t,{messages:this.messages,state:this.state,agent:this,input:a})})),n.state!==void 0&&(this.state=n.state,e.forEach(t=>{var s;(s=t.onStateChanged)==null||s.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=y(this.messages),a.state=y(this.state),a.debug=this.debug,a.isRunning=this.isRunning,a.subscribers=[...this.subscribers],a.middlewares=[...this.middlewares],a}addMessage(a){this.messages.push(a),(async()=>{var e,n,t;for(let s of this.subscribers)await((e=s.onNewMessage)==null?void 0:e.call(s,{message:a,messages:this.messages,state:this.state,agent:this}));if(a.role==="assistant"&&a.toolCalls)for(let s of a.toolCalls)for(let r of this.subscribers)await((n=r.onNewToolCall)==null?void 0:n.call(r,{toolCall:s,messages:this.messages,state:this.state,agent:this}));for(let s of this.subscribers)await((t=s.onMessagesChanged)==null?void 0:t.call(s,{messages:this.messages,state:this.state,agent:this}))})()}addMessages(a){this.messages.push(...a),(async()=>{var e,n,t;for(let s of a){for(let r of this.subscribers)await((e=r.onNewMessage)==null?void 0:e.call(r,{message:s,messages:this.messages,state:this.state,agent:this}));if(s.role==="assistant"&&s.toolCalls)for(let r of s.toolCalls)for(let o of this.subscribers)await((n=o.onNewToolCall)==null?void 0:n.call(o,{toolCall:r,messages:this.messages,state:this.state,agent:this}))}for(let s of this.subscribers)await((t=s.onMessagesChanged)==null?void 0:t.call(s,{messages:this.messages,state:this.state,agent:this}))})()}setMessages(a){this.messages=y(a),(async()=>{var e;for(let n of this.subscribers)await((e=n.onMessagesChanged)==null?void 0:e.call(n,{messages:this.messages,state:this.state,agent:this}))})()}setState(a){this.state=y(a),(async()=>{var e;for(let n of this.subscribers)await((e=n.onStateChanged)==null?void 0:e.call(n,{messages:this.messages,state:this.state,agent:this}))})()}legacy_to_be_removed_runAgentBridged(a){var t;this.agentId=(t=this.agentId)!=null?t:V();let e=this.prepareRunAgentInput(a);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((r,o)=>({run:i=>o.run(i,r)}),this).run(e)).pipe(j(this.debug),z(this.debug),at(this.threadId,e.runId,this.agentId),s=>s.pipe(Tt(r=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(r)),r))))}};var ot=class extends W{constructor(e){var n;super(e);this.abortController=new AbortController;this.url=e.url,this.headers=y((n=e.headers)!=null?n:{})}requestInit(e){return{method:"POST",headers:G(N({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e,n){var t;return this.abortController=(t=e==null?void 0:e.abortController)!=null?t:new AbortController,super.runAgent(e,n)}abortRun(){this.abortController.abort(),super.abortRun()}run(e){let n=tt(this.url,this.requestInit(e));return st(n)}clone(){var s;let e=super.clone();e.url=this.url,e.headers=y((s=this.headers)!=null?s:{});let n=new AbortController,t=this.abortController.signal;return t.aborted&&n.abort(t.reason),e.abortController=n,e}};import{EventType as B}from"@ag-ui/core";function he(g){let a=[],e=new Map,n=new Map;for(let t of g)if(t.type===B.TEXT_MESSAGE_START){let s=t,r=s.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]});let o=e.get(r);o.start=s}else if(t.type===B.TEXT_MESSAGE_CONTENT){let s=t,r=s.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]}),e.get(r).contents.push(s)}else if(t.type===B.TEXT_MESSAGE_END){let s=t,r=s.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]});let o=e.get(r);o.end=s,Rt(r,o,a),e.delete(r)}else if(t.type===B.TOOL_CALL_START){let s=t,r=s.toolCallId;n.has(r)||n.set(r,{args:[],otherEvents:[]});let o=n.get(r);o.start=s}else if(t.type===B.TOOL_CALL_ARGS){let s=t,r=s.toolCallId;n.has(r)||n.set(r,{args:[],otherEvents:[]}),n.get(r).args.push(s)}else if(t.type===B.TOOL_CALL_END){let s=t,r=s.toolCallId;n.has(r)||n.set(r,{args:[],otherEvents:[]});let o=n.get(r);o.end=s,xt(r,o,a),n.delete(r)}else{let s=!1;for(let[r,o]of e)if(o.start&&!o.end){o.otherEvents.push(t),s=!0;break}if(!s){for(let[r,o]of n)if(o.start&&!o.end){o.otherEvents.push(t),s=!0;break}}s||a.push(t)}for(let[t,s]of e)Rt(t,s,a);for(let[t,s]of n)xt(t,s,a);return a}function Rt(g,a,e){if(a.start&&e.push(a.start),a.contents.length>0){let n=a.contents.map(s=>s.delta).join(""),t={type:B.TEXT_MESSAGE_CONTENT,messageId:g,delta:n};e.push(t)}a.end&&e.push(a.end);for(let n of a.otherEvents)e.push(n)}function xt(g,a,e){if(a.start&&e.push(a.start),a.args.length>0){let n=a.args.map(s=>s.delta).join(""),t={type:B.TOOL_CALL_ARGS,toolCallId:g,delta:n};e.push(t)}a.end&&e.push(a.end);for(let n of a.otherEvents)e.push(n)}export*from"@ag-ui/core";export{W as AbstractAgent,J as BackwardCompatibility_0_0_39,Q as FilterToolCallsMiddleware,K as FunctionMiddleware,ot as HttpAgent,k as Middleware,he as compactEvents,at as convertToLegacyEvents,$ as defaultApplyEvents,nt as parseProtoStream,et as parseSSEStream,Re as randomUUID,tt as runHttpRequest,y as structuredClone_,j as transformChunks,st as transformHttpEventStream,z as verifyEvents};
1
+ import{v4 as e}from"uuid";import{AGUIConnectNotImplementedError as t,AGUIError as n,EventSchemas as r,EventType as i}from"@ag-ui/core";import*as a from"fast-json-patch";import{EMPTY as o,Observable as s,ReplaySubject as c,Subject as l,defer as u,finalize as d,from as f,lastValueFrom as p,mergeMap as m,of as h,pipe as g,throwError as _}from"rxjs";import{catchError as v,concatMap as y,defaultIfEmpty as ee,filter as te,finalize as b,map as x,mergeAll as ne,mergeMap as S,switchMap as re,takeUntil as C,tap as ie}from"rxjs/operators";import w from"untruncate-json";import*as T from"@ag-ui/proto";import{z as E}from"zod";import{compareVersions as D}from"compare-versions";export*from"@ag-ui/core";const O=e=>{if(typeof structuredClone==`function`)return structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch{return{...e}}};function k(){return e()}async function A(e,t,n,r){let i=t,a=n,o;for(let t of e)try{let e=await r(t,O(i),O(a));if(e===void 0)continue;if(e.messages!==void 0&&(i=e.messages),e.state!==void 0&&(a=e.state),o=e.stopPropagation,o===!0)break}catch(e){process.env.NODE_ENV===`test`||process.env.VITEST_WORKER_ID!==void 0||console.error(`Subscriber error:`,e);continue}return{...JSON.stringify(i)===JSON.stringify(t)?{}:{messages:i},...JSON.stringify(a)===JSON.stringify(n)?{}:{state:a},...o===void 0?{}:{stopPropagation:o}}}const j=(e,t,n,r)=>{let s=O(n.messages),c=O(e.state),l={},u=e=>{e.messages!==void 0&&(s=e.messages,l.messages=e.messages),e.state!==void 0&&(c=e.state,l.state=e.state)},d=()=>{let e=O(l);return l={},e.messages!==void 0||e.state!==void 0?h(e):o};return t.pipe(y(async t=>{let o=await A(r,s,c,(r,i,a)=>r.onEvent?.({event:t,agent:n,input:e,messages:i,state:a}));if(u(o),o.stopPropagation===!0)return d();switch(t.type){case i.TEXT_MESSAGE_START:{let i=await A(r,s,c,(r,i,a)=>r.onTextMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{messageId:e,role:n=`assistant`}=t;if(!s.find(t=>t.id===e)){let t={id:e,role:n,content:``};s.push(t),u({messages:s})}}return d()}case i.TEXT_MESSAGE_CONTENT:{let{messageId:i,delta:a}=t,o=s.find(e=>e.id===i);if(!o)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${i}'`),d();let l=await A(r,s,c,(r,i,a)=>r.onTextMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,textMessageBuffer:typeof o.content==`string`?o.content:``}));return u(l),l.stopPropagation!==!0&&(o.content=`${typeof o.content==`string`?o.content:``}${a}`,u({messages:s})),d()}case i.TEXT_MESSAGE_END:{let{messageId:i}=t,a=s.find(e=>e.id===i);return a?(u(await A(r,s,c,(r,i,o)=>r.onTextMessageEndEvent?.({event:t,messages:i,state:o,agent:n,input:e,textMessageBuffer:typeof a.content==`string`?a.content:``}))),await Promise.all(r.map(t=>{t.onNewMessage?.({message:a,messages:s,state:c,agent:n,input:e})})),d()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${i}'`),d())}case i.TOOL_CALL_START:{let i=await A(r,s,c,(r,i,a)=>r.onToolCallStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{toolCallId:e,toolCallName:n,parentMessageId:r}=t,i;r&&s.length>0&&s[s.length-1].id===r?i=s[s.length-1]:(i={id:r||e,role:`assistant`,toolCalls:[]},s.push(i)),i.toolCalls??=[],i.toolCalls.push({id:e,type:`function`,function:{name:n,arguments:``}}),u({messages:s})}return d()}case i.TOOL_CALL_ARGS:{let{toolCallId:i,delta:a}=t,o=s.find(e=>e.toolCalls?.some(e=>e.id===i));if(!o)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${i}'`),d();let l=o.toolCalls?.find(e=>e.id===i);if(!l)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${i}'`),d();let f=await A(r,s,c,(r,i,a)=>{let o=l.function.arguments,s=l.function.name,c={};try{c=w(o)}catch{}return r.onToolCallArgsEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallBuffer:o,toolCallName:s,partialToolCallArgs:c})});return u(f),f.stopPropagation!==!0&&(l.function.arguments+=a,u({messages:s})),d()}case i.TOOL_CALL_END:{let{toolCallId:i}=t,a=s.find(e=>e.toolCalls?.some(e=>e.id===i));if(!a)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${i}'`),d();let o=a.toolCalls?.find(e=>e.id===i);return o?(u(await A(r,s,c,(r,i,a)=>{let s=o.function.arguments,c=o.function.name,l={};try{l=JSON.parse(s)}catch{}return r.onToolCallEndEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallName:c,toolCallArgs:l})})),await Promise.all(r.map(t=>{t.onNewToolCall?.({toolCall:o,messages:s,state:c,agent:n,input:e})})),d()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${i}'`),d())}case i.TOOL_CALL_RESULT:{let i=await A(r,s,c,(r,i,a)=>r.onToolCallResultEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{messageId:i,toolCallId:a,content:o,role:l}=t,d={id:i,toolCallId:a,role:l||`tool`,content:o};s.push(d),await Promise.all(r.map(t=>{t.onNewMessage?.({message:d,messages:s,state:c,agent:n,input:e})})),u({messages:s})}return d()}case i.STATE_SNAPSHOT:{let i=await A(r,s,c,(r,i,a)=>r.onStateSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{snapshot:e}=t;c=e,u({state:c})}return d()}case i.STATE_DELTA:{let i=await A(r,s,c,(r,i,a)=>r.onStateDeltaEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{delta:e}=t;try{c=a.applyPatch(c,e,!0,!1).newDocument,u({state:c})}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Failed to apply state patch:\nCurrent state: ${JSON.stringify(c,null,2)}\nPatch operations: ${JSON.stringify(e,null,2)}\nError: ${n}`)}}return d()}case i.MESSAGES_SNAPSHOT:{let i=await A(r,s,c,(r,i,a)=>r.onMessagesSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{messages:e}=t;s=e,u({messages:s})}return d()}case i.ACTIVITY_SNAPSHOT:{let i=t,a=s.findIndex(e=>e.id===i.messageId),o=a>=0?s[a]:void 0,l=o?.role===`activity`?o:void 0,f=i.replace??!0,p=await A(r,s,c,(t,r,a)=>t.onActivitySnapshotEvent?.({event:i,messages:r,state:a,agent:n,input:e,activityMessage:l,existingMessage:o}));if(u(p),p.stopPropagation!==!0){let t={id:i.messageId,role:`activity`,activityType:i.activityType,content:O(i.content)},o;a===-1?(s.push(t),o=t):l?f&&(s[a]={...l,activityType:i.activityType,content:O(i.content)}):f&&(s[a]=t,o=t),u({messages:s}),o&&await Promise.all(r.map(t=>t.onNewMessage?.({message:o,messages:s,state:c,agent:n,input:e})))}return d()}case i.ACTIVITY_DELTA:{let i=t,o=s.findIndex(e=>e.id===i.messageId);if(o===-1)return console.warn(`ACTIVITY_DELTA: No message found with ID '${i.messageId}' to apply patch`),d();let l=s[o];if(l.role!==`activity`)return console.warn(`ACTIVITY_DELTA: Message '${i.messageId}' is not an activity message`),d();let f=l,p=await A(r,s,c,(t,r,a)=>t.onActivityDeltaEvent?.({event:i,messages:r,state:a,agent:n,input:e,activityMessage:f}));if(u(p),p.stopPropagation!==!0)try{let e=O(f.content??{}),t=a.applyPatch(e,i.patch??[],!0,!1).newDocument;s[o]={...f,content:O(t),activityType:i.activityType},u({messages:s})}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`Failed to apply activity patch for '${i.messageId}': ${t}`)}return d()}case i.RAW:return u(await A(r,s,c,(r,i,a)=>r.onRawEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.CUSTOM:return u(await A(r,s,c,(r,i,a)=>r.onCustomEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.RUN_STARTED:{let i=await A(r,s,c,(r,i,a)=>r.onRunStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let e=t;if(e.input?.messages){for(let t of e.input.messages)s.find(e=>e.id===t.id)||s.push(t);u({messages:s})}}return d()}case i.RUN_FINISHED:return u(await A(r,s,c,(r,i,a)=>r.onRunFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e,result:t.result}))),d();case i.RUN_ERROR:return u(await A(r,s,c,(r,i,a)=>r.onRunErrorEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.STEP_STARTED:return u(await A(r,s,c,(r,i,a)=>r.onStepStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.STEP_FINISHED:return u(await A(r,s,c,(r,i,a)=>r.onStepFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.TEXT_MESSAGE_CHUNK:throw Error(`TEXT_MESSAGE_CHUNK must be tranformed before being applied`);case i.TOOL_CALL_CHUNK:throw Error(`TOOL_CALL_CHUNK must be tranformed before being applied`);case i.THINKING_START:return d();case i.THINKING_END:return d();case i.THINKING_TEXT_MESSAGE_START:return d();case i.THINKING_TEXT_MESSAGE_CONTENT:return d();case i.THINKING_TEXT_MESSAGE_END:return d();case i.REASONING_START:return u(await A(r,s,c,(r,i,a)=>r.onReasoningStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.REASONING_MESSAGE_START:{let i=await A(r,s,c,(r,i,a)=>r.onReasoningMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{messageId:e}=t;if(!s.find(t=>t.id===e)){let t={id:e,role:`reasoning`,content:``};s.push(t),u({messages:s})}}return d()}case i.REASONING_MESSAGE_CONTENT:{let{messageId:i,delta:a}=t,o=s.find(e=>e.id===i);if(!o)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${i}'`),d();let l=await A(r,s,c,(r,i,a)=>r.onReasoningMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,reasoningMessageBuffer:typeof o.content==`string`?o.content:``}));return u(l),l.stopPropagation!==!0&&(o.content=`${typeof o.content==`string`?o.content:``}${a}`,u({messages:s})),d()}case i.REASONING_MESSAGE_END:{let{messageId:i}=t,a=s.find(e=>e.id===i);return a?(u(await A(r,s,c,(r,i,o)=>r.onReasoningMessageEndEvent?.({event:t,messages:i,state:o,agent:n,input:e,reasoningMessageBuffer:typeof a.content==`string`?a.content:``}))),await Promise.all(r.map(t=>{t.onNewMessage?.({message:a,messages:s,state:c,agent:n,input:e})})),d()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${i}'`),d())}case i.REASONING_MESSAGE_CHUNK:throw Error(`REASONING_MESSAGE_CHUNK must be transformed before being applied`);case i.REASONING_END:return u(await A(r,s,c,(r,i,a)=>r.onReasoningEndEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.REASONING_ENCRYPTED_VALUE:{let{subtype:i,entityId:a,encryptedValue:o}=t,f=await A(r,s,c,(r,i,a)=>r.onReasoningEncryptedValueEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(f),f.stopPropagation!==!0){let e=!1;if(i===`tool-call`){for(let t of s)if(t.role===`assistant`&&t.toolCalls){let n=t.toolCalls.find(e=>e.id===a);if(n){n.encryptedValue=o,e=!0;break}}}else{let t=s.find(e=>e.id===a);t?.role!==`activity`&&t&&(t.encryptedValue=o,e=!0)}e&&(l.messages=s)}return d()}}return t.type,d()}),ne(),r.length>0?ee({}):e=>e)},M=e=>t=>{let r=new Map,a=new Map,o=!1,s=!1,c=!1,l=new Map,u=!1,d=!1,f=!1,p=()=>{r.clear(),a.clear(),l.clear(),u=!1,d=!1,o=!1,s=!1,f=!0};return t.pipe(S(t=>{let m=t.type;if(e&&console.debug(`[VERIFY]:`,JSON.stringify(t)),s)return _(()=>new n(`Cannot send event type '${m}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(o&&m!==i.RUN_ERROR&&m!==i.RUN_STARTED)return _(()=>new n(`Cannot send event type '${m}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(!c){if(c=!0,m!==i.RUN_STARTED&&m!==i.RUN_ERROR)return _(()=>new n(`First event must be 'RUN_STARTED'`))}else if(m===i.RUN_STARTED){if(f&&!o)return _(()=>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.`));o&&p()}switch(m){case i.TEXT_MESSAGE_START:{let e=t.messageId;return r.has(e)?_(()=>new n(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${e}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(r.set(e,!0),h(t))}case i.TEXT_MESSAGE_CONTENT:{let e=t.messageId;return r.has(e)?h(t):_(()=>new n(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${e}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case i.TEXT_MESSAGE_END:{let e=t.messageId;return r.has(e)?(r.delete(e),h(t)):_(()=>new n(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${e}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case i.TOOL_CALL_START:{let e=t.toolCallId;return a.has(e)?_(()=>new n(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${e}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(a.set(e,!0),h(t))}case i.TOOL_CALL_ARGS:{let e=t.toolCallId;return a.has(e)?h(t):_(()=>new n(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${e}'. Start a tool call with 'TOOL_CALL_START' first.`))}case i.TOOL_CALL_END:{let e=t.toolCallId;return a.has(e)?(a.delete(e),h(t)):_(()=>new n(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${e}'. A 'TOOL_CALL_START' event must be sent first.`))}case i.STEP_STARTED:{let e=t.stepName;return l.has(e)?_(()=>new n(`Step "${e}" is already active for 'STEP_STARTED'`)):(l.set(e,!0),h(t))}case i.STEP_FINISHED:{let e=t.stepName;return l.has(e)?(l.delete(e),h(t)):_(()=>new n(`Cannot send 'STEP_FINISHED' for step "${e}" that was not started`))}case i.RUN_STARTED:return f=!0,h(t);case i.RUN_FINISHED:if(l.size>0){let e=Array.from(l.keys()).join(`, `);return _(()=>new n(`Cannot send 'RUN_FINISHED' while steps are still active: ${e}`))}if(r.size>0){let e=Array.from(r.keys()).join(`, `);return _(()=>new n(`Cannot send 'RUN_FINISHED' while text messages are still active: ${e}`))}if(a.size>0){let e=Array.from(a.keys()).join(`, `);return _(()=>new n(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${e}`))}return o=!0,h(t);case i.RUN_ERROR:return s=!0,h(t);case i.CUSTOM:return h(t);case i.THINKING_TEXT_MESSAGE_START:return u?d?_(()=>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,h(t)):_(()=>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?h(t):_(()=>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,h(t)):_(()=>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 u?_(()=>new n(`Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.`)):(u=!0,h(t));case i.THINKING_END:return u?(u=!1,h(t)):_(()=>new n(`Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first.`));default:return h(t)}}))};let N=function(e){return e.HEADERS=`headers`,e.DATA=`data`,e}({});const P=(e,t)=>u(()=>f(fetch(e,t))).pipe(re(e=>{if(!e.ok){let t=e.headers.get(`content-type`)||``;return f(e.text()).pipe(S(n=>{let r=n;if(t.includes(`application/json`))try{r=JSON.parse(n)}catch{}let i=Error(`HTTP ${e.status}: ${typeof r==`string`?r:JSON.stringify(r)}`);return i.status=e.status,i.payload=r,_(()=>i)}))}let t={type:N.HEADERS,status:e.status,headers:e.headers},n=e.body?.getReader();return n?new s(e=>(e.next(t),(async()=>{try{for(;;){let{done:t,value:r}=await n.read();if(t)break;let i={type:N.DATA,data:r};e.next(i)}e.complete()}catch(t){e.error(t)}})(),()=>{n.cancel().catch(e=>{if(e?.name!==`AbortError`)throw e})})):_(()=>Error(`Failed to getReader() from response`))})),F=e=>{let t=new l,n=new TextDecoder(`utf-8`,{fatal:!1}),r=``;e.subscribe({next:e=>{if(e.type!==N.HEADERS&&e.type===N.DATA&&e.data){let t=n.decode(e.data,{stream:!0});r+=t;let a=r.split(/\n\n/);r=a.pop()||``;for(let e of a)i(e)}},error:e=>t.error(e),complete:()=>{r&&(r+=n.decode(),i(r)),t.complete()}});function i(e){let n=e.split(`
2
+ `),r=[];for(let e of n)e.startsWith(`data:`)&&r.push(e.slice(5).replace(/^ /,``));if(r.length>0)try{let e=r.join(`
3
+ `),n=JSON.parse(e);t.next(n)}catch(e){t.error(e)}}return t.asObservable()},I=e=>{let t=new l,n=new Uint8Array;e.subscribe({next:e=>{if(e.type!==N.HEADERS&&e.type===N.DATA&&e.data){let t=new Uint8Array(n.length+e.data.length);t.set(n,0),t.set(e.data,n.length),n=t,r()}},error:e=>t.error(e),complete:()=>{if(n.length>0)try{r()}catch{console.warn(`Incomplete or invalid protocol buffer data at stream end`)}t.complete()}});function r(){for(;n.length>=4;){let e=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<e)break;try{let r=n.slice(4,e),i=T.decode(r);t.next(i),n=n.slice(e)}catch(e){let n=e instanceof Error?e.message:String(e);t.error(Error(`Failed to decode protocol buffer message: ${n}`));return}}}return t.asObservable()},L=e=>{let t=new l,n=new c,a=!1;return e.subscribe({next:e=>{n.next(e),e.type===N.HEADERS&&!a?(a=!0,e.headers.get(`content-type`)===T.AGUI_MEDIA_TYPE?I(n).subscribe({next:e=>t.next(e),error:e=>t.error(e),complete:()=>t.complete()}):F(n).subscribe({next:e=>{try{let n=r.parse(e);t.next(n)}catch(e){t.error(e)}},error:e=>{if(e?.name===`AbortError`){t.next({type:i.RUN_ERROR,message:e.message||`Request aborted`,code:`abort`,rawEvent:e}),t.complete();return}return t.error(e)},complete:()=>t.complete()})):a||t.error(Error(`No headers event received before data events`))},error:e=>{n.error(e),t.error(e)},complete:()=>{n.complete()}}),t.asObservable()},R=E.enum([`TextMessageStart`,`TextMessageContent`,`TextMessageEnd`,`ActionExecutionStart`,`ActionExecutionArgs`,`ActionExecutionEnd`,`ActionExecutionResult`,`AgentStateMessage`,`MetaEvent`,`RunStarted`,`RunFinished`,`RunError`,`NodeStarted`,`NodeFinished`]),ae=E.enum([`LangGraphInterruptEvent`,`PredictState`,`Exit`]),oe=E.object({type:E.literal(R.enum.TextMessageStart),messageId:E.string(),parentMessageId:E.string().optional(),role:E.string().optional()}),se=E.object({type:E.literal(R.enum.TextMessageContent),messageId:E.string(),content:E.string()}),ce=E.object({type:E.literal(R.enum.TextMessageEnd),messageId:E.string()}),le=E.object({type:E.literal(R.enum.ActionExecutionStart),actionExecutionId:E.string(),actionName:E.string(),parentMessageId:E.string().optional()}),ue=E.object({type:E.literal(R.enum.ActionExecutionArgs),actionExecutionId:E.string(),args:E.string()}),z=E.object({type:E.literal(R.enum.ActionExecutionEnd),actionExecutionId:E.string()}),de=E.object({type:E.literal(R.enum.ActionExecutionResult),actionName:E.string(),actionExecutionId:E.string(),result:E.string()}),fe=E.object({type:E.literal(R.enum.AgentStateMessage),threadId:E.string(),agentName:E.string(),nodeName:E.string(),runId:E.string(),active:E.boolean(),role:E.string(),state:E.string(),running:E.boolean()}),pe=E.object({type:E.literal(R.enum.MetaEvent),name:ae,value:E.any()}),me=E.object({type:E.literal(R.enum.RunError),message:E.string(),code:E.string().optional()});E.discriminatedUnion(`type`,[oe,se,ce,le,ue,z,de,fe,pe,me]),E.object({id:E.string(),role:E.string(),content:E.string(),parentMessageId:E.string().optional()}),E.object({id:E.string(),name:E.string(),arguments:E.any(),parentMessageId:E.string().optional()}),E.object({id:E.string(),result:E.any(),actionExecutionId:E.string(),actionName:E.string()});const he=e=>{if(typeof e==`string`)return e;if(!Array.isArray(e))return;let t=e.filter(e=>e.type===`text`).map(e=>e.text).filter(e=>e.length>0);if(t.length!==0)return t.join(`
4
+ `)},B=(e,t,n)=>r=>{let o={},s=!0,c=!0,l=``,u=null,d=null,f=[],p={},m=e=>{typeof e==`object`&&e&&(`messages`in e&&delete e.messages,o=e)};return r.pipe(S(r=>{switch(r.type){case i.TEXT_MESSAGE_START:{let e=r;return[{type:R.enum.TextMessageStart,messageId:e.messageId,role:e.role}]}case i.TEXT_MESSAGE_CONTENT:{let e=r;return[{type:R.enum.TextMessageContent,messageId:e.messageId,content:e.delta}]}case i.TEXT_MESSAGE_END:{let e=r;return[{type:R.enum.TextMessageEnd,messageId:e.messageId}]}case i.TOOL_CALL_START:{let e=r;return f.push({id:e.toolCallId,type:`function`,function:{name:e.toolCallName,arguments:``}}),c=!0,p[e.toolCallId]=e.toolCallName,[{type:R.enum.ActionExecutionStart,actionExecutionId:e.toolCallId,actionName:e.toolCallName,parentMessageId:e.parentMessageId}]}case i.TOOL_CALL_ARGS:{let i=r,a=f.find(e=>e.id===i.toolCallId);if(!a)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${i.toolCallId}'`),[];a.function.arguments+=i.delta;let u=!1;if(d){let e=d.find(e=>e.tool==a.function.name);if(e)try{let t=JSON.parse(w(a.function.arguments));e.tool_argument&&e.tool_argument in t?(m({...o,[e.state_key]:t[e.tool_argument]}),u=!0):e.tool_argument||(m({...o,[e.state_key]:t}),u=!0)}catch{}}return[{type:R.enum.ActionExecutionArgs,actionExecutionId:i.toolCallId,args:i.delta},...u?[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:c}]:[]]}case i.TOOL_CALL_END:{let e=r;return[{type:R.enum.ActionExecutionEnd,actionExecutionId:e.toolCallId}]}case i.TOOL_CALL_RESULT:{let e=r;return[{type:R.enum.ActionExecutionResult,actionExecutionId:e.toolCallId,result:e.content,actionName:p[e.toolCallId]||`unknown`}]}case i.RAW:return[];case i.CUSTOM:{let e=r;switch(e.name){case`Exit`:s=!1;break;case`PredictState`:d=e.value;break}return[{type:R.enum.MetaEvent,name:e.name,value:e.value}]}case i.STATE_SNAPSHOT:return m(r.snapshot),[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:c}];case i.STATE_DELTA:{let i=r,u=a.applyPatch(o,i.delta,!0,!1);return u?(m(u.newDocument),[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:c}]):[]}case i.MESSAGES_SNAPSHOT:return u=r.messages,[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify({...o,...u?{messages:u}:{}}),active:!0}];case i.RUN_STARTED:return[];case i.RUN_FINISHED:return u&&(o.messages=u),Object.keys(o).length===0?[]:[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify({...o,...u?{messages:ge(u)}:{}}),active:!1}];case i.RUN_ERROR:{let e=r;return[{type:R.enum.RunError,message:e.message,code:e.code}]}case i.STEP_STARTED:return l=r.stepName,f=[],d=null,[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:!0}];case i.STEP_FINISHED:return f=[],d=null,[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:!1}];default:return[]}}))};function ge(e){let t=[];for(let n of e)if(n.role===`assistant`||n.role===`user`||n.role===`system`){let e=he(n.content);if(e){let r={id:n.id,role:n.role,content:e};t.push(r)}if(n.role===`assistant`&&n.toolCalls&&n.toolCalls.length>0)for(let e of n.toolCalls){let r={id:e.id,name:e.function.name,arguments:JSON.parse(e.function.arguments),parentMessageId:n.id};t.push(r)}}else if(n.role===`tool`){let r=`unknown`;for(let t of e)if(t.role===`assistant`&&t.toolCalls?.length){for(let e of t.toolCalls)if(e.id===n.toolCallId){r=e.function.name;break}}let i={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};t.push(i)}return t}const V=e=>t=>{let n,r,a,o,s=()=>{if(!n||o!==`text`)throw Error(`No text message to close`);let t={type:i.TEXT_MESSAGE_END,messageId:n.messageId};return o=void 0,n=void 0,e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_END`,JSON.stringify(t)),t},c=()=>{if(!r||o!==`tool`)throw Error(`No tool call to close`);let t={type:i.TOOL_CALL_END,toolCallId:r.toolCallId};return o=void 0,r=void 0,e&&console.debug(`[TRANSFORM]: TOOL_CALL_END`,JSON.stringify(t)),t},l=()=>{if(!a||o!==`reasoning`)throw Error(`No reasoning message to close`);let t={type:i.REASONING_MESSAGE_END,messageId:a.messageId};return o=void 0,a=void 0,e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_END`,JSON.stringify(t)),t},u=()=>o===`text`?[s()]:o===`tool`?[c()]:o===`reasoning`?[l()]:[];return t.pipe(m(t=>{switch(t.type){case i.TEXT_MESSAGE_START:case i.TEXT_MESSAGE_CONTENT:case i.TEXT_MESSAGE_END:case i.TOOL_CALL_START:case i.TOOL_CALL_ARGS:case i.TOOL_CALL_END:case i.TOOL_CALL_RESULT:case i.STATE_SNAPSHOT:case i.STATE_DELTA:case i.MESSAGES_SNAPSHOT:case i.CUSTOM:case i.RUN_STARTED:case i.RUN_FINISHED:case i.RUN_ERROR:case i.STEP_STARTED:case i.STEP_FINISHED:case i.THINKING_START:case i.THINKING_END:case i.THINKING_TEXT_MESSAGE_START:case i.THINKING_TEXT_MESSAGE_CONTENT:case i.THINKING_TEXT_MESSAGE_END:case i.REASONING_START:case i.REASONING_MESSAGE_START:case i.REASONING_MESSAGE_CONTENT:case i.REASONING_MESSAGE_END:case i.REASONING_END:return[...u(),t];case i.RAW:case i.ACTIVITY_SNAPSHOT:case i.ACTIVITY_DELTA:case i.REASONING_ENCRYPTED_VALUE:return[t];case i.TEXT_MESSAGE_CHUNK:let s=t,c=[];if((o!==`text`||s.messageId!==void 0&&s.messageId!==n?.messageId)&&c.push(...u()),o!==`text`){if(s.messageId===void 0)throw Error(`First TEXT_MESSAGE_CHUNK must have a messageId`);n={messageId:s.messageId},o=`text`;let t={type:i.TEXT_MESSAGE_START,messageId:s.messageId,role:s.role||`assistant`};c.push(t),e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_START`,JSON.stringify(t))}if(s.delta!==void 0){let t={type:i.TEXT_MESSAGE_CONTENT,messageId:n.messageId,delta:s.delta};c.push(t),e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_CONTENT`,JSON.stringify(t))}return c;case i.TOOL_CALL_CHUNK:let l=t,d=[];if((o!==`tool`||l.toolCallId!==void 0&&l.toolCallId!==r?.toolCallId)&&d.push(...u()),o!==`tool`){if(l.toolCallId===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallId`);if(l.toolCallName===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallName`);r={toolCallId:l.toolCallId,toolCallName:l.toolCallName,parentMessageId:l.parentMessageId},o=`tool`;let t={type:i.TOOL_CALL_START,toolCallId:l.toolCallId,toolCallName:l.toolCallName,parentMessageId:l.parentMessageId};d.push(t),e&&console.debug(`[TRANSFORM]: TOOL_CALL_START`,JSON.stringify(t))}if(l.delta!==void 0){let t={type:i.TOOL_CALL_ARGS,toolCallId:r.toolCallId,delta:l.delta};d.push(t),e&&console.debug(`[TRANSFORM]: TOOL_CALL_ARGS`,JSON.stringify(t))}return d;case i.REASONING_MESSAGE_CHUNK:let f=t,p=[];if((o!==`reasoning`||f.messageId&&f.messageId!==a?.messageId)&&p.push(...u()),o!==`reasoning`){if(f.messageId===void 0)throw Error(`First REASONING_MESSAGE_CHUNK must have a messageId`);a={messageId:f.messageId},o=`reasoning`;let t={type:i.REASONING_MESSAGE_START,messageId:f.messageId};p.push(t),e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_START`,JSON.stringify(t))}if(f.delta!==void 0){let t={type:i.REASONING_MESSAGE_CONTENT,messageId:a.messageId,delta:f.delta};p.push(t),e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_CONTENT`,JSON.stringify(t))}return p}return t.type,[]}),d(()=>{u()}))};var H=class{runNext(e,t){return t.run(e).pipe(V(!1))}runNextWithState(e,t){let n=O(e.messages||[]),r=O(e.state||{}),i=new c;return j(e,i,t,[]).subscribe(e=>{e.messages!==void 0&&(n=e.messages),e.state!==void 0&&(r=e.state)}),this.runNext(e,t).pipe(y(async e=>(i.next(e),await new Promise(e=>setTimeout(e,0)),{event:e,messages:O(n),state:O(r)})))}},U=class extends H{constructor(e){super(),this.fn=e}run(e,t){return this.fn(e,t)}},_e=class extends H{constructor(e){if(super(),this.blockedToolCallIds=new Set,e.allowedToolCalls&&e.disallowedToolCalls)throw Error(`Cannot specify both allowedToolCalls and disallowedToolCalls`);if(!e.allowedToolCalls&&!e.disallowedToolCalls)throw Error(`Must specify either allowedToolCalls or disallowedToolCalls`);e.allowedToolCalls?this.allowedTools=new Set(e.allowedToolCalls):e.disallowedToolCalls&&(this.disallowedTools=new Set(e.disallowedToolCalls))}run(e,t){return this.runNext(e,t).pipe(te(e=>{if(e.type===i.TOOL_CALL_START){let t=e;return this.shouldFilterTool(t.toolCallName)?(this.blockedToolCallIds.add(t.toolCallId),!1):!0}if(e.type===i.TOOL_CALL_ARGS){let t=e;return!this.blockedToolCallIds.has(t.toolCallId)}if(e.type===i.TOOL_CALL_END){let t=e;return!this.blockedToolCallIds.has(t.toolCallId)}if(e.type===i.TOOL_CALL_RESULT){let t=e;return this.blockedToolCallIds.has(t.toolCallId)?(this.blockedToolCallIds.delete(t.toolCallId),!1):!0}return!0}))}shouldFilterTool(e){return this.allowedTools?!this.allowedTools.has(e):this.disallowedTools?this.disallowedTools.has(e):!1}};function ve(e){let t=e.content;if(Array.isArray(t)){let n=t.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``);return{...e,content:n}}return typeof t==`string`?e:{...e,content:``}}var W=class extends H{run(e,t){let{parentRunId:n,...r}=e,i={...r,messages:r.messages.map(ve)};return this.runNext(i,t)}};const G=`THINKING_START`,K=`THINKING_END`,q=`THINKING_TEXT_MESSAGE_START`,J=`THINKING_TEXT_MESSAGE_CONTENT`,Y=`THINKING_TEXT_MESSAGE_END`;var X=class extends H{constructor(...e){super(...e),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(e,t){process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${e} to ${t}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(e,t){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(e,t).pipe(x(e=>this.transformEvent(e)))}transformEvent(e){switch(e.type){case G:{this.currentReasoningId=k();let{title:t,...n}=e;return this.warnAboutTransformation(G,i.REASONING_START),{...n,type:i.REASONING_START,messageId:this.currentReasoningId}}case q:return this.currentMessageId=k(),this.warnAboutTransformation(q,i.REASONING_MESSAGE_START),{...e,type:i.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:`assistant`};case J:{let{delta:t,...n}=e;return this.warnAboutTransformation(J,i.REASONING_MESSAGE_CONTENT),{...n,type:i.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??k(),delta:t}}case Y:{let t=this.currentMessageId??k();return this.warnAboutTransformation(Y,i.REASONING_MESSAGE_END),{...e,type:i.REASONING_MESSAGE_END,messageId:t}}case K:{let t=this.currentReasoningId??k();return this.warnAboutTransformation(K,i.REASONING_END),{...e,type:i.REASONING_END,messageId:t}}default:return e}}},ye=`0.0.45`,Z=class{get maxVersion(){return ye}constructor({agentId:t,description:n,threadId:r,initialMessages:i,initialState:a,debug:o}={}){this.debug=!1,this.subscribers=[],this.isRunning=!1,this.middlewares=[],this.agentId=t,this.description=n??``,this.threadId=r??e(),this.messages=O(i??[]),this.state=O(a??{}),this.debug=o??!1,D(this.maxVersion,`0.0.39`)<=0&&this.middlewares.unshift(new W),D(this.maxVersion,`0.0.45`)<=0&&this.middlewares.unshift(new X)}subscribe(e){return this.subscribers.push(e),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==e)}}}use(...e){let t=e.map(e=>typeof e==`function`?new U(e):e);return this.middlewares.push(...t),this}async runAgent(t,n){try{this.isRunning=!0,this.agentId=this.agentId??e();let r=this.prepareRunAgentInput(t),i,a=new Set(this.messages.map(e=>e.id)),o=[{onRunFinishedEvent:e=>{i=e.result}},...this.subscribers,n??{}];await this.onInitialize(r,o),this.activeRunDetach$=new l;let s;this.activeRunCompletionPromise=new Promise(e=>{s=e}),await p(g(()=>this.middlewares.length===0?this.run(r):this.middlewares.reduceRight((e,t)=>({run:n=>t.run(n,e)}),this).run(r),V(this.debug),M(this.debug),e=>e.pipe(C(this.activeRunDetach$)),e=>this.apply(r,e,o),e=>this.processApplyEvents(r,e,o),v(e=>(this.isRunning=!1,this.onError(r,e,o))),b(()=>{this.isRunning=!1,this.onFinalize(r,o),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(h(null)));let c=O(this.messages).filter(e=>!a.has(e.id));return{result:i,newMessages:c}}finally{this.isRunning=!1}}connect(e){throw new t}async connectAgent(n,r){try{this.isRunning=!0,this.agentId=this.agentId??e();let i=this.prepareRunAgentInput(n),a,s=new Set(this.messages.map(e=>e.id)),c=[{onRunFinishedEvent:e=>{a=e.result}},...this.subscribers,r??{}];await this.onInitialize(i,c),this.activeRunDetach$=new l;let u;this.activeRunCompletionPromise=new Promise(e=>{u=e}),await p(g(()=>this.connect(i),V(this.debug),M(this.debug),e=>e.pipe(C(this.activeRunDetach$)),e=>this.apply(i,e,c),e=>this.processApplyEvents(i,e,c),v(e=>(this.isRunning=!1,e instanceof t?o:this.onError(i,e,c))),b(()=>{this.isRunning=!1,this.onFinalize(i,c),u?.(),u=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(h(null)));let d=O(this.messages).filter(e=>!s.has(e.id));return{result:a,newMessages:d}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let e=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await e}apply(e,t,n){return j(e,t,this,n)}processApplyEvents(e,t,n){return t.pipe(ie(t=>{t.messages&&(this.messages=t.messages,n.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),t.state&&(this.state=t.state,n.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))}))}prepareRunAgentInput(t){let n=O(this.messages).filter(e=>e.role!==`activity`);return{threadId:this.threadId,runId:t?.runId||e(),tools:O(t?.tools??[]),context:O(t?.context??[]),forwardedProps:O(t?.forwardedProps??{}),state:O(this.state),messages:n}}async onInitialize(e,t){let n=await A(t,this.messages,this.state,(t,n,r)=>t.onRunInitialized?.({messages:n,state:r,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,e.messages=n.messages,t.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state&&(this.state=n.state,e.state=n.state,t.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}onError(e,t,n){return f(A(n,this.messages,this.state,(n,r,i)=>n.onRunFailed?.({error:t,messages:r,state:i,agent:this,input:e}))).pipe(x(r=>{let i=r;if((i.messages!==void 0||i.state!==void 0)&&(i.messages!==void 0&&(this.messages=i.messages,n.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),i.state!==void 0&&(this.state=i.state,n.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))),i.stopPropagation!==!0)throw console.error(`Agent execution failed:`,t),t;return{}}))}async onFinalize(e,t){let n=await A(t,this.messages,this.state,(t,n,r)=>t.onRunFinalized?.({messages:n,state:r,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,t.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state!==void 0&&(this.state=n.state,t.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}clone(){let e=Object.create(Object.getPrototypeOf(this));return e.agentId=this.agentId,e.description=this.description,e.threadId=this.threadId,e.messages=O(this.messages),e.state=O(this.state),e.debug=this.debug,e.isRunning=this.isRunning,e.subscribers=[...this.subscribers],e.middlewares=[...this.middlewares],e}addMessage(e){this.messages.push(e),(async()=>{for(let t of this.subscribers)await t.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role===`assistant`&&e.toolCalls)for(let t of e.toolCalls)for(let e of this.subscribers)await e.onNewToolCall?.({toolCall:t,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(e){this.messages.push(...e),(async()=>{for(let t of e){for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role===`assistant`&&t.toolCalls)for(let e of t.toolCalls)for(let t of this.subscribers)await t.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(e){this.messages=O(e),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(e){this.state=O(e),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??e();let n=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((e,t)=>({run:n=>t.run(n,e)}),this).run(n)).pipe(V(this.debug),M(this.debug),B(this.threadId,n.runId,this.agentId),e=>e.pipe(x(e=>(this.debug&&console.debug(`[LEGACY]:`,JSON.stringify(e)),e))))}},be=class extends Z{requestInit(e){return{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e,t){return this.abortController=e?.abortController??new AbortController,super.runAgent(e,t)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(e){super(e),this.abortController=new AbortController,this.url=e.url,this.headers=O(e.headers??{})}run(e){return L(P(this.url,this.requestInit(e)))}clone(){let e=super.clone();e.url=this.url,e.headers=O(this.headers??{});let t=new AbortController,n=this.abortController.signal;return n.aborted&&t.abort(n.reason),e.abortController=t,e}};function xe(e){let t=[],n=new Map,r=new Map;for(let a of e)if(a.type===i.TEXT_MESSAGE_START){let e=a,t=e.messageId;n.has(t)||n.set(t,{contents:[],otherEvents:[]});let r=n.get(t);r.start=e}else if(a.type===i.TEXT_MESSAGE_CONTENT){let e=a,t=e.messageId;n.has(t)||n.set(t,{contents:[],otherEvents:[]}),n.get(t).contents.push(e)}else if(a.type===i.TEXT_MESSAGE_END){let e=a,r=e.messageId;n.has(r)||n.set(r,{contents:[],otherEvents:[]});let i=n.get(r);i.end=e,Q(r,i,t),n.delete(r)}else if(a.type===i.TOOL_CALL_START){let e=a,t=e.toolCallId;r.has(t)||r.set(t,{args:[],otherEvents:[]});let n=r.get(t);n.start=e}else if(a.type===i.TOOL_CALL_ARGS){let e=a,t=e.toolCallId;r.has(t)||r.set(t,{args:[],otherEvents:[]}),r.get(t).args.push(e)}else if(a.type===i.TOOL_CALL_END){let e=a,n=e.toolCallId;r.has(n)||r.set(n,{args:[],otherEvents:[]});let i=r.get(n);i.end=e,$(n,i,t),r.delete(n)}else{let e=!1;for(let[t,r]of n)if(r.start&&!r.end){r.otherEvents.push(a),e=!0;break}if(!e){for(let[t,n]of r)if(n.start&&!n.end){n.otherEvents.push(a),e=!0;break}}e||t.push(a)}for(let[e,r]of n)Q(e,r,t);for(let[e,n]of r)$(e,n,t);return t}function Q(e,t,n){if(t.start&&n.push(t.start),t.contents.length>0){let r=t.contents.map(e=>e.delta).join(``),a={type:i.TEXT_MESSAGE_CONTENT,messageId:e,delta:r};n.push(a)}t.end&&n.push(t.end);for(let e of t.otherEvents)n.push(e)}function $(e,t,n){if(t.start&&n.push(t.start),t.args.length>0){let r=t.args.map(e=>e.delta).join(``),a={type:i.TOOL_CALL_ARGS,toolCallId:e,delta:r};n.push(a)}t.end&&n.push(t.end);for(let e of t.otherEvents)n.push(e)}export{Z as AbstractAgent,W as BackwardCompatibility_0_0_39,X as BackwardCompatibility_0_0_45,_e as FilterToolCallsMiddleware,U as FunctionMiddleware,be as HttpAgent,H as Middleware,xe as compactEvents,B as convertToLegacyEvents,j as defaultApplyEvents,I as parseProtoStream,F as parseSSEStream,k as randomUUID,P as runHttpRequest,O as structuredClone_,V as transformChunks,L as transformHttpEventStream,M as verifyEvents};
8
5
  //# sourceMappingURL=index.mjs.map