@ag-ui/client 0.0.38 → 0.0.40-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -173,12 +173,15 @@ declare abstract class AbstractAgent {
173
173
  state: State;
174
174
  debug: boolean;
175
175
  subscribers: AgentSubscriber[];
176
+ isRunning: boolean;
176
177
  constructor({ agentId, description, threadId, initialMessages, initialState, debug, }?: AgentConfig);
177
178
  subscribe(subscriber: AgentSubscriber): {
178
179
  unsubscribe: () => void;
179
180
  };
180
181
  protected abstract run(input: RunAgentInput): Observable<BaseEvent>;
181
182
  runAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
183
+ protected connect(input: RunAgentInput): Observable<BaseEvent>;
184
+ connectAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
182
185
  abortRun(): void;
183
186
  protected apply(input: RunAgentInput, events$: Observable<BaseEvent>, subscribers: AgentSubscriber[]): Observable<AgentStateMutation>;
184
187
  protected processApplyEvents(input: RunAgentInput, events$: Observable<AgentStateMutation>, subscribers: AgentSubscriber[]): Observable<AgentStateMutation>;
@@ -356,4 +359,4 @@ declare class HttpAgent extends AbstractAgent {
356
359
  run(input: RunAgentInput): Observable<BaseEvent>;
357
360
  }
358
361
 
359
- export { AbstractAgent, type AgentConfig, HttpAgent, type HttpAgentConfig, type RunAgentParameters, type RunAgentResult, convertToLegacyEvents, defaultApplyEvents, parseProtoStream, parseSSEStream, runHttpRequest, transformHttpEventStream, verifyEvents };
362
+ export { AbstractAgent, type AgentConfig, type AgentStateMutation, type AgentSubscriber, type AgentSubscriberParams, HttpAgent, type HttpAgentConfig, type RunAgentParameters, type RunAgentResult, convertToLegacyEvents, defaultApplyEvents, parseProtoStream, parseSSEStream, runHttpRequest, transformHttpEventStream, verifyEvents };
package/dist/index.d.ts CHANGED
@@ -173,12 +173,15 @@ declare abstract class AbstractAgent {
173
173
  state: State;
174
174
  debug: boolean;
175
175
  subscribers: AgentSubscriber[];
176
+ isRunning: boolean;
176
177
  constructor({ agentId, description, threadId, initialMessages, initialState, debug, }?: AgentConfig);
177
178
  subscribe(subscriber: AgentSubscriber): {
178
179
  unsubscribe: () => void;
179
180
  };
180
181
  protected abstract run(input: RunAgentInput): Observable<BaseEvent>;
181
182
  runAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
183
+ protected connect(input: RunAgentInput): Observable<BaseEvent>;
184
+ connectAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
182
185
  abortRun(): void;
183
186
  protected apply(input: RunAgentInput, events$: Observable<BaseEvent>, subscribers: AgentSubscriber[]): Observable<AgentStateMutation>;
184
187
  protected processApplyEvents(input: RunAgentInput, events$: Observable<AgentStateMutation>, subscribers: AgentSubscriber[]): Observable<AgentStateMutation>;
@@ -356,4 +359,4 @@ declare class HttpAgent extends AbstractAgent {
356
359
  run(input: RunAgentInput): Observable<BaseEvent>;
357
360
  }
358
361
 
359
- export { AbstractAgent, type AgentConfig, HttpAgent, type HttpAgentConfig, type RunAgentParameters, type RunAgentResult, convertToLegacyEvents, defaultApplyEvents, parseProtoStream, parseSSEStream, runHttpRequest, transformHttpEventStream, verifyEvents };
362
+ export { AbstractAgent, type AgentConfig, type AgentStateMutation, type AgentSubscriber, type AgentSubscriberParams, 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,Re=Object.getOwnPropertyDescriptors,_e=Object.getOwnPropertyNames,re=Object.getOwnPropertySymbols,Ne=Object.getPrototypeOf,le=Object.prototype.hasOwnProperty,xe=Object.prototype.propertyIsEnumerable;var ie=(l,s,t)=>s in l?k(l,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):l[s]=t,x=(l,s)=>{for(var t in s||(s={}))le.call(s,t)&&ie(l,t,s[t]);if(re)for(var t of re(s))xe.call(s,t)&&ie(l,t,s[t]);return l},K=(l,s)=>Me(l,Re(s));var Ie=(l,s)=>{for(var t in s)k(l,t,{get:s[t],enumerable:!0})},J=(l,s,t,a)=>{if(s&&typeof s=="object"||typeof s=="function")for(let e of _e(s))!le.call(l,e)&&e!==t&&k(l,e,{get:()=>s[e],enumerable:!(a=Ce(s,e))||a.enumerable});return l},P=(l,s,t)=>(J(l,s,"default"),t&&J(t,s,"default")),$=(l,s,t)=>(t=l!=null?ye(Ne(l)):{},J(s||!l||!l.__esModule?k(t,"default",{value:l,enumerable:!0}):t,l)),Le=l=>J(k({},"__esModule",{value:!0}),l);var w={};Ie(w,{AbstractAgent:()=>F,HttpAgent:()=>ae,convertToLegacyEvents:()=>te,defaultApplyEvents:()=>q,parseProtoStream:()=>Q,parseSSEStream:()=>Y,runHttpRequest:()=>V,transformHttpEventStream:()=>ee,verifyEvents:()=>j});module.exports=Le(w);var y=require("@ag-ui/core"),G=require("rxjs/operators"),b=require("rxjs");var R=l=>{if(typeof structuredClone=="function")return structuredClone(l);try{return JSON.parse(JSON.stringify(l))}catch(s){return x({},l)}};var ge=require("fast-json-patch");async function C(l,s,t,a){let e=s,o=t,g;for(let r of l)try{let i=await a(r,R(e),R(o));if(i===void 0)continue;if(i.messages!==void 0&&(e=i.messages),i.state!==void 0&&(o=i.state),g=i.stopPropagation,g===!0)break}catch(i){process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0||console.error("Subscriber error:",i);continue}return x(x(x({},JSON.stringify(e)!==JSON.stringify(s)?{messages:e}:{}),JSON.stringify(o)!==JSON.stringify(t)?{state:o}:{}),g!==void 0?{stopPropagation:g}:{})}var ce=$(require("untruncate-json")),q=(l,s,t,a)=>{let e=R(l.messages),o=R(l.state),g={},r=u=>{u.messages!==void 0&&(e=u.messages,g.messages=u.messages),u.state!==void 0&&(o=u.state,g.state=u.state)},i=()=>{let u=R(g);return g={},u.messages!==void 0||u.state!==void 0?(0,b.of)(u):b.EMPTY};return s.pipe((0,G.concatMap)(async u=>{var d;let M=await C(a,e,o,(c,n,S)=>{var m;return(m=c.onEvent)==null?void 0:m.call(c,{event:u,agent:t,input:l,messages:n,state:S})});if(r(M),M.stopPropagation===!0)return i();switch(u.type){case y.EventType.TEXT_MESSAGE_START:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onTextMessageStartEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l})});if(r(c),c.stopPropagation!==!0){let{messageId:n,role:S="assistant"}=u,m={id:n,role:S,content:""};e.push(m),r({messages:e})}return i()}case y.EventType.TEXT_MESSAGE_CONTENT:{let{messageId:c,delta:n}=u,S=e.find(E=>E.id===c);if(!S)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${c}'`),i();let m=await C(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:t,input:l,textMessageBuffer:(I=S.content)!=null?I:""})});return r(m),m.stopPropagation!==!0&&(S.content=(S.content||"")+n,r({messages:e})),i()}case y.EventType.TEXT_MESSAGE_END:{let{messageId:c}=u,n=e.find(m=>m.id===c);if(!n)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${c}'`),i();let S=await C(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:t,input:l,textMessageBuffer:(N=n.content)!=null?N:""})});return r(S),await Promise.all(a.map(m=>{var E;(E=m.onNewMessage)==null||E.call(m,{message:n,messages:e,state:o,agent:t,input:l})})),i()}case y.EventType.TOOL_CALL_START:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onToolCallStartEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l})});if(r(c),c.stopPropagation!==!0){let{toolCallId:n,toolCallName:S,parentMessageId:m}=u,E;m&&e.length>0&&e[e.length-1].id===m?E=e[e.length-1]:(E={id:m||n,role:"assistant",toolCalls:[]},e.push(E)),(d=E.toolCalls)!=null||(E.toolCalls=[]),E.toolCalls.push({id:n,type:"function",function:{name:S,arguments:""}}),r({messages:e})}return i()}case y.EventType.TOOL_CALL_ARGS:{let{toolCallId:c,delta:n}=u,S=e.find(v=>{var N;return(N=v.toolCalls)==null?void 0:N.some(I=>I.id===c)});if(!S)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${c}'`),i();let m=S.toolCalls.find(v=>v.id===c);if(!m)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c}'`),i();let E=await C(a,e,o,(v,N,I)=>{var se;let D=m.function.arguments,B=m.function.name,X={};try{X=(0,ce.default)(D)}catch(ze){}return(se=v.onToolCallArgsEvent)==null?void 0:se.call(v,{event:u,messages:N,state:I,agent:t,input:l,toolCallBuffer:D,toolCallName:B,partialToolCallArgs:X})});return r(E),E.stopPropagation!==!0&&(m.function.arguments+=n,r({messages:e})),i()}case y.EventType.TOOL_CALL_END:{let{toolCallId:c}=u,n=e.find(E=>{var v;return(v=E.toolCalls)==null?void 0:v.some(N=>N.id===c)});if(!n)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${c}'`),i();let S=n.toolCalls.find(E=>E.id===c);if(!S)return console.warn(`TOOL_CALL_END: No tool call found with ID '${c}'`),i();let m=await C(a,e,o,(E,v,N)=>{var X;let I=S.function.arguments,D=S.function.name,B={};try{B=JSON.parse(I)}catch(se){}return(X=E.onToolCallEndEvent)==null?void 0:X.call(E,{event:u,messages:v,state:N,agent:t,input:l,toolCallName:D,toolCallArgs:B})});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:t,input:l})})),i()}case y.EventType.TOOL_CALL_RESULT:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onToolCallResultEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l})});if(r(c),c.stopPropagation!==!0){let{messageId:n,toolCallId:S,content:m,role:E}=u,v={id:n,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:t,input:l})})),r({messages:e})}return i()}case y.EventType.STATE_SNAPSHOT:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onStateSnapshotEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l})});if(r(c),c.stopPropagation!==!0){let{snapshot:n}=u;o=n,r({state:o})}return i()}case y.EventType.STATE_DELTA:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onStateDeltaEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l})});if(r(c),c.stopPropagation!==!0){let{delta:n}=u;try{o=(0,ge.applyPatch)(o,n,!0,!1).newDocument,r({state:o})}catch(S){let m=S instanceof Error?S.message:String(S);console.warn(`Failed to apply state patch:
1
+ "use strict";var Me=Object.create;var z=Object.defineProperty,Ce=Object.defineProperties,Re=Object.getOwnPropertyDescriptor,_e=Object.getOwnPropertyDescriptors,Ne=Object.getOwnPropertyNames,ge=Object.getOwnPropertySymbols,Ie=Object.getPrototypeOf,ue=Object.prototype.hasOwnProperty,xe=Object.prototype.propertyIsEnumerable;var ce=(g,s,t)=>s in g?z(g,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):g[s]=t,I=(g,s)=>{for(var t in s||(s={}))ue.call(s,t)&&ce(g,t,s[t]);if(ge)for(var t of ge(s))xe.call(s,t)&&ce(g,t,s[t]);return g},B=(g,s)=>Ce(g,_e(s));var Le=(g,s)=>{for(var t in s)z(g,t,{get:s[t],enumerable:!0})},J=(g,s,t,a)=>{if(s&&typeof s=="object"||typeof s=="function")for(let e of Ne(s))!ue.call(g,e)&&e!==t&&z(g,e,{get:()=>s[e],enumerable:!(a=Re(s,e))||a.enumerable});return g},D=(g,s,t)=>(J(g,s,"default"),t&&J(t,s,"default")),$=(g,s,t)=>(t=g!=null?Me(Ie(g)):{},J(s||!g||!g.__esModule?z(t,"default",{value:g,enumerable:!0}):t,g)),Oe=g=>J(z({},"__esModule",{value:!0}),g);var P={};Le(P,{AbstractAgent:()=>k,HttpAgent:()=>se,convertToLegacyEvents:()=>te,defaultApplyEvents:()=>q,parseProtoStream:()=>Q,parseSSEStream:()=>Y,runHttpRequest:()=>V,transformHttpEventStream:()=>ee,verifyEvents:()=>U});module.exports=Oe(P);var M=require("@ag-ui/core"),F=require("rxjs/operators"),b=require("rxjs");var R=g=>{if(typeof structuredClone=="function")return structuredClone(g);try{return JSON.parse(JSON.stringify(g))}catch(s){return I({},g)}};var Ee=require("fast-json-patch");async function C(g,s,t,a){let e=s,o=t,u;for(let r of g)try{let i=await a(r,R(e),R(o));if(i===void 0)continue;if(i.messages!==void 0&&(e=i.messages),i.state!==void 0&&(o=i.state),u=i.stopPropagation,u===!0)break}catch(i){process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0||console.error("Subscriber error:",i);continue}return I(I(I({},JSON.stringify(e)!==JSON.stringify(s)?{messages:e}:{}),JSON.stringify(o)!==JSON.stringify(t)?{state:o}:{}),u!==void 0?{stopPropagation:u}:{})}var pe=$(require("untruncate-json")),q=(g,s,t,a)=>{let e=R(g.messages),o=R(g.state),u={},r=l=>{l.messages!==void 0&&(e=l.messages,u.messages=l.messages),l.state!==void 0&&(o=l.state,u.state=l.state)},i=()=>{let l=R(u);return u={},l.messages!==void 0||l.state!==void 0?(0,b.of)(l):b.EMPTY};return s.pipe((0,F.concatMap)(async l=>{var S;let y=await C(a,e,o,(c,n,d)=>{var m;return(m=c.onEvent)==null?void 0:m.call(c,{event:l,agent:t,input:g,messages:n,state:d})});if(r(y),y.stopPropagation===!0)return i();switch(l.type){case M.EventType.TEXT_MESSAGE_START:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onTextMessageStartEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g})});if(r(c),c.stopPropagation!==!0){let{messageId:n,role:d="assistant"}=l,m={id:n,role:d,content:""};e.push(m),r({messages:e})}return i()}case M.EventType.TEXT_MESSAGE_CONTENT:{let{messageId:c,delta:n}=l,d=e.find(E=>E.id===c);if(!d)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${c}'`),i();let m=await C(a,e,o,(E,h,N)=>{var x,G;return(G=E.onTextMessageContentEvent)==null?void 0:G.call(E,{event:l,messages:h,state:N,agent:t,input:g,textMessageBuffer:(x=d.content)!=null?x:""})});return r(m),m.stopPropagation!==!0&&(d.content=(d.content||"")+n,r({messages:e})),i()}case M.EventType.TEXT_MESSAGE_END:{let{messageId:c}=l,n=e.find(m=>m.id===c);if(!n)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${c}'`),i();let d=await C(a,e,o,(m,E,h)=>{var N,x;return(x=m.onTextMessageEndEvent)==null?void 0:x.call(m,{event:l,messages:E,state:h,agent:t,input:g,textMessageBuffer:(N=n.content)!=null?N:""})});return r(d),await Promise.all(a.map(m=>{var E;(E=m.onNewMessage)==null||E.call(m,{message:n,messages:e,state:o,agent:t,input:g})})),i()}case M.EventType.TOOL_CALL_START:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onToolCallStartEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g})});if(r(c),c.stopPropagation!==!0){let{toolCallId:n,toolCallName:d,parentMessageId:m}=l,E;m&&e.length>0&&e[e.length-1].id===m?E=e[e.length-1]:(E={id:m||n,role:"assistant",toolCalls:[]},e.push(E)),(S=E.toolCalls)!=null||(E.toolCalls=[]),E.toolCalls.push({id:n,type:"function",function:{name:d,arguments:""}}),r({messages:e})}return i()}case M.EventType.TOOL_CALL_ARGS:{let{toolCallId:c,delta:n}=l,d=e.find(h=>{var N;return(N=h.toolCalls)==null?void 0:N.some(x=>x.id===c)});if(!d)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${c}'`),i();let m=d.toolCalls.find(h=>h.id===c);if(!m)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c}'`),i();let E=await C(a,e,o,(h,N,x)=>{var oe;let G=m.function.arguments,j=m.function.name,K={};try{K=(0,pe.default)(G)}catch(je){}return(oe=h.onToolCallArgsEvent)==null?void 0:oe.call(h,{event:l,messages:N,state:x,agent:t,input:g,toolCallBuffer:G,toolCallName:j,partialToolCallArgs:K})});return r(E),E.stopPropagation!==!0&&(m.function.arguments+=n,r({messages:e})),i()}case M.EventType.TOOL_CALL_END:{let{toolCallId:c}=l,n=e.find(E=>{var h;return(h=E.toolCalls)==null?void 0:h.some(N=>N.id===c)});if(!n)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${c}'`),i();let d=n.toolCalls.find(E=>E.id===c);if(!d)return console.warn(`TOOL_CALL_END: No tool call found with ID '${c}'`),i();let m=await C(a,e,o,(E,h,N)=>{var K;let x=d.function.arguments,G=d.function.name,j={};try{j=JSON.parse(x)}catch(oe){}return(K=E.onToolCallEndEvent)==null?void 0:K.call(E,{event:l,messages:h,state:N,agent:t,input:g,toolCallName:G,toolCallArgs:j})});return r(m),await Promise.all(a.map(E=>{var h;(h=E.onNewToolCall)==null||h.call(E,{toolCall:d,messages:e,state:o,agent:t,input:g})})),i()}case M.EventType.TOOL_CALL_RESULT:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onToolCallResultEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g})});if(r(c),c.stopPropagation!==!0){let{messageId:n,toolCallId:d,content:m,role:E}=l,h={id:n,toolCallId:d,role:E||"tool",content:m};e.push(h),await Promise.all(a.map(N=>{var x;(x=N.onNewMessage)==null||x.call(N,{message:h,messages:e,state:o,agent:t,input:g})})),r({messages:e})}return i()}case M.EventType.STATE_SNAPSHOT:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onStateSnapshotEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g})});if(r(c),c.stopPropagation!==!0){let{snapshot:n}=l;o=n,r({state:o})}return i()}case M.EventType.STATE_DELTA:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onStateDeltaEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g})});if(r(c),c.stopPropagation!==!0){let{delta:n}=l;try{o=(0,Ee.applyPatch)(o,n,!0,!1).newDocument,r({state:o})}catch(d){let m=d instanceof Error?d.message:String(d);console.warn(`Failed to apply state patch:
2
2
  Current state: ${JSON.stringify(o,null,2)}
3
3
  Patch operations: ${JSON.stringify(n,null,2)}
4
- Error: ${m}`)}}return i()}case y.EventType.MESSAGES_SNAPSHOT:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onMessagesSnapshotEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l})});if(r(c),c.stopPropagation!==!0){let{messages:n}=u;e=n,r({messages:e})}return i()}case y.EventType.RAW:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onRawEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l})});return r(c),i()}case y.EventType.CUSTOM:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onCustomEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l})});return r(c),i()}case y.EventType.RUN_STARTED:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onRunStartedEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l})});return r(c),i()}case y.EventType.RUN_FINISHED:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onRunFinishedEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l,result:u.result})});return r(c),i()}case y.EventType.RUN_ERROR:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onRunErrorEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l})});return r(c),i()}case y.EventType.STEP_STARTED:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onStepStartedEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l})});return r(c),i()}case y.EventType.STEP_FINISHED:{let c=await C(a,e,o,(n,S,m)=>{var E;return(E=n.onStepFinishedEvent)==null?void 0:E.call(n,{event:u,messages:S,state:m,agent:t,input:l})});return r(c),i()}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 i();case y.EventType.THINKING_END:return i();case y.EventType.THINKING_TEXT_MESSAGE_START:return i();case y.EventType.THINKING_TEXT_MESSAGE_CONTENT:return i();case y.EventType.THINKING_TEXT_MESSAGE_END:return i()}let L=u.type;return i()}),(0,G.mergeAll)(),a.length>0?(0,G.defaultIfEmpty)({}):u=>u)};var f=require("@ag-ui/core"),T=require("rxjs"),Ee=require("rxjs/operators"),j=l=>s=>{let t=new Map,a=new Map,e=!1,o=!1,g=!1,r=new Map,i=!1,u=!1,M=!1,L=()=>{t.clear(),a.clear(),r.clear(),i=!1,u=!1,e=!1,o=!1,M=!0};return s.pipe((0,Ee.mergeMap)(d=>{let c=d.type;if(l&&console.debug("[VERIFY]:",JSON.stringify(d)),o)return(0,T.throwError)(()=>new f.AGUIError(`Cannot send event type '${c}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(e&&c!==f.EventType.RUN_ERROR&&c!==f.EventType.RUN_STARTED)return(0,T.throwError)(()=>new f.AGUIError(`Cannot send event type '${c}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(g){if(c===f.EventType.RUN_STARTED){if(M&&!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(g=!0,c!==f.EventType.RUN_STARTED&&c!==f.EventType.RUN_ERROR)return(0,T.throwError)(()=>new f.AGUIError("First event must be 'RUN_STARTED'"));switch(c){case f.EventType.TEXT_MESSAGE_START:{let n=d.messageId;return t.has(n)?(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${n}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(t.set(n,!0),(0,T.of)(d))}case f.EventType.TEXT_MESSAGE_CONTENT:{let n=d.messageId;return t.has(n)?(0,T.of)(d):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${n}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case f.EventType.TEXT_MESSAGE_END:{let n=d.messageId;return t.has(n)?(t.delete(n),(0,T.of)(d)):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${n}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case f.EventType.TOOL_CALL_START:{let n=d.toolCallId;return a.has(n)?(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${n}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(a.set(n,!0),(0,T.of)(d))}case f.EventType.TOOL_CALL_ARGS:{let n=d.toolCallId;return a.has(n)?(0,T.of)(d):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${n}'. Start a tool call with 'TOOL_CALL_START' first.`))}case f.EventType.TOOL_CALL_END:{let n=d.toolCallId;return a.has(n)?(a.delete(n),(0,T.of)(d)):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${n}'. A 'TOOL_CALL_START' event must be sent first.`))}case f.EventType.STEP_STARTED:{let n=d.stepName;return r.has(n)?(0,T.throwError)(()=>new f.AGUIError(`Step "${n}" is already active for 'STEP_STARTED'`)):(r.set(n,!0),(0,T.of)(d))}case f.EventType.STEP_FINISHED:{let n=d.stepName;return r.has(n)?(r.delete(n),(0,T.of)(d)):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'STEP_FINISHED' for step "${n}" that was not started`))}case f.EventType.RUN_STARTED:return M=!0,(0,T.of)(d);case f.EventType.RUN_FINISHED:{if(r.size>0){let n=Array.from(r.keys()).join(", ");return(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'RUN_FINISHED' while steps are still active: ${n}`))}if(t.size>0){let n=Array.from(t.keys()).join(", ");return(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'RUN_FINISHED' while text messages are still active: ${n}`))}if(a.size>0){let n=Array.from(a.keys()).join(", ");return(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${n}`))}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 i?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 i?(0,T.throwError)(()=>new f.AGUIError("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(i=!0,(0,T.of)(d));case f.EventType.THINKING_END:return i?(i=!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"),Z=require("rxjs");var O=require("rxjs"),W=require("rxjs/operators");var V=(l,s)=>(0,O.defer)(()=>(0,O.from)(fetch(l,s))).pipe((0,W.switchMap)(t=>{var o;if(!t.ok){let g=t.headers.get("content-type")||"";return(0,O.from)(t.text()).pipe((0,W.mergeMap)(r=>{let i=r;if(g.includes("application/json"))try{i=JSON.parse(r)}catch(M){}let u=new Error(`HTTP ${t.status}: ${typeof i=="string"?i:JSON.stringify(i)}`);return u.status=t.status,u.payload=i,(0,O.throwError)(()=>u)}))}let a={type:"headers",status:t.status,headers:t.headers},e=(o=t.body)==null?void 0:o.getReader();return e?new O.Observable(g=>(g.next(a),(async()=>{try{for(;;){let{done:r,value:i}=await e.read();if(r)break;let u={type:"data",data:i};g.next(u)}g.complete()}catch(r){g.error(r)}})(),()=>{e.cancel()})):(0,O.throwError)(()=>new Error("Failed to getReader() from response"))}));var ue=require("rxjs");var Y=l=>{let s=new ue.Subject,t=new TextDecoder("utf-8",{fatal:!1}),a="";l.subscribe({next:o=>{if(o.type!=="headers"&&o.type==="data"&&o.data){let g=t.decode(o.data,{stream:!0});a+=g;let r=a.split(/\n\n/);a=r.pop()||"";for(let i of r)e(i)}},error:o=>s.error(o),complete:()=>{a&&(a+=t.decode(),e(a)),s.complete()}});function e(o){let g=o.split(`
5
- `),r=[];for(let i of g)i.startsWith("data: ")&&r.push(i.slice(6));if(r.length>0)try{let i=r.join(`
6
- `),u=JSON.parse(i);s.next(u)}catch(i){s.error(i)}}return s.asObservable()};var pe=require("rxjs");var me=$(require("@ag-ui/proto")),Q=l=>{let s=new pe.Subject,t=new Uint8Array(0);l.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,a()}},error:e=>s.error(e),complete:()=>{if(t.length>0)try{a()}catch(e){console.warn("Incomplete or invalid protocol buffer data at stream end")}s.complete()}});function a(){for(;t.length>=4;){let g=4+new DataView(t.buffer,t.byteOffset,4).getUint32(0,!1);if(t.length<g)break;try{let r=t.slice(4,g),i=me.decode(r);s.next(i),t=t.slice(g)}catch(r){let i=r instanceof Error?r.message:String(r);s.error(new Error(`Failed to decode protocol buffer message: ${i}`));return}}}return s.asObservable()};var de=$(require("@ag-ui/proto")),ee=l=>{let s=new Z.Subject,t=new Z.ReplaySubject,a=!1;return l.subscribe({next:e=>{t.next(e),e.type==="headers"&&!a?(a=!0,e.headers.get("content-type")===de.AGUI_MEDIA_TYPE?Q(t).subscribe({next:g=>s.next(g),error:g=>s.error(g),complete:()=>s.complete()}):Y(t).subscribe({next:g=>{try{let r=Se.EventSchemas.parse(g);s.next(r)}catch(r){s.error(r)}},error:g=>s.error(g),complete:()=>s.complete()})):a||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 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 te=(l,s,t)=>a=>{let e={},o=!0,g=!0,r="",i=null,u=null,M=[],L={},d=c=>{typeof c=="object"&&c!==null&&("messages"in c&&delete c.messages,e=c)};return a.pipe((0,fe.mergeMap)(c=>{switch(c.type){case _.EventType.TEXT_MESSAGE_START:{let n=c;return[{type:h.enum.TextMessageStart,messageId:n.messageId,role:n.role}]}case _.EventType.TEXT_MESSAGE_CONTENT:{let n=c;return[{type:h.enum.TextMessageContent,messageId:n.messageId,content:n.delta}]}case _.EventType.TEXT_MESSAGE_END:{let n=c;return[{type:h.enum.TextMessageEnd,messageId:n.messageId}]}case _.EventType.TOOL_CALL_START:{let n=c;return M.push({id:n.toolCallId,type:"function",function:{name:n.toolCallName,arguments:""}}),g=!0,L[n.toolCallId]=n.toolCallName,[{type:h.enum.ActionExecutionStart,actionExecutionId:n.toolCallId,actionName:n.toolCallName,parentMessageId:n.parentMessageId}]}case _.EventType.TOOL_CALL_ARGS:{let n=c,S=M.find(E=>E.id===n.toolCallId);if(!S)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${n.toolCallId}'`),[];S.function.arguments+=n.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:n.toolCallId,args:n.delta},...m?[{type:h.enum.AgentStateMessage,threadId:l,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:g}]:[]]}case _.EventType.TOOL_CALL_END:{let n=c;return[{type:h.enum.ActionExecutionEnd,actionExecutionId:n.toolCallId}]}case _.EventType.TOOL_CALL_RESULT:{let n=c;return[{type:h.enum.ActionExecutionResult,actionExecutionId:n.toolCallId,result:n.content,actionName:L[n.toolCallId]||"unknown"}]}case _.EventType.RAW:return[];case _.EventType.CUSTOM:{let n=c;switch(n.name){case"Exit":o=!1;break;case"PredictState":u=n.value;break}return[{type:h.enum.MetaEvent,name:n.name,value:n.value}]}case _.EventType.STATE_SNAPSHOT:return d(c.snapshot),[{type:h.enum.AgentStateMessage,threadId:l,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:g}];case _.EventType.STATE_DELTA:{let S=(0,Te.applyPatch)(e,c.delta,!0,!1);return S?(d(S.newDocument),[{type:h.enum.AgentStateMessage,threadId:l,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:g}]):[]}case _.EventType.MESSAGES_SNAPSHOT:return i=c.messages,[{type:h.enum.AgentStateMessage,threadId:l,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(x(x({},e),i?{messages:i}:{})),active:!0}];case _.EventType.RUN_STARTED:return[];case _.EventType.RUN_FINISHED:return i&&(e.messages=i),Object.keys(e).length===0?[]:[{type:h.enum.AgentStateMessage,threadId:l,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(x(x({},e),i?{messages:je(i)}:{})),active:!1}];case _.EventType.RUN_ERROR:{let n=c;return[{type:h.enum.RunError,message:n.message,code:n.code}]}case _.EventType.STEP_STARTED:return r=c.stepName,M=[],u=null,[{type:h.enum.AgentStateMessage,threadId:l,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:!0}];case _.EventType.STEP_FINISHED:return M=[],u=null,[{type:h.enum.AgentStateMessage,threadId:l,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:!1}];default:return[]}}))};function je(l){var t;let s=[];for(let a of l)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 g of l)if(g.role==="assistant"&&((t=g.toolCalls)!=null&&t.length)){for(let r of g.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 z=require("uuid");var H=require("rxjs/operators"),ve=require("rxjs/operators"),U=require("rxjs");var he=require("rxjs");var ne=require("rxjs"),A=require("@ag-ui/core"),oe=l=>s=>{let t,a,e,o=()=>{if(!t||e!=="text")throw new Error("No text message to close");let i={type:A.EventType.TEXT_MESSAGE_END,messageId:t.messageId};return e=void 0,t=void 0,l&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(i)),i},g=()=>{if(!a||e!=="tool")throw new Error("No tool call to close");let i={type:A.EventType.TOOL_CALL_END,toolCallId:a.toolCallId};return e=void 0,a=void 0,l&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(i)),i},r=()=>e==="text"?[o()]:e==="tool"?[g()]:[];return s.pipe((0,ne.mergeMap)(i=>{switch(i.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(),i];case A.EventType.RAW:return[i];case A.EventType.TEXT_MESSAGE_CHUNK:let M=i,L=[];if((e!=="text"||M.messageId!==void 0&&M.messageId!==(t==null?void 0:t.messageId))&&L.push(...r()),e!=="text"){if(M.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");t={messageId:M.messageId},e="text";let n={type:A.EventType.TEXT_MESSAGE_START,messageId:M.messageId,role:M.role||"assistant"};L.push(n),l&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(n))}if(M.delta!==void 0){let n={type:A.EventType.TEXT_MESSAGE_CONTENT,messageId:t.messageId,delta:M.delta};L.push(n),l&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(n))}return L;case A.EventType.TOOL_CALL_CHUNK:let d=i,c=[];if((e!=="tool"||d.toolCallId!==void 0&&d.toolCallId!==(a==null?void 0:a.toolCallId))&&c.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 n={type:A.EventType.TOOL_CALL_START,toolCallId:d.toolCallId,toolCallName:d.toolCallName,parentMessageId:d.parentMessageId};c.push(n),l&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(n))}if(d.delta!==void 0){let n={type:A.EventType.TOOL_CALL_ARGS,toolCallId:a.toolCallId,delta:d.delta};c.push(n),l&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(n))}return c}let u=i.type}),(0,ne.finalize)(()=>r()))};var F=class{constructor({agentId:s,description:t,threadId:a,initialMessages:e,initialState:o,debug:g}={}){this.debug=!1;this.subscribers=[];this.agentId=s,this.description=t!=null?t:"",this.threadId=a!=null?a:(0,z.v4)(),this.messages=R(e!=null?e:[]),this.state=R(o!=null?o:{}),this.debug=g!=null?g:!1}subscribe(s){return this.subscribers.push(s),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==s)}}}async runAgent(s,t){var i;this.agentId=(i=this.agentId)!=null?i:(0,z.v4)();let a=this.prepareRunAgentInput(s),e,o=new Set(this.messages.map(u=>u.id)),g=[{onRunFinishedEvent:u=>{e=u.result}},...this.subscribers,t!=null?t:{}];await this.onInitialize(a,g);let r=(0,U.pipe)(()=>this.run(a),oe(this.debug),j(this.debug),u=>this.apply(a,u,g),u=>this.processApplyEvents(a,u,g),(0,H.catchError)(u=>this.onError(a,u,g)),(0,ve.finalize)(()=>{this.onFinalize(a,g)}));return(0,he.lastValueFrom)(r((0,U.of)(null))).then(()=>{let u=R(this.messages).filter(M=>!o.has(M.id));return{result:e,newMessages:u}})}abortRun(){}apply(s,t,a){return q(s,t,this,a)}processApplyEvents(s,t,a){return t.pipe((0,H.tap)(e=>{e.messages&&(this.messages=e.messages,a.forEach(o=>{var g;(g=o.onMessagesChanged)==null||g.call(o,{messages:this.messages,state:this.state,agent:this,input:s})})),e.state&&(this.state=e.state,a.forEach(o=>{var g;(g=o.onStateChanged)==null||g.call(o,{state:this.state,messages:this.messages,agent:this,input:s})}))}))}prepareRunAgentInput(s){var t,a,e;return{threadId:this.threadId,runId:(s==null?void 0:s.runId)||(0,z.v4)(),tools:R((t=s==null?void 0:s.tools)!=null?t:[]),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,t){let a=await C(t,this.messages,this.state,(e,o,g)=>{var r;return(r=e.onRunInitialized)==null?void 0:r.call(e,{messages:o,state:g,agent:this,input:s})});(a.messages!==void 0||a.state!==void 0)&&(a.messages&&(this.messages=a.messages,s.messages=a.messages,t.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,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,a){return(0,U.from)(C(a,this.messages,this.state,(e,o,g)=>{var r;return(r=e.onRunFailed)==null?void 0:r.call(e,{error:t,messages:o,state:g,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(g=>{var r;(r=g.onMessagesChanged)==null||r.call(g,{messages:this.messages,state:this.state,agent:this,input:s})})),o.state!==void 0&&(this.state=o.state,a.forEach(g=>{var r;(r=g.onStateChanged)==null||r.call(g,{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 a=await C(t,this.messages,this.state,(e,o,g)=>{var r;return(r=e.onRunFinalized)==null?void 0:r.call(e,{messages:o,state:g,agent:this,input:s})});(a.messages!==void 0||a.state!==void 0)&&(a.messages!==void 0&&(this.messages=a.messages,t.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,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 a=this[t];typeof a!="function"&&(s[t]=R(a))}return s}addMessage(s){this.messages.push(s),(async()=>{var t,a,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 g of this.subscribers)await((a=g.onNewToolCall)==null?void 0:a.call(g,{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,a,e;for(let o of s){for(let g of this.subscribers)await((t=g.onNewMessage)==null?void 0:t.call(g,{message:o,messages:this.messages,state:this.state,agent:this}));if(o.role==="assistant"&&o.toolCalls)for(let g of o.toolCalls)for(let r of this.subscribers)await((a=r.onNewToolCall)==null?void 0:a.call(r,{toolCall:g,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 t;for(let a of this.subscribers)await((t=a.onMessagesChanged)==null?void 0:t.call(a,{messages:this.messages,state:this.state,agent:this}))})()}setState(s){this.state=R(s),(async()=>{var t;for(let a of this.subscribers)await((t=a.onStateChanged)==null?void 0:t.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,z.v4)();let t=this.prepareRunAgentInput(s);return this.run(t).pipe(oe(this.debug),j(this.debug),te(this.threadId,t.runId,this.agentId),e=>e.pipe((0,H.map)(o=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(o)),o))))}};var ae=class extends F{constructor(t){var a;super(t);this.abortController=new AbortController;this.url=t.url,this.headers=R((a=t.headers)!=null?a:{})}requestInit(t){return{method:"POST",headers:K(x({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(t),signal:this.abortController.signal}}runAgent(t,a){var e;return this.abortController=(e=t==null?void 0:t.abortController)!=null?e:new AbortController,super.runAgent(t,a)}abortRun(){this.abortController.abort(),super.abortRun()}run(t){let a=V(this.url,this.requestInit(t));return ee(a)}};P(w,require("@ag-ui/core"),module.exports);0&&(module.exports={AbstractAgent,HttpAgent,convertToLegacyEvents,defaultApplyEvents,parseProtoStream,parseSSEStream,runHttpRequest,transformHttpEventStream,verifyEvents,...require("@ag-ui/core")});
4
+ Error: ${m}`)}}return i()}case M.EventType.MESSAGES_SNAPSHOT:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onMessagesSnapshotEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g})});if(r(c),c.stopPropagation!==!0){let{messages:n}=l;e=n,r({messages:e})}return i()}case M.EventType.RAW:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onRawEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g})});return r(c),i()}case M.EventType.CUSTOM:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onCustomEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g})});return r(c),i()}case M.EventType.RUN_STARTED:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onRunStartedEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g})});return r(c),i()}case M.EventType.RUN_FINISHED:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onRunFinishedEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g,result:l.result})});return r(c),i()}case M.EventType.RUN_ERROR:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onRunErrorEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g})});return r(c),i()}case M.EventType.STEP_STARTED:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onStepStartedEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g})});return r(c),i()}case M.EventType.STEP_FINISHED:{let c=await C(a,e,o,(n,d,m)=>{var E;return(E=n.onStepFinishedEvent)==null?void 0:E.call(n,{event:l,messages:d,state:m,agent:t,input:g})});return r(c),i()}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 i();case M.EventType.THINKING_END:return i();case M.EventType.THINKING_TEXT_MESSAGE_START:return i();case M.EventType.THINKING_TEXT_MESSAGE_CONTENT:return i();case M.EventType.THINKING_TEXT_MESSAGE_END:return i()}let L=l.type;return i()}),(0,F.mergeAll)(),a.length>0?(0,F.defaultIfEmpty)({}):l=>l)};var f=require("@ag-ui/core"),T=require("rxjs"),me=require("rxjs/operators"),U=g=>s=>{let t=new Map,a=new Map,e=!1,o=!1,u=!1,r=new Map,i=!1,l=!1,y=!1,L=()=>{t.clear(),a.clear(),r.clear(),i=!1,l=!1,e=!1,o=!1,y=!0};return s.pipe((0,me.mergeMap)(S=>{let c=S.type;if(g&&console.debug("[VERIFY]:",JSON.stringify(S)),o)return(0,T.throwError)(()=>new f.AGUIError(`Cannot send event type '${c}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(e&&c!==f.EventType.RUN_ERROR&&c!==f.EventType.RUN_STARTED)return(0,T.throwError)(()=>new f.AGUIError(`Cannot send event type '${c}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(u){if(c===f.EventType.RUN_STARTED){if(y&&!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(u=!0,c!==f.EventType.RUN_STARTED&&c!==f.EventType.RUN_ERROR)return(0,T.throwError)(()=>new f.AGUIError("First event must be 'RUN_STARTED'"));switch(c){case f.EventType.TEXT_MESSAGE_START:{let n=S.messageId;return t.has(n)?(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${n}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(t.set(n,!0),(0,T.of)(S))}case f.EventType.TEXT_MESSAGE_CONTENT:{let n=S.messageId;return t.has(n)?(0,T.of)(S):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${n}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case f.EventType.TEXT_MESSAGE_END:{let n=S.messageId;return t.has(n)?(t.delete(n),(0,T.of)(S)):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${n}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case f.EventType.TOOL_CALL_START:{let n=S.toolCallId;return a.has(n)?(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${n}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(a.set(n,!0),(0,T.of)(S))}case f.EventType.TOOL_CALL_ARGS:{let n=S.toolCallId;return a.has(n)?(0,T.of)(S):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${n}'. Start a tool call with 'TOOL_CALL_START' first.`))}case f.EventType.TOOL_CALL_END:{let n=S.toolCallId;return a.has(n)?(a.delete(n),(0,T.of)(S)):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${n}'. A 'TOOL_CALL_START' event must be sent first.`))}case f.EventType.STEP_STARTED:{let n=S.stepName;return r.has(n)?(0,T.throwError)(()=>new f.AGUIError(`Step "${n}" is already active for 'STEP_STARTED'`)):(r.set(n,!0),(0,T.of)(S))}case f.EventType.STEP_FINISHED:{let n=S.stepName;return r.has(n)?(r.delete(n),(0,T.of)(S)):(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'STEP_FINISHED' for step "${n}" that was not started`))}case f.EventType.RUN_STARTED:return y=!0,(0,T.of)(S);case f.EventType.RUN_FINISHED:{if(r.size>0){let n=Array.from(r.keys()).join(", ");return(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'RUN_FINISHED' while steps are still active: ${n}`))}if(t.size>0){let n=Array.from(t.keys()).join(", ");return(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'RUN_FINISHED' while text messages are still active: ${n}`))}if(a.size>0){let n=Array.from(a.keys()).join(", ");return(0,T.throwError)(()=>new f.AGUIError(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${n}`))}return e=!0,(0,T.of)(S)}case f.EventType.RUN_ERROR:return o=!0,(0,T.of)(S);case f.EventType.CUSTOM:return(0,T.of)(S);case f.EventType.THINKING_TEXT_MESSAGE_START:return i?l?(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.")):(l=!0,(0,T.of)(S)):(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 l?(0,T.of)(S):(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 l?(l=!1,(0,T.of)(S)):(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 i?(0,T.throwError)(()=>new f.AGUIError("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(i=!0,(0,T.of)(S));case f.EventType.THINKING_END:return i?(i=!1,(0,T.of)(S)):(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)(S)}}))};var Te=require("@ag-ui/core"),Z=require("rxjs");var O=require("rxjs"),W=require("rxjs/operators");var V=(g,s)=>(0,O.defer)(()=>(0,O.from)(fetch(g,s))).pipe((0,W.switchMap)(t=>{var o;if(!t.ok){let u=t.headers.get("content-type")||"";return(0,O.from)(t.text()).pipe((0,W.mergeMap)(r=>{let i=r;if(u.includes("application/json"))try{i=JSON.parse(r)}catch(y){}let l=new Error(`HTTP ${t.status}: ${typeof i=="string"?i:JSON.stringify(i)}`);return l.status=t.status,l.payload=i,(0,O.throwError)(()=>l)}))}let a={type:"headers",status:t.status,headers:t.headers},e=(o=t.body)==null?void 0:o.getReader();return e?new O.Observable(u=>(u.next(a),(async()=>{try{for(;;){let{done:r,value:i}=await e.read();if(r)break;let l={type:"data",data:i};u.next(l)}u.complete()}catch(r){u.error(r)}})(),()=>{e.cancel()})):(0,O.throwError)(()=>new Error("Failed to getReader() from response"))}));var de=require("rxjs");var Y=g=>{let s=new de.Subject,t=new TextDecoder("utf-8",{fatal:!1}),a="";g.subscribe({next:o=>{if(o.type!=="headers"&&o.type==="data"&&o.data){let u=t.decode(o.data,{stream:!0});a+=u;let r=a.split(/\n\n/);a=r.pop()||"";for(let i of r)e(i)}},error:o=>s.error(o),complete:()=>{a&&(a+=t.decode(),e(a)),s.complete()}});function e(o){let u=o.split(`
5
+ `),r=[];for(let i of u)i.startsWith("data: ")&&r.push(i.slice(6));if(r.length>0)try{let i=r.join(`
6
+ `),l=JSON.parse(i);s.next(l)}catch(i){s.error(i)}}return s.asObservable()};var Se=require("rxjs");var fe=$(require("@ag-ui/proto")),Q=g=>{let s=new Se.Subject,t=new Uint8Array(0);g.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,a()}},error:e=>s.error(e),complete:()=>{if(t.length>0)try{a()}catch(e){console.warn("Incomplete or invalid protocol buffer data at stream end")}s.complete()}});function a(){for(;t.length>=4;){let u=4+new DataView(t.buffer,t.byteOffset,4).getUint32(0,!1);if(t.length<u)break;try{let r=t.slice(4,u),i=fe.decode(r);s.next(i),t=t.slice(u)}catch(r){let i=r instanceof Error?r.message:String(r);s.error(new Error(`Failed to decode protocol buffer message: ${i}`));return}}}return s.asObservable()};var Ae=$(require("@ag-ui/proto")),ee=g=>{let s=new Z.Subject,t=new Z.ReplaySubject,a=!1;return g.subscribe({next:e=>{t.next(e),e.type==="headers"&&!a?(a=!0,e.headers.get("content-type")===Ae.AGUI_MEDIA_TYPE?Q(t).subscribe({next:u=>s.next(u),error:u=>s.error(u),complete:()=>s.complete()}):Y(t).subscribe({next:u=>{try{let r=Te.EventSchemas.parse(u);s.next(r)}catch(r){s.error(r)}},error:u=>s.error(u),complete:()=>s.complete()})):a||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 he=require("rxjs/operators"),ve=require("fast-json-patch"),_=require("@ag-ui/core");var p=require("zod"),v=p.z.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),we=p.z.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Pe=p.z.object({type:p.z.literal(v.enum.TextMessageStart),messageId:p.z.string(),parentMessageId:p.z.string().optional(),role:p.z.string().optional()}),De=p.z.object({type:p.z.literal(v.enum.TextMessageContent),messageId:p.z.string(),content:p.z.string()}),He=p.z.object({type:p.z.literal(v.enum.TextMessageEnd),messageId:p.z.string()}),Ge=p.z.object({type:p.z.literal(v.enum.ActionExecutionStart),actionExecutionId:p.z.string(),actionName:p.z.string(),parentMessageId:p.z.string().optional()}),Fe=p.z.object({type:p.z.literal(v.enum.ActionExecutionArgs),actionExecutionId:p.z.string(),args:p.z.string()}),Ue=p.z.object({type:p.z.literal(v.enum.ActionExecutionEnd),actionExecutionId:p.z.string()}),Xe=p.z.object({type:p.z.literal(v.enum.ActionExecutionResult),actionName:p.z.string(),actionExecutionId:p.z.string(),result:p.z.string()}),ke=p.z.object({type:p.z.literal(v.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(v.enum.MetaEvent),name:we,value:p.z.any()}),ze=p.z.object({type:p.z.literal(v.enum.RunError),message:p.z.string(),code:p.z.string().optional()}),Yt=p.z.discriminatedUnion("type",[Pe,De,He,Ge,Fe,Ue,Xe,ke,Ke,ze]),Qt=p.z.object({id:p.z.string(),role:p.z.string(),content:p.z.string(),parentMessageId:p.z.string().optional()}),Zt=p.z.object({id:p.z.string(),name:p.z.string(),arguments:p.z.any(),parentMessageId:p.z.string().optional()}),en=p.z.object({id:p.z.string(),result:p.z.any(),actionExecutionId:p.z.string(),actionName:p.z.string()});var ye=$(require("untruncate-json"));var te=(g,s,t)=>a=>{let e={},o=!0,u=!0,r="",i=null,l=null,y=[],L={},S=c=>{typeof c=="object"&&c!==null&&("messages"in c&&delete c.messages,e=c)};return a.pipe((0,he.mergeMap)(c=>{switch(c.type){case _.EventType.TEXT_MESSAGE_START:{let n=c;return[{type:v.enum.TextMessageStart,messageId:n.messageId,role:n.role}]}case _.EventType.TEXT_MESSAGE_CONTENT:{let n=c;return[{type:v.enum.TextMessageContent,messageId:n.messageId,content:n.delta}]}case _.EventType.TEXT_MESSAGE_END:{let n=c;return[{type:v.enum.TextMessageEnd,messageId:n.messageId}]}case _.EventType.TOOL_CALL_START:{let n=c;return y.push({id:n.toolCallId,type:"function",function:{name:n.toolCallName,arguments:""}}),u=!0,L[n.toolCallId]=n.toolCallName,[{type:v.enum.ActionExecutionStart,actionExecutionId:n.toolCallId,actionName:n.toolCallName,parentMessageId:n.parentMessageId}]}case _.EventType.TOOL_CALL_ARGS:{let n=c,d=y.find(E=>E.id===n.toolCallId);if(!d)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${n.toolCallId}'`),[];d.function.arguments+=n.delta;let m=!1;if(l){let E=l.find(h=>h.tool==d.function.name);if(E)try{let h=JSON.parse((0,ye.default)(d.function.arguments));E.tool_argument&&E.tool_argument in h?(S(B(I({},e),{[E.state_key]:h[E.tool_argument]})),m=!0):E.tool_argument||(S(B(I({},e),{[E.state_key]:h})),m=!0)}catch(h){}}return[{type:v.enum.ActionExecutionArgs,actionExecutionId:n.toolCallId,args:n.delta},...m?[{type:v.enum.AgentStateMessage,threadId:g,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:u}]:[]]}case _.EventType.TOOL_CALL_END:{let n=c;return[{type:v.enum.ActionExecutionEnd,actionExecutionId:n.toolCallId}]}case _.EventType.TOOL_CALL_RESULT:{let n=c;return[{type:v.enum.ActionExecutionResult,actionExecutionId:n.toolCallId,result:n.content,actionName:L[n.toolCallId]||"unknown"}]}case _.EventType.RAW:return[];case _.EventType.CUSTOM:{let n=c;switch(n.name){case"Exit":o=!1;break;case"PredictState":l=n.value;break}return[{type:v.enum.MetaEvent,name:n.name,value:n.value}]}case _.EventType.STATE_SNAPSHOT:return S(c.snapshot),[{type:v.enum.AgentStateMessage,threadId:g,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:u}];case _.EventType.STATE_DELTA:{let d=(0,ve.applyPatch)(e,c.delta,!0,!1);return d?(S(d.newDocument),[{type:v.enum.AgentStateMessage,threadId:g,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:u}]):[]}case _.EventType.MESSAGES_SNAPSHOT:return i=c.messages,[{type:v.enum.AgentStateMessage,threadId:g,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(I(I({},e),i?{messages:i}:{})),active:!0}];case _.EventType.RUN_STARTED:return[];case _.EventType.RUN_FINISHED:return i&&(e.messages=i),Object.keys(e).length===0?[]:[{type:v.enum.AgentStateMessage,threadId:g,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(I(I({},e),i?{messages:Be(i)}:{})),active:!1}];case _.EventType.RUN_ERROR:{let n=c;return[{type:v.enum.RunError,message:n.message,code:n.code}]}case _.EventType.STEP_STARTED:return r=c.stepName,y=[],l=null,[{type:v.enum.AgentStateMessage,threadId:g,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:!0}];case _.EventType.STEP_FINISHED:return y=[],l=null,[{type:v.enum.AgentStateMessage,threadId:g,agentName:t,nodeName:r,runId:s,running:o,role:"assistant",state:JSON.stringify(e),active:!1}];default:return[]}}))};function Be(g){var t;let s=[];for(let a of g)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 u of g)if(u.role==="assistant"&&((t=u.toolCalls)!=null&&t.length)){for(let r of u.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 X=require("uuid");var H=require("rxjs/operators"),re=require("rxjs/operators"),w=require("rxjs");var ie=require("rxjs");var ne=require("rxjs"),A=require("@ag-ui/core"),ae=g=>s=>{let t,a,e,o=()=>{if(!t||e!=="text")throw new Error("No text message to close");let i={type:A.EventType.TEXT_MESSAGE_END,messageId:t.messageId};return e=void 0,t=void 0,g&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(i)),i},u=()=>{if(!a||e!=="tool")throw new Error("No tool call to close");let i={type:A.EventType.TOOL_CALL_END,toolCallId:a.toolCallId};return e=void 0,a=void 0,g&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(i)),i},r=()=>e==="text"?[o()]:e==="tool"?[u()]:[];return s.pipe((0,ne.mergeMap)(i=>{switch(i.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(),i];case A.EventType.RAW:return[i];case A.EventType.TEXT_MESSAGE_CHUNK:let y=i,L=[];if((e!=="text"||y.messageId!==void 0&&y.messageId!==(t==null?void 0:t.messageId))&&L.push(...r()),e!=="text"){if(y.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");t={messageId:y.messageId},e="text";let n={type:A.EventType.TEXT_MESSAGE_START,messageId:y.messageId,role:y.role||"assistant"};L.push(n),g&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(n))}if(y.delta!==void 0){let n={type:A.EventType.TEXT_MESSAGE_CONTENT,messageId:t.messageId,delta:y.delta};L.push(n),g&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(n))}return L;case A.EventType.TOOL_CALL_CHUNK:let S=i,c=[];if((e!=="tool"||S.toolCallId!==void 0&&S.toolCallId!==(a==null?void 0:a.toolCallId))&&c.push(...r()),e!=="tool"){if(S.toolCallId===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallId");if(S.toolCallName===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallName");a={toolCallId:S.toolCallId,toolCallName:S.toolCallName,parentMessageId:S.parentMessageId},e="tool";let n={type:A.EventType.TOOL_CALL_START,toolCallId:S.toolCallId,toolCallName:S.toolCallName,parentMessageId:S.parentMessageId};c.push(n),g&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(n))}if(S.delta!==void 0){let n={type:A.EventType.TOOL_CALL_ARGS,toolCallId:a.toolCallId,delta:S.delta};c.push(n),g&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(n))}return c}let l=i.type}),(0,ne.finalize)(()=>r()))};var le=require("@ag-ui/core"),k=class{constructor({agentId:s,description:t,threadId:a,initialMessages:e,initialState:o,debug:u}={}){this.debug=!1;this.subscribers=[];this.isRunning=!1;this.agentId=s,this.description=t!=null?t:"",this.threadId=a!=null?a:(0,X.v4)(),this.messages=R(e!=null?e:[]),this.state=R(o!=null?o:{}),this.debug=u!=null?u:!1}subscribe(s){return this.subscribers.push(s),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==s)}}}async runAgent(s,t){var a;try{this.isRunning=!0,this.agentId=(a=this.agentId)!=null?a:(0,X.v4)();let e=this.prepareRunAgentInput(s),o,u=new Set(this.messages.map(l=>l.id)),r=[{onRunFinishedEvent:l=>{o=l.result}},...this.subscribers,t!=null?t:{}];await this.onInitialize(e,r);let i=(0,w.pipe)(()=>this.run(e),ae(this.debug),U(this.debug),l=>this.apply(e,l,r),l=>this.processApplyEvents(e,l,r),(0,H.catchError)(l=>(this.isRunning=!1,this.onError(e,l,r))),(0,re.finalize)(()=>{this.isRunning=!1,this.onFinalize(e,r)}));return(0,ie.lastValueFrom)(i((0,w.of)(null))).then(()=>{let l=R(this.messages).filter(y=>!u.has(y.id));return{result:o,newMessages:l}})}finally{this.isRunning=!1}}connect(s){throw new le.AGUIConnectNotImplementedError}async connectAgent(s,t){var a;try{this.isRunning=!0,this.agentId=(a=this.agentId)!=null?a:(0,X.v4)();let e=this.prepareRunAgentInput(s),o,u=new Set(this.messages.map(l=>l.id)),r=[{onRunFinishedEvent:l=>{o=l.result}},...this.subscribers,t!=null?t:{}];await this.onInitialize(e,r);let i=(0,w.pipe)(()=>this.connect(e),ae(this.debug),U(this.debug),l=>this.apply(e,l,r),l=>this.processApplyEvents(e,l,r),(0,H.catchError)(l=>(this.isRunning=!1,l instanceof le.AGUIConnectNotImplementedError?w.EMPTY:this.onError(e,l,r))),(0,re.finalize)(()=>{this.isRunning=!1,this.onFinalize(e,r)}));return(0,ie.lastValueFrom)(i((0,w.of)(null))).then(()=>{let l=R(this.messages).filter(y=>!u.has(y.id));return{result:o,newMessages:l}})}finally{this.isRunning=!1}}abortRun(){}apply(s,t,a){return q(s,t,this,a)}processApplyEvents(s,t,a){return t.pipe((0,H.tap)(e=>{e.messages&&(this.messages=e.messages,a.forEach(o=>{var u;(u=o.onMessagesChanged)==null||u.call(o,{messages:this.messages,state:this.state,agent:this,input:s})})),e.state&&(this.state=e.state,a.forEach(o=>{var u;(u=o.onStateChanged)==null||u.call(o,{state:this.state,messages:this.messages,agent:this,input:s})}))}))}prepareRunAgentInput(s){var t,a,e;return{threadId:this.threadId,runId:(s==null?void 0:s.runId)||(0,X.v4)(),tools:R((t=s==null?void 0:s.tools)!=null?t:[]),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,t){let a=await C(t,this.messages,this.state,(e,o,u)=>{var r;return(r=e.onRunInitialized)==null?void 0:r.call(e,{messages:o,state:u,agent:this,input:s})});(a.messages!==void 0||a.state!==void 0)&&(a.messages&&(this.messages=a.messages,s.messages=a.messages,t.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,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,a){return(0,w.from)(C(a,this.messages,this.state,(e,o,u)=>{var r;return(r=e.onRunFailed)==null?void 0:r.call(e,{error:t,messages:o,state:u,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(u=>{var r;(r=u.onMessagesChanged)==null||r.call(u,{messages:this.messages,state:this.state,agent:this,input:s})})),o.state!==void 0&&(this.state=o.state,a.forEach(u=>{var r;(r=u.onStateChanged)==null||r.call(u,{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 a=await C(t,this.messages,this.state,(e,o,u)=>{var r;return(r=e.onRunFinalized)==null?void 0:r.call(e,{messages:o,state:u,agent:this,input:s})});(a.messages!==void 0||a.state!==void 0)&&(a.messages!==void 0&&(this.messages=a.messages,t.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,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 a=this[t];typeof a!="function"&&(s[t]=R(a))}return s}addMessage(s){this.messages.push(s),(async()=>{var t,a,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 u of this.subscribers)await((a=u.onNewToolCall)==null?void 0:a.call(u,{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,a,e;for(let o of s){for(let u of this.subscribers)await((t=u.onNewMessage)==null?void 0:t.call(u,{message:o,messages:this.messages,state:this.state,agent:this}));if(o.role==="assistant"&&o.toolCalls)for(let u of o.toolCalls)for(let r of this.subscribers)await((a=r.onNewToolCall)==null?void 0:a.call(r,{toolCall:u,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 t;for(let a of this.subscribers)await((t=a.onMessagesChanged)==null?void 0:t.call(a,{messages:this.messages,state:this.state,agent:this}))})()}setState(s){this.state=R(s),(async()=>{var t;for(let a of this.subscribers)await((t=a.onStateChanged)==null?void 0:t.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,X.v4)();let t=this.prepareRunAgentInput(s);return this.run(t).pipe(ae(this.debug),U(this.debug),te(this.threadId,t.runId,this.agentId),e=>e.pipe((0,H.map)(o=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(o)),o))))}};var se=class extends k{constructor(t){var a;super(t);this.abortController=new AbortController;this.url=t.url,this.headers=R((a=t.headers)!=null?a:{})}requestInit(t){return{method:"POST",headers:B(I({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(t),signal:this.abortController.signal}}runAgent(t,a){var e;return this.abortController=(e=t==null?void 0:t.abortController)!=null?e:new AbortController,super.runAgent(t,a)}abortRun(){this.abortController.abort(),super.abortRun()}run(t){let a=V(this.url,this.requestInit(t));return ee(a)}};D(P,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