@ag-ui/client 0.0.36 → 0.0.37

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 CHANGED
@@ -21,13 +21,16 @@ declare const LegacyRuntimeProtocolEvent: z.ZodDiscriminatedUnion<"type", [z.Zod
21
21
  type: z.ZodLiteral<"TextMessageStart">;
22
22
  messageId: z.ZodString;
23
23
  parentMessageId: z.ZodOptional<z.ZodString>;
24
+ role: z.ZodOptional<z.ZodString>;
24
25
  }, "strip", z.ZodTypeAny, {
25
26
  type: "TextMessageStart";
26
27
  messageId: string;
28
+ role?: string | undefined;
27
29
  parentMessageId?: string | undefined;
28
30
  }, {
29
31
  type: "TextMessageStart";
30
32
  messageId: string;
33
+ role?: string | undefined;
31
34
  parentMessageId?: string | undefined;
32
35
  }>, z.ZodObject<{
33
36
  type: z.ZodLiteral<"TextMessageContent">;
@@ -353,4 +356,4 @@ declare class HttpAgent extends AbstractAgent {
353
356
  run(input: RunAgentInput): Observable<BaseEvent>;
354
357
  }
355
358
 
356
- export { AbstractAgent, type AgentConfig, HttpAgent, convertToLegacyEvents, defaultApplyEvents, parseProtoStream, parseSSEStream, runHttpRequest, transformHttpEventStream, verifyEvents };
359
+ export { AbstractAgent, type AgentConfig, HttpAgent, type HttpAgentConfig, type RunAgentParameters, type RunAgentResult, convertToLegacyEvents, defaultApplyEvents, parseProtoStream, parseSSEStream, runHttpRequest, transformHttpEventStream, verifyEvents };
package/dist/index.d.ts CHANGED
@@ -21,13 +21,16 @@ declare const LegacyRuntimeProtocolEvent: z.ZodDiscriminatedUnion<"type", [z.Zod
21
21
  type: z.ZodLiteral<"TextMessageStart">;
22
22
  messageId: z.ZodString;
23
23
  parentMessageId: z.ZodOptional<z.ZodString>;
24
+ role: z.ZodOptional<z.ZodString>;
24
25
  }, "strip", z.ZodTypeAny, {
25
26
  type: "TextMessageStart";
26
27
  messageId: string;
28
+ role?: string | undefined;
27
29
  parentMessageId?: string | undefined;
28
30
  }, {
29
31
  type: "TextMessageStart";
30
32
  messageId: string;
33
+ role?: string | undefined;
31
34
  parentMessageId?: string | undefined;
32
35
  }>, z.ZodObject<{
33
36
  type: z.ZodLiteral<"TextMessageContent">;
@@ -353,4 +356,4 @@ declare class HttpAgent extends AbstractAgent {
353
356
  run(input: RunAgentInput): Observable<BaseEvent>;
354
357
  }
355
358
 
356
- export { AbstractAgent, type AgentConfig, HttpAgent, convertToLegacyEvents, defaultApplyEvents, parseProtoStream, parseSSEStream, runHttpRequest, transformHttpEventStream, verifyEvents };
359
+ export { AbstractAgent, type AgentConfig, HttpAgent, type HttpAgentConfig, type RunAgentParameters, type RunAgentResult, convertToLegacyEvents, defaultApplyEvents, parseProtoStream, parseSSEStream, runHttpRequest, transformHttpEventStream, verifyEvents };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";var ye=Object.create;var k=Object.defineProperty,Me=Object.defineProperties,Ce=Object.getOwnPropertyDescriptor,_e=Object.getOwnPropertyDescriptors,Re=Object.getOwnPropertyNames,se=Object.getOwnPropertySymbols,Ne=Object.getPrototypeOf,re=Object.prototype.hasOwnProperty,xe=Object.prototype.propertyIsEnumerable;var oe=(i,s,t)=>s in i?k(i,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[s]=t,x=(i,s)=>{for(var t in s||(s={}))re.call(s,t)&&oe(i,t,s[t]);if(se)for(var t of se(s))xe.call(s,t)&&oe(i,t,s[t]);return i},B=(i,s)=>Me(i,_e(s));var Le=(i,s)=>{for(var t in s)k(i,t,{get:s[t],enumerable:!0})},j=(i,s,t,n)=>{if(s&&typeof s=="object"||typeof s=="function")for(let e of Re(s))!re.call(i,e)&&e!==t&&k(i,e,{get:()=>s[e],enumerable:!(n=Ce(s,e))||n.enumerable});return i},I=(i,s,t)=>(j(i,s,"default"),t&&j(t,s,"default")),$=(i,s,t)=>(t=i!=null?ye(Ne(i)):{},j(s||!i||!i.__esModule?k(t,"default",{value:i,enumerable:!0}):t,i)),Ie=i=>j(k({},"__esModule",{value:!0}),i);var L={};Le(L,{AbstractAgent:()=>G,HttpAgent:()=>ne,convertToLegacyEvents:()=>ee,defaultApplyEvents:()=>q,parseProtoStream:()=>Y,parseSSEStream:()=>b,runHttpRequest:()=>V,transformHttpEventStream:()=>Z,verifyEvents:()=>z});module.exports=Ie(L);var y=require("@ag-ui/core"),H=require("rxjs/operators"),W=require("rxjs");var _=i=>{if(typeof structuredClone=="function")return structuredClone(i);try{return JSON.parse(JSON.stringify(i))}catch(s){return x({},i)}};var ie=require("fast-json-patch");async function M(i,s,t,n){let e=s,o=t,l;for(let r of i)try{let g=await n(r,_(e),_(o));if(g===void 0)continue;if(g.messages!==void 0&&(e=g.messages),g.state!==void 0&&(o=g.state),l=g.stopPropagation,l===!0)break}catch(g){process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0||console.error("Subscriber error:",g);continue}return x(x(x({},JSON.stringify(e)!==JSON.stringify(s)?{messages:e}:{}),JSON.stringify(o)!==JSON.stringify(t)?{state:o}:{}),l!==void 0?{stopPropagation:l}:{})}var le=$(require("untruncate-json")),q=(i,s,t,n)=>{let e=_(i.messages),o=_(i.state),l={},r=u=>{u.messages!==void 0&&(e=u.messages,l.messages=u.messages),u.state!==void 0&&(o=u.state,l.state=u.state)},g=()=>{let u=_(l);return l={},u.messages!==void 0||u.state!==void 0?(0,W.of)(u):W.EMPTY};return s.pipe((0,H.concatMap)(async u=>{var A;let T=await M(n,e,o,(p,a,c)=>{var d;return(d=p.onEvent)==null?void 0:d.call(p,{event:u,agent:t,input:i,messages:a,state:c})});if(r(T),T.stopPropagation===!0)return g();switch(u.type){case y.EventType.TEXT_MESSAGE_START:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onTextMessageStartEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i})});if(r(p),p.stopPropagation!==!0){let{messageId:a,role:c}=u,d={id:a,role:c,content:""};e.push(d),r({messages:e})}return g()}case y.EventType.TEXT_MESSAGE_CONTENT:{let p=await M(n,e,o,(a,c,d)=>{var E,R;return(R=a.onTextMessageContentEvent)==null?void 0:R.call(a,{event:u,messages:c,state:d,agent:t,input:i,textMessageBuffer:(E=c[c.length-1].content)!=null?E:""})});if(r(p),p.stopPropagation!==!0){let{delta:a}=u,c=e[e.length-1];c.content=c.content+a,r({messages:e})}return g()}case y.EventType.TEXT_MESSAGE_END:{let p=await M(n,e,o,(a,c,d)=>{var E,R;return(R=a.onTextMessageEndEvent)==null?void 0:R.call(a,{event:u,messages:c,state:d,agent:t,input:i,textMessageBuffer:(E=c[c.length-1].content)!=null?E:""})});return r(p),await Promise.all(n.map(a=>{var c;(c=a.onNewMessage)==null||c.call(a,{message:e[e.length-1],messages:e,state:o,agent:t,input:i})})),g()}case y.EventType.TOOL_CALL_START:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onToolCallStartEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i})});if(r(p),p.stopPropagation!==!0){let{toolCallId:a,toolCallName:c,parentMessageId:d}=u,E;d&&e.length>0&&e[e.length-1].id===d?E=e[e.length-1]:(E={id:d||a,role:"assistant",toolCalls:[]},e.push(E)),(A=E.toolCalls)!=null||(E.toolCalls=[]),E.toolCalls.push({id:a,type:"function",function:{name:c,arguments:""}}),r({messages:e})}return g()}case y.EventType.TOOL_CALL_ARGS:{let p=await M(n,e,o,(a,c,d)=>{var X,U,K;let E=(U=(X=c[c.length-1])==null?void 0:X.toolCalls)!=null?U:[],R=E.length>0?E[E.length-1].function.arguments:"",P=E.length>0?E[E.length-1].function.name:"",O={};try{O=(0,le.default)(R)}catch(he){}return(K=a.onToolCallArgsEvent)==null?void 0:K.call(a,{event:u,messages:c,state:d,agent:t,input:i,toolCallBuffer:R,toolCallName:P,partialToolCallArgs:O})});if(r(p),p.stopPropagation!==!0){let{delta:a}=u,c=e[e.length-1],d=c.toolCalls[c.toolCalls.length-1];d.function.arguments+=a,r({messages:e})}return g()}case y.EventType.TOOL_CALL_END:{let p=await M(n,e,o,(a,c,d)=>{var X,U,K;let E=(U=(X=c[c.length-1])==null?void 0:X.toolCalls)!=null?U:[],R=E.length>0?E[E.length-1].function.arguments:"",P=E.length>0?E[E.length-1].function.name:"",O={};try{O=JSON.parse(R)}catch(he){}return(K=a.onToolCallEndEvent)==null?void 0:K.call(a,{event:u,messages:c,state:d,agent:t,input:i,toolCallName:P,toolCallArgs:O})});return r(p),await Promise.all(n.map(a=>{var c;(c=a.onNewToolCall)==null||c.call(a,{toolCall:e[e.length-1].toolCalls[e[e.length-1].toolCalls.length-1],messages:e,state:o,agent:t,input:i})})),g()}case y.EventType.TOOL_CALL_RESULT:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onToolCallResultEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i})});if(r(p),p.stopPropagation!==!0){let{messageId:a,toolCallId:c,content:d,role:E}=u,R={id:a,toolCallId:c,role:E||"tool",content:d};e.push(R),await Promise.all(n.map(P=>{var O;(O=P.onNewMessage)==null||O.call(P,{message:R,messages:e,state:o,agent:t,input:i})})),r({messages:e})}return g()}case y.EventType.STATE_SNAPSHOT:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onStateSnapshotEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i})});if(r(p),p.stopPropagation!==!0){let{snapshot:a}=u;o=a,r({state:o})}return g()}case y.EventType.STATE_DELTA:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onStateDeltaEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i})});if(r(p),p.stopPropagation!==!0){let{delta:a}=u;try{o=(0,ie.applyPatch)(o,a,!0,!1).newDocument,r({state:o})}catch(c){let d=c instanceof Error?c.message:String(c);console.warn(`Failed to apply state patch:
1
+ "use strict";var Me=Object.create;var K=Object.defineProperty,ye=Object.defineProperties,Ce=Object.getOwnPropertyDescriptor,Re=Object.getOwnPropertyDescriptors,_e=Object.getOwnPropertyNames,oe=Object.getOwnPropertySymbols,Ne=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty,xe=Object.prototype.propertyIsEnumerable;var re=(i,s,n)=>s in i?K(i,s,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[s]=n,x=(i,s)=>{for(var n in s||(s={}))ie.call(s,n)&&re(i,n,s[n]);if(oe)for(var n of oe(s))xe.call(s,n)&&re(i,n,s[n]);return i},k=(i,s)=>ye(i,Re(s));var Ie=(i,s)=>{for(var n in s)K(i,n,{get:s[n],enumerable:!0})},J=(i,s,n,a)=>{if(s&&typeof s=="object"||typeof s=="function")for(let e of _e(s))!ie.call(i,e)&&e!==n&&K(i,e,{get:()=>s[e],enumerable:!(a=Ce(s,e))||a.enumerable});return i},w=(i,s,n)=>(J(i,s,"default"),n&&J(n,s,"default")),$=(i,s,n)=>(n=i!=null?Me(Ne(i)):{},J(s||!i||!i.__esModule?K(n,"default",{value:i,enumerable:!0}):n,i)),Le=i=>J(K({},"__esModule",{value:!0}),i);var O={};Ie(O,{AbstractAgent:()=>F,HttpAgent:()=>ne,convertToLegacyEvents:()=>ee,defaultApplyEvents:()=>W,parseProtoStream:()=>Y,parseSSEStream:()=>V,runHttpRequest:()=>b,transformHttpEventStream:()=>Z,verifyEvents:()=>z});module.exports=Le(O);var M=require("@ag-ui/core"),G=require("rxjs/operators"),q=require("rxjs");var R=i=>{if(typeof structuredClone=="function")return structuredClone(i);try{return JSON.parse(JSON.stringify(i))}catch(s){return x({},i)}};var le=require("fast-json-patch");async function y(i,s,n,a){let e=s,o=n,c;for(let r of i)try{let g=await a(r,R(e),R(o));if(g===void 0)continue;if(g.messages!==void 0&&(e=g.messages),g.state!==void 0&&(o=g.state),c=g.stopPropagation,c===!0)break}catch(g){process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0||console.error("Subscriber error:",g);continue}return x(x(x({},JSON.stringify(e)!==JSON.stringify(s)?{messages:e}:{}),JSON.stringify(o)!==JSON.stringify(n)?{state:o}:{}),c!==void 0?{stopPropagation:c}:{})}var ge=$(require("untruncate-json")),W=(i,s,n,a)=>{let e=R(i.messages),o=R(i.state),c={},r=u=>{u.messages!==void 0&&(e=u.messages,c.messages=u.messages),u.state!==void 0&&(o=u.state,c.state=u.state)},g=()=>{let u=R(c);return c={},u.messages!==void 0||u.state!==void 0?(0,q.of)(u):q.EMPTY};return s.pipe((0,G.concatMap)(async u=>{var d;let C=await y(a,e,o,(l,t,S)=>{var m;return(m=l.onEvent)==null?void 0:m.call(l,{event:u,agent:n,input:i,messages:t,state:S})});if(r(C),C.stopPropagation===!0)return g();switch(u.type){case M.EventType.TEXT_MESSAGE_START:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onTextMessageStartEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i})});if(r(l),l.stopPropagation!==!0){let{messageId:t,role:S="assistant"}=u,m={id:t,role:S,content:""};e.push(m),r({messages:e})}return g()}case M.EventType.TEXT_MESSAGE_CONTENT:{let{messageId:l,delta:t}=u,S=e.find(E=>E.id===l);if(!S)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${l}'`),g();let m=await y(a,e,o,(E,v,N)=>{var I,D;return(D=E.onTextMessageContentEvent)==null?void 0:D.call(E,{event:u,messages:v,state:N,agent:n,input:i,textMessageBuffer:(I=S.content)!=null?I:""})});return r(m),m.stopPropagation!==!0&&(S.content=(S.content||"")+t,r({messages:e})),g()}case M.EventType.TEXT_MESSAGE_END:{let{messageId:l}=u,t=e.find(m=>m.id===l);if(!t)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${l}'`),g();let S=await y(a,e,o,(m,E,v)=>{var N,I;return(I=m.onTextMessageEndEvent)==null?void 0:I.call(m,{event:u,messages:E,state:v,agent:n,input:i,textMessageBuffer:(N=t.content)!=null?N:""})});return r(S),await Promise.all(a.map(m=>{var E;(E=m.onNewMessage)==null||E.call(m,{message:t,messages:e,state:o,agent:n,input:i})})),g()}case M.EventType.TOOL_CALL_START:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onToolCallStartEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i})});if(r(l),l.stopPropagation!==!0){let{toolCallId:t,toolCallName:S,parentMessageId:m}=u,E;m&&e.length>0&&e[e.length-1].id===m?E=e[e.length-1]:(E={id:m||t,role:"assistant",toolCalls:[]},e.push(E)),(d=E.toolCalls)!=null||(E.toolCalls=[]),E.toolCalls.push({id:t,type:"function",function:{name:S,arguments:""}}),r({messages:e})}return g()}case M.EventType.TOOL_CALL_ARGS:{let{toolCallId:l,delta:t}=u,S=e.find(v=>{var N;return(N=v.toolCalls)==null?void 0:N.some(I=>I.id===l)});if(!S)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${l}'`),g();let m=S.toolCalls.find(v=>v.id===l);if(!m)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${l}'`),g();let E=await y(a,e,o,(v,N,I)=>{var ae;let D=m.function.arguments,j=m.function.name,X={};try{X=(0,ge.default)(D)}catch(Be){}return(ae=v.onToolCallArgsEvent)==null?void 0:ae.call(v,{event:u,messages:N,state:I,agent:n,input:i,toolCallBuffer:D,toolCallName:j,partialToolCallArgs:X})});return r(E),E.stopPropagation!==!0&&(m.function.arguments+=t,r({messages:e})),g()}case M.EventType.TOOL_CALL_END:{let{toolCallId:l}=u,t=e.find(E=>{var v;return(v=E.toolCalls)==null?void 0:v.some(N=>N.id===l)});if(!t)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${l}'`),g();let S=t.toolCalls.find(E=>E.id===l);if(!S)return console.warn(`TOOL_CALL_END: No tool call found with ID '${l}'`),g();let m=await y(a,e,o,(E,v,N)=>{var X;let I=S.function.arguments,D=S.function.name,j={};try{j=JSON.parse(I)}catch(ae){}return(X=E.onToolCallEndEvent)==null?void 0:X.call(E,{event:u,messages:v,state:N,agent:n,input:i,toolCallName:D,toolCallArgs:j})});return r(m),await Promise.all(a.map(E=>{var v;(v=E.onNewToolCall)==null||v.call(E,{toolCall:S,messages:e,state:o,agent:n,input:i})})),g()}case M.EventType.TOOL_CALL_RESULT:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onToolCallResultEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i})});if(r(l),l.stopPropagation!==!0){let{messageId:t,toolCallId:S,content:m,role:E}=u,v={id:t,toolCallId:S,role:E||"tool",content:m};e.push(v),await Promise.all(a.map(N=>{var I;(I=N.onNewMessage)==null||I.call(N,{message:v,messages:e,state:o,agent:n,input:i})})),r({messages:e})}return g()}case M.EventType.STATE_SNAPSHOT:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onStateSnapshotEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i})});if(r(l),l.stopPropagation!==!0){let{snapshot:t}=u;o=t,r({state:o})}return g()}case M.EventType.STATE_DELTA:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onStateDeltaEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i})});if(r(l),l.stopPropagation!==!0){let{delta:t}=u;try{o=(0,le.applyPatch)(o,t,!0,!1).newDocument,r({state:o})}catch(S){let m=S instanceof Error?S.message:String(S);console.warn(`Failed to apply state patch:
2
2
  Current state: ${JSON.stringify(o,null,2)}
3
- Patch operations: ${JSON.stringify(a,null,2)}
4
- Error: ${d}`)}}return g()}case y.EventType.MESSAGES_SNAPSHOT:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onMessagesSnapshotEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i})});if(r(p),p.stopPropagation!==!0){let{messages:a}=u;e=a,r({messages:e})}return g()}case y.EventType.RAW:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onRawEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i})});return r(p),g()}case y.EventType.CUSTOM:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onCustomEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i})});return r(p),g()}case y.EventType.RUN_STARTED:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onRunStartedEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i})});return r(p),g()}case y.EventType.RUN_FINISHED:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onRunFinishedEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i,result:u.result})});return r(p),g()}case y.EventType.RUN_ERROR:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onRunErrorEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i})});return r(p),g()}case y.EventType.STEP_STARTED:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onStepStartedEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i})});return r(p),g()}case y.EventType.STEP_FINISHED:{let p=await M(n,e,o,(a,c,d)=>{var E;return(E=a.onStepFinishedEvent)==null?void 0:E.call(a,{event:u,messages:c,state:d,agent:t,input:i})});return r(p),g()}case y.EventType.TEXT_MESSAGE_CHUNK:throw new Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case y.EventType.TOOL_CALL_CHUNK:throw new Error("TOOL_CALL_CHUNK must be tranformed before being applied");case y.EventType.THINKING_START:return g();case y.EventType.THINKING_END:return g();case y.EventType.THINKING_TEXT_MESSAGE_START:return g();case y.EventType.THINKING_TEXT_MESSAGE_CONTENT:return g();case y.EventType.THINKING_TEXT_MESSAGE_END:return g()}let C=u.type;return g()}),(0,H.mergeAll)(),n.length>0?(0,H.defaultIfEmpty)({}):u=>u)};var S=require("@ag-ui/core"),f=require("rxjs"),ge=require("rxjs/operators"),z=i=>s=>{let t,n,e=!1,o=!1,l=!1,r=new Map,g=!1,u=!1;return s.pipe((0,ge.mergeMap)(T=>{let C=T.type;if(i&&console.debug("[VERIFY]:",JSON.stringify(T)),o)return(0,f.throwError)(()=>new S.AGUIError(`Cannot send event type '${C}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(e&&C!==S.EventType.RUN_ERROR)return(0,f.throwError)(()=>new S.AGUIError(`Cannot send event type '${C}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(t!==void 0&&![S.EventType.TEXT_MESSAGE_CONTENT,S.EventType.TEXT_MESSAGE_END,S.EventType.RAW].includes(C))return(0,f.throwError)(()=>new S.AGUIError(`Cannot send event type '${C}' after 'TEXT_MESSAGE_START': Send 'TEXT_MESSAGE_END' first.`));if(n!==void 0&&![S.EventType.TOOL_CALL_ARGS,S.EventType.TOOL_CALL_END,S.EventType.RAW].includes(C))return C===S.EventType.TOOL_CALL_START?(0,f.throwError)(()=>new S.AGUIError("Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.")):(0,f.throwError)(()=>new S.AGUIError(`Cannot send event type '${C}' after 'TOOL_CALL_START': Send 'TOOL_CALL_END' first.`));if(l){if(C===S.EventType.RUN_STARTED)return(0,f.throwError)(()=>new S.AGUIError("Cannot send multiple 'RUN_STARTED' events: A 'RUN_STARTED' event was already sent. Each run must have exactly one 'RUN_STARTED' event at the beginning."))}else if(l=!0,C!==S.EventType.RUN_STARTED&&C!==S.EventType.RUN_ERROR)return(0,f.throwError)(()=>new S.AGUIError("First event must be 'RUN_STARTED'"));switch(C){case S.EventType.TEXT_MESSAGE_START:return t!==void 0?(0,f.throwError)(()=>new S.AGUIError("Cannot send 'TEXT_MESSAGE_START' event: A text message is already in progress. Complete it with 'TEXT_MESSAGE_END' first.")):(t=T.messageId,(0,f.of)(T));case S.EventType.TEXT_MESSAGE_CONTENT:return t===void 0?(0,f.throwError)(()=>new S.AGUIError("Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found. Start a text message with 'TEXT_MESSAGE_START' first.")):T.messageId!==t?(0,f.throwError)(()=>new S.AGUIError(`Cannot send 'TEXT_MESSAGE_CONTENT' event: Message ID mismatch. The ID '${T.messageId}' doesn't match the active message ID '${t}'.`)):(0,f.of)(T);case S.EventType.TEXT_MESSAGE_END:return t===void 0?(0,f.throwError)(()=>new S.AGUIError("Cannot send 'TEXT_MESSAGE_END' event: No active text message found. A 'TEXT_MESSAGE_START' event must be sent first.")):T.messageId!==t?(0,f.throwError)(()=>new S.AGUIError(`Cannot send 'TEXT_MESSAGE_END' event: Message ID mismatch. The ID '${T.messageId}' doesn't match the active message ID '${t}'.`)):(t=void 0,(0,f.of)(T));case S.EventType.TOOL_CALL_START:return n!==void 0?(0,f.throwError)(()=>new S.AGUIError("Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.")):(n=T.toolCallId,(0,f.of)(T));case S.EventType.TOOL_CALL_ARGS:return n===void 0?(0,f.throwError)(()=>new S.AGUIError("Cannot send 'TOOL_CALL_ARGS' event: No active tool call found. Start a tool call with 'TOOL_CALL_START' first.")):T.toolCallId!==n?(0,f.throwError)(()=>new S.AGUIError(`Cannot send 'TOOL_CALL_ARGS' event: Tool call ID mismatch. The ID '${T.toolCallId}' doesn't match the active tool call ID '${n}'.`)):(0,f.of)(T);case S.EventType.TOOL_CALL_END:return n===void 0?(0,f.throwError)(()=>new S.AGUIError("Cannot send 'TOOL_CALL_END' event: No active tool call found. A 'TOOL_CALL_START' event must be sent first.")):T.toolCallId!==n?(0,f.throwError)(()=>new S.AGUIError(`Cannot send 'TOOL_CALL_END' event: Tool call ID mismatch. The ID '${T.toolCallId}' doesn't match the active tool call ID '${n}'.`)):(n=void 0,(0,f.of)(T));case S.EventType.STEP_STARTED:{let A=T.stepName;return r.has(A)?(0,f.throwError)(()=>new S.AGUIError(`Step "${A}" is already active for 'STEP_STARTED'`)):(r.set(A,!0),(0,f.of)(T))}case S.EventType.STEP_FINISHED:{let A=T.stepName;return r.has(A)?(r.delete(A),(0,f.of)(T)):(0,f.throwError)(()=>new S.AGUIError(`Cannot send 'STEP_FINISHED' for step "${A}" that was not started`))}case S.EventType.RUN_STARTED:return(0,f.of)(T);case S.EventType.RUN_FINISHED:{if(r.size>0){let A=Array.from(r.keys()).join(", ");return(0,f.throwError)(()=>new S.AGUIError(`Cannot send 'RUN_FINISHED' while steps are still active: ${A}`))}return e=!0,(0,f.of)(T)}case S.EventType.RUN_ERROR:return o=!0,(0,f.of)(T);case S.EventType.CUSTOM:return(0,f.of)(T);case S.EventType.THINKING_TEXT_MESSAGE_START:return g?u?(0,f.throwError)(()=>new S.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(u=!0,(0,f.of)(T)):(0,f.throwError)(()=>new S.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case S.EventType.THINKING_TEXT_MESSAGE_CONTENT:return u?(0,f.of)(T):(0,f.throwError)(()=>new S.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case S.EventType.THINKING_TEXT_MESSAGE_END:return u?(u=!1,(0,f.of)(T)):(0,f.throwError)(()=>new S.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case S.EventType.THINKING_START:return g?(0,f.throwError)(()=>new S.AGUIError("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(g=!0,(0,f.of)(T));case S.EventType.THINKING_END:return g?(g=!1,(0,f.of)(T)):(0,f.throwError)(()=>new S.AGUIError("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return(0,f.of)(T)}}))};var me=require("@ag-ui/core"),Q=require("rxjs");var w=require("rxjs"),Ee=require("rxjs/operators");var V=(i,s)=>(0,w.defer)(()=>(0,w.from)(fetch(i,s))).pipe((0,Ee.switchMap)(t=>{var o;let n={type:"headers",status:t.status,headers:t.headers},e=(o=t.body)==null?void 0:o.getReader();return e?new w.Observable(l=>(l.next(n),(async()=>{try{for(;;){let{done:r,value:g}=await e.read();if(r)break;let u={type:"data",data:g};l.next(u)}l.complete()}catch(r){l.error(r)}})(),()=>{e.cancel()})):(0,w.throwError)(()=>new Error("Failed to getReader() from response"))}));var ce=require("rxjs");var b=i=>{let s=new ce.Subject,t=new TextDecoder("utf-8",{fatal:!1}),n="";i.subscribe({next:o=>{if(o.type!=="headers"&&o.type==="data"&&o.data){let l=t.decode(o.data,{stream:!0});n+=l;let r=n.split(/\n\n/);n=r.pop()||"";for(let g of r)e(g)}},error:o=>s.error(o),complete:()=>{n&&(n+=t.decode(),e(n)),s.complete()}});function e(o){let l=o.split(`
5
- `),r=[];for(let g of l)g.startsWith("data: ")&&r.push(g.slice(6));if(r.length>0)try{let g=r.join(`
6
- `),u=JSON.parse(g);s.next(u)}catch(g){s.error(g)}}return s.asObservable()};var ue=require("rxjs");var pe=$(require("@ag-ui/proto")),Y=i=>{let s=new ue.Subject,t=new Uint8Array(0);i.subscribe({next:e=>{if(e.type!=="headers"&&e.type==="data"&&e.data){let o=new Uint8Array(t.length+e.data.length);o.set(t,0),o.set(e.data,t.length),t=o,n()}},error:e=>s.error(e),complete:()=>{if(t.length>0)try{n()}catch(e){console.warn("Incomplete or invalid protocol buffer data at stream end")}s.complete()}});function n(){for(;t.length>=4;){let l=4+new DataView(t.buffer,t.byteOffset,4).getUint32(0,!1);if(t.length<l)break;try{let r=t.slice(4,l),g=pe.decode(r);s.next(g),t=t.slice(l)}catch(r){let g=r instanceof Error?r.message:String(r);s.error(new Error(`Failed to decode protocol buffer message: ${g}`));return}}}return s.asObservable()};var Se=$(require("@ag-ui/proto")),Z=i=>{let s=new Q.Subject,t=new Q.ReplaySubject,n=!1;return i.subscribe({next:e=>{t.next(e),e.type==="headers"&&!n?(n=!0,e.headers.get("content-type")===Se.AGUI_MEDIA_TYPE?Y(t).subscribe({next:l=>s.next(l),error:l=>s.error(l),complete:()=>s.complete()}):b(t).subscribe({next:l=>{try{let r=me.EventSchemas.parse(l);s.next(r)}catch(r){s.error(r)}},error:l=>s.error(l),complete:()=>s.complete()})):n||s.error(new Error("No headers event received before data events"))},error:e=>{t.error(e),s.error(e)},complete:()=>{t.complete()}}),s.asObservable()};var de=require("rxjs/operators"),Te=require("fast-json-patch"),N=require("@ag-ui/core");var m=require("zod"),h=m.z.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Oe=m.z.enum(["LangGraphInterruptEvent","PredictState","Exit"]),we=m.z.object({type:m.z.literal(h.enum.TextMessageStart),messageId:m.z.string(),parentMessageId:m.z.string().optional()}),Pe=m.z.object({type:m.z.literal(h.enum.TextMessageContent),messageId:m.z.string(),content:m.z.string()}),De=m.z.object({type:m.z.literal(h.enum.TextMessageEnd),messageId:m.z.string()}),He=m.z.object({type:m.z.literal(h.enum.ActionExecutionStart),actionExecutionId:m.z.string(),actionName:m.z.string(),parentMessageId:m.z.string().optional()}),Ge=m.z.object({type:m.z.literal(h.enum.ActionExecutionArgs),actionExecutionId:m.z.string(),args:m.z.string()}),Fe=m.z.object({type:m.z.literal(h.enum.ActionExecutionEnd),actionExecutionId:m.z.string()}),Xe=m.z.object({type:m.z.literal(h.enum.ActionExecutionResult),actionName:m.z.string(),actionExecutionId:m.z.string(),result:m.z.string()}),Ue=m.z.object({type:m.z.literal(h.enum.AgentStateMessage),threadId:m.z.string(),agentName:m.z.string(),nodeName:m.z.string(),runId:m.z.string(),active:m.z.boolean(),role:m.z.string(),state:m.z.string(),running:m.z.boolean()}),Ke=m.z.object({type:m.z.literal(h.enum.MetaEvent),name:Oe,value:m.z.any()}),ke=m.z.object({type:m.z.literal(h.enum.RunError),message:m.z.string(),code:m.z.string().optional()}),$t=m.z.discriminatedUnion("type",[we,Pe,De,He,Ge,Fe,Xe,Ue,Ke,ke]),Wt=m.z.object({id:m.z.string(),role:m.z.string(),content:m.z.string(),parentMessageId:m.z.string().optional()}),qt=m.z.object({id:m.z.string(),name:m.z.string(),arguments:m.z.any(),parentMessageId:m.z.string().optional()}),Vt=m.z.object({id:m.z.string(),result:m.z.any(),actionExecutionId:m.z.string(),actionName:m.z.string()});var fe=$(require("untruncate-json"));var ee=(i,s,t)=>n=>{let e={},o=!0,l=!0,r="",g=null,u=null,T=[],C={},A=p=>{typeof p=="object"&&p!==null&&("messages"in p&&delete p.messages,e=p)};return n.pipe((0,de.mergeMap)(p=>{switch(p.type){case N.EventType.TEXT_MESSAGE_START:{let a=p;return[{type:h.enum.TextMessageStart,messageId:a.messageId}]}case N.EventType.TEXT_MESSAGE_CONTENT:{let a=p;return[{type:h.enum.TextMessageContent,messageId:a.messageId,content:a.delta}]}case N.EventType.TEXT_MESSAGE_END:{let a=p;return[{type:h.enum.TextMessageEnd,messageId:a.messageId}]}case N.EventType.TOOL_CALL_START:{let a=p;return T.push({id:a.toolCallId,type:"function",function:{name:a.toolCallName,arguments:""}}),l=!0,C[a.toolCallId]=a.toolCallName,[{type:h.enum.ActionExecutionStart,actionExecutionId:a.toolCallId,actionName:a.toolCallName,parentMessageId:a.parentMessageId}]}case N.EventType.TOOL_CALL_ARGS:{let a=p,c=T[T.length-1];c.function.arguments+=a.delta;let d=!1;if(u){let E=u.find(R=>R.tool==c.function.name);if(E)try{let R=JSON.parse((0,fe.default)(c.function.arguments));E.tool_argument&&E.tool_argument in R?(A(B(x({},e),{[E.state_key]:R[E.tool_argument]})),d=!0):E.tool_argument||(A(B(x({},e),{[E.state_key]:R})),d=!0)}catch(R){}}return[{type:h.enum.ActionExecutionArgs,actionExecutionId:a.toolCallId,args:a.delta},...d?[{type:h.enum.AgentStateMessage,threadId:i,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:l}]:[]]}case N.EventType.TOOL_CALL_END:{let a=p;return[{type:h.enum.ActionExecutionEnd,actionExecutionId:a.toolCallId}]}case N.EventType.TOOL_CALL_RESULT:{let a=p;return[{type:h.enum.ActionExecutionResult,actionExecutionId:a.toolCallId,result:a.content,actionName:C[a.toolCallId]||"unknown"}]}case N.EventType.RAW:return[];case N.EventType.CUSTOM:{let a=p;switch(a.name){case"Exit":o=!1;break;case"PredictState":u=a.value;break}return[{type:h.enum.MetaEvent,name:a.name,value:a.value}]}case N.EventType.STATE_SNAPSHOT:return A(p.snapshot),[{type:h.enum.AgentStateMessage,threadId:i,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:l}];case N.EventType.STATE_DELTA:{let c=(0,Te.applyPatch)(e,p.delta,!0,!1);return c?(A(c.newDocument),[{type:h.enum.AgentStateMessage,threadId:i,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:l}]):[]}case N.EventType.MESSAGES_SNAPSHOT:return g=p.messages,[{type:h.enum.AgentStateMessage,threadId:i,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(x(x({},e),g?{messages:g}:{})),active:!0}];case N.EventType.RUN_STARTED:return[];case N.EventType.RUN_FINISHED:return g&&(e.messages=g),[{type:h.enum.AgentStateMessage,threadId:i,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(x(x({},e),g?{messages:Be(g)}:{})),active:!1}];case N.EventType.RUN_ERROR:{let a=p;return[{type:h.enum.RunError,message:a.message,code:a.code}]}case N.EventType.STEP_STARTED:return r=p.stepName,T=[],u=null,[{type:h.enum.AgentStateMessage,threadId:i,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:!0}];case N.EventType.STEP_FINISHED:return T=[],u=null,[{type:h.enum.AgentStateMessage,threadId:i,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:!1}];default:return[]}}))};function Be(i){var t;let s=[];for(let n of i)if(n.role==="assistant"||n.role==="user"||n.role==="system"){if(n.content){let e={id:n.id,role:n.role,content:n.content};s.push(e)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let e of n.toolCalls){let o={id:e.id,name:e.function.name,arguments:JSON.parse(e.function.arguments),parentMessageId:n.id};s.push(o)}}else if(n.role==="tool"){let e="unknown";for(let l of i)if(l.role==="assistant"&&((t=l.toolCalls)!=null&&t.length)){for(let r of l.toolCalls)if(r.id===n.toolCallId){e=r.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:e};s.push(o)}return s}var J=require("uuid");var D=require("rxjs/operators"),Ae=require("rxjs/operators"),F=require("rxjs");var ve=require("rxjs");var te=require("rxjs"),v=require("@ag-ui/core"),ae=i=>s=>{let t,n,e,o=()=>{if(!t||e!=="text")throw new Error("No text message to close");let g={type:v.EventType.TEXT_MESSAGE_END,messageId:t.messageId};return e=void 0,t=void 0,i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(g)),g},l=()=>{if(!n||e!=="tool")throw new Error("No tool call to close");let g={type:v.EventType.TOOL_CALL_END,toolCallId:n.toolCallId};return e=void 0,n=void 0,i&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(g)),g},r=()=>e==="text"?[o()]:e==="tool"?[l()]:[];return s.pipe((0,te.mergeMap)(g=>{switch(g.type){case v.EventType.TEXT_MESSAGE_START:case v.EventType.TEXT_MESSAGE_CONTENT:case v.EventType.TEXT_MESSAGE_END:case v.EventType.TOOL_CALL_START:case v.EventType.TOOL_CALL_ARGS:case v.EventType.TOOL_CALL_END:case v.EventType.TOOL_CALL_RESULT:case v.EventType.STATE_SNAPSHOT:case v.EventType.STATE_DELTA:case v.EventType.MESSAGES_SNAPSHOT:case v.EventType.CUSTOM:case v.EventType.RUN_STARTED:case v.EventType.RUN_FINISHED:case v.EventType.RUN_ERROR:case v.EventType.STEP_STARTED:case v.EventType.STEP_FINISHED:case v.EventType.THINKING_START:case v.EventType.THINKING_END:case v.EventType.THINKING_TEXT_MESSAGE_START:case v.EventType.THINKING_TEXT_MESSAGE_CONTENT:case v.EventType.THINKING_TEXT_MESSAGE_END:return[...r(),g];case v.EventType.RAW:return[g];case v.EventType.TEXT_MESSAGE_CHUNK:let T=g,C=[];if((e!=="text"||T.messageId!==void 0&&T.messageId!==(t==null?void 0:t.messageId))&&C.push(...r()),e!=="text"){if(T.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");t={messageId:T.messageId},e="text";let a={type:v.EventType.TEXT_MESSAGE_START,messageId:T.messageId,role:"assistant"};C.push(a),i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(a))}if(T.delta!==void 0){let a={type:v.EventType.TEXT_MESSAGE_CONTENT,messageId:t.messageId,delta:T.delta};C.push(a),i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(a))}return C;case v.EventType.TOOL_CALL_CHUNK:let A=g,p=[];if((e!=="tool"||A.toolCallId!==void 0&&A.toolCallId!==(n==null?void 0:n.toolCallId))&&p.push(...r()),e!=="tool"){if(A.toolCallId===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallId");if(A.toolCallName===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallName");n={toolCallId:A.toolCallId,toolCallName:A.toolCallName,parentMessageId:A.parentMessageId},e="tool";let a={type:v.EventType.TOOL_CALL_START,toolCallId:A.toolCallId,toolCallName:A.toolCallName,parentMessageId:A.parentMessageId};p.push(a),i&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(a))}if(A.delta!==void 0){let a={type:v.EventType.TOOL_CALL_ARGS,toolCallId:n.toolCallId,delta:A.delta};p.push(a),i&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(a))}return p}let u=g.type}),(0,te.finalize)(()=>r()))};var G=class{constructor({agentId:s,description:t,threadId:n,initialMessages:e,initialState:o,debug:l}={}){this.debug=!1;this.subscribers=[];this.agentId=s,this.description=t!=null?t:"",this.threadId=n!=null?n:(0,J.v4)(),this.messages=_(e!=null?e:[]),this.state=_(o!=null?o:{}),this.debug=l!=null?l:!1}subscribe(s){return this.subscribers.push(s),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==s)}}}async runAgent(s,t){var g;this.agentId=(g=this.agentId)!=null?g:(0,J.v4)();let n=this.prepareRunAgentInput(s),e,o=new Set(this.messages.map(u=>u.id)),l=[{onRunFinishedEvent:u=>{e=u.result}},...this.subscribers,t!=null?t:{}];await this.onInitialize(n,l);let r=(0,F.pipe)(()=>this.run(n),ae(this.debug),z(this.debug),u=>this.apply(n,u,l),u=>this.processApplyEvents(n,u,l),(0,D.catchError)(u=>this.onError(n,u,l)),(0,Ae.finalize)(()=>{this.onFinalize(n,l)}));return(0,ve.lastValueFrom)(r((0,F.of)(null))).then(()=>{let u=_(this.messages).filter(T=>!o.has(T.id));return{result:e,newMessages:u}})}abortRun(){}apply(s,t,n){return q(s,t,this,n)}processApplyEvents(s,t,n){return t.pipe((0,D.tap)(e=>{e.messages&&(this.messages=e.messages,n.forEach(o=>{var l;(l=o.onMessagesChanged)==null||l.call(o,{messages:this.messages,state:this.state,agent:this,input:s})})),e.state&&(this.state=e.state,n.forEach(o=>{var l;(l=o.onStateChanged)==null||l.call(o,{state:this.state,messages:this.messages,agent:this,input:s})}))}))}prepareRunAgentInput(s){var t,n,e;return{threadId:this.threadId,runId:(s==null?void 0:s.runId)||(0,J.v4)(),tools:_((t=s==null?void 0:s.tools)!=null?t:[]),context:_((n=s==null?void 0:s.context)!=null?n:[]),forwardedProps:_((e=s==null?void 0:s.forwardedProps)!=null?e:{}),state:_(this.state),messages:_(this.messages)}}async onInitialize(s,t){let n=await M(t,this.messages,this.state,(e,o,l)=>{var r;return(r=e.onRunInitialized)==null?void 0:r.call(e,{messages:o,state:l,agent:this,input:s})});(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,s.messages=n.messages,t.forEach(e=>{var o;(o=e.onMessagesChanged)==null||o.call(e,{messages:this.messages,state:this.state,agent:this,input:s})})),n.state&&(this.state=n.state,s.state=n.state,t.forEach(e=>{var o;(o=e.onStateChanged)==null||o.call(e,{state:this.state,messages:this.messages,agent:this,input:s})})))}onError(s,t,n){return(0,F.from)(M(n,this.messages,this.state,(e,o,l)=>{var r;return(r=e.onRunFailed)==null?void 0:r.call(e,{error:t,messages:o,state:l,agent:this,input:s})})).pipe((0,D.map)(e=>{let o=e;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(l=>{var r;(r=l.onMessagesChanged)==null||r.call(l,{messages:this.messages,state:this.state,agent:this,input:s})})),o.state!==void 0&&(this.state=o.state,n.forEach(l=>{var r;(r=l.onStateChanged)==null||r.call(l,{state:this.state,messages:this.messages,agent:this,input:s})}))),o.stopPropagation!==!0)throw console.error("Agent execution failed:",t),t;return{}}))}async onFinalize(s,t){let n=await M(t,this.messages,this.state,(e,o,l)=>{var r;return(r=e.onRunFinalized)==null?void 0:r.call(e,{messages:o,state:l,agent:this,input:s})});(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,t.forEach(e=>{var o;(o=e.onMessagesChanged)==null||o.call(e,{messages:this.messages,state:this.state,agent:this,input:s})})),n.state!==void 0&&(this.state=n.state,t.forEach(e=>{var o;(o=e.onStateChanged)==null||o.call(e,{state:this.state,messages:this.messages,agent:this,input:s})})))}clone(){let s=Object.create(Object.getPrototypeOf(this));for(let t of Object.getOwnPropertyNames(this)){let n=this[t];typeof n!="function"&&(s[t]=_(n))}return s}addMessage(s){this.messages.push(s),(async()=>{var t,n,e;for(let o of this.subscribers)await((t=o.onNewMessage)==null?void 0:t.call(o,{message:s,messages:this.messages,state:this.state,agent:this}));if(s.role==="assistant"&&s.toolCalls)for(let o of s.toolCalls)for(let l of this.subscribers)await((n=l.onNewToolCall)==null?void 0:n.call(l,{toolCall:o,messages:this.messages,state:this.state,agent:this}));for(let o of this.subscribers)await((e=o.onMessagesChanged)==null?void 0:e.call(o,{messages:this.messages,state:this.state,agent:this}))})()}addMessages(s){this.messages.push(...s),(async()=>{var t,n,e;for(let o of s){for(let l of this.subscribers)await((t=l.onNewMessage)==null?void 0:t.call(l,{message:o,messages:this.messages,state:this.state,agent:this}));if(o.role==="assistant"&&o.toolCalls)for(let l of o.toolCalls)for(let r of this.subscribers)await((n=r.onNewToolCall)==null?void 0:n.call(r,{toolCall:l,messages:this.messages,state:this.state,agent:this}))}for(let o of this.subscribers)await((e=o.onMessagesChanged)==null?void 0:e.call(o,{messages:this.messages,state:this.state,agent:this}))})()}setMessages(s){this.messages=_(s),(async()=>{var t;for(let n of this.subscribers)await((t=n.onMessagesChanged)==null?void 0:t.call(n,{messages:this.messages,state:this.state,agent:this}))})()}setState(s){this.state=_(s),(async()=>{var t;for(let n of this.subscribers)await((t=n.onStateChanged)==null?void 0:t.call(n,{messages:this.messages,state:this.state,agent:this}))})()}legacy_to_be_removed_runAgentBridged(s){var n;this.agentId=(n=this.agentId)!=null?n:(0,J.v4)();let t=this.prepareRunAgentInput(s);return this.run(t).pipe(ae(this.debug),z(this.debug),ee(this.threadId,t.runId,this.agentId),e=>e.pipe((0,D.map)(o=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(o)),o))))}};var ne=class extends G{constructor(t){var n;super(t);this.abortController=new AbortController;this.url=t.url,this.headers=_((n=t.headers)!=null?n:{})}requestInit(t){return{method:"POST",headers:B(x({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(t),signal:this.abortController.signal}}runAgent(t,n){var e;return this.abortController=(e=t==null?void 0:t.abortController)!=null?e:new AbortController,super.runAgent(t,n)}abortRun(){this.abortController.abort(),super.abortRun()}run(t){let n=V(this.url,this.requestInit(t));return Z(n)}};I(L,require("@ag-ui/core"),module.exports);0&&(module.exports={AbstractAgent,HttpAgent,convertToLegacyEvents,defaultApplyEvents,parseProtoStream,parseSSEStream,runHttpRequest,transformHttpEventStream,verifyEvents,...require("@ag-ui/core")});
3
+ Patch operations: ${JSON.stringify(t,null,2)}
4
+ Error: ${m}`)}}return g()}case M.EventType.MESSAGES_SNAPSHOT:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onMessagesSnapshotEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i})});if(r(l),l.stopPropagation!==!0){let{messages:t}=u;e=t,r({messages:e})}return g()}case M.EventType.RAW:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onRawEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i})});return r(l),g()}case M.EventType.CUSTOM:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onCustomEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i})});return r(l),g()}case M.EventType.RUN_STARTED:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onRunStartedEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i})});return r(l),g()}case M.EventType.RUN_FINISHED:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onRunFinishedEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i,result:u.result})});return r(l),g()}case M.EventType.RUN_ERROR:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onRunErrorEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i})});return r(l),g()}case M.EventType.STEP_STARTED:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onStepStartedEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i})});return r(l),g()}case M.EventType.STEP_FINISHED:{let l=await y(a,e,o,(t,S,m)=>{var E;return(E=t.onStepFinishedEvent)==null?void 0:E.call(t,{event:u,messages:S,state:m,agent:n,input:i})});return r(l),g()}case M.EventType.TEXT_MESSAGE_CHUNK:throw new Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case M.EventType.TOOL_CALL_CHUNK:throw new Error("TOOL_CALL_CHUNK must be tranformed before being applied");case M.EventType.THINKING_START:return g();case M.EventType.THINKING_END:return g();case M.EventType.THINKING_TEXT_MESSAGE_START:return g();case M.EventType.THINKING_TEXT_MESSAGE_CONTENT:return g();case M.EventType.THINKING_TEXT_MESSAGE_END:return g()}let L=u.type;return g()}),(0,G.mergeAll)(),a.length>0?(0,G.defaultIfEmpty)({}):u=>u)};var f=require("@ag-ui/core"),T=require("rxjs"),ce=require("rxjs/operators"),z=i=>s=>{let n=new Map,a=new Map,e=!1,o=!1,c=!1,r=new Map,g=!1,u=!1,C=!1,L=()=>{n.clear(),a.clear(),r.clear(),g=!1,u=!1,e=!1,o=!1,C=!0};return s.pipe((0,ce.mergeMap)(d=>{let l=d.type;if(i&&console.debug("[VERIFY]:",JSON.stringify(d)),o)return(0,T.throwError)(()=>new f.AGUIError(`Cannot send event type '${l}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(e&&l!==f.EventType.RUN_ERROR&&l!==f.EventType.RUN_STARTED)return(0,T.throwError)(()=>new f.AGUIError(`Cannot send event type '${l}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(c){if(l===f.EventType.RUN_STARTED){if(C&&!e)return(0,T.throwError)(()=>new f.AGUIError("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&&L()}}else if(c=!0,l!==f.EventType.RUN_STARTED&&l!==f.EventType.RUN_ERROR)return(0,T.throwError)(()=>new f.AGUIError("First event must be 'RUN_STARTED'"));switch(l){case f.EventType.TEXT_MESSAGE_START:{let t=d.messageId;return n.has(t)?(0,T.throwError)(()=>new f.AGUIError(`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),(0,T.of)(d))}case f.EventType.TEXT_MESSAGE_CONTENT:{let t=d.messageId;return n.has(t)?(0,T.of)(d):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${t}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case f.EventType.TEXT_MESSAGE_END:{let t=d.messageId;return n.has(t)?(n.delete(t),(0,T.of)(d)):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${t}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case f.EventType.TOOL_CALL_START:{let t=d.toolCallId;return a.has(t)?(0,T.throwError)(()=>new f.AGUIError(`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),(0,T.of)(d))}case f.EventType.TOOL_CALL_ARGS:{let t=d.toolCallId;return a.has(t)?(0,T.of)(d):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${t}'. Start a tool call with 'TOOL_CALL_START' first.`))}case f.EventType.TOOL_CALL_END:{let t=d.toolCallId;return a.has(t)?(a.delete(t),(0,T.of)(d)):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${t}'. A 'TOOL_CALL_START' event must be sent first.`))}case f.EventType.STEP_STARTED:{let t=d.stepName;return r.has(t)?(0,T.throwError)(()=>new f.AGUIError(`Step "${t}" is already active for 'STEP_STARTED'`)):(r.set(t,!0),(0,T.of)(d))}case f.EventType.STEP_FINISHED:{let t=d.stepName;return r.has(t)?(r.delete(t),(0,T.of)(d)):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'STEP_FINISHED' for step "${t}" that was not started`))}case f.EventType.RUN_STARTED:return C=!0,(0,T.of)(d);case f.EventType.RUN_FINISHED:{if(r.size>0){let t=Array.from(r.keys()).join(", ");return(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'RUN_FINISHED' while steps are still active: ${t}`))}if(n.size>0){let t=Array.from(n.keys()).join(", ");return(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'RUN_FINISHED' while text messages are still active: ${t}`))}if(a.size>0){let t=Array.from(a.keys()).join(", ");return(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${t}`))}return e=!0,(0,T.of)(d)}case f.EventType.RUN_ERROR:return o=!0,(0,T.of)(d);case f.EventType.CUSTOM:return(0,T.of)(d);case f.EventType.THINKING_TEXT_MESSAGE_START:return g?u?(0,T.throwError)(()=>new f.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(u=!0,(0,T.of)(d)):(0,T.throwError)(()=>new f.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case f.EventType.THINKING_TEXT_MESSAGE_CONTENT:return u?(0,T.of)(d):(0,T.throwError)(()=>new f.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case f.EventType.THINKING_TEXT_MESSAGE_END:return u?(u=!1,(0,T.of)(d)):(0,T.throwError)(()=>new f.AGUIError("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case f.EventType.THINKING_START:return g?(0,T.throwError)(()=>new f.AGUIError("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(g=!0,(0,T.of)(d));case f.EventType.THINKING_END:return g?(g=!1,(0,T.of)(d)):(0,T.throwError)(()=>new f.AGUIError("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return(0,T.of)(d)}}))};var Se=require("@ag-ui/core"),Q=require("rxjs");var P=require("rxjs"),Ee=require("rxjs/operators");var b=(i,s)=>(0,P.defer)(()=>(0,P.from)(fetch(i,s))).pipe((0,Ee.switchMap)(n=>{var o;let a={type:"headers",status:n.status,headers:n.headers},e=(o=n.body)==null?void 0:o.getReader();return e?new P.Observable(c=>(c.next(a),(async()=>{try{for(;;){let{done:r,value:g}=await e.read();if(r)break;let u={type:"data",data:g};c.next(u)}c.complete()}catch(r){c.error(r)}})(),()=>{e.cancel()})):(0,P.throwError)(()=>new Error("Failed to getReader() from response"))}));var ue=require("rxjs");var V=i=>{let s=new ue.Subject,n=new TextDecoder("utf-8",{fatal:!1}),a="";i.subscribe({next:o=>{if(o.type!=="headers"&&o.type==="data"&&o.data){let c=n.decode(o.data,{stream:!0});a+=c;let r=a.split(/\n\n/);a=r.pop()||"";for(let g of r)e(g)}},error:o=>s.error(o),complete:()=>{a&&(a+=n.decode(),e(a)),s.complete()}});function e(o){let c=o.split(`
5
+ `),r=[];for(let g of c)g.startsWith("data: ")&&r.push(g.slice(6));if(r.length>0)try{let g=r.join(`
6
+ `),u=JSON.parse(g);s.next(u)}catch(g){s.error(g)}}return s.asObservable()};var pe=require("rxjs");var me=$(require("@ag-ui/proto")),Y=i=>{let s=new pe.Subject,n=new Uint8Array(0);i.subscribe({next:e=>{if(e.type!=="headers"&&e.type==="data"&&e.data){let o=new Uint8Array(n.length+e.data.length);o.set(n,0),o.set(e.data,n.length),n=o,a()}},error:e=>s.error(e),complete:()=>{if(n.length>0)try{a()}catch(e){console.warn("Incomplete or invalid protocol buffer data at stream end")}s.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),g=me.decode(r);s.next(g),n=n.slice(c)}catch(r){let g=r instanceof Error?r.message:String(r);s.error(new Error(`Failed to decode protocol buffer message: ${g}`));return}}}return s.asObservable()};var de=$(require("@ag-ui/proto")),Z=i=>{let s=new Q.Subject,n=new Q.ReplaySubject,a=!1;return i.subscribe({next:e=>{n.next(e),e.type==="headers"&&!a?(a=!0,e.headers.get("content-type")===de.AGUI_MEDIA_TYPE?Y(n).subscribe({next:c=>s.next(c),error:c=>s.error(c),complete:()=>s.complete()}):V(n).subscribe({next:c=>{try{let r=Se.EventSchemas.parse(c);s.next(r)}catch(r){s.error(r)}},error:c=>s.error(c),complete:()=>s.complete()})):a||s.error(new Error("No headers event received before data events"))},error:e=>{n.error(e),s.error(e)},complete:()=>{n.complete()}}),s.asObservable()};var fe=require("rxjs/operators"),Te=require("fast-json-patch"),_=require("@ag-ui/core");var p=require("zod"),h=p.z.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Oe=p.z.enum(["LangGraphInterruptEvent","PredictState","Exit"]),we=p.z.object({type:p.z.literal(h.enum.TextMessageStart),messageId:p.z.string(),parentMessageId:p.z.string().optional(),role:p.z.string().optional()}),Pe=p.z.object({type:p.z.literal(h.enum.TextMessageContent),messageId:p.z.string(),content:p.z.string()}),De=p.z.object({type:p.z.literal(h.enum.TextMessageEnd),messageId:p.z.string()}),He=p.z.object({type:p.z.literal(h.enum.ActionExecutionStart),actionExecutionId:p.z.string(),actionName:p.z.string(),parentMessageId:p.z.string().optional()}),Ge=p.z.object({type:p.z.literal(h.enum.ActionExecutionArgs),actionExecutionId:p.z.string(),args:p.z.string()}),Fe=p.z.object({type:p.z.literal(h.enum.ActionExecutionEnd),actionExecutionId:p.z.string()}),Ue=p.z.object({type:p.z.literal(h.enum.ActionExecutionResult),actionName:p.z.string(),actionExecutionId:p.z.string(),result:p.z.string()}),Xe=p.z.object({type:p.z.literal(h.enum.AgentStateMessage),threadId:p.z.string(),agentName:p.z.string(),nodeName:p.z.string(),runId:p.z.string(),active:p.z.boolean(),role:p.z.string(),state:p.z.string(),running:p.z.boolean()}),Ke=p.z.object({type:p.z.literal(h.enum.MetaEvent),name:Oe,value:p.z.any()}),ke=p.z.object({type:p.z.literal(h.enum.RunError),message:p.z.string(),code:p.z.string().optional()}),Vt=p.z.discriminatedUnion("type",[we,Pe,De,He,Ge,Fe,Ue,Xe,Ke,ke]),Yt=p.z.object({id:p.z.string(),role:p.z.string(),content:p.z.string(),parentMessageId:p.z.string().optional()}),Qt=p.z.object({id:p.z.string(),name:p.z.string(),arguments:p.z.any(),parentMessageId:p.z.string().optional()}),Zt=p.z.object({id:p.z.string(),result:p.z.any(),actionExecutionId:p.z.string(),actionName:p.z.string()});var Ae=$(require("untruncate-json"));var ee=(i,s,n)=>a=>{let e={},o=!0,c=!0,r="",g=null,u=null,C=[],L={},d=l=>{typeof l=="object"&&l!==null&&("messages"in l&&delete l.messages,e=l)};return a.pipe((0,fe.mergeMap)(l=>{switch(l.type){case _.EventType.TEXT_MESSAGE_START:{let t=l;return[{type:h.enum.TextMessageStart,messageId:t.messageId,role:t.role}]}case _.EventType.TEXT_MESSAGE_CONTENT:{let t=l;return[{type:h.enum.TextMessageContent,messageId:t.messageId,content:t.delta}]}case _.EventType.TEXT_MESSAGE_END:{let t=l;return[{type:h.enum.TextMessageEnd,messageId:t.messageId}]}case _.EventType.TOOL_CALL_START:{let t=l;return C.push({id:t.toolCallId,type:"function",function:{name:t.toolCallName,arguments:""}}),c=!0,L[t.toolCallId]=t.toolCallName,[{type:h.enum.ActionExecutionStart,actionExecutionId:t.toolCallId,actionName:t.toolCallName,parentMessageId:t.parentMessageId}]}case _.EventType.TOOL_CALL_ARGS:{let t=l,S=C.find(E=>E.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(u){let E=u.find(v=>v.tool==S.function.name);if(E)try{let v=JSON.parse((0,Ae.default)(S.function.arguments));E.tool_argument&&E.tool_argument in v?(d(k(x({},e),{[E.state_key]:v[E.tool_argument]})),m=!0):E.tool_argument||(d(k(x({},e),{[E.state_key]:v})),m=!0)}catch(v){}}return[{type:h.enum.ActionExecutionArgs,actionExecutionId:t.toolCallId,args:t.delta},...m?[{type:h.enum.AgentStateMessage,threadId:i,agentName:n,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:c}]:[]]}case _.EventType.TOOL_CALL_END:{let t=l;return[{type:h.enum.ActionExecutionEnd,actionExecutionId:t.toolCallId}]}case _.EventType.TOOL_CALL_RESULT:{let t=l;return[{type:h.enum.ActionExecutionResult,actionExecutionId:t.toolCallId,result:t.content,actionName:L[t.toolCallId]||"unknown"}]}case _.EventType.RAW:return[];case _.EventType.CUSTOM:{let t=l;switch(t.name){case"Exit":o=!1;break;case"PredictState":u=t.value;break}return[{type:h.enum.MetaEvent,name:t.name,value:t.value}]}case _.EventType.STATE_SNAPSHOT:return d(l.snapshot),[{type:h.enum.AgentStateMessage,threadId:i,agentName:n,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:c}];case _.EventType.STATE_DELTA:{let S=(0,Te.applyPatch)(e,l.delta,!0,!1);return S?(d(S.newDocument),[{type:h.enum.AgentStateMessage,threadId:i,agentName:n,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:c}]):[]}case _.EventType.MESSAGES_SNAPSHOT:return g=l.messages,[{type:h.enum.AgentStateMessage,threadId:i,agentName:n,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(x(x({},e),g?{messages:g}:{})),active:!0}];case _.EventType.RUN_STARTED:return[];case _.EventType.RUN_FINISHED:return g&&(e.messages=g),[{type:h.enum.AgentStateMessage,threadId:i,agentName:n,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(x(x({},e),g?{messages:ze(g)}:{})),active:!1}];case _.EventType.RUN_ERROR:{let t=l;return[{type:h.enum.RunError,message:t.message,code:t.code}]}case _.EventType.STEP_STARTED:return r=l.stepName,C=[],u=null,[{type:h.enum.AgentStateMessage,threadId:i,agentName:n,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:!0}];case _.EventType.STEP_FINISHED:return C=[],u=null,[{type:h.enum.AgentStateMessage,threadId:i,agentName:n,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:!1}];default:return[]}}))};function ze(i){var n;let s=[];for(let a of i)if(a.role==="assistant"||a.role==="user"||a.role==="system"){if(a.content){let e={id:a.id,role:a.role,content:a.content};s.push(e)}if(a.role==="assistant"&&a.toolCalls&&a.toolCalls.length>0)for(let e of a.toolCalls){let o={id:e.id,name:e.function.name,arguments:JSON.parse(e.function.arguments),parentMessageId:a.id};s.push(o)}}else if(a.role==="tool"){let e="unknown";for(let c of i)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 o={id:a.id,result:a.content,actionExecutionId:a.toolCallId,actionName:e};s.push(o)}return s}var B=require("uuid");var H=require("rxjs/operators"),ve=require("rxjs/operators"),U=require("rxjs");var he=require("rxjs");var te=require("rxjs"),A=require("@ag-ui/core"),se=i=>s=>{let n,a,e,o=()=>{if(!n||e!=="text")throw new Error("No text message to close");let g={type:A.EventType.TEXT_MESSAGE_END,messageId:n.messageId};return e=void 0,n=void 0,i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(g)),g},c=()=>{if(!a||e!=="tool")throw new Error("No tool call to close");let g={type:A.EventType.TOOL_CALL_END,toolCallId:a.toolCallId};return e=void 0,a=void 0,i&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(g)),g},r=()=>e==="text"?[o()]:e==="tool"?[c()]:[];return s.pipe((0,te.mergeMap)(g=>{switch(g.type){case A.EventType.TEXT_MESSAGE_START:case A.EventType.TEXT_MESSAGE_CONTENT:case A.EventType.TEXT_MESSAGE_END:case A.EventType.TOOL_CALL_START:case A.EventType.TOOL_CALL_ARGS:case A.EventType.TOOL_CALL_END:case A.EventType.TOOL_CALL_RESULT:case A.EventType.STATE_SNAPSHOT:case A.EventType.STATE_DELTA:case A.EventType.MESSAGES_SNAPSHOT:case A.EventType.CUSTOM:case A.EventType.RUN_STARTED:case A.EventType.RUN_FINISHED:case A.EventType.RUN_ERROR:case A.EventType.STEP_STARTED:case A.EventType.STEP_FINISHED:case A.EventType.THINKING_START:case A.EventType.THINKING_END:case A.EventType.THINKING_TEXT_MESSAGE_START:case A.EventType.THINKING_TEXT_MESSAGE_CONTENT:case A.EventType.THINKING_TEXT_MESSAGE_END:return[...r(),g];case A.EventType.RAW:return[g];case A.EventType.TEXT_MESSAGE_CHUNK:let C=g,L=[];if((e!=="text"||C.messageId!==void 0&&C.messageId!==(n==null?void 0:n.messageId))&&L.push(...r()),e!=="text"){if(C.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");n={messageId:C.messageId},e="text";let t={type:A.EventType.TEXT_MESSAGE_START,messageId:C.messageId,role:C.role||"assistant"};L.push(t),i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(t))}if(C.delta!==void 0){let t={type:A.EventType.TEXT_MESSAGE_CONTENT,messageId:n.messageId,delta:C.delta};L.push(t),i&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(t))}return L;case A.EventType.TOOL_CALL_CHUNK:let d=g,l=[];if((e!=="tool"||d.toolCallId!==void 0&&d.toolCallId!==(a==null?void 0:a.toolCallId))&&l.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:A.EventType.TOOL_CALL_START,toolCallId:d.toolCallId,toolCallName:d.toolCallName,parentMessageId:d.parentMessageId};l.push(t),i&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(t))}if(d.delta!==void 0){let t={type:A.EventType.TOOL_CALL_ARGS,toolCallId:a.toolCallId,delta:d.delta};l.push(t),i&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(t))}return l}let u=g.type}),(0,te.finalize)(()=>r()))};var F=class{constructor({agentId:s,description:n,threadId:a,initialMessages:e,initialState:o,debug:c}={}){this.debug=!1;this.subscribers=[];this.agentId=s,this.description=n!=null?n:"",this.threadId=a!=null?a:(0,B.v4)(),this.messages=R(e!=null?e:[]),this.state=R(o!=null?o:{}),this.debug=c!=null?c:!1}subscribe(s){return this.subscribers.push(s),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(n=>n!==s)}}}async runAgent(s,n){var g;this.agentId=(g=this.agentId)!=null?g:(0,B.v4)();let a=this.prepareRunAgentInput(s),e,o=new Set(this.messages.map(u=>u.id)),c=[{onRunFinishedEvent:u=>{e=u.result}},...this.subscribers,n!=null?n:{}];await this.onInitialize(a,c);let r=(0,U.pipe)(()=>this.run(a),se(this.debug),z(this.debug),u=>this.apply(a,u,c),u=>this.processApplyEvents(a,u,c),(0,H.catchError)(u=>this.onError(a,u,c)),(0,ve.finalize)(()=>{this.onFinalize(a,c)}));return(0,he.lastValueFrom)(r((0,U.of)(null))).then(()=>{let u=R(this.messages).filter(C=>!o.has(C.id));return{result:e,newMessages:u}})}abortRun(){}apply(s,n,a){return W(s,n,this,a)}processApplyEvents(s,n,a){return n.pipe((0,H.tap)(e=>{e.messages&&(this.messages=e.messages,a.forEach(o=>{var c;(c=o.onMessagesChanged)==null||c.call(o,{messages:this.messages,state:this.state,agent:this,input:s})})),e.state&&(this.state=e.state,a.forEach(o=>{var c;(c=o.onStateChanged)==null||c.call(o,{state:this.state,messages:this.messages,agent:this,input:s})}))}))}prepareRunAgentInput(s){var n,a,e;return{threadId:this.threadId,runId:(s==null?void 0:s.runId)||(0,B.v4)(),tools:R((n=s==null?void 0:s.tools)!=null?n:[]),context:R((a=s==null?void 0:s.context)!=null?a:[]),forwardedProps:R((e=s==null?void 0:s.forwardedProps)!=null?e:{}),state:R(this.state),messages:R(this.messages)}}async onInitialize(s,n){let a=await y(n,this.messages,this.state,(e,o,c)=>{var r;return(r=e.onRunInitialized)==null?void 0:r.call(e,{messages:o,state:c,agent:this,input:s})});(a.messages!==void 0||a.state!==void 0)&&(a.messages&&(this.messages=a.messages,s.messages=a.messages,n.forEach(e=>{var o;(o=e.onMessagesChanged)==null||o.call(e,{messages:this.messages,state:this.state,agent:this,input:s})})),a.state&&(this.state=a.state,s.state=a.state,n.forEach(e=>{var o;(o=e.onStateChanged)==null||o.call(e,{state:this.state,messages:this.messages,agent:this,input:s})})))}onError(s,n,a){return(0,U.from)(y(a,this.messages,this.state,(e,o,c)=>{var r;return(r=e.onRunFailed)==null?void 0:r.call(e,{error:n,messages:o,state:c,agent:this,input:s})})).pipe((0,H.map)(e=>{let o=e;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,a.forEach(c=>{var r;(r=c.onMessagesChanged)==null||r.call(c,{messages:this.messages,state:this.state,agent:this,input:s})})),o.state!==void 0&&(this.state=o.state,a.forEach(c=>{var r;(r=c.onStateChanged)==null||r.call(c,{state:this.state,messages:this.messages,agent:this,input:s})}))),o.stopPropagation!==!0)throw console.error("Agent execution failed:",n),n;return{}}))}async onFinalize(s,n){let a=await y(n,this.messages,this.state,(e,o,c)=>{var r;return(r=e.onRunFinalized)==null?void 0:r.call(e,{messages:o,state:c,agent:this,input:s})});(a.messages!==void 0||a.state!==void 0)&&(a.messages!==void 0&&(this.messages=a.messages,n.forEach(e=>{var o;(o=e.onMessagesChanged)==null||o.call(e,{messages:this.messages,state:this.state,agent:this,input:s})})),a.state!==void 0&&(this.state=a.state,n.forEach(e=>{var o;(o=e.onStateChanged)==null||o.call(e,{state:this.state,messages:this.messages,agent:this,input:s})})))}clone(){let s=Object.create(Object.getPrototypeOf(this));for(let n of Object.getOwnPropertyNames(this)){let a=this[n];typeof a!="function"&&(s[n]=R(a))}return s}addMessage(s){this.messages.push(s),(async()=>{var n,a,e;for(let o of this.subscribers)await((n=o.onNewMessage)==null?void 0:n.call(o,{message:s,messages:this.messages,state:this.state,agent:this}));if(s.role==="assistant"&&s.toolCalls)for(let o of s.toolCalls)for(let c of this.subscribers)await((a=c.onNewToolCall)==null?void 0:a.call(c,{toolCall:o,messages:this.messages,state:this.state,agent:this}));for(let o of this.subscribers)await((e=o.onMessagesChanged)==null?void 0:e.call(o,{messages:this.messages,state:this.state,agent:this}))})()}addMessages(s){this.messages.push(...s),(async()=>{var n,a,e;for(let o of s){for(let c of this.subscribers)await((n=c.onNewMessage)==null?void 0:n.call(c,{message:o,messages:this.messages,state:this.state,agent:this}));if(o.role==="assistant"&&o.toolCalls)for(let c of o.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 o of this.subscribers)await((e=o.onMessagesChanged)==null?void 0:e.call(o,{messages:this.messages,state:this.state,agent:this}))})()}setMessages(s){this.messages=R(s),(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(s){this.state=R(s),(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(s){var a;this.agentId=(a=this.agentId)!=null?a:(0,B.v4)();let n=this.prepareRunAgentInput(s);return this.run(n).pipe(se(this.debug),z(this.debug),ee(this.threadId,n.runId,this.agentId),e=>e.pipe((0,H.map)(o=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(o)),o))))}};var ne=class extends F{constructor(n){var a;super(n);this.abortController=new AbortController;this.url=n.url,this.headers=R((a=n.headers)!=null?a:{})}requestInit(n){return{method:"POST",headers:k(x({},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 Z(a)}};w(O,require("@ag-ui/core"),module.exports);0&&(module.exports={AbstractAgent,HttpAgent,convertToLegacyEvents,defaultApplyEvents,parseProtoStream,parseSSEStream,runHttpRequest,transformHttpEventStream,verifyEvents,...require("@ag-ui/core")});
7
7
  //# sourceMappingURL=index.js.map