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