@ag-ui/client 0.0.28-alpha.3 → 0.0.28-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,8 @@
1
+ Copyright (c) 2025 Tawkit Inc.
2
+ Copyright (c) 2025 Markus Ecker
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/dist/index.d.mts CHANGED
@@ -191,12 +191,12 @@ interface HttpAgentConfig extends AgentConfig {
191
191
  type RunAgentParameters = Partial<Pick<RunAgentInput, "runId" | "tools" | "context" | "forwardedProps">>;
192
192
 
193
193
  declare abstract class AbstractAgent {
194
+ #private;
194
195
  agentId?: string;
195
196
  description: string;
196
197
  threadId: string;
197
198
  messages: Message[];
198
199
  state: State;
199
- debug: boolean;
200
200
  constructor({ agentId, description, threadId, initialMessages, initialState, debug, }?: AgentConfig);
201
201
  protected abstract run(...args: Parameters<RunAgent>): ReturnType<RunAgent>;
202
202
  runAgent(parameters?: RunAgentParameters): Promise<void>;
package/dist/index.d.ts CHANGED
@@ -191,12 +191,12 @@ interface HttpAgentConfig extends AgentConfig {
191
191
  type RunAgentParameters = Partial<Pick<RunAgentInput, "runId" | "tools" | "context" | "forwardedProps">>;
192
192
 
193
193
  declare abstract class AbstractAgent {
194
+ #private;
194
195
  agentId?: string;
195
196
  description: string;
196
197
  threadId: string;
197
198
  messages: Message[];
198
199
  state: State;
199
- debug: boolean;
200
200
  constructor({ agentId, description, threadId, initialMessages, initialState, debug, }?: AgentConfig);
201
201
  protected abstract run(...args: Parameters<RunAgent>): ReturnType<RunAgent>;
202
202
  runAgent(parameters?: RunAgentParameters): Promise<void>;
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- "use strict";var pe=Object.create;var w=Object.defineProperty,de=Object.defineProperties,fe=Object.getOwnPropertyDescriptor,Te=Object.getOwnPropertyDescriptors,me=Object.getOwnPropertyNames,W=Object.getOwnPropertySymbols,Se=Object.getPrototypeOf,Q=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable;var Y=(a,n,e)=>n in a?w(a,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[n]=e,_=(a,n)=>{for(var e in n||(n={}))Q.call(n,e)&&Y(a,e,n[e]);if(W)for(var e of W(n))Ae.call(n,e)&&Y(a,e,n[e]);return a},M=(a,n)=>de(a,Te(n));var ye=(a,n)=>{for(var e in n)w(a,e,{get:n[e],enumerable:!0})},P=(a,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of me(n))!Q.call(a,s)&&s!==e&&w(a,s,{get:()=>n[s],enumerable:!(t=fe(n,s))||t.enumerable});return a},h=(a,n,e)=>(P(a,n,"default"),e&&P(e,n,"default")),G=(a,n,e)=>(e=a!=null?pe(Se(a)):{},P(n||!a||!a.__esModule?w(e,"default",{value:a,enumerable:!0}):e,a)),ve=a=>P(w({},"__esModule",{value:!0}),a);var x={};ye(x,{AbstractAgent:()=>N,HttpAgent:()=>V,convertToLegacyEvents:()=>z,defaultApplyEvents:()=>U,parseProtoStream:()=>j,parseSSEStream:()=>X,runHttpRequest:()=>F,transformHttpEventStream:()=>J,verifyEvents:()=>D});module.exports=ve(x);var y=require("@ag-ui/core"),Z=require("rxjs/operators");var C=a=>{if(typeof structuredClone=="function")return structuredClone(a);try{return JSON.parse(JSON.stringify(a))}catch(n){return _({},a)}};var ee=require("fast-json-patch"),te=G(require("untruncate-json"));var U=(...a)=>{let[n,e]=a,t=C(n.messages),s=C(n.state),l,c=r=>[C(r)],i=()=>[];return e.pipe((0,Z.mergeMap)(r=>{var f;switch(r.type){case y.EventType.TEXT_MESSAGE_START:{let{messageId:T,role:u}=r,E={id:T,role:u,content:""};return t.push(E),c({messages:t})}case y.EventType.TEXT_MESSAGE_CONTENT:{let{delta:T}=r,u=t[t.length-1];return u.content=u.content+T,c({messages:t})}case y.EventType.TEXT_MESSAGE_END:return i();case y.EventType.TOOL_CALL_START:{let{toolCallId:T,toolCallName:u,parentMessageId:E}=r,d;return E&&t.length>0&&t[t.length-1].id===E?d=t[t.length-1]:(d={id:E||T,role:"assistant",toolCalls:[]},t.push(d)),(f=d.toolCalls)!=null||(d.toolCalls=[]),d.toolCalls.push({id:T,type:"function",function:{name:u,arguments:""}}),c({messages:t})}case y.EventType.TOOL_CALL_ARGS:{let{delta:T}=r,u=t[t.length-1],E=u.toolCalls[u.toolCalls.length-1];if(E.function.arguments+=T,l){let d=l.find(L=>L.tool===E.function.name);if(d)try{let L=JSON.parse((0,te.default)(E.function.arguments));return d.tool_argument&&d.tool_argument in L?(s=M(_({},s),{[d.state_key]:L[d.tool_argument]}),c({messages:t,state:s})):(s=M(_({},s),{[d.state_key]:L}),c({messages:t,state:s}))}catch(L){}}return c({messages:t})}case y.EventType.TOOL_CALL_END:return i();case y.EventType.STATE_SNAPSHOT:{let{snapshot:T}=r;return s=T,c({state:s})}case y.EventType.STATE_DELTA:{let{delta:T}=r;try{return s=(0,ee.applyPatch)(s,T,!0,!1).newDocument,c({state:s})}catch(u){let E=u instanceof Error?u.message:String(u);return console.warn(`Failed to apply state patch:
1
+ "use strict";var Ae=Object.create;var H=Object.defineProperty,ye=Object.defineProperties,ve=Object.getOwnPropertyDescriptor,Ce=Object.getOwnPropertyDescriptors,_e=Object.getOwnPropertyNames,Q=Object.getOwnPropertySymbols,Le=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty,xe=Object.prototype.propertyIsEnumerable;var te=r=>{throw TypeError(r)};var Z=(r,t,e)=>t in r?H(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,_=(r,t)=>{for(var e in t||(t={}))ee.call(t,e)&&Z(r,e,t[e]);if(Q)for(var e of Q(t))xe.call(t,e)&&Z(r,e,t[e]);return r},R=(r,t)=>ye(r,Ce(t));var he=(r,t)=>{for(var e in t)H(r,e,{get:t[e],enumerable:!0})},U=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of _e(t))!ee.call(r,s)&&s!==e&&H(r,s,{get:()=>t[s],enumerable:!(n=ve(t,s))||n.enumerable});return r},h=(r,t,e)=>(U(r,t,"default"),e&&U(e,t,"default")),F=(r,t,e)=>(e=r!=null?Ae(Le(r)):{},U(t||!r||!r.__esModule?H(e,"default",{value:r,enumerable:!0}):e,r)),Me=r=>U(H({},"__esModule",{value:!0}),r);var ne=(r,t,e)=>t.has(r)||te("Cannot "+e);var I=(r,t,e)=>(ne(r,t,"read from private field"),e?e.call(r):t.get(r)),se=(r,t,e)=>t.has(r)?te("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(r):t.set(r,e),re=(r,t,e,n)=>(ne(r,t,"write to private field"),n?n.call(r,e):t.set(r,e),e);var x={};he(x,{AbstractAgent:()=>w,HttpAgent:()=>W,convertToLegacyEvents:()=>$,defaultApplyEvents:()=>X,parseProtoStream:()=>J,parseSSEStream:()=>k,runHttpRequest:()=>j,transformHttpEventStream:()=>B,verifyEvents:()=>P});module.exports=Me(x);var y=require("@ag-ui/core"),ae=require("rxjs/operators");var C=r=>{if(typeof structuredClone=="function")return structuredClone(r);try{return JSON.parse(JSON.stringify(r))}catch(t){return _({},r)}};var oe=require("fast-json-patch"),ie=F(require("untruncate-json"));var X=(...r)=>{let[t,e]=r,n=C(t.messages),s=C(t.state),c,l=a=>[C(a)],o=()=>[];return e.pipe((0,ae.mergeMap)(a=>{var d;switch(a.type){case y.EventType.TEXT_MESSAGE_START:{let{messageId:T,role:u}=a,E={id:T,role:u,content:""};return n.push(E),l({messages:n})}case y.EventType.TEXT_MESSAGE_CONTENT:{let{delta:T}=a,u=n[n.length-1];return u.content=u.content+T,l({messages:n})}case y.EventType.TEXT_MESSAGE_END:return o();case y.EventType.TOOL_CALL_START:{let{toolCallId:T,toolCallName:u,parentMessageId:E}=a,f;return E&&n.length>0&&n[n.length-1].id===E?f=n[n.length-1]:(f={id:E||T,role:"assistant",toolCalls:[]},n.push(f)),(d=f.toolCalls)!=null||(f.toolCalls=[]),f.toolCalls.push({id:T,type:"function",function:{name:u,arguments:""}}),l({messages:n})}case y.EventType.TOOL_CALL_ARGS:{let{delta:T}=a,u=n[n.length-1],E=u.toolCalls[u.toolCalls.length-1];if(E.function.arguments+=T,c){let f=c.find(L=>L.tool===E.function.name);if(f)try{let L=JSON.parse((0,ie.default)(E.function.arguments));return f.tool_argument&&f.tool_argument in L?(s=R(_({},s),{[f.state_key]:L[f.tool_argument]}),l({messages:n,state:s})):(s=R(_({},s),{[f.state_key]:L}),l({messages:n,state:s}))}catch(L){}}return l({messages:n})}case y.EventType.TOOL_CALL_END:return o();case y.EventType.STATE_SNAPSHOT:{let{snapshot:T}=a;return s=T,l({state:s})}case y.EventType.STATE_DELTA:{let{delta:T}=a;try{return s=(0,oe.applyPatch)(s,T,!0,!1).newDocument,l({state:s})}catch(u){let E=u instanceof Error?u.message:String(u);return console.warn(`Failed to apply state patch:
2
2
  Current state: ${JSON.stringify(s,null,2)}
3
3
  Patch operations: ${JSON.stringify(T,null,2)}
4
- Error: ${E}`),i()}}case y.EventType.MESSAGES_SNAPSHOT:{let{messages:T}=r;return t=T,c({messages:t})}case y.EventType.RAW:return i();case y.EventType.CUSTOM:{let T=r;return T.name==="PredictState"&&(l=T.value),i()}case y.EventType.RUN_STARTED:return i();case y.EventType.RUN_FINISHED:return i();case y.EventType.RUN_ERROR:return i();case y.EventType.STEP_STARTED:return i();case y.EventType.STEP_FINISHED:return l=void 0,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")}let S=r.type;return i()}))};var g=require("@ag-ui/core"),p=require("rxjs"),ne=require("rxjs/operators"),D=a=>n=>{let e,t,s=!1,l=!1,c=!1,i=new Map;return n.pipe((0,ne.mergeMap)(r=>{let S=r.type;if(a&&console.debug("[VERIFY]:",JSON.stringify(r)),l)return(0,p.throwError)(()=>new g.AGUIError(`Cannot send event type '${S}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(s&&S!==g.EventType.RUN_ERROR)return(0,p.throwError)(()=>new g.AGUIError(`Cannot send event type '${S}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(e!==void 0&&![g.EventType.TEXT_MESSAGE_CONTENT,g.EventType.TEXT_MESSAGE_END,g.EventType.RAW].includes(S))return(0,p.throwError)(()=>new g.AGUIError(`Cannot send event type '${S}' after 'TEXT_MESSAGE_START': Send 'TEXT_MESSAGE_END' first.`));if(t!==void 0&&![g.EventType.TOOL_CALL_ARGS,g.EventType.TOOL_CALL_END,g.EventType.RAW].includes(S))return S===g.EventType.TOOL_CALL_START?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.")):(0,p.throwError)(()=>new g.AGUIError(`Cannot send event type '${S}' after 'TOOL_CALL_START': Send 'TOOL_CALL_END' first.`));if(c){if(S===g.EventType.RUN_STARTED)return(0,p.throwError)(()=>new g.AGUIError("Cannot send multiple 'RUN_STARTED' events: A 'RUN_STARTED' event was already sent. Each run must have exactly one 'RUN_STARTED' event at the beginning."))}else if(c=!0,S!==g.EventType.RUN_STARTED&&S!==g.EventType.RUN_ERROR)return(0,p.throwError)(()=>new g.AGUIError("First event must be 'RUN_STARTED'"));switch(S){case g.EventType.TEXT_MESSAGE_START:return e!==void 0?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TEXT_MESSAGE_START' event: A text message is already in progress. Complete it with 'TEXT_MESSAGE_END' first.")):(e=r.messageId,(0,p.of)(r));case g.EventType.TEXT_MESSAGE_CONTENT:return e===void 0?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found. Start a text message with 'TEXT_MESSAGE_START' first.")):r.messageId!==e?(0,p.throwError)(()=>new g.AGUIError(`Cannot send 'TEXT_MESSAGE_CONTENT' event: Message ID mismatch. The ID '${r.messageId}' doesn't match the active message ID '${e}'.`)):(0,p.of)(r);case g.EventType.TEXT_MESSAGE_END:return e===void 0?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TEXT_MESSAGE_END' event: No active text message found. A 'TEXT_MESSAGE_START' event must be sent first.")):r.messageId!==e?(0,p.throwError)(()=>new g.AGUIError(`Cannot send 'TEXT_MESSAGE_END' event: Message ID mismatch. The ID '${r.messageId}' doesn't match the active message ID '${e}'.`)):(e=void 0,(0,p.of)(r));case g.EventType.TOOL_CALL_START:return t!==void 0?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.")):(t=r.toolCallId,(0,p.of)(r));case g.EventType.TOOL_CALL_ARGS:return t===void 0?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TOOL_CALL_ARGS' event: No active tool call found. Start a tool call with 'TOOL_CALL_START' first.")):r.toolCallId!==t?(0,p.throwError)(()=>new g.AGUIError(`Cannot send 'TOOL_CALL_ARGS' event: Tool call ID mismatch. The ID '${r.toolCallId}' doesn't match the active tool call ID '${t}'.`)):(0,p.of)(r);case g.EventType.TOOL_CALL_END:return t===void 0?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TOOL_CALL_END' event: No active tool call found. A 'TOOL_CALL_START' event must be sent first.")):r.toolCallId!==t?(0,p.throwError)(()=>new g.AGUIError(`Cannot send 'TOOL_CALL_END' event: Tool call ID mismatch. The ID '${r.toolCallId}' doesn't match the active tool call ID '${t}'.`)):(t=void 0,(0,p.of)(r));case g.EventType.STEP_STARTED:{let f=r.name;return i.has(f)?(0,p.throwError)(()=>new g.AGUIError(`Step "${f}" is already active for 'STEP_STARTED'`)):(i.set(f,!0),(0,p.of)(r))}case g.EventType.STEP_FINISHED:{let f=r.name;return i.has(f)?(i.delete(f),(0,p.of)(r)):(0,p.throwError)(()=>new g.AGUIError(`Cannot send 'STEP_FINISHED' for step "${f}" that was not started`))}case g.EventType.RUN_STARTED:return(0,p.of)(r);case g.EventType.RUN_FINISHED:{if(i.size>0){let f=Array.from(i.keys()).join(", ");return(0,p.throwError)(()=>new g.AGUIError(`Cannot send 'RUN_FINISHED' while steps are still active: ${f}`))}return s=!0,(0,p.of)(r)}case g.EventType.RUN_ERROR:return l=!0,(0,p.of)(r);case g.EventType.CUSTOM:return(0,p.of)(r);default:return(0,p.of)(r)}}))};var ie=require("@ag-ui/core"),k=require("rxjs");var R=require("rxjs"),se=require("rxjs/operators");var F=(a,n)=>(0,R.defer)(()=>(0,R.from)(fetch(a,n))).pipe((0,se.switchMap)(e=>{var l;let t={type:"headers",status:e.status,headers:e.headers},s=(l=e.body)==null?void 0:l.getReader();return s?new R.Observable(c=>(c.next(t),(async()=>{try{for(;;){let{done:i,value:r}=await s.read();if(i)break;let S={type:"data",data:r};c.next(S)}c.complete()}catch(i){c.error(i)}})(),()=>{s.cancel()})):(0,R.throwError)(()=>new Error("Failed to getReader() from response"))}));var re=require("rxjs");var X=a=>{let n=new re.Subject,e=new TextDecoder("utf-8",{fatal:!1}),t="";a.subscribe({next:l=>{if(l.type!=="headers"&&l.type==="data"&&l.data){let c=e.decode(l.data,{stream:!0});t+=c;let i=t.split(/\n\n/);t=i.pop()||"";for(let r of i)s(r)}},error:l=>n.error(l),complete:()=>{t&&(t+=e.decode(),s(t)),n.complete()}});function s(l){let c=l.split(`
5
- `),i=[];for(let r of c)r.startsWith("data: ")&&i.push(r.slice(6));if(i.length>0)try{let r=i.join(`
6
- `),S=JSON.parse(r);n.next(S)}catch(r){n.error(r)}}return n.asObservable()};var ae=require("rxjs");var oe=G(require("@ag-ui/proto")),j=a=>{let n=new ae.Subject,e=new Uint8Array(0);a.subscribe({next:s=>{if(s.type!=="headers"&&s.type==="data"&&s.data){let l=new Uint8Array(e.length+s.data.length);l.set(e,0),l.set(s.data,e.length),e=l,t()}},error:s=>n.error(s),complete:()=>{if(e.length>0)try{t()}catch(s){console.warn("Incomplete or invalid protocol buffer data at stream end")}n.complete()}});function t(){for(;e.length>=4;){let c=4+new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1);if(e.length<c)break;try{let i=e.slice(4,c),r=oe.decode(i);n.next(r),e=e.slice(c)}catch(i){let r=i instanceof Error?i.message:String(i);n.error(new Error(`Failed to decode protocol buffer message: ${r}`));return}}}return n.asObservable()};var le=G(require("@ag-ui/proto")),J=a=>{let n=new k.Subject,e=new k.ReplaySubject,t=!1;return a.subscribe({next:s=>{e.next(s),s.type==="headers"&&!t?(t=!0,s.headers.get("content-type")===le.AGUI_MEDIA_TYPE?j(e).subscribe({next:c=>n.next(c),error:c=>n.error(c),complete:()=>n.complete()}):X(e).subscribe({next:c=>{try{let i=ie.EventSchemas.parse(c);n.next(i)}catch(i){n.error(i)}},error:c=>n.error(c),complete:()=>n.complete()})):t||n.error(new Error("No headers event received before data events"))},error:s=>{e.error(s),n.error(s)},complete:()=>{e.complete()}}),n.asObservable()};var ce=require("rxjs/operators"),ue=require("fast-json-patch"),v=require("@ag-ui/core");var o=require("zod"),A=o.z.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Ce=o.z.enum(["LangGraphInterruptEvent","PredictState","Exit"]),_e=o.z.object({type:o.z.literal(A.enum.TextMessageStart),messageId:o.z.string(),parentMessageId:o.z.string().optional()}),Le=o.z.object({type:o.z.literal(A.enum.TextMessageContent),messageId:o.z.string(),content:o.z.string()}),xe=o.z.object({type:o.z.literal(A.enum.TextMessageEnd),messageId:o.z.string()}),he=o.z.object({type:o.z.literal(A.enum.ActionExecutionStart),actionExecutionId:o.z.string(),actionName:o.z.string(),parentMessageId:o.z.string().optional()}),Me=o.z.object({type:o.z.literal(A.enum.ActionExecutionArgs),actionExecutionId:o.z.string(),args:o.z.string()}),Re=o.z.object({type:o.z.literal(A.enum.ActionExecutionEnd),actionExecutionId:o.z.string()}),Oe=o.z.object({type:o.z.literal(A.enum.ActionExecutionResult),actionName:o.z.string(),actionExecutionId:o.z.string(),result:o.z.string()}),be=o.z.object({type:o.z.literal(A.enum.AgentStateMessage),threadId:o.z.string(),agentName:o.z.string(),nodeName:o.z.string(),runId:o.z.string(),active:o.z.boolean(),role:o.z.string(),state:o.z.string(),running:o.z.boolean()}),Ne=o.z.object({type:o.z.literal(A.enum.MetaEvent),name:Ce,value:o.z.any()}),yt=o.z.discriminatedUnion("type",[_e,Le,xe,he,Me,Re,Oe,be,Ne]),vt=o.z.object({id:o.z.string(),role:o.z.string(),content:o.z.string(),parentMessageId:o.z.string().optional()}),Ct=o.z.object({id:o.z.string(),name:o.z.string(),arguments:o.z.any(),parentMessageId:o.z.string().optional()}),_t=o.z.object({id:o.z.string(),result:o.z.any(),actionExecutionId:o.z.string(),actionName:o.z.string()});var ge=G(require("untruncate-json"));var z=(a,n,e)=>t=>{let s={},l=!0,c=!0,i="",r=null,S=null,f=[],T=u=>{typeof u=="object"&&u!==null&&("messages"in u&&delete u.messages,s=u)};return t.pipe((0,ce.mergeMap)(u=>{switch(u.type){case v.EventType.TEXT_MESSAGE_START:{let E=u;return[{type:A.enum.TextMessageStart,messageId:E.messageId}]}case v.EventType.TEXT_MESSAGE_CONTENT:{let E=u;return[{type:A.enum.TextMessageContent,messageId:E.messageId,content:E.delta}]}case v.EventType.TEXT_MESSAGE_END:{let E=u;return[{type:A.enum.TextMessageEnd,messageId:E.messageId}]}case v.EventType.TOOL_CALL_START:{let E=u;return f.push({id:E.toolCallId,type:"function",function:{name:E.toolCallName,arguments:""}}),c=!0,[{type:A.enum.ActionExecutionStart,actionExecutionId:E.toolCallId,actionName:E.toolCallName,parentMessageId:E.parentMessageId}]}case v.EventType.TOOL_CALL_ARGS:{let E=u,d=f[f.length-1];d.function.arguments+=E.delta;let L=!1;if(S){let O=S.find(b=>b.tool==d.function.name);if(O)try{let b=JSON.parse((0,ge.default)(d.function.arguments));O.tool_argument&&O.tool_argument in b?(T(M(_({},s),{[O.state_key]:b[O.tool_argument]})),L=!0):O.tool_argument||(T(M(_({},s),{[O.state_key]:b})),L=!0)}catch(b){}}return[{type:A.enum.ActionExecutionArgs,actionExecutionId:E.toolCallId,args:E.delta},...L?[{type:A.enum.AgentStateMessage,threadId:a,agentName:e,nodeName:i,runId:n,running:l,role:"assistant",state:JSON.stringify(s),active:c}]:[]]}case v.EventType.TOOL_CALL_END:{let E=u;return[{type:A.enum.ActionExecutionEnd,actionExecutionId:E.toolCallId}]}case v.EventType.RAW:return[];case v.EventType.CUSTOM:{let E=u;switch(E.name){case"Exit":l=!1;break;case"PredictState":S=E.value;break}return[{type:A.enum.MetaEvent,name:E.name,value:E.value}]}case v.EventType.STATE_SNAPSHOT:return T(u.snapshot),[{type:A.enum.AgentStateMessage,threadId:a,agentName:e,nodeName:i,runId:n,running:l,role:"assistant",state:JSON.stringify(s),active:c}];case v.EventType.STATE_DELTA:{let d=(0,ue.applyPatch)(s,u.delta,!0,!1);return d?(T(d.newDocument),[{type:A.enum.AgentStateMessage,threadId:a,agentName:e,nodeName:i,runId:n,running:l,role:"assistant",state:JSON.stringify(s),active:c}]):[]}case v.EventType.MESSAGES_SNAPSHOT:return r=u.messages,[{type:A.enum.AgentStateMessage,threadId:a,agentName:e,nodeName:i,runId:n,running:l,role:"assistant",state:JSON.stringify(_(_({},s),r?{messages:r}:{})),active:!0}];case v.EventType.RUN_STARTED:return[];case v.EventType.RUN_FINISHED:return r&&(s.messages=r),[{type:A.enum.AgentStateMessage,threadId:a,agentName:e,nodeName:i,runId:n,running:l,role:"assistant",state:JSON.stringify(_(_({},s),r?{messages:Ie(r)}:{})),active:!1}];case v.EventType.RUN_ERROR:return console.error("Run error",u),[];case v.EventType.STEP_STARTED:return i=u.stepName,f=[],S=null,[{type:A.enum.AgentStateMessage,threadId:a,agentName:e,nodeName:i,runId:n,running:l,role:"assistant",state:JSON.stringify(s),active:!0}];case v.EventType.STEP_FINISHED:return f=[],S=null,[{type:A.enum.AgentStateMessage,threadId:a,agentName:e,nodeName:i,runId:n,running:l,role:"assistant",state:JSON.stringify(s),active:!1}];default:return[]}}))};function Ie(a){var e;let n=[];for(let t of a)if(t.role==="assistant"||t.role==="user"||t.role==="system"){if(t.content){let s={id:t.id,role:t.role,content:t.content};n.push(s)}if(t.role==="assistant"&&t.toolCalls&&t.toolCalls.length>0)for(let s of t.toolCalls){let l={id:s.id,name:s.function.name,arguments:JSON.parse(s.function.arguments),parentMessageId:t.id};n.push(l)}}else if(t.role==="tool"){let s="unknown";for(let c of a)if(c.role==="assistant"&&((e=c.toolCalls)!=null&&e.length)){for(let i of c.toolCalls)if(i.id===t.toolCallId){s=i.function.name;break}}let l={id:t.id,result:t.content,actionExecutionId:t.toolCallId,actionName:s};n.push(l)}return n}var H=require("uuid");var I=require("rxjs/operators"),Ee=require("rxjs/operators"),$=require("rxjs");var K=require("rxjs");var B=require("rxjs"),m=require("@ag-ui/core"),q=a=>n=>{let e,t,s,l=()=>{if(!e||s!=="text")throw new Error("No text message to close");let r={type:m.EventType.TEXT_MESSAGE_END,messageId:e.messageId};return s=void 0,e=void 0,a&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(r)),r},c=()=>{if(!t||s!=="tool")throw new Error("No tool call to close");let r={type:m.EventType.TOOL_CALL_END,toolCallId:t.toolCallId};return s=void 0,t=void 0,a&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(r)),r},i=()=>s==="text"?[l()]:s==="tool"?[c()]:[];return n.pipe((0,B.mergeMap)(r=>{switch(r.type){case m.EventType.TEXT_MESSAGE_START:case m.EventType.TEXT_MESSAGE_CONTENT:case m.EventType.TEXT_MESSAGE_END:case m.EventType.TOOL_CALL_START:case m.EventType.TOOL_CALL_ARGS:case m.EventType.TOOL_CALL_END:case m.EventType.STATE_SNAPSHOT:case m.EventType.STATE_DELTA:case m.EventType.MESSAGES_SNAPSHOT:case m.EventType.CUSTOM:case m.EventType.RUN_STARTED:case m.EventType.RUN_FINISHED:case m.EventType.RUN_ERROR:case m.EventType.STEP_STARTED:case m.EventType.STEP_FINISHED:return[...i(),r];case m.EventType.RAW:return[r];case m.EventType.TEXT_MESSAGE_CHUNK:let f=r,T=[];if((s!=="text"||f.messageId!==void 0&&f.messageId!==(e==null?void 0:e.messageId))&&T.push(...i()),s!=="text"){if(f.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:f.messageId},s="text";let d={type:m.EventType.TEXT_MESSAGE_START,messageId:f.messageId,role:"assistant"};T.push(d),a&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(d))}if(f.delta!==void 0){let d={type:m.EventType.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:f.delta};T.push(d),a&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(d))}return T;case m.EventType.TOOL_CALL_CHUNK:let u=r,E=[];if((s!=="tool"||u.toolCallId!==void 0&&u.toolCallId!==(t==null?void 0:t.toolCallId))&&E.push(...i()),s!=="tool"){if(u.toolCallId===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallId");if(u.toolCallName===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallName");t={toolCallId:u.toolCallId,toolCallName:u.toolCallName,parentMessageId:u.parentMessageId},s="tool";let d={type:m.EventType.TOOL_CALL_START,toolCallId:u.toolCallId,toolCallName:u.toolCallName,parentMessageId:u.parentMessageId};E.push(d),a&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(d))}if(u.delta!==void 0){let d={type:m.EventType.TOOL_CALL_ARGS,toolCallId:t.toolCallId,delta:u.delta};E.push(d),a&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(d))}return E}let S=r.type}),(0,B.finalize)(()=>i()))};var N=class{constructor({agentId:n,description:e,threadId:t,initialMessages:s,initialState:l,debug:c}={}){this.agentId=n,this.description=e!=null?e:"",this.threadId=t!=null?t:(0,H.v4)(),this.messages=C(s!=null?s:[]),this.state=C(l!=null?l:{}),this.debug=c!=null?c:!1}async runAgent(n){var s;this.agentId=(s=this.agentId)!=null?s:(0,H.v4)();let e=this.prepareRunAgentInput(n),t=(0,$.pipe)(()=>this.run(e),q(this.debug),D(this.debug),l=>this.apply(e,l),l=>this.processApplyEvents(e,l),(0,I.catchError)(l=>(this.onError(l),(0,$.throwError)(()=>l))),(0,Ee.finalize)(()=>{this.onFinalize()}));return(0,K.lastValueFrom)(t((0,K.of)(null))).then(()=>{})}abortRun(){}apply(...n){return U(...n)}processApplyEvents(n,e){return e.pipe((0,I.tap)(t=>{t.messages&&(this.messages=t.messages),t.state&&(this.state=t.state)}))}prepareRunAgentInput(n){var e,t,s;return{threadId:this.threadId,runId:(n==null?void 0:n.runId)||(0,H.v4)(),tools:C((e=n==null?void 0:n.tools)!=null?e:[]),context:C((t=n==null?void 0:n.context)!=null?t:[]),forwardedProps:C((s=n==null?void 0:n.forwardedProps)!=null?s:{}),state:C(this.state),messages:C(this.messages)}}onError(n){console.error("Agent execution failed:",n)}onFinalize(){}clone(){let n=Object.create(Object.getPrototypeOf(this));for(let e of Object.getOwnPropertyNames(this)){let t=this[e];typeof t!="function"&&(n[e]=C(t))}return n}legacy_to_be_removed_runAgentBridged(n){var t;this.agentId=(t=this.agentId)!=null?t:(0,H.v4)();let e=this.prepareRunAgentInput(n);return this.run(e).pipe(q(this.debug),D(this.debug),z(this.threadId,e.runId,this.agentId),s=>s.pipe((0,I.map)(l=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(l)),l))))}};var V=class extends N{constructor(e){var t;super(e);this.abortController=new AbortController;this.url=e.url,this.headers=C((t=e.headers)!=null?t:{})}requestInit(e){return{method:"POST",headers:M(_({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e){var t;return this.abortController=(t=e==null?void 0:e.abortController)!=null?t:new AbortController,super.runAgent(e)}abortRun(){this.abortController.abort(),super.abortRun()}run(e){let t=F(this.url,this.requestInit(e));return J(t)}};h(x,require("@ag-ui/core"),module.exports);0&&(module.exports={AbstractAgent,HttpAgent,convertToLegacyEvents,defaultApplyEvents,parseProtoStream,parseSSEStream,runHttpRequest,transformHttpEventStream,verifyEvents,...require("@ag-ui/core")});
4
+ Error: ${E}`),o()}}case y.EventType.MESSAGES_SNAPSHOT:{let{messages:T}=a;return n=T,l({messages:n})}case y.EventType.RAW:return o();case y.EventType.CUSTOM:{let T=a;return T.name==="PredictState"&&(c=T.value),o()}case y.EventType.RUN_STARTED:return o();case y.EventType.RUN_FINISHED:return o();case y.EventType.RUN_ERROR:return o();case y.EventType.STEP_STARTED:return o();case y.EventType.STEP_FINISHED:return c=void 0,o();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")}let S=a.type;return o()}))};var g=require("@ag-ui/core"),p=require("rxjs"),le=require("rxjs/operators"),P=r=>t=>{let e,n,s=!1,c=!1,l=!1,o=new Map;return t.pipe((0,le.mergeMap)(a=>{let S=a.type;if(r&&console.debug("[VERIFY]:",JSON.stringify(a)),c)return(0,p.throwError)(()=>new g.AGUIError(`Cannot send event type '${S}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(s&&S!==g.EventType.RUN_ERROR)return(0,p.throwError)(()=>new g.AGUIError(`Cannot send event type '${S}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(e!==void 0&&![g.EventType.TEXT_MESSAGE_CONTENT,g.EventType.TEXT_MESSAGE_END,g.EventType.RAW].includes(S))return(0,p.throwError)(()=>new g.AGUIError(`Cannot send event type '${S}' after 'TEXT_MESSAGE_START': Send 'TEXT_MESSAGE_END' first.`));if(n!==void 0&&![g.EventType.TOOL_CALL_ARGS,g.EventType.TOOL_CALL_END,g.EventType.RAW].includes(S))return S===g.EventType.TOOL_CALL_START?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.")):(0,p.throwError)(()=>new g.AGUIError(`Cannot send event type '${S}' after 'TOOL_CALL_START': Send 'TOOL_CALL_END' first.`));if(l){if(S===g.EventType.RUN_STARTED)return(0,p.throwError)(()=>new g.AGUIError("Cannot send multiple 'RUN_STARTED' events: A 'RUN_STARTED' event was already sent. Each run must have exactly one 'RUN_STARTED' event at the beginning."))}else if(l=!0,S!==g.EventType.RUN_STARTED&&S!==g.EventType.RUN_ERROR)return(0,p.throwError)(()=>new g.AGUIError("First event must be 'RUN_STARTED'"));switch(S){case g.EventType.TEXT_MESSAGE_START:return e!==void 0?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TEXT_MESSAGE_START' event: A text message is already in progress. Complete it with 'TEXT_MESSAGE_END' first.")):(e=a.messageId,(0,p.of)(a));case g.EventType.TEXT_MESSAGE_CONTENT:return e===void 0?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found. Start a text message with 'TEXT_MESSAGE_START' first.")):a.messageId!==e?(0,p.throwError)(()=>new g.AGUIError(`Cannot send 'TEXT_MESSAGE_CONTENT' event: Message ID mismatch. The ID '${a.messageId}' doesn't match the active message ID '${e}'.`)):(0,p.of)(a);case g.EventType.TEXT_MESSAGE_END:return e===void 0?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TEXT_MESSAGE_END' event: No active text message found. A 'TEXT_MESSAGE_START' event must be sent first.")):a.messageId!==e?(0,p.throwError)(()=>new g.AGUIError(`Cannot send 'TEXT_MESSAGE_END' event: Message ID mismatch. The ID '${a.messageId}' doesn't match the active message ID '${e}'.`)):(e=void 0,(0,p.of)(a));case g.EventType.TOOL_CALL_START:return n!==void 0?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.")):(n=a.toolCallId,(0,p.of)(a));case g.EventType.TOOL_CALL_ARGS:return n===void 0?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TOOL_CALL_ARGS' event: No active tool call found. Start a tool call with 'TOOL_CALL_START' first.")):a.toolCallId!==n?(0,p.throwError)(()=>new g.AGUIError(`Cannot send 'TOOL_CALL_ARGS' event: Tool call ID mismatch. The ID '${a.toolCallId}' doesn't match the active tool call ID '${n}'.`)):(0,p.of)(a);case g.EventType.TOOL_CALL_END:return n===void 0?(0,p.throwError)(()=>new g.AGUIError("Cannot send 'TOOL_CALL_END' event: No active tool call found. A 'TOOL_CALL_START' event must be sent first.")):a.toolCallId!==n?(0,p.throwError)(()=>new g.AGUIError(`Cannot send 'TOOL_CALL_END' event: Tool call ID mismatch. The ID '${a.toolCallId}' doesn't match the active tool call ID '${n}'.`)):(n=void 0,(0,p.of)(a));case g.EventType.STEP_STARTED:{let d=a.name;return o.has(d)?(0,p.throwError)(()=>new g.AGUIError(`Step "${d}" is already active for 'STEP_STARTED'`)):(o.set(d,!0),(0,p.of)(a))}case g.EventType.STEP_FINISHED:{let d=a.name;return o.has(d)?(o.delete(d),(0,p.of)(a)):(0,p.throwError)(()=>new g.AGUIError(`Cannot send 'STEP_FINISHED' for step "${d}" that was not started`))}case g.EventType.RUN_STARTED:return(0,p.of)(a);case g.EventType.RUN_FINISHED:{if(o.size>0){let d=Array.from(o.keys()).join(", ");return(0,p.throwError)(()=>new g.AGUIError(`Cannot send 'RUN_FINISHED' while steps are still active: ${d}`))}return s=!0,(0,p.of)(a)}case g.EventType.RUN_ERROR:return c=!0,(0,p.of)(a);case g.EventType.CUSTOM:return(0,p.of)(a);default:return(0,p.of)(a)}}))};var pe=require("@ag-ui/core"),z=require("rxjs");var O=require("rxjs"),ce=require("rxjs/operators");var j=(r,t)=>(0,O.defer)(()=>(0,O.from)(fetch(r,t))).pipe((0,ce.switchMap)(e=>{var c;let n={type:"headers",status:e.status,headers:e.headers},s=(c=e.body)==null?void 0:c.getReader();return s?new O.Observable(l=>(l.next(n),(async()=>{try{for(;;){let{done:o,value:a}=await s.read();if(o)break;let S={type:"data",data:a};l.next(S)}l.complete()}catch(o){l.error(o)}})(),()=>{s.cancel()})):(0,O.throwError)(()=>new Error("Failed to getReader() from response"))}));var ue=require("rxjs");var k=r=>{let t=new ue.Subject,e=new TextDecoder("utf-8",{fatal:!1}),n="";r.subscribe({next:c=>{if(c.type!=="headers"&&c.type==="data"&&c.data){let l=e.decode(c.data,{stream:!0});n+=l;let o=n.split(/\n\n/);n=o.pop()||"";for(let a of o)s(a)}},error:c=>t.error(c),complete:()=>{n&&(n+=e.decode(),s(n)),t.complete()}});function s(c){let l=c.split(`
5
+ `),o=[];for(let a of l)a.startsWith("data: ")&&o.push(a.slice(6));if(o.length>0)try{let a=o.join(`
6
+ `),S=JSON.parse(a);t.next(S)}catch(a){t.error(a)}}return t.asObservable()};var ge=require("rxjs");var Ee=F(require("@ag-ui/proto")),J=r=>{let t=new ge.Subject,e=new Uint8Array(0);r.subscribe({next:s=>{if(s.type!=="headers"&&s.type==="data"&&s.data){let c=new Uint8Array(e.length+s.data.length);c.set(e,0),c.set(s.data,e.length),e=c,n()}},error:s=>t.error(s),complete:()=>{if(e.length>0)try{n()}catch(s){console.warn("Incomplete or invalid protocol buffer data at stream end")}t.complete()}});function n(){for(;e.length>=4;){let l=4+new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1);if(e.length<l)break;try{let o=e.slice(4,l),a=Ee.decode(o);t.next(a),e=e.slice(l)}catch(o){let a=o instanceof Error?o.message:String(o);t.error(new Error(`Failed to decode protocol buffer message: ${a}`));return}}}return t.asObservable()};var fe=F(require("@ag-ui/proto")),B=r=>{let t=new z.Subject,e=new z.ReplaySubject,n=!1;return r.subscribe({next:s=>{e.next(s),s.type==="headers"&&!n?(n=!0,s.headers.get("content-type")===fe.AGUI_MEDIA_TYPE?J(e).subscribe({next:l=>t.next(l),error:l=>t.error(l),complete:()=>t.complete()}):k(e).subscribe({next:l=>{try{let o=pe.EventSchemas.parse(l);t.next(o)}catch(o){t.error(o)}},error:l=>t.error(l),complete:()=>t.complete()})):n||t.error(new Error("No headers event received before data events"))},error:s=>{e.error(s),t.error(s)},complete:()=>{e.complete()}}),t.asObservable()};var de=require("rxjs/operators"),Te=require("fast-json-patch"),v=require("@ag-ui/core");var i=require("zod"),A=i.z.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Re=i.z.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Oe=i.z.object({type:i.z.literal(A.enum.TextMessageStart),messageId:i.z.string(),parentMessageId:i.z.string().optional()}),Ne=i.z.object({type:i.z.literal(A.enum.TextMessageContent),messageId:i.z.string(),content:i.z.string()}),be=i.z.object({type:i.z.literal(A.enum.TextMessageEnd),messageId:i.z.string()}),Ie=i.z.object({type:i.z.literal(A.enum.ActionExecutionStart),actionExecutionId:i.z.string(),actionName:i.z.string(),parentMessageId:i.z.string().optional()}),we=i.z.object({type:i.z.literal(A.enum.ActionExecutionArgs),actionExecutionId:i.z.string(),args:i.z.string()}),De=i.z.object({type:i.z.literal(A.enum.ActionExecutionEnd),actionExecutionId:i.z.string()}),He=i.z.object({type:i.z.literal(A.enum.ActionExecutionResult),actionName:i.z.string(),actionExecutionId:i.z.string(),result:i.z.string()}),Pe=i.z.object({type:i.z.literal(A.enum.AgentStateMessage),threadId:i.z.string(),agentName:i.z.string(),nodeName:i.z.string(),runId:i.z.string(),active:i.z.boolean(),role:i.z.string(),state:i.z.string(),running:i.z.boolean()}),Ge=i.z.object({type:i.z.literal(A.enum.MetaEvent),name:Re,value:i.z.any()}),ht=i.z.discriminatedUnion("type",[Oe,Ne,be,Ie,we,De,He,Pe,Ge]),Mt=i.z.object({id:i.z.string(),role:i.z.string(),content:i.z.string(),parentMessageId:i.z.string().optional()}),Rt=i.z.object({id:i.z.string(),name:i.z.string(),arguments:i.z.any(),parentMessageId:i.z.string().optional()}),Ot=i.z.object({id:i.z.string(),result:i.z.any(),actionExecutionId:i.z.string(),actionName:i.z.string()});var me=F(require("untruncate-json"));var $=(r,t,e)=>n=>{let s={},c=!0,l=!0,o="",a=null,S=null,d=[],T=u=>{typeof u=="object"&&u!==null&&("messages"in u&&delete u.messages,s=u)};return n.pipe((0,de.mergeMap)(u=>{switch(u.type){case v.EventType.TEXT_MESSAGE_START:{let E=u;return[{type:A.enum.TextMessageStart,messageId:E.messageId}]}case v.EventType.TEXT_MESSAGE_CONTENT:{let E=u;return[{type:A.enum.TextMessageContent,messageId:E.messageId,content:E.delta}]}case v.EventType.TEXT_MESSAGE_END:{let E=u;return[{type:A.enum.TextMessageEnd,messageId:E.messageId}]}case v.EventType.TOOL_CALL_START:{let E=u;return d.push({id:E.toolCallId,type:"function",function:{name:E.toolCallName,arguments:""}}),l=!0,[{type:A.enum.ActionExecutionStart,actionExecutionId:E.toolCallId,actionName:E.toolCallName,parentMessageId:E.parentMessageId}]}case v.EventType.TOOL_CALL_ARGS:{let E=u,f=d[d.length-1];f.function.arguments+=E.delta;let L=!1;if(S){let N=S.find(b=>b.tool==f.function.name);if(N)try{let b=JSON.parse((0,me.default)(f.function.arguments));N.tool_argument&&N.tool_argument in b?(T(R(_({},s),{[N.state_key]:b[N.tool_argument]})),L=!0):N.tool_argument||(T(R(_({},s),{[N.state_key]:b})),L=!0)}catch(b){}}return[{type:A.enum.ActionExecutionArgs,actionExecutionId:E.toolCallId,args:E.delta},...L?[{type:A.enum.AgentStateMessage,threadId:r,agentName:e,nodeName:o,runId:t,running:c,role:"assistant",state:JSON.stringify(s),active:l}]:[]]}case v.EventType.TOOL_CALL_END:{let E=u;return[{type:A.enum.ActionExecutionEnd,actionExecutionId:E.toolCallId}]}case v.EventType.RAW:return[];case v.EventType.CUSTOM:{let E=u;switch(E.name){case"Exit":c=!1;break;case"PredictState":S=E.value;break}return[{type:A.enum.MetaEvent,name:E.name,value:E.value}]}case v.EventType.STATE_SNAPSHOT:return T(u.snapshot),[{type:A.enum.AgentStateMessage,threadId:r,agentName:e,nodeName:o,runId:t,running:c,role:"assistant",state:JSON.stringify(s),active:l}];case v.EventType.STATE_DELTA:{let f=(0,Te.applyPatch)(s,u.delta,!0,!1);return f?(T(f.newDocument),[{type:A.enum.AgentStateMessage,threadId:r,agentName:e,nodeName:o,runId:t,running:c,role:"assistant",state:JSON.stringify(s),active:l}]):[]}case v.EventType.MESSAGES_SNAPSHOT:return a=u.messages,[{type:A.enum.AgentStateMessage,threadId:r,agentName:e,nodeName:o,runId:t,running:c,role:"assistant",state:JSON.stringify(_(_({},s),a?{messages:a}:{})),active:!0}];case v.EventType.RUN_STARTED:return[];case v.EventType.RUN_FINISHED:return a&&(s.messages=a),[{type:A.enum.AgentStateMessage,threadId:r,agentName:e,nodeName:o,runId:t,running:c,role:"assistant",state:JSON.stringify(_(_({},s),a?{messages:Ue(a)}:{})),active:!1}];case v.EventType.RUN_ERROR:return console.error("Run error",u),[];case v.EventType.STEP_STARTED:return o=u.stepName,d=[],S=null,[{type:A.enum.AgentStateMessage,threadId:r,agentName:e,nodeName:o,runId:t,running:c,role:"assistant",state:JSON.stringify(s),active:!0}];case v.EventType.STEP_FINISHED:return d=[],S=null,[{type:A.enum.AgentStateMessage,threadId:r,agentName:e,nodeName:o,runId:t,running:c,role:"assistant",state:JSON.stringify(s),active:!1}];default:return[]}}))};function Ue(r){var e;let t=[];for(let n of r)if(n.role==="assistant"||n.role==="user"||n.role==="system"){if(n.content){let s={id:n.id,role:n.role,content:n.content};t.push(s)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let s of n.toolCalls){let c={id:s.id,name:s.function.name,arguments:JSON.parse(s.function.arguments),parentMessageId:n.id};t.push(c)}}else if(n.role==="tool"){let s="unknown";for(let l of r)if(l.role==="assistant"&&((e=l.toolCalls)!=null&&e.length)){for(let o of l.toolCalls)if(o.id===n.toolCallId){s=o.function.name;break}}let c={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:s};t.push(c)}return t}var G=require("uuid");var D=require("rxjs/operators"),Se=require("rxjs/operators"),V=require("rxjs");var q=require("rxjs");var K=require("rxjs"),m=require("@ag-ui/core"),Y=r=>t=>{let e,n,s,c=()=>{if(!e||s!=="text")throw new Error("No text message to close");let a={type:m.EventType.TEXT_MESSAGE_END,messageId:e.messageId};return s=void 0,e=void 0,r&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(a)),a},l=()=>{if(!n||s!=="tool")throw new Error("No tool call to close");let a={type:m.EventType.TOOL_CALL_END,toolCallId:n.toolCallId};return s=void 0,n=void 0,r&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(a)),a},o=()=>s==="text"?[c()]:s==="tool"?[l()]:[];return t.pipe((0,K.mergeMap)(a=>{switch(a.type){case m.EventType.TEXT_MESSAGE_START:case m.EventType.TEXT_MESSAGE_CONTENT:case m.EventType.TEXT_MESSAGE_END:case m.EventType.TOOL_CALL_START:case m.EventType.TOOL_CALL_ARGS:case m.EventType.TOOL_CALL_END:case m.EventType.STATE_SNAPSHOT:case m.EventType.STATE_DELTA:case m.EventType.MESSAGES_SNAPSHOT:case m.EventType.CUSTOM:case m.EventType.RUN_STARTED:case m.EventType.RUN_FINISHED:case m.EventType.RUN_ERROR:case m.EventType.STEP_STARTED:case m.EventType.STEP_FINISHED:return[...o(),a];case m.EventType.RAW:return[a];case m.EventType.TEXT_MESSAGE_CHUNK:let d=a,T=[];if((s!=="text"||d.messageId!==void 0&&d.messageId!==(e==null?void 0:e.messageId))&&T.push(...o()),s!=="text"){if(d.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:d.messageId},s="text";let f={type:m.EventType.TEXT_MESSAGE_START,messageId:d.messageId,role:"assistant"};T.push(f),r&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(f))}if(d.delta!==void 0){let f={type:m.EventType.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:d.delta};T.push(f),r&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(f))}return T;case m.EventType.TOOL_CALL_CHUNK:let u=a,E=[];if((s!=="tool"||u.toolCallId!==void 0&&u.toolCallId!==(n==null?void 0:n.toolCallId))&&E.push(...o()),s!=="tool"){if(u.toolCallId===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallId");if(u.toolCallName===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallName");n={toolCallId:u.toolCallId,toolCallName:u.toolCallName,parentMessageId:u.parentMessageId},s="tool";let f={type:m.EventType.TOOL_CALL_START,toolCallId:u.toolCallId,toolCallName:u.toolCallName,parentMessageId:u.parentMessageId};E.push(f),r&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(f))}if(u.delta!==void 0){let f={type:m.EventType.TOOL_CALL_ARGS,toolCallId:n.toolCallId,delta:u.delta};E.push(f),r&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(f))}return E}let S=a.type}),(0,K.finalize)(()=>o()))};var M,w=class{constructor({agentId:t,description:e,threadId:n,initialMessages:s,initialState:c,debug:l}={}){se(this,M);this.agentId=t,this.description=e!=null?e:"",this.threadId=n!=null?n:(0,G.v4)(),this.messages=C(s!=null?s:[]),this.state=C(c!=null?c:{}),re(this,M,l!=null?l:!1)}async runAgent(t){var s,c,l;this.agentId=(s=this.agentId)!=null?s:(0,G.v4)();let e=this.prepareRunAgentInput(t),n=(0,V.pipe)(()=>this.run(e),Y((c=I(this,M))!=null?c:!1),P((l=I(this,M))!=null?l:!1),o=>this.apply(e,o),o=>this.processApplyEvents(e,o),(0,D.catchError)(o=>(this.onError(o),(0,V.throwError)(()=>o))),(0,Se.finalize)(()=>{this.onFinalize()}));return(0,q.lastValueFrom)(n((0,q.of)(null))).then(()=>{})}abortRun(){}apply(...t){return X(...t)}processApplyEvents(t,e){return e.pipe((0,D.tap)(n=>{n.messages&&(this.messages=n.messages),n.state&&(this.state=n.state)}))}prepareRunAgentInput(t){var e,n,s;return{threadId:this.threadId,runId:(t==null?void 0:t.runId)||(0,G.v4)(),tools:C((e=t==null?void 0:t.tools)!=null?e:[]),context:C((n=t==null?void 0:t.context)!=null?n:[]),forwardedProps:C((s=t==null?void 0:t.forwardedProps)!=null?s:{}),state:C(this.state),messages:C(this.messages)}}onError(t){console.error("Agent execution failed:",t)}onFinalize(){}clone(){let t=Object.create(Object.getPrototypeOf(this));for(let e of Object.getOwnPropertyNames(this)){let n=this[e];typeof n!="function"&&(t[e]=C(n))}return t}legacy_to_be_removed_runAgentBridged(t){var n,s,c;this.agentId=(n=this.agentId)!=null?n:(0,G.v4)();let e=this.prepareRunAgentInput(t);return this.run(e).pipe(Y((s=I(this,M))!=null?s:!1),P((c=I(this,M))!=null?c:!1),$(this.threadId,e.runId,this.agentId),l=>l.pipe((0,D.map)(o=>(I(this,M)&&console.debug("[LEGACY]:",JSON.stringify(o)),o))))}};M=new WeakMap;var W=class extends w{constructor(e){var n;super(e);this.abortController=new AbortController;this.url=e.url,this.headers=C((n=e.headers)!=null?n:{})}requestInit(e){return{method:"POST",headers:R(_({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e){var n;return this.abortController=(n=e==null?void 0:e.abortController)!=null?n:new AbortController,super.runAgent(e)}abortRun(){this.abortController.abort(),super.abortRun()}run(e){let n=j(this.url,this.requestInit(e));return B(n)}};h(x,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