@ag-ui/client
Advanced tools
+1
-1
@@ -7,3 +7,3 @@ "use strict";var Kt=Object.create;var tt=Object.defineProperty,Jt=Object.defineProperties,Vt=Object.getOwnPropertyDescriptor,Wt=Object.getOwnPropertyDescriptors,Yt=Object.getOwnPropertyNames,st=Object.getOwnPropertySymbols,qt=Object.getPrototypeOf,Tt=Object.prototype.hasOwnProperty,Ct=Object.prototype.propertyIsEnumerable;var Mt=(i,a,e)=>a in i?tt(i,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[a]=e,L=(i,a)=>{for(var e in a||(a={}))Tt.call(a,e)&&Mt(i,e,a[e]);if(st)for(var e of st(a))Ct.call(a,e)&&Mt(i,e,a[e]);return i},b=(i,a)=>Jt(i,Wt(a));var Rt=(i,a)=>{var e={};for(var n in i)Tt.call(i,n)&&a.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&st)for(var n of st(i))a.indexOf(n)<0&&Ct.call(i,n)&&(e[n]=i[n]);return e};var Qt=(i,a)=>{for(var e in a)tt(i,e,{get:a[e],enumerable:!0})},at=(i,a,e,n)=>{if(a&&typeof a=="object"||typeof a=="function")for(let t of Yt(a))!Tt.call(i,t)&&t!==e&&tt(i,t,{get:()=>a[t],enumerable:!(n=Vt(a,t))||n.enumerable});return i},D=(i,a,e)=>(at(i,a,"default"),e&&at(e,a,"default")),ot=(i,a,e)=>(e=i!=null?Kt(qt(i)):{},at(a||!i||!i.__esModule?tt(e,"default",{value:i,enumerable:!0}):e,i)),Zt=i=>at(tt({},"__esModule",{value:!0}),i);var P={};Qt(P,{AbstractAgent:()=>Q,BackwardCompatibility_0_0_39:()=>Y,FilterToolCallsMiddleware:()=>nt,FunctionMiddleware:()=>W,HttpAgent:()=>mt,Middleware:()=>U,compactEvents:()=>zt,convertToLegacyEvents:()=>dt,defaultApplyEvents:()=>J,parseProtoStream:()=>ct,parseSSEStream:()=>gt,randomUUID:()=>te,runHttpRequest:()=>lt,structuredClone_:()=>M,transformChunks:()=>$,transformHttpEventStream:()=>Et,verifyEvents:()=>V});module.exports=Zt(P);var I=require("@ag-ui/core"),K=require("rxjs/operators"),rt=require("rxjs");var It=require("uuid");var M=i=>{if(typeof structuredClone=="function")return structuredClone(i);try{return JSON.parse(JSON.stringify(i))}catch(a){return L({},i)}};function te(){return(0,It.v4)()}var St=require("fast-json-patch");async function N(i,a,e,n){let t=a,s=e,r;for(let o of i)try{let l=await n(o,M(t),M(s));if(l===void 0)continue;if(l.messages!==void 0&&(t=l.messages),l.state!==void 0&&(s=l.state),r=l.stopPropagation,r===!0)break}catch(l){process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0||console.error("Subscriber error:",l);continue}return L(L(L({},JSON.stringify(t)!==JSON.stringify(a)?{messages:t}:{}),JSON.stringify(s)!==JSON.stringify(e)?{state:s}:{}),r!==void 0?{stopPropagation:r}:{})}var xt=ot(require("untruncate-json"));var J=(i,a,e,n)=>{let t=M(e.messages),s=M(i.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)},l=()=>{let d=M(r);return r={},d.messages!==void 0||d.state!==void 0?(0,rt.of)(d):rt.EMPTY};return a.pipe((0,K.concatMap)(async d=>{var T,h,c,F,z;let _=await N(n,t,s,(E,g,p)=>{var m;return(m=E.onEvent)==null?void 0:m.call(E,{event:d,agent:e,input:i,messages:g,state:p})});if(o(_),_.stopPropagation===!0)return l();switch(d.type){case I.EventType.TEXT_MESSAGE_START:{let E=await N(n,t,s,(g,p,m)=>{var u;return(u=g.onTextMessageStartEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:i})});if(o(E),E.stopPropagation!==!0){let{messageId:g,role:p="assistant"}=d,m={id:g,role:p,content:""};t.push(m),o({messages:t})}return l()}case I.EventType.TEXT_MESSAGE_CONTENT:{let{messageId:E,delta:g}=d,p=t.find(u=>u.id===E);if(!p)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${E}'`),l();let m=await N(n,t,s,(u,y,C)=>{var w;return(w=u.onTextMessageContentEvent)==null?void 0:w.call(u,{event:d,messages:y,state:C,agent:e,input:i,textMessageBuffer:typeof p.content=="string"?p.content:""})});if(o(m),m.stopPropagation!==!0){let u=typeof p.content=="string"?p.content:"";p.content=`${u}${g}`,o({messages:t})}return l()}case I.EventType.TEXT_MESSAGE_END:{let{messageId:E}=d,g=t.find(m=>m.id===E);if(!g)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${E}'`),l();let p=await N(n,t,s,(m,u,y)=>{var C;return(C=m.onTextMessageEndEvent)==null?void 0:C.call(m,{event:d,messages:u,state:y,agent:e,input:i,textMessageBuffer:typeof g.content=="string"?g.content:""})});return o(p),await Promise.all(n.map(m=>{var u;(u=m.onNewMessage)==null||u.call(m,{message:g,messages:t,state:s,agent:e,input:i})})),l()}case I.EventType.TOOL_CALL_START:{let E=await N(n,t,s,(g,p,m)=>{var u;return(u=g.onToolCallStartEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:i})});if(o(E),E.stopPropagation!==!0){let{toolCallId:g,toolCallName:p,parentMessageId:m}=d,u;m&&t.length>0&&t[t.length-1].id===m?u=t[t.length-1]:(u={id:m||g,role:"assistant",toolCalls:[]},t.push(u)),(T=u.toolCalls)!=null||(u.toolCalls=[]),u.toolCalls.push({id:g,type:"function",function:{name:p,arguments:""}}),o({messages:t})}return l()}case I.EventType.TOOL_CALL_ARGS:{let{toolCallId:E,delta:g}=d,p=t.find(y=>{var C;return(C=y.toolCalls)==null?void 0:C.some(w=>w.id===E)});if(!p)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${E}'`),l();let m=p.toolCalls.find(y=>y.id===E);if(!m)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${E}'`),l();let u=await N(n,t,s,(y,C,w)=>{var ft;let H=m.function.arguments,k=m.function.name,Z={};try{Z=(0,xt.default)(H)}catch(fe){}return(ft=y.onToolCallArgsEvent)==null?void 0:ft.call(y,{event:d,messages:C,state:w,agent:e,input:i,toolCallBuffer:H,toolCallName:k,partialToolCallArgs:Z})});return o(u),u.stopPropagation!==!0&&(m.function.arguments+=g,o({messages:t})),l()}case I.EventType.TOOL_CALL_END:{let{toolCallId:E}=d,g=t.find(u=>{var y;return(y=u.toolCalls)==null?void 0:y.some(C=>C.id===E)});if(!g)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${E}'`),l();let p=g.toolCalls.find(u=>u.id===E);if(!p)return console.warn(`TOOL_CALL_END: No tool call found with ID '${E}'`),l();let m=await N(n,t,s,(u,y,C)=>{var Z;let w=p.function.arguments,H=p.function.name,k={};try{k=JSON.parse(w)}catch(ft){}return(Z=u.onToolCallEndEvent)==null?void 0:Z.call(u,{event:d,messages:y,state:C,agent:e,input:i,toolCallName:H,toolCallArgs:k})});return o(m),await Promise.all(n.map(u=>{var y;(y=u.onNewToolCall)==null||y.call(u,{toolCall:p,messages:t,state:s,agent:e,input:i})})),l()}case I.EventType.TOOL_CALL_RESULT:{let E=await N(n,t,s,(g,p,m)=>{var u;return(u=g.onToolCallResultEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:i})});if(o(E),E.stopPropagation!==!0){let{messageId:g,toolCallId:p,content:m,role:u}=d,y={id:g,toolCallId:p,role:u||"tool",content:m};t.push(y),await Promise.all(n.map(C=>{var w;(w=C.onNewMessage)==null||w.call(C,{message:y,messages:t,state:s,agent:e,input:i})})),o({messages:t})}return l()}case I.EventType.STATE_SNAPSHOT:{let E=await N(n,t,s,(g,p,m)=>{var u;return(u=g.onStateSnapshotEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:i})});if(o(E),E.stopPropagation!==!0){let{snapshot:g}=d;s=g,o({state:s})}return l()}case I.EventType.STATE_DELTA:{let E=await N(n,t,s,(g,p,m)=>{var u;return(u=g.onStateDeltaEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:i})});if(o(E),E.stopPropagation!==!0){let{delta:g}=d;try{s=(0,St.applyPatch)(s,g,!0,!1).newDocument,o({state:s})}catch(p){let m=p instanceof Error?p.message:String(p);console.warn(`Failed to apply state patch: | ||
| `),d=JSON.parse(l);a.next(d)}catch(l){a.error(l)}}return a.asObservable()};var wt=require("rxjs");var Lt=ot(require("@ag-ui/proto")),ct=i=>{let a=new wt.Subject,e=new Uint8Array(0);i.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),l=Lt.decode(o);a.next(l),e=e.slice(r)}catch(o){let l=o instanceof Error?o.message:String(o);a.error(new Error(`Failed to decode protocol buffer message: ${l}`));return}}}return a.asObservable()};var Pt=ot(require("@ag-ui/proto")),Dt=require("@ag-ui/core"),Et=i=>{let a=new ut.Subject,e=new ut.ReplaySubject,n=!1;return i.subscribe({next:t=>{e.next(t),t.type==="headers"&&!n?(n=!0,t.headers.get("content-type")===Pt.AGUI_MEDIA_TYPE?ct(e).subscribe({next:r=>a.next(r),error:r=>a.error(r),complete:()=>a.complete()}):gt(e).subscribe({next:r=>{try{let o=Ot.EventSchemas.parse(r);a.next(o)}catch(o){a.error(o)}},error:r=>{if((r==null?void 0:r.name)==="AbortError"){a.next({type:Dt.EventType.RUN_ERROR,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()};var Ht=require("rxjs/operators"),Gt=require("fast-json-patch"),O=require("@ag-ui/core");var f=require("zod"),x=f.z.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),ee=f.z.enum(["LangGraphInterruptEvent","PredictState","Exit"]),ne=f.z.object({type:f.z.literal(x.enum.TextMessageStart),messageId:f.z.string(),parentMessageId:f.z.string().optional(),role:f.z.string().optional()}),se=f.z.object({type:f.z.literal(x.enum.TextMessageContent),messageId:f.z.string(),content:f.z.string()}),ae=f.z.object({type:f.z.literal(x.enum.TextMessageEnd),messageId:f.z.string()}),oe=f.z.object({type:f.z.literal(x.enum.ActionExecutionStart),actionExecutionId:f.z.string(),actionName:f.z.string(),parentMessageId:f.z.string().optional()}),re=f.z.object({type:f.z.literal(x.enum.ActionExecutionArgs),actionExecutionId:f.z.string(),args:f.z.string()}),ie=f.z.object({type:f.z.literal(x.enum.ActionExecutionEnd),actionExecutionId:f.z.string()}),le=f.z.object({type:f.z.literal(x.enum.ActionExecutionResult),actionName:f.z.string(),actionExecutionId:f.z.string(),result:f.z.string()}),ge=f.z.object({type:f.z.literal(x.enum.AgentStateMessage),threadId:f.z.string(),agentName:f.z.string(),nodeName:f.z.string(),runId:f.z.string(),active:f.z.boolean(),role:f.z.string(),state:f.z.string(),running:f.z.boolean()}),ce=f.z.object({type:f.z.literal(x.enum.MetaEvent),name:ee,value:f.z.any()}),ue=f.z.object({type:f.z.literal(x.enum.RunError),message:f.z.string(),code:f.z.string().optional()}),_n=f.z.discriminatedUnion("type",[ne,se,ae,oe,re,ie,le,ge,ce,ue]),Nn=f.z.object({id:f.z.string(),role:f.z.string(),content:f.z.string(),parentMessageId:f.z.string().optional()}),wn=f.z.object({id:f.z.string(),name:f.z.string(),arguments:f.z.any(),parentMessageId:f.z.string().optional()}),Ln=f.z.object({id:f.z.string(),result:f.z.any(),actionExecutionId:f.z.string(),actionName:f.z.string()});var bt=ot(require("untruncate-json"));var Ee=i=>{if(typeof i=="string")return i;if(!Array.isArray(i))return;let a=i.filter(e=>e.type==="text").map(e=>e.text).filter(e=>e.length>0);if(a.length!==0)return a.join(` | ||
| `)},dt=(i,a,e)=>n=>{let t={},s=!0,r=!0,o="",l=null,d=null,_=[],v={},T=h=>{typeof h=="object"&&h!==null&&("messages"in h&&delete h.messages,t=h)};return n.pipe((0,Ht.mergeMap)(h=>{switch(h.type){case O.EventType.TEXT_MESSAGE_START:{let c=h;return[{type:x.enum.TextMessageStart,messageId:c.messageId,role:c.role}]}case O.EventType.TEXT_MESSAGE_CONTENT:{let c=h;return[{type:x.enum.TextMessageContent,messageId:c.messageId,content:c.delta}]}case O.EventType.TEXT_MESSAGE_END:{let c=h;return[{type:x.enum.TextMessageEnd,messageId:c.messageId}]}case O.EventType.TOOL_CALL_START:{let c=h;return _.push({id:c.toolCallId,type:"function",function:{name:c.toolCallName,arguments:""}}),r=!0,v[c.toolCallId]=c.toolCallName,[{type:x.enum.ActionExecutionStart,actionExecutionId:c.toolCallId,actionName:c.toolCallName,parentMessageId:c.parentMessageId}]}case O.EventType.TOOL_CALL_ARGS:{let c=h,F=_.find(E=>E.id===c.toolCallId);if(!F)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c.toolCallId}'`),[];F.function.arguments+=c.delta;let z=!1;if(d){let E=d.find(g=>g.tool==F.function.name);if(E)try{let g=JSON.parse((0,bt.default)(F.function.arguments));E.tool_argument&&E.tool_argument in g?(T(b(L({},t),{[E.state_key]:g[E.tool_argument]})),z=!0):E.tool_argument||(T(b(L({},t),{[E.state_key]:g})),z=!0)}catch(g){}}return[{type:x.enum.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...z?[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}]:[]]}case O.EventType.TOOL_CALL_END:{let c=h;return[{type:x.enum.ActionExecutionEnd,actionExecutionId:c.toolCallId}]}case O.EventType.TOOL_CALL_RESULT:{let c=h;return[{type:x.enum.ActionExecutionResult,actionExecutionId:c.toolCallId,result:c.content,actionName:v[c.toolCallId]||"unknown"}]}case O.EventType.RAW:return[];case O.EventType.CUSTOM:{let c=h;switch(c.name){case"Exit":s=!1;break;case"PredictState":d=c.value;break}return[{type:x.enum.MetaEvent,name:c.name,value:c.value}]}case O.EventType.STATE_SNAPSHOT:return T(h.snapshot),[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}];case O.EventType.STATE_DELTA:{let F=(0,Gt.applyPatch)(t,h.delta,!0,!1);return F?(T(F.newDocument),[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}]):[]}case O.EventType.MESSAGES_SNAPSHOT:return l=h.messages,[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(L(L({},t),l?{messages:l}:{})),active:!0}];case O.EventType.RUN_STARTED:return[];case O.EventType.RUN_FINISHED:return l&&(t.messages=l),Object.keys(t).length===0?[]:[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(L(L({},t),l?{messages:de(l)}:{})),active:!1}];case O.EventType.RUN_ERROR:{let c=h;return[{type:x.enum.RunError,message:c.message,code:c.code}]}case O.EventType.STEP_STARTED:return o=h.stepName,_=[],d=null,[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!0}];case O.EventType.STEP_FINISHED:return _=[],d=null,[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!1}];default:return[]}}))};function de(i){var e;let a=[];for(let n of i)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let t=Ee(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 i)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}var q=require("uuid");var jt=require("compare-versions"),X=require("rxjs/operators"),vt=require("rxjs/operators"),At=require("rxjs/operators"),G=require("rxjs");var ht=require("rxjs");var pt=require("rxjs"),R=require("@ag-ui/core"),$=i=>a=>{let e,n,t,s=()=>{if(!e||t!=="text")throw new Error("No text message to close");let l={type:R.EventType.TEXT_MESSAGE_END,messageId:e.messageId};return t=void 0,e=void 0,i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(l)),l},r=()=>{if(!n||t!=="tool")throw new Error("No tool call to close");let l={type:R.EventType.TOOL_CALL_END,toolCallId:n.toolCallId};return t=void 0,n=void 0,i&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(l)),l},o=()=>t==="text"?[s()]:t==="tool"?[r()]:[];return a.pipe((0,pt.mergeMap)(l=>{switch(l.type){case R.EventType.TEXT_MESSAGE_START:case R.EventType.TEXT_MESSAGE_CONTENT:case R.EventType.TEXT_MESSAGE_END:case R.EventType.TOOL_CALL_START:case R.EventType.TOOL_CALL_ARGS:case R.EventType.TOOL_CALL_END:case R.EventType.TOOL_CALL_RESULT:case R.EventType.STATE_SNAPSHOT:case R.EventType.STATE_DELTA:case R.EventType.MESSAGES_SNAPSHOT:case R.EventType.CUSTOM:case R.EventType.RUN_STARTED:case R.EventType.RUN_FINISHED:case R.EventType.RUN_ERROR:case R.EventType.STEP_STARTED:case R.EventType.STEP_FINISHED:case R.EventType.THINKING_START:case R.EventType.THINKING_END:case R.EventType.THINKING_TEXT_MESSAGE_START:case R.EventType.THINKING_TEXT_MESSAGE_CONTENT:case R.EventType.THINKING_TEXT_MESSAGE_END:return[...o(),l];case R.EventType.RAW:case R.EventType.ACTIVITY_SNAPSHOT:case R.EventType.ACTIVITY_DELTA:return[l];case R.EventType.TEXT_MESSAGE_CHUNK:let _=l,v=[];if((t!=="text"||_.messageId!==void 0&&_.messageId!==(e==null?void 0:e.messageId))&&v.push(...o()),t!=="text"){if(_.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:_.messageId},t="text";let c={type:R.EventType.TEXT_MESSAGE_START,messageId:_.messageId,role:_.role||"assistant"};v.push(c),i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(c))}if(_.delta!==void 0){let c={type:R.EventType.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:_.delta};v.push(c),i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(c))}return v;case R.EventType.TOOL_CALL_CHUNK:let T=l,h=[];if((t!=="tool"||T.toolCallId!==void 0&&T.toolCallId!==(n==null?void 0:n.toolCallId))&&h.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:R.EventType.TOOL_CALL_START,toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId};h.push(c),i&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(c))}if(T.delta!==void 0){let c={type:R.EventType.TOOL_CALL_ARGS,toolCallId:n.toolCallId,delta:T.delta};h.push(c),i&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(c))}return h}let d=l.type;return[]}),(0,pt.finalize)(()=>{o()}))};var yt=require("@ag-ui/core");var Ft=require("rxjs"),kt=require("rxjs/operators");var U=class{runNext(a,e){return e.run(a).pipe($(!1))}runNextWithState(a,e){let n=M(a.messages||[]),t=M(a.state||{}),s=new Ft.ReplaySubject;return J(a,s,e,[]).subscribe(o=>{o.messages!==void 0&&(n=o.messages),o.state!==void 0&&(t=o.state)}),this.runNext(a,e).pipe((0,kt.concatMap)(async o=>(s.next(o),await new Promise(l=>setTimeout(l,0)),{event:o,messages:M(n),state:M(t)})))}},W=class extends U{constructor(e){super();this.fn=e}run(e,n){return this.fn(e,n)}};var et=require("@ag-ui/core"),Bt=require("rxjs/operators"),nt=class extends U{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((0,Bt.filter)(t=>{if(t.type===et.EventType.TOOL_CALL_START){let s=t;return this.shouldFilterTool(s.toolCallName)?(this.blockedToolCallIds.add(s.toolCallId),!1):!0}if(t.type===et.EventType.TOOL_CALL_ARGS){let s=t;return!this.blockedToolCallIds.has(s.toolCallId)}if(t.type===et.EventType.TOOL_CALL_END){let s=t;return!this.blockedToolCallIds.has(s.toolCallId)}if(t.type===et.EventType.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 pe(i){let a=i.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 b(L({},i),{content:e})}return typeof a=="string"?i:b(L({},i),{content:""})}var Y=class extends U{run(a,e){let r=a,{parentRunId:n}=r,t=Rt(r,["parentRunId"]),s=b(L({},t),{messages:t.messages.map(pe)});return this.runNext(s,e)}};var Ut={name:"@ag-ui/client",author:"Markus Ecker <markus.ecker@gmail.com>",version:"0.0.42-alpha.3",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 Q=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:(0,q.v4)(),this.messages=M(t!=null?t:[]),this.state=M(s!=null?s:{}),this.debug=r!=null?r:!1,(0,jt.compareVersions)(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new Y)}get maxVersion(){return Ut.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 W(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:(0,q.v4)();let t=this.prepareRunAgentInput(a),s,r=new Set(this.messages.map(v=>v.id)),o=[{onRunFinishedEvent:v=>{s=v.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o),this.activeRunDetach$=new G.Subject;let l;this.activeRunCompletionPromise=new Promise(v=>{l=v});let d=(0,G.pipe)(()=>this.middlewares.length===0?this.run(t):this.middlewares.reduceRight((T,h)=>({run:c=>h.run(c,T)}),this).run(t),$(this.debug),V(this.debug),v=>v.pipe((0,At.takeUntil)(this.activeRunDetach$)),v=>this.apply(t,v,o),v=>this.processApplyEvents(t,v,o),(0,X.catchError)(v=>(this.isRunning=!1,this.onError(t,v,o))),(0,vt.finalize)(()=>{this.isRunning=!1,this.onFinalize(t,o),l==null||l(),l=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}));await(0,ht.lastValueFrom)(d((0,G.of)(null)));let _=M(this.messages).filter(v=>!r.has(v.id));return{result:s,newMessages:_}}finally{this.isRunning=!1}}connect(a){throw new yt.AGUIConnectNotImplementedError}async connectAgent(a,e){var n;try{this.isRunning=!0,this.agentId=(n=this.agentId)!=null?n:(0,q.v4)();let t=this.prepareRunAgentInput(a),s,r=new Set(this.messages.map(v=>v.id)),o=[{onRunFinishedEvent:v=>{s=v.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o),this.activeRunDetach$=new G.Subject;let l;this.activeRunCompletionPromise=new Promise(v=>{l=v});let d=(0,G.pipe)(()=>this.connect(t),$(this.debug),V(this.debug),v=>v.pipe((0,At.takeUntil)(this.activeRunDetach$)),v=>this.apply(t,v,o),v=>this.processApplyEvents(t,v,o),(0,X.catchError)(v=>(this.isRunning=!1,v instanceof yt.AGUIConnectNotImplementedError?G.EMPTY:this.onError(t,v,o))),(0,vt.finalize)(()=>{this.isRunning=!1,this.onFinalize(t,o),l==null||l(),l=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}));await(0,ht.lastValueFrom)(d((0,G.of)(null)));let _=M(this.messages).filter(v=>!r.has(v.id));return{result:s,newMessages:_}}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 J(a,e,this,n)}processApplyEvents(a,e,n){return e.pipe((0,X.tap)(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=M(this.messages).filter(o=>o.role!=="activity");return{threadId:this.threadId,runId:(a==null?void 0:a.runId)||(0,q.v4)(),tools:M((t=a==null?void 0:a.tools)!=null?t:[]),context:M((s=a==null?void 0:a.context)!=null?s:[]),forwardedProps:M((r=a==null?void 0:a.forwardedProps)!=null?r:{}),state:M(this.state),messages:n}}async onInitialize(a,e){let n=await N(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(0,G.from)(N(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((0,X.map)(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 N(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=M(this.messages),a.state=M(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=M(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=M(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:(0,q.v4)();let e=this.prepareRunAgentInput(a);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((r,o)=>({run:l=>o.run(l,r)}),this).run(e)).pipe($(this.debug),V(this.debug),dt(this.threadId,e.runId,this.agentId),s=>s.pipe((0,X.map)(r=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(r)),r))))}};var mt=class extends Q{constructor(e){var n;super(e);this.abortController=new AbortController;this.url=e.url,this.headers=M((n=e.headers)!=null?n:{})}requestInit(e){return{method:"POST",headers:b(L({},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=lt(this.url,this.requestInit(e));return Et(n)}clone(){var s;let e=super.clone();e.url=this.url,e.headers=M((s=this.headers)!=null?s:{});let n=new AbortController,t=this.abortController.signal;return t.aborted&&n.abort(t.reason),e.abortController=n,e}};var j=require("@ag-ui/core");function zt(i){let a=[],e=new Map,n=new Map;for(let t of i)if(t.type===j.EventType.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===j.EventType.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===j.EventType.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,Xt(r,o,a),e.delete(r)}else if(t.type===j.EventType.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===j.EventType.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===j.EventType.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,$t(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)Xt(t,s,a);for(let[t,s]of n)$t(t,s,a);return a}function Xt(i,a,e){if(a.start&&e.push(a.start),a.contents.length>0){let n=a.contents.map(s=>s.delta).join(""),t={type:j.EventType.TEXT_MESSAGE_CONTENT,messageId:i,delta:n};e.push(t)}a.end&&e.push(a.end);for(let n of a.otherEvents)e.push(n)}function $t(i,a,e){if(a.start&&e.push(a.start),a.args.length>0){let n=a.args.map(s=>s.delta).join(""),t={type:j.EventType.TOOL_CALL_ARGS,toolCallId:i,delta:n};e.push(t)}a.end&&e.push(a.end);for(let n of a.otherEvents)e.push(n)}D(P,require("@ag-ui/core"),module.exports);0&&(module.exports={AbstractAgent,BackwardCompatibility_0_0_39,FilterToolCallsMiddleware,FunctionMiddleware,HttpAgent,Middleware,compactEvents,convertToLegacyEvents,defaultApplyEvents,parseProtoStream,parseSSEStream,randomUUID,runHttpRequest,structuredClone_,transformChunks,transformHttpEventStream,verifyEvents,...require("@ag-ui/core")}); | ||
| `)},dt=(i,a,e)=>n=>{let t={},s=!0,r=!0,o="",l=null,d=null,_=[],v={},T=h=>{typeof h=="object"&&h!==null&&("messages"in h&&delete h.messages,t=h)};return n.pipe((0,Ht.mergeMap)(h=>{switch(h.type){case O.EventType.TEXT_MESSAGE_START:{let c=h;return[{type:x.enum.TextMessageStart,messageId:c.messageId,role:c.role}]}case O.EventType.TEXT_MESSAGE_CONTENT:{let c=h;return[{type:x.enum.TextMessageContent,messageId:c.messageId,content:c.delta}]}case O.EventType.TEXT_MESSAGE_END:{let c=h;return[{type:x.enum.TextMessageEnd,messageId:c.messageId}]}case O.EventType.TOOL_CALL_START:{let c=h;return _.push({id:c.toolCallId,type:"function",function:{name:c.toolCallName,arguments:""}}),r=!0,v[c.toolCallId]=c.toolCallName,[{type:x.enum.ActionExecutionStart,actionExecutionId:c.toolCallId,actionName:c.toolCallName,parentMessageId:c.parentMessageId}]}case O.EventType.TOOL_CALL_ARGS:{let c=h,F=_.find(E=>E.id===c.toolCallId);if(!F)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c.toolCallId}'`),[];F.function.arguments+=c.delta;let z=!1;if(d){let E=d.find(g=>g.tool==F.function.name);if(E)try{let g=JSON.parse((0,bt.default)(F.function.arguments));E.tool_argument&&E.tool_argument in g?(T(b(L({},t),{[E.state_key]:g[E.tool_argument]})),z=!0):E.tool_argument||(T(b(L({},t),{[E.state_key]:g})),z=!0)}catch(g){}}return[{type:x.enum.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...z?[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}]:[]]}case O.EventType.TOOL_CALL_END:{let c=h;return[{type:x.enum.ActionExecutionEnd,actionExecutionId:c.toolCallId}]}case O.EventType.TOOL_CALL_RESULT:{let c=h;return[{type:x.enum.ActionExecutionResult,actionExecutionId:c.toolCallId,result:c.content,actionName:v[c.toolCallId]||"unknown"}]}case O.EventType.RAW:return[];case O.EventType.CUSTOM:{let c=h;switch(c.name){case"Exit":s=!1;break;case"PredictState":d=c.value;break}return[{type:x.enum.MetaEvent,name:c.name,value:c.value}]}case O.EventType.STATE_SNAPSHOT:return T(h.snapshot),[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}];case O.EventType.STATE_DELTA:{let F=(0,Gt.applyPatch)(t,h.delta,!0,!1);return F?(T(F.newDocument),[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}]):[]}case O.EventType.MESSAGES_SNAPSHOT:return l=h.messages,[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(L(L({},t),l?{messages:l}:{})),active:!0}];case O.EventType.RUN_STARTED:return[];case O.EventType.RUN_FINISHED:return l&&(t.messages=l),Object.keys(t).length===0?[]:[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(L(L({},t),l?{messages:de(l)}:{})),active:!1}];case O.EventType.RUN_ERROR:{let c=h;return[{type:x.enum.RunError,message:c.message,code:c.code}]}case O.EventType.STEP_STARTED:return o=h.stepName,_=[],d=null,[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!0}];case O.EventType.STEP_FINISHED:return _=[],d=null,[{type:x.enum.AgentStateMessage,threadId:i,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!1}];default:return[]}}))};function de(i){var e;let a=[];for(let n of i)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let t=Ee(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 i)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}var q=require("uuid");var jt=require("compare-versions"),X=require("rxjs/operators"),vt=require("rxjs/operators"),At=require("rxjs/operators"),G=require("rxjs");var ht=require("rxjs");var pt=require("rxjs"),R=require("@ag-ui/core"),$=i=>a=>{let e,n,t,s=()=>{if(!e||t!=="text")throw new Error("No text message to close");let l={type:R.EventType.TEXT_MESSAGE_END,messageId:e.messageId};return t=void 0,e=void 0,i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(l)),l},r=()=>{if(!n||t!=="tool")throw new Error("No tool call to close");let l={type:R.EventType.TOOL_CALL_END,toolCallId:n.toolCallId};return t=void 0,n=void 0,i&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(l)),l},o=()=>t==="text"?[s()]:t==="tool"?[r()]:[];return a.pipe((0,pt.mergeMap)(l=>{switch(l.type){case R.EventType.TEXT_MESSAGE_START:case R.EventType.TEXT_MESSAGE_CONTENT:case R.EventType.TEXT_MESSAGE_END:case R.EventType.TOOL_CALL_START:case R.EventType.TOOL_CALL_ARGS:case R.EventType.TOOL_CALL_END:case R.EventType.TOOL_CALL_RESULT:case R.EventType.STATE_SNAPSHOT:case R.EventType.STATE_DELTA:case R.EventType.MESSAGES_SNAPSHOT:case R.EventType.CUSTOM:case R.EventType.RUN_STARTED:case R.EventType.RUN_FINISHED:case R.EventType.RUN_ERROR:case R.EventType.STEP_STARTED:case R.EventType.STEP_FINISHED:case R.EventType.THINKING_START:case R.EventType.THINKING_END:case R.EventType.THINKING_TEXT_MESSAGE_START:case R.EventType.THINKING_TEXT_MESSAGE_CONTENT:case R.EventType.THINKING_TEXT_MESSAGE_END:return[...o(),l];case R.EventType.RAW:case R.EventType.ACTIVITY_SNAPSHOT:case R.EventType.ACTIVITY_DELTA:return[l];case R.EventType.TEXT_MESSAGE_CHUNK:let _=l,v=[];if((t!=="text"||_.messageId!==void 0&&_.messageId!==(e==null?void 0:e.messageId))&&v.push(...o()),t!=="text"){if(_.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:_.messageId},t="text";let c={type:R.EventType.TEXT_MESSAGE_START,messageId:_.messageId,role:_.role||"assistant"};v.push(c),i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(c))}if(_.delta!==void 0){let c={type:R.EventType.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:_.delta};v.push(c),i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(c))}return v;case R.EventType.TOOL_CALL_CHUNK:let T=l,h=[];if((t!=="tool"||T.toolCallId!==void 0&&T.toolCallId!==(n==null?void 0:n.toolCallId))&&h.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:R.EventType.TOOL_CALL_START,toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId};h.push(c),i&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(c))}if(T.delta!==void 0){let c={type:R.EventType.TOOL_CALL_ARGS,toolCallId:n.toolCallId,delta:T.delta};h.push(c),i&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(c))}return h}let d=l.type;return[]}),(0,pt.finalize)(()=>{o()}))};var yt=require("@ag-ui/core");var Ft=require("rxjs"),kt=require("rxjs/operators");var U=class{runNext(a,e){return e.run(a).pipe($(!1))}runNextWithState(a,e){let n=M(a.messages||[]),t=M(a.state||{}),s=new Ft.ReplaySubject;return J(a,s,e,[]).subscribe(o=>{o.messages!==void 0&&(n=o.messages),o.state!==void 0&&(t=o.state)}),this.runNext(a,e).pipe((0,kt.concatMap)(async o=>(s.next(o),await new Promise(l=>setTimeout(l,0)),{event:o,messages:M(n),state:M(t)})))}},W=class extends U{constructor(e){super();this.fn=e}run(e,n){return this.fn(e,n)}};var et=require("@ag-ui/core"),Bt=require("rxjs/operators"),nt=class extends U{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((0,Bt.filter)(t=>{if(t.type===et.EventType.TOOL_CALL_START){let s=t;return this.shouldFilterTool(s.toolCallName)?(this.blockedToolCallIds.add(s.toolCallId),!1):!0}if(t.type===et.EventType.TOOL_CALL_ARGS){let s=t;return!this.blockedToolCallIds.has(s.toolCallId)}if(t.type===et.EventType.TOOL_CALL_END){let s=t;return!this.blockedToolCallIds.has(s.toolCallId)}if(t.type===et.EventType.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 pe(i){let a=i.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 b(L({},i),{content:e})}return typeof a=="string"?i:b(L({},i),{content:""})}var Y=class extends U{run(a,e){let r=a,{parentRunId:n}=r,t=Rt(r,["parentRunId"]),s=b(L({},t),{messages:t.messages.map(pe)});return this.runNext(s,e)}};var Ut={name:"@ag-ui/client",author:"Markus Ecker <markus.ecker@gmail.com>",version:"0.0.42",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 Q=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:(0,q.v4)(),this.messages=M(t!=null?t:[]),this.state=M(s!=null?s:{}),this.debug=r!=null?r:!1,(0,jt.compareVersions)(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new Y)}get maxVersion(){return Ut.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 W(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:(0,q.v4)();let t=this.prepareRunAgentInput(a),s,r=new Set(this.messages.map(v=>v.id)),o=[{onRunFinishedEvent:v=>{s=v.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o),this.activeRunDetach$=new G.Subject;let l;this.activeRunCompletionPromise=new Promise(v=>{l=v});let d=(0,G.pipe)(()=>this.middlewares.length===0?this.run(t):this.middlewares.reduceRight((T,h)=>({run:c=>h.run(c,T)}),this).run(t),$(this.debug),V(this.debug),v=>v.pipe((0,At.takeUntil)(this.activeRunDetach$)),v=>this.apply(t,v,o),v=>this.processApplyEvents(t,v,o),(0,X.catchError)(v=>(this.isRunning=!1,this.onError(t,v,o))),(0,vt.finalize)(()=>{this.isRunning=!1,this.onFinalize(t,o),l==null||l(),l=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}));await(0,ht.lastValueFrom)(d((0,G.of)(null)));let _=M(this.messages).filter(v=>!r.has(v.id));return{result:s,newMessages:_}}finally{this.isRunning=!1}}connect(a){throw new yt.AGUIConnectNotImplementedError}async connectAgent(a,e){var n;try{this.isRunning=!0,this.agentId=(n=this.agentId)!=null?n:(0,q.v4)();let t=this.prepareRunAgentInput(a),s,r=new Set(this.messages.map(v=>v.id)),o=[{onRunFinishedEvent:v=>{s=v.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o),this.activeRunDetach$=new G.Subject;let l;this.activeRunCompletionPromise=new Promise(v=>{l=v});let d=(0,G.pipe)(()=>this.connect(t),$(this.debug),V(this.debug),v=>v.pipe((0,At.takeUntil)(this.activeRunDetach$)),v=>this.apply(t,v,o),v=>this.processApplyEvents(t,v,o),(0,X.catchError)(v=>(this.isRunning=!1,v instanceof yt.AGUIConnectNotImplementedError?G.EMPTY:this.onError(t,v,o))),(0,vt.finalize)(()=>{this.isRunning=!1,this.onFinalize(t,o),l==null||l(),l=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}));await(0,ht.lastValueFrom)(d((0,G.of)(null)));let _=M(this.messages).filter(v=>!r.has(v.id));return{result:s,newMessages:_}}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 J(a,e,this,n)}processApplyEvents(a,e,n){return e.pipe((0,X.tap)(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=M(this.messages).filter(o=>o.role!=="activity");return{threadId:this.threadId,runId:(a==null?void 0:a.runId)||(0,q.v4)(),tools:M((t=a==null?void 0:a.tools)!=null?t:[]),context:M((s=a==null?void 0:a.context)!=null?s:[]),forwardedProps:M((r=a==null?void 0:a.forwardedProps)!=null?r:{}),state:M(this.state),messages:n}}async onInitialize(a,e){let n=await N(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(0,G.from)(N(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((0,X.map)(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 N(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=M(this.messages),a.state=M(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=M(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=M(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:(0,q.v4)();let e=this.prepareRunAgentInput(a);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((r,o)=>({run:l=>o.run(l,r)}),this).run(e)).pipe($(this.debug),V(this.debug),dt(this.threadId,e.runId,this.agentId),s=>s.pipe((0,X.map)(r=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(r)),r))))}};var mt=class extends Q{constructor(e){var n;super(e);this.abortController=new AbortController;this.url=e.url,this.headers=M((n=e.headers)!=null?n:{})}requestInit(e){return{method:"POST",headers:b(L({},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=lt(this.url,this.requestInit(e));return Et(n)}clone(){var s;let e=super.clone();e.url=this.url,e.headers=M((s=this.headers)!=null?s:{});let n=new AbortController,t=this.abortController.signal;return t.aborted&&n.abort(t.reason),e.abortController=n,e}};var j=require("@ag-ui/core");function zt(i){let a=[],e=new Map,n=new Map;for(let t of i)if(t.type===j.EventType.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===j.EventType.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===j.EventType.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,Xt(r,o,a),e.delete(r)}else if(t.type===j.EventType.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===j.EventType.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===j.EventType.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,$t(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)Xt(t,s,a);for(let[t,s]of n)$t(t,s,a);return a}function Xt(i,a,e){if(a.start&&e.push(a.start),a.contents.length>0){let n=a.contents.map(s=>s.delta).join(""),t={type:j.EventType.TEXT_MESSAGE_CONTENT,messageId:i,delta:n};e.push(t)}a.end&&e.push(a.end);for(let n of a.otherEvents)e.push(n)}function $t(i,a,e){if(a.start&&e.push(a.start),a.args.length>0){let n=a.args.map(s=>s.delta).join(""),t={type:j.EventType.TOOL_CALL_ARGS,toolCallId:i,delta:n};e.push(t)}a.end&&e.push(a.end);for(let n of a.otherEvents)e.push(n)}D(P,require("@ag-ui/core"),module.exports);0&&(module.exports={AbstractAgent,BackwardCompatibility_0_0_39,FilterToolCallsMiddleware,FunctionMiddleware,HttpAgent,Middleware,compactEvents,convertToLegacyEvents,defaultApplyEvents,parseProtoStream,parseSSEStream,randomUUID,runHttpRequest,structuredClone_,transformChunks,transformHttpEventStream,verifyEvents,...require("@ag-ui/core")}); | ||
| //# sourceMappingURL=index.js.map |
+1
-1
@@ -7,3 +7,3 @@ var xt=Object.defineProperty,_t=Object.defineProperties;var Nt=Object.getOwnPropertyDescriptors;var Y=Object.getOwnPropertySymbols;var it=Object.prototype.hasOwnProperty,lt=Object.prototype.propertyIsEnumerable;var rt=(l,a,e)=>a in l?xt(l,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):l[a]=e,N=(l,a)=>{for(var e in a||(a={}))it.call(a,e)&&rt(l,e,a[e]);if(Y)for(var e of Y(a))lt.call(a,e)&&rt(l,e,a[e]);return l},G=(l,a)=>_t(l,Nt(a));var gt=(l,a)=>{var e={};for(var n in l)it.call(l,n)&&a.indexOf(n)<0&&(e[n]=l[n]);if(l!=null&&Y)for(var n of Y(l))a.indexOf(n)<0&<.call(l,n)&&(e[n]=l[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=l=>{if(typeof structuredClone=="function")return structuredClone(l);try{return JSON.parse(JSON.stringify(l))}catch(a){return N({},l)}};function Re(){return wt()}import{applyPatch as ct}from"fast-json-patch";async function x(l,a,e,n){let t=a,s=e,r;for(let o of l)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 $=(l,a,e,n)=>{let t=y(e.messages),s=y(l.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 I=await x(n,t,s,(E,g,p)=>{var m;return(m=E.onEvent)==null?void 0:m.call(E,{event:d,agent:e,input:l,messages:g,state:p})});if(o(I),I.stopPropagation===!0)return i();switch(d.type){case R.TEXT_MESSAGE_START:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onTextMessageStartEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l})});if(o(E),E.stopPropagation!==!0){let{messageId:g,role:p="assistant"}=d,m={id:g,role:p,content:""};t.push(m),o({messages:t})}return i()}case R.TEXT_MESSAGE_CONTENT:{let{messageId:E,delta:g}=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 x(n,t,s,(u,A,h)=>{var _;return(_=u.onTextMessageContentEvent)==null?void 0:_.call(u,{event:d,messages:A,state:h,agent:e,input:l,textMessageBuffer:typeof p.content=="string"?p.content:""})});if(o(m),m.stopPropagation!==!0){let u=typeof p.content=="string"?p.content:"";p.content=`${u}${g}`,o({messages:t})}return i()}case R.TEXT_MESSAGE_END:{let{messageId:E}=d,g=t.find(m=>m.id===E);if(!g)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${E}'`),i();let p=await x(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:l,textMessageBuffer:typeof g.content=="string"?g.content:""})});return o(p),await Promise.all(n.map(m=>{var u;(u=m.onNewMessage)==null||u.call(m,{message:g,messages:t,state:s,agent:e,input:l})})),i()}case R.TOOL_CALL_START:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onToolCallStartEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l})});if(o(E),E.stopPropagation!==!0){let{toolCallId:g,toolCallName:p,parentMessageId:m}=d,u;m&&t.length>0&&t[t.length-1].id===m?u=t[t.length-1]:(u={id:m||g,role:"assistant",toolCalls:[]},t.push(u)),(T=u.toolCalls)!=null||(u.toolCalls=[]),u.toolCalls.push({id:g,type:"function",function:{name:p,arguments:""}}),o({messages:t})}return i()}case R.TOOL_CALL_ARGS:{let{toolCallId:E,delta:g}=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 x(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:l,toolCallBuffer:H,toolCallName:F,partialToolCallArgs:X})});return o(u),u.stopPropagation!==!0&&(m.function.arguments+=g,o({messages:t})),i()}case R.TOOL_CALL_END:{let{toolCallId:E}=d,g=t.find(u=>{var A;return(A=u.toolCalls)==null?void 0:A.some(h=>h.id===E)});if(!g)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${E}'`),i();let p=g.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 x(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:l,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:l})})),i()}case R.TOOL_CALL_RESULT:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onToolCallResultEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l})});if(o(E),E.stopPropagation!==!0){let{messageId:g,toolCallId:p,content:m,role:u}=d,A={id:g,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:l})})),o({messages:t})}return i()}case R.STATE_SNAPSHOT:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onStateSnapshotEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l})});if(o(E),E.stopPropagation!==!0){let{snapshot:g}=d;s=g,o({state:s})}return i()}case R.STATE_DELTA:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onStateDeltaEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l})});if(o(E),E.stopPropagation!==!0){let{delta:g}=d;try{s=ct(s,g,!0,!1).newDocument,o({state:s})}catch(p){let m=p instanceof Error?p.message:String(p);console.warn(`Failed to apply state patch: | ||
| `),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=l=>{let a=new Xt,e=new Uint8Array(0);l.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=l=>{let a=new zt,e=new Kt,n=!1;return l.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,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=l=>{if(typeof l=="string")return l;if(!Array.isArray(l))return;let a=l.filter(e=>e.type==="text").map(e=>e.text).filter(e=>e.length>0);if(a.length!==0)return a.join(` | ||
| `)},at=(l,a,e)=>n=>{let t={},s=!0,r=!0,o="",i=null,d=null,I=[],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 I.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=I.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(g=>g.tool==b.function.name);if(E)try{let g=JSON.parse(ie(b.function.arguments));E.tool_argument&&E.tool_argument in g?(T(G(N({},t),{[E.state_key]:g[E.tool_argument]})),U=!0):E.tool_argument||(T(G(N({},t),{[E.state_key]:g})),U=!0)}catch(g){}}return[{type:C.enum.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...U?[{type:C.enum.AgentStateMessage,threadId:l,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:l,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:l,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:l,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:l,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,I=[],d=null,[{type:C.enum.AgentStateMessage,threadId:l,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!0}];case D.STEP_FINISHED:return I=[],d=null,[{type:C.enum.AgentStateMessage,threadId:l,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!1}];default:return[]}}))};function ge(l){var e;let a=[];for(let n of l)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 l)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=l=>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,l&&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,l&&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 I=i,S=[];if((t!=="text"||I.messageId!==void 0&&I.messageId!==(e==null?void 0:e.messageId))&&S.push(...o()),t!=="text"){if(I.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:I.messageId},t="text";let c={type:M.TEXT_MESSAGE_START,messageId:I.messageId,role:I.role||"assistant"};S.push(c),l&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(c))}if(I.delta!==void 0){let c={type:M.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:I.delta};S.push(c),l&&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),l&&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),l&&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(l){let a=l.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({},l),{content:e})}return typeof a=="string"?l:G(N({},l),{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.42-alpha.3",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 I=y(this.messages).filter(S=>!r.has(S.id));return{result:s,newMessages:I}}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 I=y(this.messages).filter(S=>!r.has(S.id));return{result:s,newMessages:I}}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 x(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(x(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 x(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(l){let a=[],e=new Map,n=new Map;for(let t of l)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,It(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)It(t,s,a);return a}function Rt(l,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:l,delta:n};e.push(t)}a.end&&e.push(a.end);for(let n of a.otherEvents)e.push(n)}function It(l,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:l,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}; | ||
| `)},at=(l,a,e)=>n=>{let t={},s=!0,r=!0,o="",i=null,d=null,I=[],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 I.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=I.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(g=>g.tool==b.function.name);if(E)try{let g=JSON.parse(ie(b.function.arguments));E.tool_argument&&E.tool_argument in g?(T(G(N({},t),{[E.state_key]:g[E.tool_argument]})),U=!0):E.tool_argument||(T(G(N({},t),{[E.state_key]:g})),U=!0)}catch(g){}}return[{type:C.enum.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...U?[{type:C.enum.AgentStateMessage,threadId:l,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:l,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:l,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:l,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:l,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,I=[],d=null,[{type:C.enum.AgentStateMessage,threadId:l,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!0}];case D.STEP_FINISHED:return I=[],d=null,[{type:C.enum.AgentStateMessage,threadId:l,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!1}];default:return[]}}))};function ge(l){var e;let a=[];for(let n of l)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 l)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=l=>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,l&&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,l&&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 I=i,S=[];if((t!=="text"||I.messageId!==void 0&&I.messageId!==(e==null?void 0:e.messageId))&&S.push(...o()),t!=="text"){if(I.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:I.messageId},t="text";let c={type:M.TEXT_MESSAGE_START,messageId:I.messageId,role:I.role||"assistant"};S.push(c),l&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(c))}if(I.delta!==void 0){let c={type:M.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:I.delta};S.push(c),l&&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),l&&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),l&&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(l){let a=l.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({},l),{content:e})}return typeof a=="string"?l:G(N({},l),{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.42",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 I=y(this.messages).filter(S=>!r.has(S.id));return{result:s,newMessages:I}}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 I=y(this.messages).filter(S=>!r.has(S.id));return{result:s,newMessages:I}}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 x(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(x(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 x(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(l){let a=[],e=new Map,n=new Map;for(let t of l)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,It(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)It(t,s,a);return a}function Rt(l,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:l,delta:n};e.push(t)}a.end&&e.push(a.end);for(let n of a.otherEvents)e.push(n)}function It(l,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:l,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}; | ||
| //# sourceMappingURL=index.mjs.map |
+4
-4
| { | ||
| "name": "@ag-ui/client", | ||
| "author": "Markus Ecker <markus.ecker@gmail.com>", | ||
| "version": "0.0.42-alpha.3", | ||
| "version": "0.0.42", | ||
| "private": false, | ||
@@ -25,5 +25,5 @@ "publishConfig": { | ||
| "zod": "^3.22.4", | ||
| "@ag-ui/core": "0.0.42-alpha.3", | ||
| "@ag-ui/proto": "0.0.42-alpha.3", | ||
| "@ag-ui/encoder": "0.0.42-alpha.3" | ||
| "@ag-ui/core": "0.0.42", | ||
| "@ag-ui/encoder": "0.0.42", | ||
| "@ag-ui/proto": "0.0.42" | ||
| }, | ||
@@ -30,0 +30,0 @@ "devDependencies": { |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 2 instances in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 2 instances in 1 package
482939
-0.01%+ Added
+ Added
+ Added
- Removed
- Removed
- Removed
Updated
Updated
Updated