@ag-ui/client 0.0.39 → 0.0.40-alpha.2
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 +3 -0
- package/dist/index.d.ts +3 -0
- 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 le=Object.defineProperty,ge=Object.defineProperties;var ce=Object.getOwnPropertyDescriptors;var W=Object.getOwnPropertySymbols;var ue=Object.prototype.hasOwnProperty,Ee=Object.prototype.propertyIsEnumerable;var V=(E,o,n)=>o in E?le(E,o,{enumerable:!0,configurable:!0,writable:!0,value:n}):E[o]=n,L=(E,o)=>{for(var n in o||(o={}))ue.call(o,n)&&V(E,n,o[n]);if(W)for(var n of W(o))Ee.call(o,n)&&V(E,n,o[n]);return E},H=(E,o)=>ge(E,ce(o));import{EventType as v}from"@ag-ui/core";import{mergeAll as pe,defaultIfEmpty as me,concatMap as de}from"rxjs/operators";import{of as Se,EMPTY as fe}from"rxjs";var M=E=>{if(typeof structuredClone=="function")return structuredClone(E);try{return JSON.parse(JSON.stringify(E))}catch(o){return L({},E)}};import{applyPatch as Te}from"fast-json-patch";async function y(E,o,n,a){let e=o,s=n,c;for(let r of E)try{let i=await a(r,M(e),M(s));if(i===void 0)continue;if(i.messages!==void 0&&(e=i.messages),i.state!==void 0&&(s=i.state),c=i.stopPropagation,c===!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}:{}),c!==void 0?{stopPropagation:c}:{})}import Ae from"untruncate-json";var z=(E,o,n,a)=>{let e=M(E.messages),s=M(E.state),c={},r=l=>{l.messages!==void 0&&(e=l.messages,c.messages=l.messages),l.state!==void 0&&(s=l.state,c.state=l.state)},i=()=>{let l=M(c);return c={},l.messages!==void 0||l.state!==void 0?Se(l):fe};return o.pipe(de(async l=>{var S;let h=await y(a,e,s,(g,t,d)=>{var m;return(m=g.onEvent)==null?void 0:m.call(g,{event:l,agent:n,input:E,messages:t,state:d})});if(r(h),h.stopPropagation===!0)return i();switch(l.type){case v.TEXT_MESSAGE_START:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onTextMessageStartEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E})});if(r(g),g.stopPropagation!==!0){let{messageId:t,role:d="assistant"}=l,m={id:t,role:d,content:""};e.push(m),r({messages:e})}return i()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:g,delta:t}=l,d=e.find(u=>u.id===g);if(!d)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${g}'`),i();let m=await y(a,e,s,(u,T,I)=>{var O,P;return(P=u.onTextMessageContentEvent)==null?void 0:P.call(u,{event:l,messages:T,state:I,agent:n,input:E,textMessageBuffer:(O=d.content)!=null?O:""})});return r(m),m.stopPropagation!==!0&&(d.content=(d.content||"")+t,r({messages:e})),i()}case v.TEXT_MESSAGE_END:{let{messageId:g}=l,t=e.find(m=>m.id===g);if(!t)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${g}'`),i();let d=await y(a,e,s,(m,u,T)=>{var I,O;return(O=m.onTextMessageEndEvent)==null?void 0:O.call(m,{event:l,messages:u,state:T,agent:n,input:E,textMessageBuffer:(I=t.content)!=null?I:""})});return r(d),await Promise.all(a.map(m=>{var u;(u=m.onNewMessage)==null||u.call(m,{message:t,messages:e,state:s,agent:n,input:E})})),i()}case v.TOOL_CALL_START:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onToolCallStartEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E})});if(r(g),g.stopPropagation!==!0){let{toolCallId:t,toolCallName:d,parentMessageId:m}=l,u;m&&e.length>0&&e[e.length-1].id===m?u=e[e.length-1]:(u={id:m||t,role:"assistant",toolCalls:[]},e.push(u)),(S=u.toolCalls)!=null||(u.toolCalls=[]),u.toolCalls.push({id:t,type:"function",function:{name:d,arguments:""}}),r({messages:e})}return i()}case v.TOOL_CALL_ARGS:{let{toolCallId:g,delta:t}=l,d=e.find(T=>{var I;return(I=T.toolCalls)==null?void 0:I.some(O=>O.id===g)});if(!d)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${g}'`),i();let m=d.toolCalls.find(T=>T.id===g);if(!m)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${g}'`),i();let u=await y(a,e,s,(T,I,O)=>{var K;let P=m.function.arguments,X=m.function.name,D={};try{D=Ae(P)}catch(Ve){}return(K=T.onToolCallArgsEvent)==null?void 0:K.call(T,{event:l,messages:I,state:O,agent:n,input:E,toolCallBuffer:P,toolCallName:X,partialToolCallArgs:D})});return r(u),u.stopPropagation!==!0&&(m.function.arguments+=t,r({messages:e})),i()}case v.TOOL_CALL_END:{let{toolCallId:g}=l,t=e.find(u=>{var T;return(T=u.toolCalls)==null?void 0:T.some(I=>I.id===g)});if(!t)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${g}'`),i();let d=t.toolCalls.find(u=>u.id===g);if(!d)return console.warn(`TOOL_CALL_END: No tool call found with ID '${g}'`),i();let m=await y(a,e,s,(u,T,I)=>{var D;let O=d.function.arguments,P=d.function.name,X={};try{X=JSON.parse(O)}catch(K){}return(D=u.onToolCallEndEvent)==null?void 0:D.call(u,{event:l,messages:T,state:I,agent:n,input:E,toolCallName:P,toolCallArgs:X})});return r(m),await Promise.all(a.map(u=>{var T;(T=u.onNewToolCall)==null||T.call(u,{toolCall:d,messages:e,state:s,agent:n,input:E})})),i()}case v.TOOL_CALL_RESULT:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onToolCallResultEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E})});if(r(g),g.stopPropagation!==!0){let{messageId:t,toolCallId:d,content:m,role:u}=l,T={id:t,toolCallId:d,role:u||"tool",content:m};e.push(T),await Promise.all(a.map(I=>{var O;(O=I.onNewMessage)==null||O.call(I,{message:T,messages:e,state:s,agent:n,input:E})})),r({messages:e})}return i()}case v.STATE_SNAPSHOT:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onStateSnapshotEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E})});if(r(g),g.stopPropagation!==!0){let{snapshot:t}=l;s=t,r({state:s})}return i()}case v.STATE_DELTA:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onStateDeltaEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E})});if(r(g),g.stopPropagation!==!0){let{delta:t}=l;try{s=Te(s,t,!0,!1).newDocument,r({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
3
|
Patch operations: ${JSON.stringify(t,null,2)}
|
|
4
|
-
Error: ${m}`)}}return i()}case v.MESSAGES_SNAPSHOT:{let g=await y(a,e,s,(t,
|
|
5
|
-
`),r=[];for(let i of
|
|
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,J as transformHttpEventStream,U as verifyEvents};
|
|
4
|
+
Error: ${m}`)}}return i()}case v.MESSAGES_SNAPSHOT:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onMessagesSnapshotEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E})});if(r(g),g.stopPropagation!==!0){let{messages:t}=l;e=t,r({messages:e})}return i()}case v.RAW:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onRawEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E})});return r(g),i()}case v.CUSTOM:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onCustomEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E})});return r(g),i()}case v.RUN_STARTED:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onRunStartedEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E})});return r(g),i()}case v.RUN_FINISHED:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onRunFinishedEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E,result:l.result})});return r(g),i()}case v.RUN_ERROR:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onRunErrorEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E})});return r(g),i()}case v.STEP_STARTED:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onStepStartedEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E})});return r(g),i()}case v.STEP_FINISHED:{let g=await y(a,e,s,(t,d,m)=>{var u;return(u=t.onStepFinishedEvent)==null?void 0:u.call(t,{event:l,messages:d,state:m,agent:n,input:E})});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=l.type;return i()}),pe(),a.length>0?me({}):l=>l)};import{EventType as C,AGUIError as R}from"@ag-ui/core";import{throwError as _,of as N}from"rxjs";import{mergeMap as he}from"rxjs/operators";var G=E=>o=>{let n=new Map,a=new Map,e=!1,s=!1,c=!1,r=new Map,i=!1,l=!1,h=!1,w=()=>{n.clear(),a.clear(),r.clear(),i=!1,l=!1,e=!1,s=!1,h=!0};return o.pipe(he(S=>{let g=S.type;if(E&&console.debug("[VERIFY]:",JSON.stringify(S)),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!==C.RUN_ERROR&&g!==C.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(c){if(g===C.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(c=!0,g!==C.RUN_STARTED&&g!==C.RUN_ERROR)return _(()=>new R("First event must be 'RUN_STARTED'"));switch(g){case C.TEXT_MESSAGE_START:{let t=S.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(S))}case C.TEXT_MESSAGE_CONTENT:{let t=S.messageId;return n.has(t)?N(S):_(()=>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 C.TEXT_MESSAGE_END:{let t=S.messageId;return n.has(t)?(n.delete(t),N(S)):_(()=>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 C.TOOL_CALL_START:{let t=S.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(S))}case C.TOOL_CALL_ARGS:{let t=S.toolCallId;return a.has(t)?N(S):_(()=>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 C.TOOL_CALL_END:{let t=S.toolCallId;return a.has(t)?(a.delete(t),N(S)):_(()=>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 C.STEP_STARTED:{let t=S.stepName;return r.has(t)?_(()=>new R(`Step "${t}" is already active for 'STEP_STARTED'`)):(r.set(t,!0),N(S))}case C.STEP_FINISHED:{let t=S.stepName;return r.has(t)?(r.delete(t),N(S)):_(()=>new R(`Cannot send 'STEP_FINISHED' for step "${t}" that was not started`))}case C.RUN_STARTED:return h=!0,N(S);case C.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(S)}case C.RUN_ERROR:return s=!0,N(S);case C.CUSTOM:return N(S);case C.THINKING_TEXT_MESSAGE_START:return i?l?_(()=>new R("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(l=!0,N(S)):_(()=>new R("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case C.THINKING_TEXT_MESSAGE_CONTENT:return l?N(S):_(()=>new R("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case C.THINKING_TEXT_MESSAGE_END:return l?(l=!1,N(S)):_(()=>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 C.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(S));case C.THINKING_END:return i?(i=!1,N(S)):_(()=>new R("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return N(S)}}))};import{EventSchemas as Ne}from"@ag-ui/core";import{Subject as Ie,ReplaySubject as xe}from"rxjs";import{Observable as ve,from as Y,defer as ye,throwError as Q}from"rxjs";import{mergeMap as Me,switchMap as Ce}from"rxjs/operators";var B=(E,o)=>ye(()=>Y(fetch(E,o))).pipe(Ce(n=>{var s;if(!n.ok){let c=n.headers.get("content-type")||"";return Y(n.text()).pipe(Me(r=>{let i=r;if(c.includes("application/json"))try{i=JSON.parse(r)}catch(h){}let l=new Error(`HTTP ${n.status}: ${typeof i=="string"?i:JSON.stringify(i)}`);return l.status=n.status,l.payload=i,Q(()=>l)}))}let a={type:"headers",status:n.status,headers:n.headers},e=(s=n.body)==null?void 0:s.getReader();return e?new ve(c=>(c.next(a),(async()=>{try{for(;;){let{done:r,value:i}=await e.read();if(r)break;let l={type:"data",data:i};c.next(l)}c.complete()}catch(r){c.error(r)}})(),()=>{e.cancel()})):Q(()=>new Error("Failed to getReader() from response"))}));import{Subject as Re}from"rxjs";var j=E=>{let o=new Re,n=new TextDecoder("utf-8",{fatal:!1}),a="";E.subscribe({next:s=>{if(s.type!=="headers"&&s.type==="data"&&s.data){let c=n.decode(s.data,{stream:!0});a+=c;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 c=s.split(`
|
|
5
|
+
`),r=[];for(let i of c)i.startsWith("data: ")&&r.push(i.slice(6));if(r.length>0)try{let i=r.join(`
|
|
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 $=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()}):j(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 b=(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:je(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 je(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 be}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 $e}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}),$e(()=>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=M(e!=null?e:[]),this.state=M(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=M(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=M(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(be(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:M((n=o==null?void 0:o.tools)!=null?n:[]),context:M((a=o==null?void 0:o.context)!=null?a:[]),forwardedProps:M((e=o==null?void 0:o.forwardedProps)!=null?e:{}),state:M(this.state),messages:M(this.messages)}}async onInitialize(o,n){let a=await y(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(y(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 y(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));for(let n of Object.getOwnPropertyNames(this)){let a=this[n];typeof a!="function"&&(o[n]=M(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 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=M(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=M(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),b(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=M((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 $(a)}};export*from"@ag-ui/core";export{U as AbstractAgent,q as HttpAgent,b as convertToLegacyEvents,z as defaultApplyEvents,J as parseProtoStream,j as parseSSEStream,B as runHttpRequest,$ as transformHttpEventStream,G as verifyEvents};
|
|
7
7
|
//# sourceMappingURL=index.mjs.map
|