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

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
@@ -1,4 +1,3 @@
1
- import * as _ag_ui_core from '@ag-ui/core';
2
1
  import { Message, State, RunAgentInput, BaseEvent, RunStartedEvent, RunFinishedEvent, RunErrorEvent, StepStartedEvent, StepFinishedEvent, TextMessageStartEvent, TextMessageContentEvent, TextMessageEndEvent, ToolCallStartEvent, ToolCallArgsEvent, ToolCallEndEvent, ToolCallResultEvent, StateSnapshotEvent, StateDeltaEvent, MessagesSnapshotEvent, RawEvent, CustomEvent, ToolCall } from '@ag-ui/core';
3
2
  export * from '@ag-ui/core';
4
3
  import { Observable } from 'rxjs';
@@ -174,21 +173,12 @@ declare abstract class AbstractAgent {
174
173
  state: State;
175
174
  debug: boolean;
176
175
  subscribers: AgentSubscriber[];
177
- isRunning: boolean;
178
- private readonly eventsSubject;
179
- readonly events$: Observable<{
180
- type: _ag_ui_core.EventType;
181
- timestamp?: number | undefined;
182
- rawEvent?: any;
183
- }>;
184
176
  constructor({ agentId, description, threadId, initialMessages, initialState, debug, }?: AgentConfig);
185
177
  subscribe(subscriber: AgentSubscriber): {
186
178
  unsubscribe: () => void;
187
179
  };
188
180
  protected abstract run(input: RunAgentInput): Observable<BaseEvent>;
189
181
  runAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
190
- protected connect(input: RunAgentInput): Observable<BaseEvent>;
191
- connectAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
192
182
  abortRun(): void;
193
183
  protected apply(input: RunAgentInput, events$: Observable<BaseEvent>, subscribers: AgentSubscriber[]): Observable<AgentStateMutation>;
194
184
  protected processApplyEvents(input: RunAgentInput, events$: Observable<AgentStateMutation>, subscribers: AgentSubscriber[]): Observable<AgentStateMutation>;
@@ -366,4 +356,4 @@ declare class HttpAgent extends AbstractAgent {
366
356
  run(input: RunAgentInput): Observable<BaseEvent>;
367
357
  }
368
358
 
369
- export { AbstractAgent, type AgentConfig, type AgentStateMutation, type AgentSubscriber, type AgentSubscriberParams, HttpAgent, type HttpAgentConfig, type RunAgentParameters, type RunAgentResult, 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
@@ -1,4 +1,3 @@
1
- import * as _ag_ui_core from '@ag-ui/core';
2
1
  import { Message, State, RunAgentInput, BaseEvent, RunStartedEvent, RunFinishedEvent, RunErrorEvent, StepStartedEvent, StepFinishedEvent, TextMessageStartEvent, TextMessageContentEvent, TextMessageEndEvent, ToolCallStartEvent, ToolCallArgsEvent, ToolCallEndEvent, ToolCallResultEvent, StateSnapshotEvent, StateDeltaEvent, MessagesSnapshotEvent, RawEvent, CustomEvent, ToolCall } from '@ag-ui/core';
3
2
  export * from '@ag-ui/core';
4
3
  import { Observable } from 'rxjs';
@@ -174,21 +173,12 @@ declare abstract class AbstractAgent {
174
173
  state: State;
175
174
  debug: boolean;
176
175
  subscribers: AgentSubscriber[];
177
- isRunning: boolean;
178
- private readonly eventsSubject;
179
- readonly events$: Observable<{
180
- type: _ag_ui_core.EventType;
181
- timestamp?: number | undefined;
182
- rawEvent?: any;
183
- }>;
184
176
  constructor({ agentId, description, threadId, initialMessages, initialState, debug, }?: AgentConfig);
185
177
  subscribe(subscriber: AgentSubscriber): {
186
178
  unsubscribe: () => void;
187
179
  };
188
180
  protected abstract run(input: RunAgentInput): Observable<BaseEvent>;
189
181
  runAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
190
- protected connect(input: RunAgentInput): Observable<BaseEvent>;
191
- connectAgent(parameters?: RunAgentParameters, subscriber?: AgentSubscriber): Promise<RunAgentResult>;
192
182
  abortRun(): void;
193
183
  protected apply(input: RunAgentInput, events$: Observable<BaseEvent>, subscribers: AgentSubscriber[]): Observable<AgentStateMutation>;
194
184
  protected processApplyEvents(input: RunAgentInput, events$: Observable<AgentStateMutation>, subscribers: AgentSubscriber[]): Observable<AgentStateMutation>;
@@ -366,4 +356,4 @@ declare class HttpAgent extends AbstractAgent {
366
356
  run(input: RunAgentInput): Observable<BaseEvent>;
367
357
  }
368
358
 
369
- export { AbstractAgent, type AgentConfig, type AgentStateMutation, type AgentSubscriber, type AgentSubscriberParams, HttpAgent, type HttpAgentConfig, type RunAgentParameters, type RunAgentResult, 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 Me=Object.create;var K=Object.defineProperty,Ce=Object.defineProperties,Re=Object.getOwnPropertyDescriptor,_e=Object.getOwnPropertyDescriptors,Ne=Object.getOwnPropertyNames,le=Object.getOwnPropertySymbols,xe=Object.getPrototypeOf,ce=Object.prototype.hasOwnProperty,Ie=Object.prototype.propertyIsEnumerable;var ge=(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={}))ce.call(s,t)&&ge(l,t,s[t]);if(le)for(var t of le(s))Ie.call(s,t)&&ge(l,t,s[t]);return l},z=(l,s)=>Ce(l,_e(s));var Le=(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 Ne(s))!ce.call(l,e)&&e!==t&&K(l,e,{get:()=>s[e],enumerable:!(a=Re(s,e))||a.enumerable});return l},D=(l,s,t)=>(J(l,s,"default"),t&&J(t,s,"default")),b=(l,s,t)=>(t=l!=null?Me(xe(l)):{},J(s||!l||!l.__esModule?K(t,"default",{value:l,enumerable:!0}):t,l)),Oe=l=>J(K({},"__esModule",{value:!0}),l);var P={};Le(P,{AbstractAgent:()=>j,HttpAgent:()=>ae,convertToLegacyEvents:()=>ee,defaultApplyEvents:()=>q,parseProtoStream:()=>Y,parseSSEStream:()=>V,runHttpRequest:()=>W,transformHttpEventStream:()=>Z,verifyEvents:()=>U});module.exports=Oe(P);var y=require("@ag-ui/core"),F=require("rxjs/operators"),$=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 ue=require("fast-json-patch");async function C(l,s,t,a){let e=s,o=t,E;for(let r of l)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),E=g.stopPropagation,E===!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}:{}),E!==void 0?{stopPropagation:E}:{})}var Ee=b(require("untruncate-json")),q=(l,s,t,a)=>{let e=R(l.messages),o=R(l.state),E={},r=i=>{i.messages!==void 0&&(e=i.messages,E.messages=i.messages),i.state!==void 0&&(o=i.state,E.state=i.state)},g=()=>{let i=R(E);return E={},i.messages!==void 0||i.state!==void 0?(0,$.of)(i):$.EMPTY};return s.pipe((0,F.concatMap)(async i=>{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:i,agent:t,input:l,messages:n,state:S})});if(r(M),M.stopPropagation===!0)return g();switch(i.type){case y.EventType.TEXT_MESSAGE_START:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onTextMessageStartEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l})});if(r(c),c.stopPropagation!==!0){let{messageId:n,role:S="assistant"}=i,m={id:n,role:S,content:""};e.push(m),r({messages:e})}return g()}case y.EventType.TEXT_MESSAGE_CONTENT:{let{messageId:c,delta:n}=i,S=e.find(u=>u.id===c);if(!S)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${c}'`),g();let m=await C(a,e,o,(u,v,N)=>{var I,G;return(G=u.onTextMessageContentEvent)==null?void 0:G.call(u,{event:i,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})),g()}case y.EventType.TEXT_MESSAGE_END:{let{messageId:c}=i,n=e.find(m=>m.id===c);if(!n)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${c}'`),g();let S=await C(a,e,o,(m,u,v)=>{var N,I;return(I=m.onTextMessageEndEvent)==null?void 0:I.call(m,{event:i,messages:u,state:v,agent:t,input:l,textMessageBuffer:(N=n.content)!=null?N:""})});return r(S),await Promise.all(a.map(m=>{var u;(u=m.onNewMessage)==null||u.call(m,{message:n,messages:e,state:o,agent:t,input:l})})),g()}case y.EventType.TOOL_CALL_START:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onToolCallStartEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l})});if(r(c),c.stopPropagation!==!0){let{toolCallId:n,toolCallName:S,parentMessageId:m}=i,u;m&&e.length>0&&e[e.length-1].id===m?u=e[e.length-1]:(u={id:m||n,role:"assistant",toolCalls:[]},e.push(u)),(d=u.toolCalls)!=null||(u.toolCalls=[]),u.toolCalls.push({id:n,type:"function",function:{name:S,arguments:""}}),r({messages:e})}return g()}case y.EventType.TOOL_CALL_ARGS:{let{toolCallId:c,delta:n}=i,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}'`),g();let m=S.toolCalls.find(v=>v.id===c);if(!m)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c}'`),g();let u=await C(a,e,o,(v,N,I)=>{var se;let G=m.function.arguments,B=m.function.name,k={};try{k=(0,Ee.default)(G)}catch(Be){}return(se=v.onToolCallArgsEvent)==null?void 0:se.call(v,{event:i,messages:N,state:I,agent:t,input:l,toolCallBuffer:G,toolCallName:B,partialToolCallArgs:k})});return r(u),u.stopPropagation!==!0&&(m.function.arguments+=n,r({messages:e})),g()}case y.EventType.TOOL_CALL_END:{let{toolCallId:c}=i,n=e.find(u=>{var v;return(v=u.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}'`),g();let S=n.toolCalls.find(u=>u.id===c);if(!S)return console.warn(`TOOL_CALL_END: No tool call found with ID '${c}'`),g();let m=await C(a,e,o,(u,v,N)=>{var k;let I=S.function.arguments,G=S.function.name,B={};try{B=JSON.parse(I)}catch(se){}return(k=u.onToolCallEndEvent)==null?void 0:k.call(u,{event:i,messages:v,state:N,agent:t,input:l,toolCallName:G,toolCallArgs:B})});return r(m),await Promise.all(a.map(u=>{var v;(v=u.onNewToolCall)==null||v.call(u,{toolCall:S,messages:e,state:o,agent:t,input:l})})),g()}case y.EventType.TOOL_CALL_RESULT:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onToolCallResultEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l})});if(r(c),c.stopPropagation!==!0){let{messageId:n,toolCallId:S,content:m,role:u}=i,v={id:n,toolCallId:S,role:u||"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 g()}case y.EventType.STATE_SNAPSHOT:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onStateSnapshotEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l})});if(r(c),c.stopPropagation!==!0){let{snapshot:n}=i;o=n,r({state:o})}return g()}case y.EventType.STATE_DELTA:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onStateDeltaEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l})});if(r(c),c.stopPropagation!==!0){let{delta:n}=i;try{o=(0,ue.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 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:
2
2
  Current state: ${JSON.stringify(o,null,2)}
3
3
  Patch operations: ${JSON.stringify(n,null,2)}
4
- Error: ${m}`)}}return g()}case y.EventType.MESSAGES_SNAPSHOT:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onMessagesSnapshotEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l})});if(r(c),c.stopPropagation!==!0){let{messages:n}=i;e=n,r({messages:e})}return g()}case y.EventType.RAW:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onRawEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l})});return r(c),g()}case y.EventType.CUSTOM:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onCustomEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l})});return r(c),g()}case y.EventType.RUN_STARTED:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onRunStartedEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l})});return r(c),g()}case y.EventType.RUN_FINISHED:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onRunFinishedEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l,result:i.result})});return r(c),g()}case y.EventType.RUN_ERROR:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onRunErrorEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l})});return r(c),g()}case y.EventType.STEP_STARTED:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onStepStartedEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l})});return r(c),g()}case y.EventType.STEP_FINISHED:{let c=await C(a,e,o,(n,S,m)=>{var u;return(u=n.onStepFinishedEvent)==null?void 0:u.call(n,{event:i,messages:S,state:m,agent:t,input:l})});return r(c),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 w=i.type;return g()}),(0,F.mergeAll)(),a.length>0?(0,F.defaultIfEmpty)({}):i=>i)};var f=require("@ag-ui/core"),T=require("rxjs"),pe=require("rxjs/operators"),U=l=>s=>{let t=new Map,a=new Map,e=!1,o=!1,E=!1,r=new Map,g=!1,i=!1,M=!1,w=()=>{t.clear(),a.clear(),r.clear(),g=!1,i=!1,e=!1,o=!1,M=!0};return s.pipe((0,pe.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(E){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&&w()}}else if(E=!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 g?i?(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.")):(i=!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 i?(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 i?(i=!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 Te=require("@ag-ui/core"),Q=require("rxjs");var H=require("rxjs"),me=require("rxjs/operators");var W=(l,s)=>(0,H.defer)(()=>(0,H.from)(fetch(l,s))).pipe((0,me.switchMap)(t=>{var o;let a={type:"headers",status:t.status,headers:t.headers},e=(o=t.body)==null?void 0:o.getReader();return e?new H.Observable(E=>(E.next(a),(async()=>{try{for(;;){let{done:r,value:g}=await e.read();if(r)break;let i={type:"data",data:g};E.next(i)}E.complete()}catch(r){E.error(r)}})(),()=>{e.cancel()})):(0,H.throwError)(()=>new Error("Failed to getReader() from response"))}));var Se=require("rxjs");var V=l=>{let s=new Se.Subject,t=new TextDecoder("utf-8",{fatal:!1}),a="";l.subscribe({next:o=>{if(o.type!=="headers"&&o.type==="data"&&o.data){let E=t.decode(o.data,{stream:!0});a+=E;let r=a.split(/\n\n/);a=r.pop()||"";for(let g of r)e(g)}},error:o=>s.error(o),complete:()=>{a&&(a+=t.decode(),e(a)),s.complete()}});function e(o){let E=o.split(`
5
- `),r=[];for(let g of E)g.startsWith("data: ")&&r.push(g.slice(6));if(r.length>0)try{let g=r.join(`
6
- `),i=JSON.parse(g);s.next(i)}catch(g){s.error(g)}}return s.asObservable()};var de=require("rxjs");var fe=b(require("@ag-ui/proto")),Y=l=>{let s=new de.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 E=4+new DataView(t.buffer,t.byteOffset,4).getUint32(0,!1);if(t.length<E)break;try{let r=t.slice(4,E),g=fe.decode(r);s.next(g),t=t.slice(E)}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 Ae=b(require("@ag-ui/proto")),Z=l=>{let s=new Q.Subject,t=new Q.ReplaySubject,a=!1;return l.subscribe({next:e=>{t.next(e),e.type==="headers"&&!a?(a=!0,e.headers.get("content-type")===Ae.AGUI_MEDIA_TYPE?Y(t).subscribe({next:E=>s.next(E),error:E=>s.error(E),complete:()=>s.complete()}):V(t).subscribe({next:E=>{try{let r=Te.EventSchemas.parse(E);s.next(r)}catch(r){s.error(r)}},error:E=>s.error(E),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 ve=require("rxjs/operators"),he=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"]),we=p.z.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Pe=p.z.object({type:p.z.literal(h.enum.TextMessageStart),messageId:p.z.string(),parentMessageId:p.z.string().optional(),role:p.z.string().optional()}),De=p.z.object({type:p.z.literal(h.enum.TextMessageContent),messageId:p.z.string(),content:p.z.string()}),He=p.z.object({type:p.z.literal(h.enum.TextMessageEnd),messageId:p.z.string()}),Ge=p.z.object({type:p.z.literal(h.enum.ActionExecutionStart),actionExecutionId:p.z.string(),actionName:p.z.string(),parentMessageId:p.z.string().optional()}),Fe=p.z.object({type:p.z.literal(h.enum.ActionExecutionArgs),actionExecutionId:p.z.string(),args:p.z.string()}),Ue=p.z.object({type:p.z.literal(h.enum.ActionExecutionEnd),actionExecutionId:p.z.string()}),Xe=p.z.object({type:p.z.literal(h.enum.ActionExecutionResult),actionName:p.z.string(),actionExecutionId:p.z.string(),result:p.z.string()}),je=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:we,value:p.z.any()}),Ke=p.z.object({type:p.z.literal(h.enum.RunError),message:p.z.string(),code:p.z.string().optional()}),Yt=p.z.discriminatedUnion("type",[Pe,De,He,Ge,Fe,Ue,Xe,je,ke,Ke]),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=b(require("untruncate-json"));var ee=(l,s,t)=>a=>{let e={},o=!0,E=!0,r="",g=null,i=null,M=[],w={},d=c=>{typeof c=="object"&&c!==null&&("messages"in c&&delete c.messages,e=c)};return a.pipe((0,ve.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:""}}),E=!0,w[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(u=>u.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(i){let u=i.find(v=>v.tool==S.function.name);if(u)try{let v=JSON.parse((0,ye.default)(S.function.arguments));u.tool_argument&&u.tool_argument in v?(d(z(x({},e),{[u.state_key]:v[u.tool_argument]})),m=!0):u.tool_argument||(d(z(x({},e),{[u.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:E}]:[]]}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:w[n.toolCallId]||"unknown"}]}case _.EventType.RAW:return[];case _.EventType.CUSTOM:{let n=c;switch(n.name){case"Exit":o=!1;break;case"PredictState":i=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:E}];case _.EventType.STATE_DELTA:{let S=(0,he.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:E}]):[]}case _.EventType.MESSAGES_SNAPSHOT:return g=c.messages,[{type:h.enum.AgentStateMessage,threadId:l,agentName:t,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),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),g?{messages:ze(g)}:{})),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=[],i=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=[],i=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 ze(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 E of l)if(E.role==="assistant"&&((t=E.toolCalls)!=null&&t.length)){for(let r of E.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 O=require("rxjs/operators"),oe=require("rxjs/operators"),L=require("rxjs");var re=require("rxjs");var te=require("rxjs"),A=require("@ag-ui/core"),ne=l=>s=>{let t,a,e,o=()=>{if(!t||e!=="text")throw new Error("No text message to close");let g={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(g)),g},E=()=>{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,l&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(g)),g},r=()=>e==="text"?[o()]:e==="tool"?[E()]:[];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 M=g,w=[];if((e!=="text"||M.messageId!==void 0&&M.messageId!==(t==null?void 0:t.messageId))&&w.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"};w.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};w.push(n),l&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(n))}return w;case A.EventType.TOOL_CALL_CHUNK:let d=g,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 i=g.type}),(0,te.finalize)(()=>r()))};var ie=require("@ag-ui/core"),j=class{constructor({agentId:s,description:t,threadId:a,initialMessages:e,initialState:o,debug:E}={}){this.debug=!1;this.subscribers=[];this.isRunning=!1;this.eventsSubject=new L.ReplaySubject;this.events$=this.eventsSubject.asObservable();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=E!=null?E:!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,E=new Set(this.messages.map(i=>i.id)),r=[{onRunFinishedEvent:i=>{o=i.result}},...this.subscribers,t!=null?t:{}];await this.onInitialize(e,r);let g=(0,L.pipe)(()=>this.run(e),ne(this.debug),U(this.debug),(0,O.tap)(i=>{this.eventsSubject.next(i)}),i=>this.apply(e,i,r),i=>this.processApplyEvents(e,i,r),(0,O.catchError)(i=>(this.isRunning=!1,this.onError(e,i,r))),(0,oe.finalize)(()=>{this.isRunning=!1,this.onFinalize(e,r)}));return(0,re.lastValueFrom)(g((0,L.of)(null))).then(()=>{let i=R(this.messages).filter(M=>!E.has(M.id));return{result:o,newMessages:i}})}finally{this.isRunning=!1}}connect(s){throw new ie.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,E=new Set(this.messages.map(i=>i.id)),r=[{onRunFinishedEvent:i=>{o=i.result}},...this.subscribers,t!=null?t:{}];await this.onInitialize(e,r);let g=(0,L.pipe)(()=>this.connect(e),ne(this.debug),U(this.debug),(0,O.tap)(i=>{this.eventsSubject.next(i)}),i=>this.apply(e,i,r),i=>this.processApplyEvents(e,i,r),(0,O.catchError)(i=>(this.isRunning=!1,i instanceof ie.AGUIConnectNotImplementedError?L.EMPTY:this.onError(e,i,r))),(0,oe.finalize)(()=>{this.isRunning=!1,this.onFinalize(e,r)}));return(0,re.lastValueFrom)(g((0,L.of)(null))).then(()=>{let i=R(this.messages).filter(M=>!E.has(M.id));return{result:o,newMessages:i}})}finally{this.isRunning=!1}}abortRun(){}apply(s,t,a){return q(s,t,this,a)}processApplyEvents(s,t,a){return t.pipe((0,O.tap)(e=>{e.messages&&(this.messages=e.messages,a.forEach(o=>{var E;(E=o.onMessagesChanged)==null||E.call(o,{messages:this.messages,state:this.state,agent:this,input:s})})),e.state&&(this.state=e.state,a.forEach(o=>{var E;(E=o.onStateChanged)==null||E.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,E)=>{var r;return(r=e.onRunInitialized)==null?void 0:r.call(e,{messages:o,state:E,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,L.from)(C(a,this.messages,this.state,(e,o,E)=>{var r;return(r=e.onRunFailed)==null?void 0:r.call(e,{error:t,messages:o,state:E,agent:this,input:s})})).pipe((0,O.map)(e=>{let o=e;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,a.forEach(E=>{var r;(r=E.onMessagesChanged)==null||r.call(E,{messages:this.messages,state:this.state,agent:this,input:s})})),o.state!==void 0&&(this.state=o.state,a.forEach(E=>{var r;(r=E.onStateChanged)==null||r.call(E,{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,E)=>{var r;return(r=e.onRunFinalized)==null?void 0:r.call(e,{messages:o,state:E,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 E of this.subscribers)await((a=E.onNewToolCall)==null?void 0:a.call(E,{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 E of this.subscribers)await((t=E.onNewMessage)==null?void 0:t.call(E,{message:o,messages:this.messages,state:this.state,agent:this}));if(o.role==="assistant"&&o.toolCalls)for(let E of o.toolCalls)for(let r of this.subscribers)await((a=r.onNewToolCall)==null?void 0:a.call(r,{toolCall:E,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(ne(this.debug),U(this.debug),(0,O.tap)(e=>{this.eventsSubject.next(e)}),ee(this.threadId,t.runId,this.agentId),e=>e.pipe((0,O.map)(o=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(o)),o))))}};var ae=class extends j{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:z(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=W(this.url,this.requestInit(t));return Z(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")});
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")});
7
7
  //# sourceMappingURL=index.js.map