@ag-ui/client 0.0.40-alpha.3 → 0.0.40
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.d.mts +4 -6
- package/dist/index.d.ts +4 -6
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var
|
|
1
|
+
var ne=Object.defineProperty,ae=Object.defineProperties;var se=Object.getOwnPropertyDescriptors;var W=Object.getOwnPropertySymbols;var oe=Object.prototype.hasOwnProperty,re=Object.prototype.propertyIsEnumerable;var V=(u,o,n)=>o in u?ne(u,o,{enumerable:!0,configurable:!0,writable:!0,value:n}):u[o]=n,L=(u,o)=>{for(var n in o||(o={}))oe.call(o,n)&&V(u,n,o[n]);if(W)for(var n of W(o))re.call(o,n)&&V(u,n,o[n]);return u},H=(u,o)=>ae(u,se(o));import{EventType as v}from"@ag-ui/core";import{mergeAll as ie,defaultIfEmpty as le,concatMap as ge}from"rxjs/operators";import{of as ce,EMPTY as Ee}from"rxjs";var C=u=>{if(typeof structuredClone=="function")return structuredClone(u);try{return JSON.parse(JSON.stringify(u))}catch(o){return L({},u)}};import{applyPatch as ue}from"fast-json-patch";async function y(u,o,n,a){let e=o,s=n,l;for(let r of u)try{let i=await a(r,C(e),C(s));if(i===void 0)continue;if(i.messages!==void 0&&(e=i.messages),i.state!==void 0&&(s=i.state),l=i.stopPropagation,l===!0)break}catch(i){process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0||console.error("Subscriber error:",i);continue}return L(L(L({},JSON.stringify(e)!==JSON.stringify(o)?{messages:e}:{}),JSON.stringify(s)!==JSON.stringify(n)?{state:s}:{}),l!==void 0?{stopPropagation:l}:{})}import pe from"untruncate-json";var K=(u,o,n,a)=>{let e=C(u.messages),s=C(u.state),l={},r=E=>{E.messages!==void 0&&(e=E.messages,l.messages=E.messages),E.state!==void 0&&(s=E.state,l.state=E.state)},i=()=>{let E=C(l);return l={},E.messages!==void 0||E.state!==void 0?ce(E):Ee};return o.pipe(ge(async E=>{var d;let h=await y(a,e,s,(g,t,S)=>{var m;return(m=g.onEvent)==null?void 0:m.call(g,{event:E,agent:n,input:u,messages:t,state:S})});if(r(h),h.stopPropagation===!0)return i();switch(E.type){case v.TEXT_MESSAGE_START:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onTextMessageStartEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});if(r(g),g.stopPropagation!==!0){let{messageId:t,role:S="assistant"}=E,m={id:t,role:S,content:""};e.push(m),r({messages:e})}return i()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:g,delta:t}=E,S=e.find(c=>c.id===g);if(!S)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${g}'`),i();let m=await y(a,e,s,(c,T,x)=>{var O,P;return(P=c.onTextMessageContentEvent)==null?void 0:P.call(c,{event:E,messages:T,state:x,agent:n,input:u,textMessageBuffer:(O=S.content)!=null?O:""})});return r(m),m.stopPropagation!==!0&&(S.content=(S.content||"")+t,r({messages:e})),i()}case v.TEXT_MESSAGE_END:{let{messageId:g}=E,t=e.find(m=>m.id===g);if(!t)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${g}'`),i();let S=await y(a,e,s,(m,c,T)=>{var x,O;return(O=m.onTextMessageEndEvent)==null?void 0:O.call(m,{event:E,messages:c,state:T,agent:n,input:u,textMessageBuffer:(x=t.content)!=null?x:""})});return r(S),await Promise.all(a.map(m=>{var c;(c=m.onNewMessage)==null||c.call(m,{message:t,messages:e,state:s,agent:n,input:u})})),i()}case v.TOOL_CALL_START:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onToolCallStartEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});if(r(g),g.stopPropagation!==!0){let{toolCallId:t,toolCallName:S,parentMessageId:m}=E,c;m&&e.length>0&&e[e.length-1].id===m?c=e[e.length-1]:(c={id:m||t,role:"assistant",toolCalls:[]},e.push(c)),(d=c.toolCalls)!=null||(c.toolCalls=[]),c.toolCalls.push({id:t,type:"function",function:{name:S,arguments:""}}),r({messages:e})}return i()}case v.TOOL_CALL_ARGS:{let{toolCallId:g,delta:t}=E,S=e.find(T=>{var x;return(x=T.toolCalls)==null?void 0:x.some(O=>O.id===g)});if(!S)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${g}'`),i();let m=S.toolCalls.find(T=>T.id===g);if(!m)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${g}'`),i();let c=await y(a,e,s,(T,x,O)=>{var k;let P=m.function.arguments,F=m.function.name,D={};try{D=pe(P)}catch(We){}return(k=T.onToolCallArgsEvent)==null?void 0:k.call(T,{event:E,messages:x,state:O,agent:n,input:u,toolCallBuffer:P,toolCallName:F,partialToolCallArgs:D})});return r(c),c.stopPropagation!==!0&&(m.function.arguments+=t,r({messages:e})),i()}case v.TOOL_CALL_END:{let{toolCallId:g}=E,t=e.find(c=>{var T;return(T=c.toolCalls)==null?void 0:T.some(x=>x.id===g)});if(!t)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${g}'`),i();let S=t.toolCalls.find(c=>c.id===g);if(!S)return console.warn(`TOOL_CALL_END: No tool call found with ID '${g}'`),i();let m=await y(a,e,s,(c,T,x)=>{var D;let O=S.function.arguments,P=S.function.name,F={};try{F=JSON.parse(O)}catch(k){}return(D=c.onToolCallEndEvent)==null?void 0:D.call(c,{event:E,messages:T,state:x,agent:n,input:u,toolCallName:P,toolCallArgs:F})});return r(m),await Promise.all(a.map(c=>{var T;(T=c.onNewToolCall)==null||T.call(c,{toolCall:S,messages:e,state:s,agent:n,input:u})})),i()}case v.TOOL_CALL_RESULT:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onToolCallResultEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});if(r(g),g.stopPropagation!==!0){let{messageId:t,toolCallId:S,content:m,role:c}=E,T={id:t,toolCallId:S,role:c||"tool",content:m};e.push(T),await Promise.all(a.map(x=>{var O;(O=x.onNewMessage)==null||O.call(x,{message:T,messages:e,state:s,agent:n,input:u})})),r({messages:e})}return i()}case v.STATE_SNAPSHOT:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onStateSnapshotEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});if(r(g),g.stopPropagation!==!0){let{snapshot:t}=E;s=t,r({state:s})}return i()}case v.STATE_DELTA:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onStateDeltaEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});if(r(g),g.stopPropagation!==!0){let{delta:t}=E;try{s=ue(s,t,!0,!1).newDocument,r({state:s})}catch(S){let m=S instanceof Error?S.message:String(S);console.warn(`Failed to apply state patch:
|
|
2
2
|
Current state: ${JSON.stringify(s,null,2)}
|
|
3
3
|
Patch operations: ${JSON.stringify(t,null,2)}
|
|
4
|
-
Error: ${m}`)}}return i()}case
|
|
5
|
-
`),r=[];for(let i of
|
|
6
|
-
`),l=JSON.parse(i);o.next(l)}catch(i){o.error(i)}}return o.asObservable()};import{Subject as _e}from"rxjs";import*as Z from"@ag-ui/proto";var J=E=>{let o=new _e,n=new Uint8Array(0);E.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 c=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<c)break;try{let r=n.slice(4,c),i=Z.decode(r);o.next(i),n=n.slice(c)}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";var j=E=>{let o=new Ie,n=new xe,a=!1;return E.subscribe({next:e=>{n.next(e),e.type==="headers"&&!a?(a=!0,e.headers.get("content-type")===ee.AGUI_MEDIA_TYPE?J(n).subscribe({next:c=>o.next(c),error:c=>o.error(c),complete:()=>o.complete()}):b(n).subscribe({next:c=>{try{let r=Ne.parse(c);o.next(r)}catch(r){o.error(r)}},error:c=>o.error(c),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 Ke}from"rxjs/operators";import{applyPatch as ze}from"fast-json-patch";import{EventType as x}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"]),Le=p.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Oe=p.object({type:p.literal(A.enum.TextMessageStart),messageId:p.string(),parentMessageId:p.string().optional(),role:p.string().optional()}),we=p.object({type:p.literal(A.enum.TextMessageContent),messageId:p.string(),content:p.string()}),Pe=p.object({type:p.literal(A.enum.TextMessageEnd),messageId:p.string()}),De=p.object({type:p.literal(A.enum.ActionExecutionStart),actionExecutionId:p.string(),actionName:p.string(),parentMessageId:p.string().optional()}),He=p.object({type:p.literal(A.enum.ActionExecutionArgs),actionExecutionId:p.string(),args:p.string()}),Ge=p.object({type:p.literal(A.enum.ActionExecutionEnd),actionExecutionId:p.string()}),Fe=p.object({type:p.literal(A.enum.ActionExecutionResult),actionName:p.string(),actionExecutionId:p.string(),result:p.string()}),Ue=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()}),Xe=p.object({type:p.literal(A.enum.MetaEvent),name:Le,value:p.any()}),ke=p.object({type:p.literal(A.enum.RunError),message:p.string(),code:p.string().optional()}),An=p.discriminatedUnion("type",[Oe,we,Pe,De,He,Ge,Fe,Ue,Xe,ke]),hn=p.object({id:p.string(),role:p.string(),content:p.string(),parentMessageId:p.string().optional()}),vn=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 Be from"untruncate-json";var $=(E,o,n)=>a=>{let e={},s=!0,c=!0,r="",i=null,l=null,h=[],w={},S=g=>{typeof g=="object"&&g!==null&&("messages"in g&&delete g.messages,e=g)};return a.pipe(Ke(g=>{switch(g.type){case x.TEXT_MESSAGE_START:{let t=g;return[{type:A.enum.TextMessageStart,messageId:t.messageId,role:t.role}]}case x.TEXT_MESSAGE_CONTENT:{let t=g;return[{type:A.enum.TextMessageContent,messageId:t.messageId,content:t.delta}]}case x.TEXT_MESSAGE_END:{let t=g;return[{type:A.enum.TextMessageEnd,messageId:t.messageId}]}case x.TOOL_CALL_START:{let t=g;return h.push({id:t.toolCallId,type:"function",function:{name:t.toolCallName,arguments:""}}),c=!0,w[t.toolCallId]=t.toolCallName,[{type:A.enum.ActionExecutionStart,actionExecutionId:t.toolCallId,actionName:t.toolCallName,parentMessageId:t.parentMessageId}]}case x.TOOL_CALL_ARGS:{let t=g,d=h.find(u=>u.id===t.toolCallId);if(!d)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${t.toolCallId}'`),[];d.function.arguments+=t.delta;let m=!1;if(l){let u=l.find(T=>T.tool==d.function.name);if(u)try{let T=JSON.parse(Be(d.function.arguments));u.tool_argument&&u.tool_argument in T?(S(H(L({},e),{[u.state_key]:T[u.tool_argument]})),m=!0):u.tool_argument||(S(H(L({},e),{[u.state_key]:T})),m=!0)}catch(T){}}return[{type:A.enum.ActionExecutionArgs,actionExecutionId:t.toolCallId,args:t.delta},...m?[{type:A.enum.AgentStateMessage,threadId:E,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:c}]:[]]}case x.TOOL_CALL_END:{let t=g;return[{type:A.enum.ActionExecutionEnd,actionExecutionId:t.toolCallId}]}case x.TOOL_CALL_RESULT:{let t=g;return[{type:A.enum.ActionExecutionResult,actionExecutionId:t.toolCallId,result:t.content,actionName:w[t.toolCallId]||"unknown"}]}case x.RAW:return[];case x.CUSTOM:{let t=g;switch(t.name){case"Exit":s=!1;break;case"PredictState":l=t.value;break}return[{type:A.enum.MetaEvent,name:t.name,value:t.value}]}case x.STATE_SNAPSHOT:return S(g.snapshot),[{type:A.enum.AgentStateMessage,threadId:E,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:c}];case x.STATE_DELTA:{let d=ze(e,g.delta,!0,!1);return d?(S(d.newDocument),[{type:A.enum.AgentStateMessage,threadId:E,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:c}]):[]}case x.MESSAGES_SNAPSHOT:return i=g.messages,[{type:A.enum.AgentStateMessage,threadId:E,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(L(L({},e),i?{messages:i}:{})),active:!0}];case x.RUN_STARTED:return[];case x.RUN_FINISHED:return i&&(e.messages=i),Object.keys(e).length===0?[]:[{type:A.enum.AgentStateMessage,threadId:E,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(L(L({},e),i?{messages:be(i)}:{})),active:!1}];case x.RUN_ERROR:{let t=g;return[{type:A.enum.RunError,message:t.message,code:t.code}]}case x.STEP_STARTED:return r=g.stepName,h=[],l=null,[{type:A.enum.AgentStateMessage,threadId:E,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:!0}];case x.STEP_FINISHED:return h=[],l=null,[{type:A.enum.AgentStateMessage,threadId:E,agentName:n,nodeName:r,runId:o,running:s,role:"assistant",state:JSON.stringify(e),active:!1}];default:return[]}}))};function be(E){var n;let o=[];for(let a of E)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 c of E)if(c.role==="assistant"&&((n=c.toolCalls)!=null&&n.length)){for(let r of c.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 F}from"uuid";import{catchError as te,map as ne,tap as $e}from"rxjs/operators";import{finalize as ae}from"rxjs/operators";import{pipe as se,from as qe,of as oe,EMPTY as We}from"rxjs";import{lastValueFrom as re}from"rxjs";import{mergeMap as Je,finalize as je}from"rxjs";import{EventType as f}from"@ag-ui/core";var k=E=>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,E&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(i)),i},c=()=>{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,E&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(i)),i},r=()=>e==="text"?[s()]:e==="tool"?[c()]:[];return o.pipe(Je(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),E&&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),E&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(t))}return w;case f.TOOL_CALL_CHUNK:let S=i,g=[];if((e!=="tool"||S.toolCallId!==void 0&&S.toolCallId!==(a==null?void 0:a.toolCallId))&&g.push(...r()),e!=="tool"){if(S.toolCallId===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallId");if(S.toolCallName===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallName");a={toolCallId:S.toolCallId,toolCallName:S.toolCallName,parentMessageId:S.parentMessageId},e="tool";let t={type:f.TOOL_CALL_START,toolCallId:S.toolCallId,toolCallName:S.toolCallName,parentMessageId:S.parentMessageId};g.push(t),E&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(t))}if(S.delta!==void 0){let t={type:f.TOOL_CALL_ARGS,toolCallId:a.toolCallId,delta:S.delta};g.push(t),E&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(t))}return g}let l=i.type}),je(()=>r()))};import{AGUIConnectNotImplementedError as ie}from"@ag-ui/core";var U=class{constructor({agentId:o,description:n,threadId:a,initialMessages:e,initialState:s,debug:c}={}){this.debug=!1;this.subscribers=[];this.isRunning=!1;this.agentId=o,this.description=n!=null?n:"",this.threadId=a!=null?a:F(),this.messages=v(e!=null?e:[]),this.state=v(s!=null?s:{}),this.debug=c!=null?c:!1}subscribe(o){return this.subscribers.push(o),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(n=>n!==o)}}}async runAgent(o,n){var a;try{this.isRunning=!0,this.agentId=(a=this.agentId)!=null?a:F();let e=this.prepareRunAgentInput(o),s,c=new Set(this.messages.map(l=>l.id)),r=[{onRunFinishedEvent:l=>{s=l.result}},...this.subscribers,n!=null?n:{}];await this.onInitialize(e,r);let i=se(()=>this.run(e),k(this.debug),G(this.debug),l=>this.apply(e,l,r),l=>this.processApplyEvents(e,l,r),te(l=>(this.isRunning=!1,this.onError(e,l,r))),ae(()=>{this.isRunning=!1,this.onFinalize(e,r)}));return re(i(oe(null))).then(()=>{let l=v(this.messages).filter(h=>!c.has(h.id));return{result:s,newMessages:l}})}finally{this.isRunning=!1}}connect(o){throw new ie}async connectAgent(o,n){var a;try{this.isRunning=!0,this.agentId=(a=this.agentId)!=null?a:F();let e=this.prepareRunAgentInput(o),s,c=new Set(this.messages.map(l=>l.id)),r=[{onRunFinishedEvent:l=>{s=l.result}},...this.subscribers,n!=null?n:{}];await this.onInitialize(e,r);let i=se(()=>this.connect(e),k(this.debug),G(this.debug),l=>this.apply(e,l,r),l=>this.processApplyEvents(e,l,r),te(l=>(this.isRunning=!1,l instanceof ie?We:this.onError(e,l,r))),ae(()=>{this.isRunning=!1,this.onFinalize(e,r)}));return re(i(oe(null))).then(()=>{let l=v(this.messages).filter(h=>!c.has(h.id));return{result:s,newMessages:l}})}finally{this.isRunning=!1}}abortRun(){}apply(o,n,a){return z(o,n,this,a)}processApplyEvents(o,n,a){return n.pipe($e(e=>{e.messages&&(this.messages=e.messages,a.forEach(s=>{var c;(c=s.onMessagesChanged)==null||c.call(s,{messages:this.messages,state:this.state,agent:this,input:o})})),e.state&&(this.state=e.state,a.forEach(s=>{var c;(c=s.onStateChanged)==null||c.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)||F(),tools:v((n=o==null?void 0:o.tools)!=null?n:[]),context:v((a=o==null?void 0:o.context)!=null?a:[]),forwardedProps:v((e=o==null?void 0:o.forwardedProps)!=null?e:{}),state:v(this.state),messages:v(this.messages)}}async onInitialize(o,n){let a=await M(n,this.messages,this.state,(e,s,c)=>{var r;return(r=e.onRunInitialized)==null?void 0:r.call(e,{messages:s,state:c,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 qe(M(a,this.messages,this.state,(e,s,c)=>{var r;return(r=e.onRunFailed)==null?void 0:r.call(e,{error:n,messages:s,state:c,agent:this,input:o})})).pipe(ne(e=>{let s=e;if((s.messages!==void 0||s.state!==void 0)&&(s.messages!==void 0&&(this.messages=s.messages,a.forEach(c=>{var r;(r=c.onMessagesChanged)==null||r.call(c,{messages:this.messages,state:this.state,agent:this,input:o})})),s.state!==void 0&&(this.state=s.state,a.forEach(c=>{var r;(r=c.onStateChanged)==null||r.call(c,{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 M(n,this.messages,this.state,(e,s,c)=>{var r;return(r=e.onRunFinalized)==null?void 0:r.call(e,{messages:s,state:c,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));return o.agentId=this.agentId,o.description=this.description,o.threadId=this.threadId,o.messages=v(this.messages),o.state=v(this.state),o.debug=this.debug,o.isRunning=this.isRunning,o.subscribers=[...this.subscribers],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 c of this.subscribers)await((a=c.onNewToolCall)==null?void 0:a.call(c,{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 c of this.subscribers)await((n=c.onNewMessage)==null?void 0:n.call(c,{message:s,messages:this.messages,state:this.state,agent:this}));if(s.role==="assistant"&&s.toolCalls)for(let c of s.toolCalls)for(let r of this.subscribers)await((a=r.onNewToolCall)==null?void 0:a.call(r,{toolCall:c,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=v(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=v(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:F();let n=this.prepareRunAgentInput(o);return this.run(n).pipe(k(this.debug),G(this.debug),$(this.threadId,n.runId,this.agentId),e=>e.pipe(ne(s=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(s)),s))))}};var q=class extends U{constructor(n){var a;super(n);this.abortController=new AbortController;this.url=n.url,this.headers=v((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=B(this.url,this.requestInit(n));return j(a)}clone(){var s;let n=super.clone();n.url=this.url,n.headers=v((s=this.headers)!=null?s:{});let a=new AbortController,e=this.abortController.signal;return e.aborted&&a.abort(e.reason),n.abortController=a,n}};export*from"@ag-ui/core";export{U as AbstractAgent,q as HttpAgent,$ as convertToLegacyEvents,z as defaultApplyEvents,J as parseProtoStream,b as parseSSEStream,B as runHttpRequest,j as transformHttpEventStream,G as verifyEvents};
|
|
4
|
+
Error: ${m}`)}}return i()}case v.MESSAGES_SNAPSHOT:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onMessagesSnapshotEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});if(r(g),g.stopPropagation!==!0){let{messages:t}=E;e=t,r({messages:e})}return i()}case v.RAW:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onRawEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});return r(g),i()}case v.CUSTOM:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onCustomEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});return r(g),i()}case v.RUN_STARTED:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onRunStartedEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});return r(g),i()}case v.RUN_FINISHED:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onRunFinishedEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u,result:E.result})});return r(g),i()}case v.RUN_ERROR:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onRunErrorEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});return r(g),i()}case v.STEP_STARTED:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onStepStartedEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});return r(g),i()}case v.STEP_FINISHED:{let g=await y(a,e,s,(t,S,m)=>{var c;return(c=t.onStepFinishedEvent)==null?void 0:c.call(t,{event:E,messages:S,state:m,agent:n,input:u})});return r(g),i()}case v.TEXT_MESSAGE_CHUNK:throw new Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case v.TOOL_CALL_CHUNK:throw new Error("TOOL_CALL_CHUNK must be tranformed before being applied");case v.THINKING_START:return i();case v.THINKING_END:return i();case v.THINKING_TEXT_MESSAGE_START:return i();case v.THINKING_TEXT_MESSAGE_CONTENT:return i();case v.THINKING_TEXT_MESSAGE_END:return i()}let w=E.type;return i()}),ie(),a.length>0?le({}):E=>E)};import{EventType as M,AGUIError as R}from"@ag-ui/core";import{throwError as _,of as N}from"rxjs";import{mergeMap as me}from"rxjs/operators";var U=u=>o=>{let n=new Map,a=new Map,e=!1,s=!1,l=!1,r=new Map,i=!1,E=!1,h=!1,w=()=>{n.clear(),a.clear(),r.clear(),i=!1,E=!1,e=!1,s=!1,h=!0};return o.pipe(me(d=>{let g=d.type;if(u&&console.debug("[VERIFY]:",JSON.stringify(d)),s)return _(()=>new R(`Cannot send event type '${g}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(e&&g!==M.RUN_ERROR&&g!==M.RUN_STARTED)return _(()=>new R(`Cannot send event type '${g}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(l){if(g===M.RUN_STARTED){if(h&&!e)return _(()=>new R("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));e&&w()}}else if(l=!0,g!==M.RUN_STARTED&&g!==M.RUN_ERROR)return _(()=>new R("First event must be 'RUN_STARTED'"));switch(g){case M.TEXT_MESSAGE_START:{let t=d.messageId;return n.has(t)?_(()=>new R(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${t}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(n.set(t,!0),N(d))}case M.TEXT_MESSAGE_CONTENT:{let t=d.messageId;return n.has(t)?N(d):_(()=>new R(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${t}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case M.TEXT_MESSAGE_END:{let t=d.messageId;return n.has(t)?(n.delete(t),N(d)):_(()=>new R(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${t}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case M.TOOL_CALL_START:{let t=d.toolCallId;return a.has(t)?_(()=>new R(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${t}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(a.set(t,!0),N(d))}case M.TOOL_CALL_ARGS:{let t=d.toolCallId;return a.has(t)?N(d):_(()=>new R(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${t}'. Start a tool call with 'TOOL_CALL_START' first.`))}case M.TOOL_CALL_END:{let t=d.toolCallId;return a.has(t)?(a.delete(t),N(d)):_(()=>new R(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${t}'. A 'TOOL_CALL_START' event must be sent first.`))}case M.STEP_STARTED:{let t=d.stepName;return r.has(t)?_(()=>new R(`Step "${t}" is already active for 'STEP_STARTED'`)):(r.set(t,!0),N(d))}case M.STEP_FINISHED:{let t=d.stepName;return r.has(t)?(r.delete(t),N(d)):_(()=>new R(`Cannot send 'STEP_FINISHED' for step "${t}" that was not started`))}case M.RUN_STARTED:return h=!0,N(d);case M.RUN_FINISHED:{if(r.size>0){let t=Array.from(r.keys()).join(", ");return _(()=>new R(`Cannot send 'RUN_FINISHED' while steps are still active: ${t}`))}if(n.size>0){let t=Array.from(n.keys()).join(", ");return _(()=>new R(`Cannot send 'RUN_FINISHED' while text messages are still active: ${t}`))}if(a.size>0){let t=Array.from(a.keys()).join(", ");return _(()=>new R(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${t}`))}return e=!0,N(d)}case M.RUN_ERROR:return s=!0,N(d);case M.CUSTOM:return N(d);case M.THINKING_TEXT_MESSAGE_START:return i?E?_(()=>new R("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(E=!0,N(d)):_(()=>new R("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case M.THINKING_TEXT_MESSAGE_CONTENT:return E?N(d):_(()=>new R("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case M.THINKING_TEXT_MESSAGE_END:return E?(E=!1,N(d)):_(()=>new R("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case M.THINKING_START:return i?_(()=>new R("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(i=!0,N(d));case M.THINKING_END:return i?(i=!1,N(d)):_(()=>new R("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return N(d)}}))};import{EventSchemas as he}from"@ag-ui/core";import{Subject as ye,ReplaySubject as Me}from"rxjs";import{Observable as Se,from as Y,defer as de,throwError as Q}from"rxjs";import{mergeMap as fe,switchMap as Te}from"rxjs/operators";var j=(u,o)=>de(()=>Y(fetch(u,o))).pipe(Te(n=>{var s;if(!n.ok){let l=n.headers.get("content-type")||"";return Y(n.text()).pipe(fe(r=>{let i=r;if(l.includes("application/json"))try{i=JSON.parse(r)}catch(h){}let E=new Error(`HTTP ${n.status}: ${typeof i=="string"?i:JSON.stringify(i)}`);return E.status=n.status,E.payload=i,Q(()=>E)}))}let a={type:"headers",status:n.status,headers:n.headers},e=(s=n.body)==null?void 0:s.getReader();return e?new Se(l=>(l.next(a),(async()=>{try{for(;;){let{done:r,value:i}=await e.read();if(r)break;let E={type:"data",data:i};l.next(E)}l.complete()}catch(r){l.error(r)}})(),()=>{e.cancel().catch(r=>{if((r==null?void 0:r.name)!=="AbortError")throw r})})):Q(()=>new Error("Failed to getReader() from response"))}));import{Subject as Ae}from"rxjs";var z=u=>{let o=new Ae,n=new TextDecoder("utf-8",{fatal:!1}),a="";u.subscribe({next:s=>{if(s.type!=="headers"&&s.type==="data"&&s.data){let l=n.decode(s.data,{stream:!0});a+=l;let r=a.split(/\n\n/);a=r.pop()||"";for(let i of r)e(i)}},error:s=>o.error(s),complete:()=>{a&&(a+=n.decode(),e(a)),o.complete()}});function e(s){let l=s.split(`
|
|
5
|
+
`),r=[];for(let i of l)i.startsWith("data: ")&&r.push(i.slice(6));if(r.length>0)try{let i=r.join(`
|
|
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};
|
|
7
7
|
//# sourceMappingURL=index.mjs.map
|