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