@ag-ui/client 0.0.42-alpha.3 → 0.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -4,5 +4,5 @@ Patch operations: ${JSON.stringify(g,null,2)}
4
4
  Error: ${m}`)}}return i()}case R.MESSAGES_SNAPSHOT:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onMessagesSnapshotEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l})});if(o(E),E.stopPropagation!==!0){let{messages:g}=d;t=g,o({messages:t})}return i()}case R.ACTIVITY_SNAPSHOT:{let E=d,g=t.findIndex(h=>h.id===E.messageId),p=g>=0?t[g]:void 0,m=(p==null?void 0:p.role)==="activity"?p:void 0,u=(v=E.replace)!=null?v:!0,A=await x(n,t,s,(h,_,H)=>{var F;return(F=h.onActivitySnapshotEvent)==null?void 0:F.call(h,{event:E,messages:_,state:H,agent:e,input:l,activityMessage:m,existingMessage:p})});if(o(A),A.stopPropagation!==!0){let h={id:E.messageId,role:"activity",activityType:E.activityType,content:y(E.content)},_;g===-1?(t.push(h),_=h):m?u&&(t[g]=G(N({},m),{activityType:E.activityType,content:y(E.content)})):u&&(t[g]=h,_=h),o({messages:t}),_&&await Promise.all(n.map(H=>{var F;return(F=H.onNewMessage)==null?void 0:F.call(H,{message:_,messages:t,state:s,agent:e,input:l})}))}return i()}case R.ACTIVITY_DELTA:{let E=d,g=t.findIndex(A=>A.id===E.messageId);if(g===-1)return console.warn(`ACTIVITY_DELTA: No message found with ID '${E.messageId}' to apply patch`),i();let p=t[g];if(p.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${E.messageId}' is not an activity message`),i();let m=p,u=await x(n,t,s,(A,h,_)=>{var H;return(H=A.onActivityDeltaEvent)==null?void 0:H.call(A,{event:E,messages:h,state:_,agent:e,input:l,activityMessage:m})});if(o(u),u.stopPropagation!==!0)try{let A=y((c=m.content)!=null?c:{}),_=ct(A,(b=E.patch)!=null?b:[],!0,!1).newDocument;t[g]=G(N({},m),{content:y(_),activityType:E.activityType}),o({messages:t})}catch(A){let h=A instanceof Error?A.message:String(A);console.warn(`Failed to apply activity patch for '${E.messageId}': ${h}`)}return i()}case R.RAW:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onRawEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l})});return o(E),i()}case R.CUSTOM:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onCustomEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l})});return o(E),i()}case R.RUN_STARTED:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onRunStartedEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l})});if(o(E),E.stopPropagation!==!0){let g=d;if((U=g.input)!=null&&U.messages){for(let p of g.input.messages)t.find(u=>u.id===p.id)||t.push(p);o({messages:t})}}return i()}case R.RUN_FINISHED:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onRunFinishedEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l,result:d.result})});return o(E),i()}case R.RUN_ERROR:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onRunErrorEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l})});return o(E),i()}case R.STEP_STARTED:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onStepStartedEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l})});return o(E),i()}case R.STEP_FINISHED:{let E=await x(n,t,s,(g,p,m)=>{var u;return(u=g.onStepFinishedEvent)==null?void 0:u.call(g,{event:d,messages:p,state:m,agent:e,input:l})});return o(E),i()}case R.TEXT_MESSAGE_CHUNK:throw new Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case R.TOOL_CALL_CHUNK:throw new Error("TOOL_CALL_CHUNK must be tranformed before being applied");case R.THINKING_START:return i();case R.THINKING_END:return i();case R.THINKING_TEXT_MESSAGE_START:return i();case R.THINKING_TEXT_MESSAGE_CONTENT:return i();case R.THINKING_TEXT_MESSAGE_END:return i()}let S=d.type;return i()}),Lt(),n.length>0?Ot({}):d=>d)};import{EventType as w,AGUIError as L}from"@ag-ui/core";import{throwError as O,of as P}from"rxjs";import{mergeMap as bt}from"rxjs/operators";var z=l=>a=>{let e=new Map,n=new Map,t=!1,s=!1,r=!1,o=new Map,i=!1,d=!1,I=!1,S=()=>{e.clear(),n.clear(),o.clear(),i=!1,d=!1,t=!1,s=!1,I=!0};return a.pipe(bt(T=>{let v=T.type;if(l&&console.debug("[VERIFY]:",JSON.stringify(T)),s)return O(()=>new L(`Cannot send event type '${v}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(t&&v!==w.RUN_ERROR&&v!==w.RUN_STARTED)return O(()=>new L(`Cannot send event type '${v}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(r){if(v===w.RUN_STARTED){if(I&&!t)return O(()=>new L("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));t&&S()}}else if(r=!0,v!==w.RUN_STARTED&&v!==w.RUN_ERROR)return O(()=>new L("First event must be 'RUN_STARTED'"));switch(v){case w.TEXT_MESSAGE_START:{let c=T.messageId;return e.has(c)?O(()=>new L(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${c}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(e.set(c,!0),P(T))}case w.TEXT_MESSAGE_CONTENT:{let c=T.messageId;return e.has(c)?P(T):O(()=>new L(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${c}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case w.TEXT_MESSAGE_END:{let c=T.messageId;return e.has(c)?(e.delete(c),P(T)):O(()=>new L(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${c}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case w.TOOL_CALL_START:{let c=T.toolCallId;return n.has(c)?O(()=>new L(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${c}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(n.set(c,!0),P(T))}case w.TOOL_CALL_ARGS:{let c=T.toolCallId;return n.has(c)?P(T):O(()=>new L(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${c}'. Start a tool call with 'TOOL_CALL_START' first.`))}case w.TOOL_CALL_END:{let c=T.toolCallId;return n.has(c)?(n.delete(c),P(T)):O(()=>new L(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${c}'. A 'TOOL_CALL_START' event must be sent first.`))}case w.STEP_STARTED:{let c=T.stepName;return o.has(c)?O(()=>new L(`Step "${c}" is already active for 'STEP_STARTED'`)):(o.set(c,!0),P(T))}case w.STEP_FINISHED:{let c=T.stepName;return o.has(c)?(o.delete(c),P(T)):O(()=>new L(`Cannot send 'STEP_FINISHED' for step "${c}" that was not started`))}case w.RUN_STARTED:return I=!0,P(T);case w.RUN_FINISHED:{if(o.size>0){let c=Array.from(o.keys()).join(", ");return O(()=>new L(`Cannot send 'RUN_FINISHED' while steps are still active: ${c}`))}if(e.size>0){let c=Array.from(e.keys()).join(", ");return O(()=>new L(`Cannot send 'RUN_FINISHED' while text messages are still active: ${c}`))}if(n.size>0){let c=Array.from(n.keys()).join(", ");return O(()=>new L(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${c}`))}return t=!0,P(T)}case w.RUN_ERROR:return s=!0,P(T);case w.CUSTOM:return P(T);case w.THINKING_TEXT_MESSAGE_START:return i?d?O(()=>new L("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(d=!0,P(T)):O(()=>new L("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case w.THINKING_TEXT_MESSAGE_CONTENT:return d?P(T):O(()=>new L("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case w.THINKING_TEXT_MESSAGE_END:return d?(d=!1,P(T)):O(()=>new L("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case w.THINKING_START:return i?O(()=>new L("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(i=!0,P(T));case w.THINKING_END:return i?(i=!1,P(T)):O(()=>new L("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return P(T)}}))};import{EventSchemas as $t}from"@ag-ui/core";import{Subject as zt,ReplaySubject as Kt}from"rxjs";import{Observable as Ft,from as ut,defer as kt,throwError as Et}from"rxjs";import{mergeMap as Bt,switchMap as Ut}from"rxjs/operators";var tt=(l,a)=>kt(()=>ut(fetch(l,a))).pipe(Ut(e=>{var s;if(!e.ok){let r=e.headers.get("content-type")||"";return ut(e.text()).pipe(Bt(o=>{let i=o;if(r.includes("application/json"))try{i=JSON.parse(o)}catch(I){}let d=new Error(`HTTP ${e.status}: ${typeof i=="string"?i:JSON.stringify(i)}`);return d.status=e.status,d.payload=i,Et(()=>d)}))}let n={type:"headers",status:e.status,headers:e.headers},t=(s=e.body)==null?void 0:s.getReader();return t?new Ft(r=>(r.next(n),(async()=>{try{for(;;){let{done:o,value:i}=await t.read();if(o)break;let d={type:"data",data:i};r.next(d)}r.complete()}catch(o){r.error(o)}})(),()=>{t.cancel().catch(o=>{if((o==null?void 0:o.name)!=="AbortError")throw o})})):Et(()=>new Error("Failed to getReader() from response"))}));import{Subject as jt}from"rxjs";var et=l=>{let a=new jt,e=new TextDecoder("utf-8",{fatal:!1}),n="";l.subscribe({next:s=>{if(s.type!=="headers"&&s.type==="data"&&s.data){let r=e.decode(s.data,{stream:!0});n+=r;let o=n.split(/\n\n/);n=o.pop()||"";for(let i of o)t(i)}},error:s=>a.error(s),complete:()=>{n&&(n+=e.decode(),t(n)),a.complete()}});function t(s){let r=s.split(`
5
5
  `),o=[];for(let i of r)i.startsWith("data: ")&&o.push(i.slice(6));if(o.length>0)try{let i=o.join(`
6
6
  `),d=JSON.parse(i);a.next(d)}catch(i){a.error(i)}}return a.asObservable()};import{Subject as Xt}from"rxjs";import*as dt from"@ag-ui/proto";var nt=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(`
7
- `)},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};
7
+ `)},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};
8
8
  //# sourceMappingURL=index.mjs.map