@ag-ui/client 0.0.45 → 0.0.46
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.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`uuid`),l=require(`@ag-ui/core`),u=require(`fast-json-patch`);u=s(u);let d=require(`rxjs`),f=require(`rxjs/operators`),p=require(`untruncate-json`);p=s(p);let m=require(`@ag-ui/proto`);m=s(m);let h=require(`zod`),g=require(`compare-versions`);const _=e=>{if(typeof structuredClone==`function`)return structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch{return{...e}}};function v(){return(0,c.v4)()}async function y(e,t,n,r){let i=t,a=n,o;for(let t of e)try{let e=await r(t,_(i),_(a));if(e===void 0)continue;if(e.messages!==void 0&&(i=e.messages),e.state!==void 0&&(a=e.state),o=e.stopPropagation,o===!0)break}catch(e){process.env.NODE_ENV===`test`||process.env.VITEST_WORKER_ID!==void 0||console.error(`Subscriber error:`,e);continue}return{...JSON.stringify(i)===JSON.stringify(t)?{}:{messages:i},...JSON.stringify(a)===JSON.stringify(n)?{}:{state:a},...o===void 0?{}:{stopPropagation:o}}}const b=(e,t,n,r)=>{let i=_(n.messages),a=_(e.state),o={},s=e=>{e.messages!==void 0&&(i=e.messages,o.messages=e.messages),e.state!==void 0&&(a=e.state,o.state=e.state)},c=()=>{let e=_(o);return o={},e.messages!==void 0||e.state!==void 0?(0,d.of)(e):d.EMPTY};return t.pipe((0,f.concatMap)(async t=>{let d=await y(r,i,a,(r,i,a)=>r.onEvent?.({event:t,agent:n,input:e,messages:i,state:a}));if(s(d),d.stopPropagation===!0)return c();switch(t.type){case l.EventType.TEXT_MESSAGE_START:{let o=await y(r,i,a,(r,i,a)=>r.onTextMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{messageId:e,role:n=`assistant`}=t;if(!i.find(t=>t.id===e)){let t={id:e,role:n,content:``};i.push(t),s({messages:i})}}return c()}case l.EventType.TEXT_MESSAGE_CONTENT:{let{messageId:o,delta:l}=t,u=i.find(e=>e.id===o);if(!u)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${o}'`),c();let d=await y(r,i,a,(r,i,a)=>r.onTextMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,textMessageBuffer:typeof u.content==`string`?u.content:``}));return s(d),d.stopPropagation!==!0&&(u.content=`${typeof u.content==`string`?u.content:``}${l}`,s({messages:i})),c()}case l.EventType.TEXT_MESSAGE_END:{let{messageId:o}=t,l=i.find(e=>e.id===o);return l?(s(await y(r,i,a,(r,i,a)=>r.onTextMessageEndEvent?.({event:t,messages:i,state:a,agent:n,input:e,textMessageBuffer:typeof l.content==`string`?l.content:``}))),await Promise.all(r.map(t=>{t.onNewMessage?.({message:l,messages:i,state:a,agent:n,input:e})})),c()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${o}'`),c())}case l.EventType.TOOL_CALL_START:{let o=await y(r,i,a,(r,i,a)=>r.onToolCallStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{toolCallId:e,toolCallName:n,parentMessageId:r}=t,a;r&&i.length>0&&i[i.length-1].id===r?a=i[i.length-1]:(a={id:r||e,role:`assistant`,toolCalls:[]},i.push(a)),a.toolCalls??=[],a.toolCalls.push({id:e,type:`function`,function:{name:n,arguments:``}}),s({messages:i})}return c()}case l.EventType.TOOL_CALL_ARGS:{let{toolCallId:o,delta:l}=t,u=i.find(e=>e.toolCalls?.some(e=>e.id===o));if(!u)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${o}'`),c();let d=u.toolCalls?.find(e=>e.id===o);if(!d)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${o}'`),c();let f=await y(r,i,a,(r,i,a)=>{let o=d.function.arguments,s=d.function.name,c={};try{c=(0,p.default)(o)}catch{}return r.onToolCallArgsEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallBuffer:o,toolCallName:s,partialToolCallArgs:c})});return s(f),f.stopPropagation!==!0&&(d.function.arguments+=l,s({messages:i})),c()}case l.EventType.TOOL_CALL_END:{let{toolCallId:o}=t,l=i.find(e=>e.toolCalls?.some(e=>e.id===o));if(!l)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${o}'`),c();let u=l.toolCalls?.find(e=>e.id===o);return u?(s(await y(r,i,a,(r,i,a)=>{let o=u.function.arguments,s=u.function.name,c={};try{c=JSON.parse(o)}catch{}return r.onToolCallEndEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallName:s,toolCallArgs:c})})),await Promise.all(r.map(t=>{t.onNewToolCall?.({toolCall:u,messages:i,state:a,agent:n,input:e})})),c()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${o}'`),c())}case l.EventType.TOOL_CALL_RESULT:{let o=await y(r,i,a,(r,i,a)=>r.onToolCallResultEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{messageId:o,toolCallId:c,content:l,role:u}=t,d={id:o,toolCallId:c,role:u||`tool`,content:l};i.push(d),await Promise.all(r.map(t=>{t.onNewMessage?.({message:d,messages:i,state:a,agent:n,input:e})})),s({messages:i})}return c()}case l.EventType.STATE_SNAPSHOT:{let o=await y(r,i,a,(r,i,a)=>r.onStateSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{snapshot:e}=t;a=e,s({state:a})}return c()}case l.EventType.STATE_DELTA:{let o=await y(r,i,a,(r,i,a)=>r.onStateDeltaEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{delta:e}=t;try{a=u.applyPatch(a,e,!0,!1).newDocument,s({state:a})}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Failed to apply state patch:\nCurrent state: ${JSON.stringify(a,null,2)}\nPatch operations: ${JSON.stringify(e,null,2)}\nError: ${n}`)}}return c()}case l.EventType.MESSAGES_SNAPSHOT:{let o=await y(r,i,a,(r,i,a)=>r.onMessagesSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{messages:e}=t;i=e,s({messages:i})}return c()}case l.EventType.ACTIVITY_SNAPSHOT:{let o=t,l=i.findIndex(e=>e.id===o.messageId),u=l>=0?i[l]:void 0,d=u?.role===`activity`?u:void 0,f=o.replace??!0,p=await y(r,i,a,(t,r,i)=>t.onActivitySnapshotEvent?.({event:o,messages:r,state:i,agent:n,input:e,activityMessage:d,existingMessage:u}));if(s(p),p.stopPropagation!==!0){let t={id:o.messageId,role:`activity`,activityType:o.activityType,content:_(o.content)},c;l===-1?(i.push(t),c=t):d?f&&(i[l]={...d,activityType:o.activityType,content:_(o.content)}):f&&(i[l]=t,c=t),s({messages:i}),c&&await Promise.all(r.map(t=>t.onNewMessage?.({message:c,messages:i,state:a,agent:n,input:e})))}return c()}case l.EventType.ACTIVITY_DELTA:{let o=t,l=i.findIndex(e=>e.id===o.messageId);if(l===-1)return console.warn(`ACTIVITY_DELTA: No message found with ID '${o.messageId}' to apply patch`),c();let d=i[l];if(d.role!==`activity`)return console.warn(`ACTIVITY_DELTA: Message '${o.messageId}' is not an activity message`),c();let f=d,p=await y(r,i,a,(t,r,i)=>t.onActivityDeltaEvent?.({event:o,messages:r,state:i,agent:n,input:e,activityMessage:f}));if(s(p),p.stopPropagation!==!0)try{let e=_(f.content??{}),t=u.applyPatch(e,o.patch??[],!0,!1).newDocument;i[l]={...f,content:_(t),activityType:o.activityType},s({messages:i})}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`Failed to apply activity patch for '${o.messageId}': ${t}`)}return c()}case l.EventType.RAW:return s(await y(r,i,a,(r,i,a)=>r.onRawEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.CUSTOM:return s(await y(r,i,a,(r,i,a)=>r.onCustomEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.RUN_STARTED:{let o=await y(r,i,a,(r,i,a)=>r.onRunStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let e=t;if(e.input?.messages){for(let t of e.input.messages)i.find(e=>e.id===t.id)||i.push(t);s({messages:i})}}return c()}case l.EventType.RUN_FINISHED:return s(await y(r,i,a,(r,i,a)=>r.onRunFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e,result:t.result}))),c();case l.EventType.RUN_ERROR:return s(await y(r,i,a,(r,i,a)=>r.onRunErrorEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.STEP_STARTED:return s(await y(r,i,a,(r,i,a)=>r.onStepStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.STEP_FINISHED:return s(await y(r,i,a,(r,i,a)=>r.onStepFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.TEXT_MESSAGE_CHUNK:throw Error(`TEXT_MESSAGE_CHUNK must be tranformed before being applied`);case l.EventType.TOOL_CALL_CHUNK:throw Error(`TOOL_CALL_CHUNK must be tranformed before being applied`);case l.EventType.THINKING_START:return c();case l.EventType.THINKING_END:return c();case l.EventType.THINKING_TEXT_MESSAGE_START:return c();case l.EventType.THINKING_TEXT_MESSAGE_CONTENT:return c();case l.EventType.THINKING_TEXT_MESSAGE_END:return c();case l.EventType.REASONING_START:return s(await y(r,i,a,(r,i,a)=>r.onReasoningStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.REASONING_MESSAGE_START:{let o=await y(r,i,a,(r,i,a)=>r.onReasoningMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{messageId:e}=t;if(!i.find(t=>t.id===e)){let t={id:e,role:`reasoning`,content:``};i.push(t),s({messages:i})}}return c()}case l.EventType.REASONING_MESSAGE_CONTENT:{let{messageId:o,delta:l}=t,u=i.find(e=>e.id===o);if(!u)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${o}'`),c();let d=await y(r,i,a,(r,i,a)=>r.onReasoningMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,reasoningMessageBuffer:typeof u.content==`string`?u.content:``}));return s(d),d.stopPropagation!==!0&&(u.content=`${typeof u.content==`string`?u.content:``}${l}`,s({messages:i})),c()}case l.EventType.REASONING_MESSAGE_END:{let{messageId:o}=t,l=i.find(e=>e.id===o);return l?(s(await y(r,i,a,(r,i,a)=>r.onReasoningMessageEndEvent?.({event:t,messages:i,state:a,agent:n,input:e,reasoningMessageBuffer:typeof l.content==`string`?l.content:``}))),await Promise.all(r.map(t=>{t.onNewMessage?.({message:l,messages:i,state:a,agent:n,input:e})})),c()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${o}'`),c())}case l.EventType.REASONING_MESSAGE_CHUNK:throw Error(`REASONING_MESSAGE_CHUNK must be transformed before being applied`);case l.EventType.REASONING_END:return s(await y(r,i,a,(r,i,a)=>r.onReasoningEndEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.REASONING_ENCRYPTED_VALUE:{let{subtype:l,entityId:u,encryptedValue:d}=t,f=await y(r,i,a,(r,i,a)=>r.onReasoningEncryptedValueEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(f),f.stopPropagation!==!0){let e=!1;if(l===`tool-call`){for(let t of i)if(t.role===`assistant`&&t.toolCalls){let n=t.toolCalls.find(e=>e.id===u);if(n){n.encryptedValue=d,e=!0;break}}}else{let t=i.find(e=>e.id===u);t?.role!==`activity`&&t&&(t.encryptedValue=d,e=!0)}e&&(o.messages=i)}return c()}}return t.type,c()}),(0,f.mergeAll)(),r.length>0?(0,f.defaultIfEmpty)({}):e=>e)},x=e=>t=>{let n=new Map,r=new Map,i=!1,a=!1,o=!1,s=new Map,c=!1,u=!1,p=!1,m=()=>{n.clear(),r.clear(),s.clear(),c=!1,u=!1,i=!1,a=!1,p=!0};return t.pipe((0,f.mergeMap)(t=>{let f=t.type;if(e&&console.debug(`[VERIFY]:`,JSON.stringify(t)),a)return(0,d.throwError)(()=>new l.AGUIError(`Cannot send event type '${f}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(i&&f!==l.EventType.RUN_ERROR&&f!==l.EventType.RUN_STARTED)return(0,d.throwError)(()=>new l.AGUIError(`Cannot send event type '${f}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(!o){if(o=!0,f!==l.EventType.RUN_STARTED&&f!==l.EventType.RUN_ERROR)return(0,d.throwError)(()=>new l.AGUIError(`First event must be 'RUN_STARTED'`))}else if(f===l.EventType.RUN_STARTED){if(p&&!i)return(0,d.throwError)(()=>new l.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.`));i&&m()}switch(f){case l.EventType.TEXT_MESSAGE_START:{let e=t.messageId;return n.has(e)?(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${e}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(n.set(e,!0),(0,d.of)(t))}case l.EventType.TEXT_MESSAGE_CONTENT:{let e=t.messageId;return n.has(e)?(0,d.of)(t):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${e}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case l.EventType.TEXT_MESSAGE_END:{let e=t.messageId;return n.has(e)?(n.delete(e),(0,d.of)(t)):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${e}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case l.EventType.TOOL_CALL_START:{let e=t.toolCallId;return r.has(e)?(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${e}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(r.set(e,!0),(0,d.of)(t))}case l.EventType.TOOL_CALL_ARGS:{let e=t.toolCallId;return r.has(e)?(0,d.of)(t):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${e}'. Start a tool call with 'TOOL_CALL_START' first.`))}case l.EventType.TOOL_CALL_END:{let e=t.toolCallId;return r.has(e)?(r.delete(e),(0,d.of)(t)):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${e}'. A 'TOOL_CALL_START' event must be sent first.`))}case l.EventType.STEP_STARTED:{let e=t.stepName;return s.has(e)?(0,d.throwError)(()=>new l.AGUIError(`Step "${e}" is already active for 'STEP_STARTED'`)):(s.set(e,!0),(0,d.of)(t))}case l.EventType.STEP_FINISHED:{let e=t.stepName;return s.has(e)?(s.delete(e),(0,d.of)(t)):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'STEP_FINISHED' for step "${e}" that was not started`))}case l.EventType.RUN_STARTED:return p=!0,(0,d.of)(t);case l.EventType.RUN_FINISHED:if(s.size>0){let e=Array.from(s.keys()).join(`, `);return(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'RUN_FINISHED' while steps are still active: ${e}`))}if(n.size>0){let e=Array.from(n.keys()).join(`, `);return(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'RUN_FINISHED' while text messages are still active: ${e}`))}if(r.size>0){let e=Array.from(r.keys()).join(`, `);return(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${e}`))}return i=!0,(0,d.of)(t);case l.EventType.RUN_ERROR:return a=!0,(0,d.of)(t);case l.EventType.CUSTOM:return(0,d.of)(t);case l.EventType.THINKING_TEXT_MESSAGE_START:return c?u?(0,d.throwError)(()=>new l.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,d.of)(t)):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first.`));case l.EventType.THINKING_TEXT_MESSAGE_CONTENT:return u?(0,d.of)(t):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first.`));case l.EventType.THINKING_TEXT_MESSAGE_END:return u?(u=!1,(0,d.of)(t)):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first.`));case l.EventType.THINKING_START:return c?(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.`)):(c=!0,(0,d.of)(t));case l.EventType.THINKING_END:return c?(c=!1,(0,d.of)(t)):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first.`));default:return(0,d.of)(t)}}))};let S=function(e){return e.HEADERS=`headers`,e.DATA=`data`,e}({});const C=(e,t)=>(0,d.defer)(()=>(0,d.from)(fetch(e,t))).pipe((0,f.switchMap)(e=>{if(!e.ok){let t=e.headers.get(`content-type`)||``;return(0,d.from)(e.text()).pipe((0,f.mergeMap)(n=>{let r=n;if(t.includes(`application/json`))try{r=JSON.parse(n)}catch{}let i=Error(`HTTP ${e.status}: ${typeof r==`string`?r:JSON.stringify(r)}`);return i.status=e.status,i.payload=r,(0,d.throwError)(()=>i)}))}let t={type:S.HEADERS,status:e.status,headers:e.headers},n=e.body?.getReader();return n?new d.Observable(e=>(e.next(t),(async()=>{try{for(;;){let{done:t,value:r}=await n.read();if(t)break;let i={type:S.DATA,data:r};e.next(i)}e.complete()}catch(t){e.error(t)}})(),()=>{n.cancel().catch(e=>{if(e?.name!==`AbortError`)throw e})})):(0,d.throwError)(()=>Error(`Failed to getReader() from response`))})),w=e=>{let t=new d.Subject,n=new TextDecoder(`utf-8`,{fatal:!1}),r=``;e.subscribe({next:e=>{if(e.type!==S.HEADERS&&e.type===S.DATA&&e.data){let t=n.decode(e.data,{stream:!0});r+=t;let a=r.split(/\n\n/);r=a.pop()||``;for(let e of a)i(e)}},error:e=>t.error(e),complete:()=>{r&&(r+=n.decode(),i(r)),t.complete()}});function i(e){let n=e.split(`
|
|
1
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`uuid`),l=require(`@ag-ui/core`),u=require(`fast-json-patch`);u=s(u);let d=require(`rxjs`),f=require(`rxjs/operators`),p=require(`untruncate-json`);p=s(p);let m=require(`@ag-ui/proto`);m=s(m);let h=require(`zod`),g=require(`compare-versions`);const _=e=>{if(typeof structuredClone==`function`)return structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch{return{...e}}};function v(){return(0,c.v4)()}async function y(e,t,n,r){let i=t,a=n,o;for(let t of e)try{let e=await r(t,_(i),_(a));if(e===void 0)continue;if(e.messages!==void 0&&(i=e.messages),e.state!==void 0&&(a=e.state),o=e.stopPropagation,o===!0)break}catch(e){process.env.NODE_ENV===`test`||process.env.VITEST_WORKER_ID!==void 0||console.error(`Subscriber error:`,e);continue}return{...JSON.stringify(i)===JSON.stringify(t)?{}:{messages:i},...JSON.stringify(a)===JSON.stringify(n)?{}:{state:a},...o===void 0?{}:{stopPropagation:o}}}const b=(e,t,n,r)=>{let i=_(n.messages),a=_(e.state),o={},s=e=>{e.messages!==void 0&&(i=e.messages,o.messages=e.messages),e.state!==void 0&&(a=e.state,o.state=e.state)},c=()=>{let e=_(o);return o={},e.messages!==void 0||e.state!==void 0?(0,d.of)(e):d.EMPTY};return t.pipe((0,f.concatMap)(async t=>{let d=await y(r,i,a,(r,i,a)=>r.onEvent?.({event:t,agent:n,input:e,messages:i,state:a}));if(s(d),d.stopPropagation===!0)return c();switch(t.type){case l.EventType.TEXT_MESSAGE_START:{let o=await y(r,i,a,(r,i,a)=>r.onTextMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{messageId:e,role:n=`assistant`}=t;if(!i.find(t=>t.id===e)){let t={id:e,role:n,content:``};i.push(t),s({messages:i})}}return c()}case l.EventType.TEXT_MESSAGE_CONTENT:{let{messageId:o,delta:l}=t,u=i.find(e=>e.id===o);if(!u)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${o}'`),c();let d=await y(r,i,a,(r,i,a)=>r.onTextMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,textMessageBuffer:typeof u.content==`string`?u.content:``}));return s(d),d.stopPropagation!==!0&&(u.content=`${typeof u.content==`string`?u.content:``}${l}`,s({messages:i})),c()}case l.EventType.TEXT_MESSAGE_END:{let{messageId:o}=t,l=i.find(e=>e.id===o);return l?(s(await y(r,i,a,(r,i,a)=>r.onTextMessageEndEvent?.({event:t,messages:i,state:a,agent:n,input:e,textMessageBuffer:typeof l.content==`string`?l.content:``}))),await Promise.all(r.map(t=>{t.onNewMessage?.({message:l,messages:i,state:a,agent:n,input:e})})),c()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${o}'`),c())}case l.EventType.TOOL_CALL_START:{let o=await y(r,i,a,(r,i,a)=>r.onToolCallStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{toolCallId:e,toolCallName:n,parentMessageId:r}=t,a;r&&i.length>0&&i[i.length-1].id===r?a=i[i.length-1]:(a={id:r||e,role:`assistant`,toolCalls:[]},i.push(a)),a.toolCalls??=[],a.toolCalls.push({id:e,type:`function`,function:{name:n,arguments:``}}),s({messages:i})}return c()}case l.EventType.TOOL_CALL_ARGS:{let{toolCallId:o,delta:l}=t,u=i.find(e=>e.toolCalls?.some(e=>e.id===o));if(!u)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${o}'`),c();let d=u.toolCalls?.find(e=>e.id===o);if(!d)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${o}'`),c();let f=await y(r,i,a,(r,i,a)=>{let o=d.function.arguments,s=d.function.name,c={};try{c=(0,p.default)(o)}catch{}return r.onToolCallArgsEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallBuffer:o,toolCallName:s,partialToolCallArgs:c})});return s(f),f.stopPropagation!==!0&&(d.function.arguments+=l,s({messages:i})),c()}case l.EventType.TOOL_CALL_END:{let{toolCallId:o}=t,l=i.find(e=>e.toolCalls?.some(e=>e.id===o));if(!l)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${o}'`),c();let u=l.toolCalls?.find(e=>e.id===o);return u?(s(await y(r,i,a,(r,i,a)=>{let o=u.function.arguments,s=u.function.name,c={};try{c=JSON.parse(o)}catch{}return r.onToolCallEndEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallName:s,toolCallArgs:c})})),await Promise.all(r.map(t=>{t.onNewToolCall?.({toolCall:u,messages:i,state:a,agent:n,input:e})})),c()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${o}'`),c())}case l.EventType.TOOL_CALL_RESULT:{let o=await y(r,i,a,(r,i,a)=>r.onToolCallResultEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{messageId:o,toolCallId:c,content:l,role:u}=t,d={id:o,toolCallId:c,role:u||`tool`,content:l};i.push(d),await Promise.all(r.map(t=>{t.onNewMessage?.({message:d,messages:i,state:a,agent:n,input:e})})),s({messages:i})}return c()}case l.EventType.STATE_SNAPSHOT:{let o=await y(r,i,a,(r,i,a)=>r.onStateSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{snapshot:e}=t;a=e,s({state:a})}return c()}case l.EventType.STATE_DELTA:{let o=await y(r,i,a,(r,i,a)=>r.onStateDeltaEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{delta:e}=t;try{a=u.applyPatch(a,e,!0,!1).newDocument,s({state:a})}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Failed to apply state patch:\nCurrent state: ${JSON.stringify(a,null,2)}\nPatch operations: ${JSON.stringify(e,null,2)}\nError: ${n}`)}}return c()}case l.EventType.MESSAGES_SNAPSHOT:{let o=await y(r,i,a,(r,i,a)=>r.onMessagesSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{messages:e}=t,n=new Map(e.map(e=>[e.id,e]));i=i.filter(e=>e.role===`activity`||n.has(e.id)).map(e=>e.role===`activity`?e:n.get(e.id));let r=new Set(i.map(e=>e.id));for(let t of e)r.has(t.id)||i.push(t);s({messages:i})}return c()}case l.EventType.ACTIVITY_SNAPSHOT:{let o=t,l=i.findIndex(e=>e.id===o.messageId),u=l>=0?i[l]:void 0,d=u?.role===`activity`?u:void 0,f=o.replace??!0,p=await y(r,i,a,(t,r,i)=>t.onActivitySnapshotEvent?.({event:o,messages:r,state:i,agent:n,input:e,activityMessage:d,existingMessage:u}));if(s(p),p.stopPropagation!==!0){let t={id:o.messageId,role:`activity`,activityType:o.activityType,content:_(o.content)},c;l===-1?(i.push(t),c=t):d?f&&(i[l]={...d,activityType:o.activityType,content:_(o.content)}):f&&(i[l]=t,c=t),s({messages:i}),c&&await Promise.all(r.map(t=>t.onNewMessage?.({message:c,messages:i,state:a,agent:n,input:e})))}return c()}case l.EventType.ACTIVITY_DELTA:{let o=t,l=i.findIndex(e=>e.id===o.messageId);if(l===-1)return c();let d=i[l];if(d.role!==`activity`)return console.warn(`ACTIVITY_DELTA: Message '${o.messageId}' is not an activity message`),c();let f=d,p=await y(r,i,a,(t,r,i)=>t.onActivityDeltaEvent?.({event:o,messages:r,state:i,agent:n,input:e,activityMessage:f}));if(s(p),p.stopPropagation!==!0)try{let e=_(f.content??{}),t=u.applyPatch(e,o.patch??[],!0,!1).newDocument;i[l]={...f,content:_(t),activityType:o.activityType},s({messages:i})}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`Failed to apply activity patch for '${o.messageId}': ${t}`)}return c()}case l.EventType.RAW:return s(await y(r,i,a,(r,i,a)=>r.onRawEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.CUSTOM:return s(await y(r,i,a,(r,i,a)=>r.onCustomEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.RUN_STARTED:{let o=await y(r,i,a,(r,i,a)=>r.onRunStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let e=t;if(e.input?.messages){for(let t of e.input.messages)i.find(e=>e.id===t.id)||i.push(t);s({messages:i})}}return c()}case l.EventType.RUN_FINISHED:return s(await y(r,i,a,(r,i,a)=>r.onRunFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e,result:t.result}))),c();case l.EventType.RUN_ERROR:return s(await y(r,i,a,(r,i,a)=>r.onRunErrorEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.STEP_STARTED:return s(await y(r,i,a,(r,i,a)=>r.onStepStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.STEP_FINISHED:return s(await y(r,i,a,(r,i,a)=>r.onStepFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.TEXT_MESSAGE_CHUNK:throw Error(`TEXT_MESSAGE_CHUNK must be tranformed before being applied`);case l.EventType.TOOL_CALL_CHUNK:throw Error(`TOOL_CALL_CHUNK must be tranformed before being applied`);case l.EventType.THINKING_START:return c();case l.EventType.THINKING_END:return c();case l.EventType.THINKING_TEXT_MESSAGE_START:return c();case l.EventType.THINKING_TEXT_MESSAGE_CONTENT:return c();case l.EventType.THINKING_TEXT_MESSAGE_END:return c();case l.EventType.REASONING_START:return s(await y(r,i,a,(r,i,a)=>r.onReasoningStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.REASONING_MESSAGE_START:{let o=await y(r,i,a,(r,i,a)=>r.onReasoningMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(o),o.stopPropagation!==!0){let{messageId:e}=t;if(!i.find(t=>t.id===e)){let t={id:e,role:`reasoning`,content:``};i.push(t),s({messages:i})}}return c()}case l.EventType.REASONING_MESSAGE_CONTENT:{let{messageId:o,delta:l}=t,u=i.find(e=>e.id===o);if(!u)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${o}'`),c();let d=await y(r,i,a,(r,i,a)=>r.onReasoningMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,reasoningMessageBuffer:typeof u.content==`string`?u.content:``}));return s(d),d.stopPropagation!==!0&&(u.content=`${typeof u.content==`string`?u.content:``}${l}`,s({messages:i})),c()}case l.EventType.REASONING_MESSAGE_END:{let{messageId:o}=t,l=i.find(e=>e.id===o);return l?(s(await y(r,i,a,(r,i,a)=>r.onReasoningMessageEndEvent?.({event:t,messages:i,state:a,agent:n,input:e,reasoningMessageBuffer:typeof l.content==`string`?l.content:``}))),await Promise.all(r.map(t=>{t.onNewMessage?.({message:l,messages:i,state:a,agent:n,input:e})})),c()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${o}'`),c())}case l.EventType.REASONING_MESSAGE_CHUNK:throw Error(`REASONING_MESSAGE_CHUNK must be transformed before being applied`);case l.EventType.REASONING_END:return s(await y(r,i,a,(r,i,a)=>r.onReasoningEndEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),c();case l.EventType.REASONING_ENCRYPTED_VALUE:{let{subtype:l,entityId:u,encryptedValue:d}=t,f=await y(r,i,a,(r,i,a)=>r.onReasoningEncryptedValueEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(s(f),f.stopPropagation!==!0){let e=!1;if(l===`tool-call`){for(let t of i)if(t.role===`assistant`&&t.toolCalls){let n=t.toolCalls.find(e=>e.id===u);if(n){n.encryptedValue=d,e=!0;break}}}else{let t=i.find(e=>e.id===u);t?.role!==`activity`&&t&&(t.encryptedValue=d,e=!0)}e&&(o.messages=i)}return c()}}return t.type,c()}),(0,f.mergeAll)(),r.length>0?(0,f.defaultIfEmpty)({}):e=>e)},x=e=>t=>{let n=new Map,r=new Map,i=!1,a=!1,o=!1,s=new Map,c=!1,u=!1,p=!1,m=()=>{n.clear(),r.clear(),s.clear(),c=!1,u=!1,i=!1,a=!1,p=!0};return t.pipe((0,f.mergeMap)(t=>{let f=t.type;if(e&&console.debug(`[VERIFY]:`,JSON.stringify(t)),a)return(0,d.throwError)(()=>new l.AGUIError(`Cannot send event type '${f}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(i&&f!==l.EventType.RUN_ERROR&&f!==l.EventType.RUN_STARTED)return(0,d.throwError)(()=>new l.AGUIError(`Cannot send event type '${f}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(!o){if(o=!0,f!==l.EventType.RUN_STARTED&&f!==l.EventType.RUN_ERROR)return(0,d.throwError)(()=>new l.AGUIError(`First event must be 'RUN_STARTED'`))}else if(f===l.EventType.RUN_STARTED){if(p&&!i)return(0,d.throwError)(()=>new l.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.`));i&&m()}switch(f){case l.EventType.TEXT_MESSAGE_START:{let e=t.messageId;return n.has(e)?(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${e}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(n.set(e,!0),(0,d.of)(t))}case l.EventType.TEXT_MESSAGE_CONTENT:{let e=t.messageId;return n.has(e)?(0,d.of)(t):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${e}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case l.EventType.TEXT_MESSAGE_END:{let e=t.messageId;return n.has(e)?(n.delete(e),(0,d.of)(t)):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${e}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case l.EventType.TOOL_CALL_START:{let e=t.toolCallId;return r.has(e)?(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${e}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(r.set(e,!0),(0,d.of)(t))}case l.EventType.TOOL_CALL_ARGS:{let e=t.toolCallId;return r.has(e)?(0,d.of)(t):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${e}'. Start a tool call with 'TOOL_CALL_START' first.`))}case l.EventType.TOOL_CALL_END:{let e=t.toolCallId;return r.has(e)?(r.delete(e),(0,d.of)(t)):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${e}'. A 'TOOL_CALL_START' event must be sent first.`))}case l.EventType.STEP_STARTED:{let e=t.stepName;return s.has(e)?(0,d.throwError)(()=>new l.AGUIError(`Step "${e}" is already active for 'STEP_STARTED'`)):(s.set(e,!0),(0,d.of)(t))}case l.EventType.STEP_FINISHED:{let e=t.stepName;return s.has(e)?(s.delete(e),(0,d.of)(t)):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'STEP_FINISHED' for step "${e}" that was not started`))}case l.EventType.RUN_STARTED:return p=!0,(0,d.of)(t);case l.EventType.RUN_FINISHED:if(s.size>0){let e=Array.from(s.keys()).join(`, `);return(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'RUN_FINISHED' while steps are still active: ${e}`))}if(n.size>0){let e=Array.from(n.keys()).join(`, `);return(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'RUN_FINISHED' while text messages are still active: ${e}`))}if(r.size>0){let e=Array.from(r.keys()).join(`, `);return(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${e}`))}return i=!0,(0,d.of)(t);case l.EventType.RUN_ERROR:return a=!0,(0,d.of)(t);case l.EventType.CUSTOM:return(0,d.of)(t);case l.EventType.THINKING_TEXT_MESSAGE_START:return c?u?(0,d.throwError)(()=>new l.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,d.of)(t)):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first.`));case l.EventType.THINKING_TEXT_MESSAGE_CONTENT:return u?(0,d.of)(t):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first.`));case l.EventType.THINKING_TEXT_MESSAGE_END:return u?(u=!1,(0,d.of)(t)):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first.`));case l.EventType.THINKING_START:return c?(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.`)):(c=!0,(0,d.of)(t));case l.EventType.THINKING_END:return c?(c=!1,(0,d.of)(t)):(0,d.throwError)(()=>new l.AGUIError(`Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first.`));default:return(0,d.of)(t)}}))};let S=function(e){return e.HEADERS=`headers`,e.DATA=`data`,e}({});const C=(e,t)=>(0,d.defer)(()=>(0,d.from)(fetch(e,t))).pipe((0,f.switchMap)(e=>{if(!e.ok){let t=e.headers.get(`content-type`)||``;return(0,d.from)(e.text()).pipe((0,f.mergeMap)(n=>{let r=n;if(t.includes(`application/json`))try{r=JSON.parse(n)}catch{}let i=Error(`HTTP ${e.status}: ${typeof r==`string`?r:JSON.stringify(r)}`);return i.status=e.status,i.payload=r,(0,d.throwError)(()=>i)}))}let t={type:S.HEADERS,status:e.status,headers:e.headers},n=e.body?.getReader();return n?new d.Observable(e=>(e.next(t),(async()=>{try{for(;;){let{done:t,value:r}=await n.read();if(t)break;let i={type:S.DATA,data:r};e.next(i)}e.complete()}catch(t){e.error(t)}})(),()=>{n.cancel().catch(e=>{if(e?.name!==`AbortError`)throw e})})):(0,d.throwError)(()=>Error(`Failed to getReader() from response`))})),w=e=>{let t=new d.Subject,n=new TextDecoder(`utf-8`,{fatal:!1}),r=``;e.subscribe({next:e=>{if(e.type!==S.HEADERS&&e.type===S.DATA&&e.data){let t=n.decode(e.data,{stream:!0});r+=t;let a=r.split(/\n\n/);r=a.pop()||``;for(let e of a)i(e)}},error:e=>t.error(e),complete:()=>{r&&(r+=n.decode(),i(r)),t.complete()}});function i(e){let n=e.split(`
|
|
2
2
|
`),r=[];for(let e of n)e.startsWith(`data:`)&&r.push(e.slice(5).replace(/^ /,``));if(r.length>0)try{let e=r.join(`
|
|
3
3
|
`),n=JSON.parse(e);t.next(n)}catch(e){t.error(e)}}return t.asObservable()},T=e=>{let t=new d.Subject,n=new Uint8Array;e.subscribe({next:e=>{if(e.type!==S.HEADERS&&e.type===S.DATA&&e.data){let t=new Uint8Array(n.length+e.data.length);t.set(n,0),t.set(e.data,n.length),n=t,r()}},error:e=>t.error(e),complete:()=>{if(n.length>0)try{r()}catch{console.warn(`Incomplete or invalid protocol buffer data at stream end`)}t.complete()}});function r(){for(;n.length>=4;){let e=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<e)break;try{let r=n.slice(4,e),i=m.decode(r);t.next(i),n=n.slice(e)}catch(e){let n=e instanceof Error?e.message:String(e);t.error(Error(`Failed to decode protocol buffer message: ${n}`));return}}}return t.asObservable()},E=e=>{let t=new d.Subject,n=new d.ReplaySubject,r=!1;return e.subscribe({next:e=>{n.next(e),e.type===S.HEADERS&&!r?(r=!0,e.headers.get(`content-type`)===m.AGUI_MEDIA_TYPE?T(n).subscribe({next:e=>t.next(e),error:e=>t.error(e),complete:()=>t.complete()}):w(n).subscribe({next:e=>{try{let n=l.EventSchemas.parse(e);t.next(n)}catch(e){t.error(e)}},error:e=>{if(e?.name===`AbortError`){t.next({type:l.EventType.RUN_ERROR,message:e.message||`Request aborted`,code:`abort`,rawEvent:e}),t.complete();return}return t.error(e)},complete:()=>t.complete()})):r||t.error(Error(`No headers event received before data events`))},error:e=>{n.error(e),t.error(e)},complete:()=>{n.complete()}}),t.asObservable()},D=h.z.enum([`TextMessageStart`,`TextMessageContent`,`TextMessageEnd`,`ActionExecutionStart`,`ActionExecutionArgs`,`ActionExecutionEnd`,`ActionExecutionResult`,`AgentStateMessage`,`MetaEvent`,`RunStarted`,`RunFinished`,`RunError`,`NodeStarted`,`NodeFinished`]),O=h.z.enum([`LangGraphInterruptEvent`,`PredictState`,`Exit`]),ee=h.z.object({type:h.z.literal(D.enum.TextMessageStart),messageId:h.z.string(),parentMessageId:h.z.string().optional(),role:h.z.string().optional()}),te=h.z.object({type:h.z.literal(D.enum.TextMessageContent),messageId:h.z.string(),content:h.z.string()}),k=h.z.object({type:h.z.literal(D.enum.TextMessageEnd),messageId:h.z.string()}),A=h.z.object({type:h.z.literal(D.enum.ActionExecutionStart),actionExecutionId:h.z.string(),actionName:h.z.string(),parentMessageId:h.z.string().optional()}),j=h.z.object({type:h.z.literal(D.enum.ActionExecutionArgs),actionExecutionId:h.z.string(),args:h.z.string()}),M=h.z.object({type:h.z.literal(D.enum.ActionExecutionEnd),actionExecutionId:h.z.string()}),N=h.z.object({type:h.z.literal(D.enum.ActionExecutionResult),actionName:h.z.string(),actionExecutionId:h.z.string(),result:h.z.string()}),P=h.z.object({type:h.z.literal(D.enum.AgentStateMessage),threadId:h.z.string(),agentName:h.z.string(),nodeName:h.z.string(),runId:h.z.string(),active:h.z.boolean(),role:h.z.string(),state:h.z.string(),running:h.z.boolean()}),F=h.z.object({type:h.z.literal(D.enum.MetaEvent),name:O,value:h.z.any()}),I=h.z.object({type:h.z.literal(D.enum.RunError),message:h.z.string(),code:h.z.string().optional()});h.z.discriminatedUnion(`type`,[ee,te,k,A,j,M,N,P,F,I]),h.z.object({id:h.z.string(),role:h.z.string(),content:h.z.string(),parentMessageId:h.z.string().optional()}),h.z.object({id:h.z.string(),name:h.z.string(),arguments:h.z.any(),parentMessageId:h.z.string().optional()}),h.z.object({id:h.z.string(),result:h.z.any(),actionExecutionId:h.z.string(),actionName:h.z.string()});const L=e=>{if(typeof e==`string`)return e;if(!Array.isArray(e))return;let t=e.filter(e=>e.type===`text`).map(e=>e.text).filter(e=>e.length>0);if(t.length!==0)return t.join(`
|
|
4
|
-
`)},R=(e,t,n)=>r=>{let i={},a=!0,o=!0,s=``,c=null,d=null,m=[],h={},g=e=>{typeof e==`object`&&e&&(`messages`in e&&delete e.messages,i=e)};return r.pipe((0,f.mergeMap)(r=>{switch(r.type){case l.EventType.TEXT_MESSAGE_START:{let e=r;return[{type:D.enum.TextMessageStart,messageId:e.messageId,role:e.role}]}case l.EventType.TEXT_MESSAGE_CONTENT:{let e=r;return[{type:D.enum.TextMessageContent,messageId:e.messageId,content:e.delta}]}case l.EventType.TEXT_MESSAGE_END:{let e=r;return[{type:D.enum.TextMessageEnd,messageId:e.messageId}]}case l.EventType.TOOL_CALL_START:{let e=r;return m.push({id:e.toolCallId,type:`function`,function:{name:e.toolCallName,arguments:``}}),o=!0,h[e.toolCallId]=e.toolCallName,[{type:D.enum.ActionExecutionStart,actionExecutionId:e.toolCallId,actionName:e.toolCallName,parentMessageId:e.parentMessageId}]}case l.EventType.TOOL_CALL_ARGS:{let c=r,l=m.find(e=>e.id===c.toolCallId);if(!l)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c.toolCallId}'`),[];l.function.arguments+=c.delta;let u=!1;if(d){let e=d.find(e=>e.tool==l.function.name);if(e)try{let t=JSON.parse((0,p.default)(l.function.arguments));e.tool_argument&&e.tool_argument in t?(g({...i,[e.state_key]:t[e.tool_argument]}),u=!0):e.tool_argument||(g({...i,[e.state_key]:t}),u=!0)}catch{}}return[{type:D.enum.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...u?[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}]:[]]}case l.EventType.TOOL_CALL_END:{let e=r;return[{type:D.enum.ActionExecutionEnd,actionExecutionId:e.toolCallId}]}case l.EventType.TOOL_CALL_RESULT:{let e=r;return[{type:D.enum.ActionExecutionResult,actionExecutionId:e.toolCallId,result:e.content,actionName:h[e.toolCallId]||`unknown`}]}case l.EventType.RAW:return[];case l.EventType.CUSTOM:{let e=r;switch(e.name){case`Exit`:a=!1;break;case`PredictState`:d=e.value;break}return[{type:D.enum.MetaEvent,name:e.name,value:e.value}]}case l.EventType.STATE_SNAPSHOT:return g(r.snapshot),[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}];case l.EventType.STATE_DELTA:{let c=r,l=u.applyPatch(i,c.delta,!0,!1);return l?(g(l.newDocument),[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}]):[]}case l.EventType.MESSAGES_SNAPSHOT:return c=r.messages,[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify({...i,...c?{messages:c}:{}}),active:!0}];case l.EventType.RUN_STARTED:return[];case l.EventType.RUN_FINISHED:return c&&(i.messages=c),Object.keys(i).length===0?[]:[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify({...i,...c?{messages:ne(c)}:{}}),active:!1}];case l.EventType.RUN_ERROR:{let e=r;return[{type:D.enum.RunError,message:e.message,code:e.code}]}case l.EventType.STEP_STARTED:return s=r.stepName,m=[],d=null,[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:!0}];case l.EventType.STEP_FINISHED:return m=[],d=null,[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:!1}];default:return[]}}))};function ne(e){let t=[];for(let n of e)if(n.role===`assistant`||n.role===`user`||n.role===`system`){let e=L(n.content);if(e){let r={id:n.id,role:n.role,content:e};t.push(r)}if(n.role===`assistant`&&n.toolCalls&&n.toolCalls.length>0)for(let e of n.toolCalls){let r={id:e.id,name:e.function.name,arguments:JSON.parse(e.function.arguments),parentMessageId:n.id};t.push(r)}}else if(n.role===`tool`){let r=`unknown`;for(let t of e)if(t.role===`assistant`&&t.toolCalls?.length){for(let e of t.toolCalls)if(e.id===n.toolCallId){r=e.function.name;break}}let i={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};t.push(i)}return t}const z=e=>t=>{let n,r,i,a,o=()=>{if(!n||a!==`text`)throw Error(`No text message to close`);let t={type:l.EventType.TEXT_MESSAGE_END,messageId:n.messageId};return a=void 0,n=void 0,e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_END`,JSON.stringify(t)),t},s=()=>{if(!r||a!==`tool`)throw Error(`No tool call to close`);let t={type:l.EventType.TOOL_CALL_END,toolCallId:r.toolCallId};return a=void 0,r=void 0,e&&console.debug(`[TRANSFORM]: TOOL_CALL_END`,JSON.stringify(t)),t},c=()=>{if(!i||a!==`reasoning`)throw Error(`No reasoning message to close`);let t={type:l.EventType.REASONING_MESSAGE_END,messageId:i.messageId};return a=void 0,i=void 0,e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_END`,JSON.stringify(t)),t},u=()=>a===`text`?[o()]:a===`tool`?[s()]:a===`reasoning`?[c()]:[];return t.pipe((0,d.mergeMap)(t=>{switch(t.type){case l.EventType.TEXT_MESSAGE_START:case l.EventType.TEXT_MESSAGE_CONTENT:case l.EventType.TEXT_MESSAGE_END:case l.EventType.TOOL_CALL_START:case l.EventType.TOOL_CALL_ARGS:case l.EventType.TOOL_CALL_END:case l.EventType.TOOL_CALL_RESULT:case l.EventType.STATE_SNAPSHOT:case l.EventType.STATE_DELTA:case l.EventType.MESSAGES_SNAPSHOT:case l.EventType.CUSTOM:case l.EventType.RUN_STARTED:case l.EventType.RUN_FINISHED:case l.EventType.RUN_ERROR:case l.EventType.STEP_STARTED:case l.EventType.STEP_FINISHED:case l.EventType.THINKING_START:case l.EventType.THINKING_END:case l.EventType.THINKING_TEXT_MESSAGE_START:case l.EventType.THINKING_TEXT_MESSAGE_CONTENT:case l.EventType.THINKING_TEXT_MESSAGE_END:case l.EventType.REASONING_START:case l.EventType.REASONING_MESSAGE_START:case l.EventType.REASONING_MESSAGE_CONTENT:case l.EventType.REASONING_MESSAGE_END:case l.EventType.REASONING_END:return[...u(),t];case l.EventType.RAW:case l.EventType.ACTIVITY_SNAPSHOT:case l.EventType.ACTIVITY_DELTA:case l.EventType.REASONING_ENCRYPTED_VALUE:return[t];case l.EventType.TEXT_MESSAGE_CHUNK:let o=t,s=[];if((a!==`text`||o.messageId!==void 0&&o.messageId!==n?.messageId)&&s.push(...u()),a!==`text`){if(o.messageId===void 0)throw Error(`First TEXT_MESSAGE_CHUNK must have a messageId`);n={messageId:o.messageId},a=`text`;let t={type:l.EventType.TEXT_MESSAGE_START,messageId:o.messageId,role:o.role||`assistant`};s.push(t),e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_START`,JSON.stringify(t))}if(o.delta!==void 0){let t={type:l.EventType.TEXT_MESSAGE_CONTENT,messageId:n.messageId,delta:o.delta};s.push(t),e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_CONTENT`,JSON.stringify(t))}return s;case l.EventType.TOOL_CALL_CHUNK:let c=t,d=[];if((a!==`tool`||c.toolCallId!==void 0&&c.toolCallId!==r?.toolCallId)&&d.push(...u()),a!==`tool`){if(c.toolCallId===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallId`);if(c.toolCallName===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallName`);r={toolCallId:c.toolCallId,toolCallName:c.toolCallName,parentMessageId:c.parentMessageId},a=`tool`;let t={type:l.EventType.TOOL_CALL_START,toolCallId:c.toolCallId,toolCallName:c.toolCallName,parentMessageId:c.parentMessageId};d.push(t),e&&console.debug(`[TRANSFORM]: TOOL_CALL_START`,JSON.stringify(t))}if(c.delta!==void 0){let t={type:l.EventType.TOOL_CALL_ARGS,toolCallId:r.toolCallId,delta:c.delta};d.push(t),e&&console.debug(`[TRANSFORM]: TOOL_CALL_ARGS`,JSON.stringify(t))}return d;case l.EventType.REASONING_MESSAGE_CHUNK:let f=t,p=[];if((a!==`reasoning`||f.messageId&&f.messageId!==i?.messageId)&&p.push(...u()),a!==`reasoning`){if(f.messageId===void 0)throw Error(`First REASONING_MESSAGE_CHUNK must have a messageId`);i={messageId:f.messageId},a=`reasoning`;let t={type:l.EventType.REASONING_MESSAGE_START,messageId:f.messageId};p.push(t),e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_START`,JSON.stringify(t))}if(f.delta!==void 0){let t={type:l.EventType.REASONING_MESSAGE_CONTENT,messageId:i.messageId,delta:f.delta};p.push(t),e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_CONTENT`,JSON.stringify(t))}return p}return t.type,[]}),(0,d.finalize)(()=>{u()}))};var B=class{runNext(e,t){return t.run(e).pipe(z(!1))}runNextWithState(e,t){let n=_(e.messages||[]),r=_(e.state||{}),i=new d.ReplaySubject;return b(e,i,t,[]).subscribe(e=>{e.messages!==void 0&&(n=e.messages),e.state!==void 0&&(r=e.state)}),this.runNext(e,t).pipe((0,f.concatMap)(async e=>(i.next(e),await new Promise(e=>setTimeout(e,0)),{event:e,messages:_(n),state:_(r)})))}},V=class extends B{constructor(e){super(),this.fn=e}run(e,t){return this.fn(e,t)}},H=class extends B{constructor(e){if(super(),this.blockedToolCallIds=new Set,e.allowedToolCalls&&e.disallowedToolCalls)throw Error(`Cannot specify both allowedToolCalls and disallowedToolCalls`);if(!e.allowedToolCalls&&!e.disallowedToolCalls)throw Error(`Must specify either allowedToolCalls or disallowedToolCalls`);e.allowedToolCalls?this.allowedTools=new Set(e.allowedToolCalls):e.disallowedToolCalls&&(this.disallowedTools=new Set(e.disallowedToolCalls))}run(e,t){return this.runNext(e,t).pipe((0,f.filter)(e=>{if(e.type===l.EventType.TOOL_CALL_START){let t=e;return this.shouldFilterTool(t.toolCallName)?(this.blockedToolCallIds.add(t.toolCallId),!1):!0}if(e.type===l.EventType.TOOL_CALL_ARGS){let t=e;return!this.blockedToolCallIds.has(t.toolCallId)}if(e.type===l.EventType.TOOL_CALL_END){let t=e;return!this.blockedToolCallIds.has(t.toolCallId)}if(e.type===l.EventType.TOOL_CALL_RESULT){let t=e;return this.blockedToolCallIds.has(t.toolCallId)?(this.blockedToolCallIds.delete(t.toolCallId),!1):!0}return!0}))}shouldFilterTool(e){return this.allowedTools?!this.allowedTools.has(e):this.disallowedTools?this.disallowedTools.has(e):!1}};function U(e){let t=e.content;if(Array.isArray(t)){let n=t.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``);return{...e,content:n}}return typeof t==`string`?e:{...e,content:``}}var W=class extends B{run(e,t){let{parentRunId:n,...r}=e,i={...r,messages:r.messages.map(U)};return this.runNext(i,t)}};const G=`THINKING_START`,K=`THINKING_END`,q=`THINKING_TEXT_MESSAGE_START`,J=`THINKING_TEXT_MESSAGE_CONTENT`,Y=`THINKING_TEXT_MESSAGE_END`;var X=class extends B{constructor(...e){super(...e),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(e,t){process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${e} to ${t}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(e,t){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(e,t).pipe((0,f.map)(e=>this.transformEvent(e)))}transformEvent(e){switch(e.type){case G:{this.currentReasoningId=v();let{title:t,...n}=e;return this.warnAboutTransformation(G,l.EventType.REASONING_START),{...n,type:l.EventType.REASONING_START,messageId:this.currentReasoningId}}case q:return this.currentMessageId=v(),this.warnAboutTransformation(q,l.EventType.REASONING_MESSAGE_START),{...e,type:l.EventType.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:`assistant`};case J:{let{delta:t,...n}=e;return this.warnAboutTransformation(J,l.EventType.REASONING_MESSAGE_CONTENT),{...n,type:l.EventType.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??v(),delta:t}}case Y:{let t=this.currentMessageId??v();return this.warnAboutTransformation(Y,l.EventType.REASONING_MESSAGE_END),{...e,type:l.EventType.REASONING_MESSAGE_END,messageId:t}}case K:{let t=this.currentReasoningId??v();return this.warnAboutTransformation(K,l.EventType.REASONING_END),{...e,type:l.EventType.REASONING_END,messageId:t}}default:return e}}},re=`0.0.45`,Z=class{get maxVersion(){return re}constructor({agentId:e,description:t,threadId:n,initialMessages:r,initialState:i,debug:a}={}){this.debug=!1,this.subscribers=[],this.isRunning=!1,this.middlewares=[],this.agentId=e,this.description=t??``,this.threadId=n??(0,c.v4)(),this.messages=_(r??[]),this.state=_(i??{}),this.debug=a??!1,(0,g.compareVersions)(this.maxVersion,`0.0.39`)<=0&&this.middlewares.unshift(new W),(0,g.compareVersions)(this.maxVersion,`0.0.45`)<=0&&this.middlewares.unshift(new X)}subscribe(e){return this.subscribers.push(e),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==e)}}}use(...e){let t=e.map(e=>typeof e==`function`?new V(e):e);return this.middlewares.push(...t),this}async runAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??(0,c.v4)();let n=this.prepareRunAgentInput(e),r,i=new Set(this.messages.map(e=>e.id)),a=[{onRunFinishedEvent:e=>{r=e.result}},...this.subscribers,t??{}];await this.onInitialize(n,a),this.activeRunDetach$=new d.Subject;let o;this.activeRunCompletionPromise=new Promise(e=>{o=e}),await(0,d.lastValueFrom)((0,d.pipe)(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((e,t)=>({run:n=>t.run(n,e)}),this).run(n),z(this.debug),x(this.debug),e=>e.pipe((0,f.takeUntil)(this.activeRunDetach$)),e=>this.apply(n,e,a),e=>this.processApplyEvents(n,e,a),(0,f.catchError)(e=>(this.isRunning=!1,this.onError(n,e,a))),(0,f.finalize)(()=>{this.isRunning=!1,this.onFinalize(n,a),o?.(),o=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))((0,d.of)(null)));let s=_(this.messages).filter(e=>!i.has(e.id));return{result:r,newMessages:s}}finally{this.isRunning=!1}}connect(e){throw new l.AGUIConnectNotImplementedError}async connectAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??(0,c.v4)();let n=this.prepareRunAgentInput(e),r,i=new Set(this.messages.map(e=>e.id)),a=[{onRunFinishedEvent:e=>{r=e.result}},...this.subscribers,t??{}];await this.onInitialize(n,a),this.activeRunDetach$=new d.Subject;let o;this.activeRunCompletionPromise=new Promise(e=>{o=e}),await(0,d.lastValueFrom)((0,d.pipe)(()=>this.connect(n),z(this.debug),x(this.debug),e=>e.pipe((0,f.takeUntil)(this.activeRunDetach$)),e=>this.apply(n,e,a),e=>this.processApplyEvents(n,e,a),(0,f.catchError)(e=>(this.isRunning=!1,e instanceof l.AGUIConnectNotImplementedError?d.EMPTY:this.onError(n,e,a))),(0,f.finalize)(()=>{this.isRunning=!1,this.onFinalize(n,a),o?.(),o=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))((0,d.of)(null)));let s=_(this.messages).filter(e=>!i.has(e.id));return{result:r,newMessages:s}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let e=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await e}apply(e,t,n){return b(e,t,this,n)}processApplyEvents(e,t,n){return t.pipe((0,f.tap)(t=>{t.messages&&(this.messages=t.messages,n.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),t.state&&(this.state=t.state,n.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))}))}prepareRunAgentInput(e){let t=_(this.messages).filter(e=>e.role!==`activity`);return{threadId:this.threadId,runId:e?.runId||(0,c.v4)(),tools:_(e?.tools??[]),context:_(e?.context??[]),forwardedProps:_(e?.forwardedProps??{}),state:_(this.state),messages:t}}async onInitialize(e,t){let n=await y(t,this.messages,this.state,(t,n,r)=>t.onRunInitialized?.({messages:n,state:r,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,e.messages=n.messages,t.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state&&(this.state=n.state,e.state=n.state,t.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}onError(e,t,n){return(0,d.from)(y(n,this.messages,this.state,(n,r,i)=>n.onRunFailed?.({error:t,messages:r,state:i,agent:this,input:e}))).pipe((0,f.map)(r=>{let i=r;if((i.messages!==void 0||i.state!==void 0)&&(i.messages!==void 0&&(this.messages=i.messages,n.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),i.state!==void 0&&(this.state=i.state,n.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))),i.stopPropagation!==!0)throw console.error(`Agent execution failed:`,t),t;return{}}))}async onFinalize(e,t){let n=await y(t,this.messages,this.state,(t,n,r)=>t.onRunFinalized?.({messages:n,state:r,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,t.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state!==void 0&&(this.state=n.state,t.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}clone(){let e=Object.create(Object.getPrototypeOf(this));return e.agentId=this.agentId,e.description=this.description,e.threadId=this.threadId,e.messages=_(this.messages),e.state=_(this.state),e.debug=this.debug,e.isRunning=this.isRunning,e.subscribers=[...this.subscribers],e.middlewares=[...this.middlewares],e}addMessage(e){this.messages.push(e),(async()=>{for(let t of this.subscribers)await t.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role===`assistant`&&e.toolCalls)for(let t of e.toolCalls)for(let e of this.subscribers)await e.onNewToolCall?.({toolCall:t,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(e){this.messages.push(...e),(async()=>{for(let t of e){for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role===`assistant`&&t.toolCalls)for(let e of t.toolCalls)for(let t of this.subscribers)await t.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(e){this.messages=_(e),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(e){this.state=_(e),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(e){this.agentId=this.agentId??(0,c.v4)();let t=this.prepareRunAgentInput(e);return(this.middlewares.length===0?this.run(t):this.middlewares.reduceRight((e,t)=>({run:n=>t.run(n,e)}),this).run(t)).pipe(z(this.debug),x(this.debug),R(this.threadId,t.runId,this.agentId),e=>e.pipe((0,f.map)(e=>(this.debug&&console.debug(`[LEGACY]:`,JSON.stringify(e)),e))))}},ie=class extends Z{requestInit(e){return{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e,t){return this.abortController=e?.abortController??new AbortController,super.runAgent(e,t)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(e){super(e),this.abortController=new AbortController,this.url=e.url,this.headers=_(e.headers??{})}run(e){return E(C(this.url,this.requestInit(e)))}clone(){let e=super.clone();e.url=this.url,e.headers=_(this.headers??{});let t=new AbortController,n=this.abortController.signal;return n.aborted&&t.abort(n.reason),e.abortController=t,e}};function ae(e){let t=[],n=new Map,r=new Map;for(let i of e)if(i.type===l.EventType.TEXT_MESSAGE_START){let e=i,t=e.messageId;n.has(t)||n.set(t,{contents:[],otherEvents:[]});let r=n.get(t);r.start=e}else if(i.type===l.EventType.TEXT_MESSAGE_CONTENT){let e=i,t=e.messageId;n.has(t)||n.set(t,{contents:[],otherEvents:[]}),n.get(t).contents.push(e)}else if(i.type===l.EventType.TEXT_MESSAGE_END){let e=i,r=e.messageId;n.has(r)||n.set(r,{contents:[],otherEvents:[]});let a=n.get(r);a.end=e,Q(r,a,t),n.delete(r)}else if(i.type===l.EventType.TOOL_CALL_START){let e=i,t=e.toolCallId;r.has(t)||r.set(t,{args:[],otherEvents:[]});let n=r.get(t);n.start=e}else if(i.type===l.EventType.TOOL_CALL_ARGS){let e=i,t=e.toolCallId;r.has(t)||r.set(t,{args:[],otherEvents:[]}),r.get(t).args.push(e)}else if(i.type===l.EventType.TOOL_CALL_END){let e=i,n=e.toolCallId;r.has(n)||r.set(n,{args:[],otherEvents:[]});let a=r.get(n);a.end=e,$(n,a,t),r.delete(n)}else{let e=!1;for(let[t,r]of n)if(r.start&&!r.end){r.otherEvents.push(i),e=!0;break}if(!e){for(let[t,n]of r)if(n.start&&!n.end){n.otherEvents.push(i),e=!0;break}}e||t.push(i)}for(let[e,r]of n)Q(e,r,t);for(let[e,n]of r)$(e,n,t);return t}function Q(e,t,n){if(t.start&&n.push(t.start),t.contents.length>0){let r=t.contents.map(e=>e.delta).join(``),i={type:l.EventType.TEXT_MESSAGE_CONTENT,messageId:e,delta:r};n.push(i)}t.end&&n.push(t.end);for(let e of t.otherEvents)n.push(e)}function $(e,t,n){if(t.start&&n.push(t.start),t.args.length>0){let r=t.args.map(e=>e.delta).join(``),i={type:l.EventType.TOOL_CALL_ARGS,toolCallId:e,delta:r};n.push(i)}t.end&&n.push(t.end);for(let e of t.otherEvents)n.push(e)}exports.AbstractAgent=Z,exports.BackwardCompatibility_0_0_39=W,exports.BackwardCompatibility_0_0_45=X,exports.FilterToolCallsMiddleware=H,exports.FunctionMiddleware=V,exports.HttpAgent=ie,exports.Middleware=B,exports.compactEvents=ae,exports.convertToLegacyEvents=R,exports.defaultApplyEvents=b,exports.parseProtoStream=T,exports.parseSSEStream=w,exports.randomUUID=v,exports.runHttpRequest=C,exports.structuredClone_=_,exports.transformChunks=z,exports.transformHttpEventStream=E,exports.verifyEvents=x,Object.keys(l).forEach(function(e){e!==`default`&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:function(){return l[e]}})});
|
|
4
|
+
`)},R=(e,t,n)=>r=>{let i={},a=!0,o=!0,s=``,c=null,d=null,m=[],h={},g=e=>{typeof e==`object`&&e&&(`messages`in e&&delete e.messages,i=e)};return r.pipe((0,f.mergeMap)(r=>{switch(r.type){case l.EventType.TEXT_MESSAGE_START:{let e=r;return[{type:D.enum.TextMessageStart,messageId:e.messageId,role:e.role}]}case l.EventType.TEXT_MESSAGE_CONTENT:{let e=r;return[{type:D.enum.TextMessageContent,messageId:e.messageId,content:e.delta}]}case l.EventType.TEXT_MESSAGE_END:{let e=r;return[{type:D.enum.TextMessageEnd,messageId:e.messageId}]}case l.EventType.TOOL_CALL_START:{let e=r;return m.push({id:e.toolCallId,type:`function`,function:{name:e.toolCallName,arguments:``}}),o=!0,h[e.toolCallId]=e.toolCallName,[{type:D.enum.ActionExecutionStart,actionExecutionId:e.toolCallId,actionName:e.toolCallName,parentMessageId:e.parentMessageId}]}case l.EventType.TOOL_CALL_ARGS:{let c=r,l=m.find(e=>e.id===c.toolCallId);if(!l)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c.toolCallId}'`),[];l.function.arguments+=c.delta;let u=!1;if(d){let e=d.find(e=>e.tool==l.function.name);if(e)try{let t=JSON.parse((0,p.default)(l.function.arguments));e.tool_argument&&e.tool_argument in t?(g({...i,[e.state_key]:t[e.tool_argument]}),u=!0):e.tool_argument||(g({...i,[e.state_key]:t}),u=!0)}catch{}}return[{type:D.enum.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...u?[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}]:[]]}case l.EventType.TOOL_CALL_END:{let e=r;return[{type:D.enum.ActionExecutionEnd,actionExecutionId:e.toolCallId}]}case l.EventType.TOOL_CALL_RESULT:{let e=r;return[{type:D.enum.ActionExecutionResult,actionExecutionId:e.toolCallId,result:e.content,actionName:h[e.toolCallId]||`unknown`}]}case l.EventType.RAW:return[];case l.EventType.CUSTOM:{let e=r;switch(e.name){case`Exit`:a=!1;break;case`PredictState`:d=e.value;break}return[{type:D.enum.MetaEvent,name:e.name,value:e.value}]}case l.EventType.STATE_SNAPSHOT:return g(r.snapshot),[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}];case l.EventType.STATE_DELTA:{let c=r,l=u.applyPatch(i,c.delta,!0,!1);return l?(g(l.newDocument),[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}]):[]}case l.EventType.MESSAGES_SNAPSHOT:return c=r.messages,[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify({...i,...c?{messages:c}:{}}),active:!0}];case l.EventType.RUN_STARTED:return[];case l.EventType.RUN_FINISHED:return c&&(i.messages=c),Object.keys(i).length===0?[]:[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify({...i,...c?{messages:ne(c)}:{}}),active:!1}];case l.EventType.RUN_ERROR:{let e=r;return[{type:D.enum.RunError,message:e.message,code:e.code}]}case l.EventType.STEP_STARTED:return s=r.stepName,m=[],d=null,[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:!0}];case l.EventType.STEP_FINISHED:return m=[],d=null,[{type:D.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:!1}];default:return[]}}))};function ne(e){let t=[];for(let n of e)if(n.role===`assistant`||n.role===`user`||n.role===`system`){let e=L(n.content);if(e){let r={id:n.id,role:n.role,content:e};t.push(r)}if(n.role===`assistant`&&n.toolCalls&&n.toolCalls.length>0)for(let e of n.toolCalls){let r={id:e.id,name:e.function.name,arguments:JSON.parse(e.function.arguments),parentMessageId:n.id};t.push(r)}}else if(n.role===`tool`){let r=`unknown`;for(let t of e)if(t.role===`assistant`&&t.toolCalls?.length){for(let e of t.toolCalls)if(e.id===n.toolCallId){r=e.function.name;break}}let i={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};t.push(i)}return t}const z=e=>t=>{let n,r,i,a,o=()=>{if(!n||a!==`text`)throw Error(`No text message to close`);let t={type:l.EventType.TEXT_MESSAGE_END,messageId:n.messageId};return a=void 0,n=void 0,e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_END`,JSON.stringify(t)),t},s=()=>{if(!r||a!==`tool`)throw Error(`No tool call to close`);let t={type:l.EventType.TOOL_CALL_END,toolCallId:r.toolCallId};return a=void 0,r=void 0,e&&console.debug(`[TRANSFORM]: TOOL_CALL_END`,JSON.stringify(t)),t},c=()=>{if(!i||a!==`reasoning`)throw Error(`No reasoning message to close`);let t={type:l.EventType.REASONING_MESSAGE_END,messageId:i.messageId};return a=void 0,i=void 0,e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_END`,JSON.stringify(t)),t},u=()=>a===`text`?[o()]:a===`tool`?[s()]:a===`reasoning`?[c()]:[];return t.pipe((0,d.mergeMap)(t=>{switch(t.type){case l.EventType.TEXT_MESSAGE_START:case l.EventType.TEXT_MESSAGE_CONTENT:case l.EventType.TEXT_MESSAGE_END:case l.EventType.TOOL_CALL_START:case l.EventType.TOOL_CALL_ARGS:case l.EventType.TOOL_CALL_END:case l.EventType.TOOL_CALL_RESULT:case l.EventType.STATE_SNAPSHOT:case l.EventType.STATE_DELTA:case l.EventType.MESSAGES_SNAPSHOT:case l.EventType.CUSTOM:case l.EventType.RUN_STARTED:case l.EventType.RUN_FINISHED:case l.EventType.RUN_ERROR:case l.EventType.STEP_STARTED:case l.EventType.STEP_FINISHED:case l.EventType.THINKING_START:case l.EventType.THINKING_END:case l.EventType.THINKING_TEXT_MESSAGE_START:case l.EventType.THINKING_TEXT_MESSAGE_CONTENT:case l.EventType.THINKING_TEXT_MESSAGE_END:case l.EventType.REASONING_START:case l.EventType.REASONING_MESSAGE_START:case l.EventType.REASONING_MESSAGE_CONTENT:case l.EventType.REASONING_MESSAGE_END:case l.EventType.REASONING_END:return[...u(),t];case l.EventType.RAW:case l.EventType.ACTIVITY_SNAPSHOT:case l.EventType.ACTIVITY_DELTA:case l.EventType.REASONING_ENCRYPTED_VALUE:return[t];case l.EventType.TEXT_MESSAGE_CHUNK:let o=t,s=[];if((a!==`text`||o.messageId!==void 0&&o.messageId!==n?.messageId)&&s.push(...u()),a!==`text`){if(o.messageId===void 0)throw Error(`First TEXT_MESSAGE_CHUNK must have a messageId`);n={messageId:o.messageId},a=`text`;let t={type:l.EventType.TEXT_MESSAGE_START,messageId:o.messageId,role:o.role||`assistant`};s.push(t),e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_START`,JSON.stringify(t))}if(o.delta!==void 0){let t={type:l.EventType.TEXT_MESSAGE_CONTENT,messageId:n.messageId,delta:o.delta};s.push(t),e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_CONTENT`,JSON.stringify(t))}return s;case l.EventType.TOOL_CALL_CHUNK:let c=t,d=[];if((a!==`tool`||c.toolCallId!==void 0&&c.toolCallId!==r?.toolCallId)&&d.push(...u()),a!==`tool`){if(c.toolCallId===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallId`);if(c.toolCallName===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallName`);r={toolCallId:c.toolCallId,toolCallName:c.toolCallName,parentMessageId:c.parentMessageId},a=`tool`;let t={type:l.EventType.TOOL_CALL_START,toolCallId:c.toolCallId,toolCallName:c.toolCallName,parentMessageId:c.parentMessageId};d.push(t),e&&console.debug(`[TRANSFORM]: TOOL_CALL_START`,JSON.stringify(t))}if(c.delta!==void 0){let t={type:l.EventType.TOOL_CALL_ARGS,toolCallId:r.toolCallId,delta:c.delta};d.push(t),e&&console.debug(`[TRANSFORM]: TOOL_CALL_ARGS`,JSON.stringify(t))}return d;case l.EventType.REASONING_MESSAGE_CHUNK:let f=t,p=[];if((a!==`reasoning`||f.messageId&&f.messageId!==i?.messageId)&&p.push(...u()),a!==`reasoning`){if(f.messageId===void 0)throw Error(`First REASONING_MESSAGE_CHUNK must have a messageId`);i={messageId:f.messageId},a=`reasoning`;let t={type:l.EventType.REASONING_MESSAGE_START,messageId:f.messageId};p.push(t),e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_START`,JSON.stringify(t))}if(f.delta!==void 0){let t={type:l.EventType.REASONING_MESSAGE_CONTENT,messageId:i.messageId,delta:f.delta};p.push(t),e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_CONTENT`,JSON.stringify(t))}return p}return t.type,[]}),(0,d.finalize)(()=>{u()}))};var B=class{runNext(e,t){return t.run(e).pipe(z(!1))}runNextWithState(e,t){let n=_(e.messages||[]),r=_(e.state||{}),i=new d.ReplaySubject;return b(e,i,t,[]).subscribe(e=>{e.messages!==void 0&&(n=e.messages),e.state!==void 0&&(r=e.state)}),this.runNext(e,t).pipe((0,f.concatMap)(async e=>(i.next(e),await new Promise(e=>setTimeout(e,0)),{event:e,messages:_(n),state:_(r)})))}},V=class extends B{constructor(e){super(),this.fn=e}run(e,t){return this.fn(e,t)}},H=class extends B{constructor(e){if(super(),this.blockedToolCallIds=new Set,e.allowedToolCalls&&e.disallowedToolCalls)throw Error(`Cannot specify both allowedToolCalls and disallowedToolCalls`);if(!e.allowedToolCalls&&!e.disallowedToolCalls)throw Error(`Must specify either allowedToolCalls or disallowedToolCalls`);e.allowedToolCalls?this.allowedTools=new Set(e.allowedToolCalls):e.disallowedToolCalls&&(this.disallowedTools=new Set(e.disallowedToolCalls))}run(e,t){return this.runNext(e,t).pipe((0,f.filter)(e=>{if(e.type===l.EventType.TOOL_CALL_START){let t=e;return this.shouldFilterTool(t.toolCallName)?(this.blockedToolCallIds.add(t.toolCallId),!1):!0}if(e.type===l.EventType.TOOL_CALL_ARGS){let t=e;return!this.blockedToolCallIds.has(t.toolCallId)}if(e.type===l.EventType.TOOL_CALL_END){let t=e;return!this.blockedToolCallIds.has(t.toolCallId)}if(e.type===l.EventType.TOOL_CALL_RESULT){let t=e;return this.blockedToolCallIds.has(t.toolCallId)?(this.blockedToolCallIds.delete(t.toolCallId),!1):!0}return!0}))}shouldFilterTool(e){return this.allowedTools?!this.allowedTools.has(e):this.disallowedTools?this.disallowedTools.has(e):!1}};function U(e){let t=e.content;if(Array.isArray(t)){let n=t.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&typeof e.text==`string`).map(e=>e.text).join(``);return{...e,content:n}}return typeof t==`string`?e:{...e,content:``}}var W=class extends B{run(e,t){let{parentRunId:n,...r}=e,i={...r,messages:r.messages.map(U)};return this.runNext(i,t)}};const G=`THINKING_START`,K=`THINKING_END`,q=`THINKING_TEXT_MESSAGE_START`,J=`THINKING_TEXT_MESSAGE_CONTENT`,Y=`THINKING_TEXT_MESSAGE_END`;var X=class extends B{constructor(...e){super(...e),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(e,t){process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${e} to ${t}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(e,t){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(e,t).pipe((0,f.map)(e=>this.transformEvent(e)))}transformEvent(e){switch(e.type){case G:{this.currentReasoningId=v();let{title:t,...n}=e;return this.warnAboutTransformation(G,l.EventType.REASONING_START),{...n,type:l.EventType.REASONING_START,messageId:this.currentReasoningId}}case q:return this.currentMessageId=v(),this.warnAboutTransformation(q,l.EventType.REASONING_MESSAGE_START),{...e,type:l.EventType.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:`assistant`};case J:{let{delta:t,...n}=e;return this.warnAboutTransformation(J,l.EventType.REASONING_MESSAGE_CONTENT),{...n,type:l.EventType.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??v(),delta:t}}case Y:{let t=this.currentMessageId??v();return this.warnAboutTransformation(Y,l.EventType.REASONING_MESSAGE_END),{...e,type:l.EventType.REASONING_MESSAGE_END,messageId:t}}case K:{let t=this.currentReasoningId??v();return this.warnAboutTransformation(K,l.EventType.REASONING_END),{...e,type:l.EventType.REASONING_END,messageId:t}}default:return e}}},re=`0.0.46`,Z=class{get maxVersion(){return re}constructor({agentId:e,description:t,threadId:n,initialMessages:r,initialState:i,debug:a}={}){this.debug=!1,this.subscribers=[],this.isRunning=!1,this.middlewares=[],this.agentId=e,this.description=t??``,this.threadId=n??(0,c.v4)(),this.messages=_(r??[]),this.state=_(i??{}),this.debug=a??!1,(0,g.compareVersions)(this.maxVersion,`0.0.39`)<=0&&this.middlewares.unshift(new W),(0,g.compareVersions)(this.maxVersion,`0.0.45`)<=0&&this.middlewares.unshift(new X)}subscribe(e){return this.subscribers.push(e),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==e)}}}use(...e){let t=e.map(e=>typeof e==`function`?new V(e):e);return this.middlewares.push(...t),this}async runAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??(0,c.v4)();let n=this.prepareRunAgentInput(e),r,i=new Set(this.messages.map(e=>e.id)),a=[{onRunFinishedEvent:e=>{r=e.result}},...this.subscribers,t??{}];await this.onInitialize(n,a),this.activeRunDetach$=new d.Subject;let o;this.activeRunCompletionPromise=new Promise(e=>{o=e}),await(0,d.lastValueFrom)((0,d.pipe)(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((e,t)=>({run:n=>t.run(n,e)}),this).run(n),z(this.debug),x(this.debug),e=>e.pipe((0,f.takeUntil)(this.activeRunDetach$)),e=>this.apply(n,e,a),e=>this.processApplyEvents(n,e,a),(0,f.catchError)(e=>(this.isRunning=!1,this.onError(n,e,a))),(0,f.finalize)(()=>{this.isRunning=!1,this.onFinalize(n,a),o?.(),o=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))((0,d.of)(null)));let s=_(this.messages).filter(e=>!i.has(e.id));return{result:r,newMessages:s}}finally{this.isRunning=!1}}connect(e){throw new l.AGUIConnectNotImplementedError}async connectAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??(0,c.v4)();let n=this.prepareRunAgentInput(e),r,i=new Set(this.messages.map(e=>e.id)),a=[{onRunFinishedEvent:e=>{r=e.result}},...this.subscribers,t??{}];await this.onInitialize(n,a),this.activeRunDetach$=new d.Subject;let o;this.activeRunCompletionPromise=new Promise(e=>{o=e}),await(0,d.lastValueFrom)((0,d.pipe)(()=>this.connect(n),z(this.debug),x(this.debug),e=>e.pipe((0,f.takeUntil)(this.activeRunDetach$)),e=>this.apply(n,e,a),e=>this.processApplyEvents(n,e,a),(0,f.catchError)(e=>(this.isRunning=!1,e instanceof l.AGUIConnectNotImplementedError?d.EMPTY:this.onError(n,e,a))),(0,f.finalize)(()=>{this.isRunning=!1,this.onFinalize(n,a),o?.(),o=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))((0,d.of)(null)));let s=_(this.messages).filter(e=>!i.has(e.id));return{result:r,newMessages:s}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let e=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await e}apply(e,t,n){return b(e,t,this,n)}processApplyEvents(e,t,n){return t.pipe((0,f.tap)(t=>{t.messages&&(this.messages=t.messages,n.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),t.state&&(this.state=t.state,n.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))}))}prepareRunAgentInput(e){let t=_(this.messages).filter(e=>e.role!==`activity`);return{threadId:this.threadId,runId:e?.runId||(0,c.v4)(),tools:_(e?.tools??[]),context:_(e?.context??[]),forwardedProps:_(e?.forwardedProps??{}),state:_(this.state),messages:t}}async onInitialize(e,t){let n=await y(t,this.messages,this.state,(t,n,r)=>t.onRunInitialized?.({messages:n,state:r,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,e.messages=n.messages,t.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state&&(this.state=n.state,e.state=n.state,t.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}onError(e,t,n){return(0,d.from)(y(n,this.messages,this.state,(n,r,i)=>n.onRunFailed?.({error:t,messages:r,state:i,agent:this,input:e}))).pipe((0,f.map)(r=>{let i=r;if((i.messages!==void 0||i.state!==void 0)&&(i.messages!==void 0&&(this.messages=i.messages,n.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),i.state!==void 0&&(this.state=i.state,n.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))),i.stopPropagation!==!0)throw console.error(`Agent execution failed:`,t),t;return{}}))}async onFinalize(e,t){let n=await y(t,this.messages,this.state,(t,n,r)=>t.onRunFinalized?.({messages:n,state:r,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,t.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state!==void 0&&(this.state=n.state,t.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}clone(){let e=Object.create(Object.getPrototypeOf(this));return e.agentId=this.agentId,e.description=this.description,e.threadId=this.threadId,e.messages=_(this.messages),e.state=_(this.state),e.debug=this.debug,e.isRunning=this.isRunning,e.subscribers=[...this.subscribers],e.middlewares=[...this.middlewares],e}addMessage(e){this.messages.push(e),(async()=>{for(let t of this.subscribers)await t.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role===`assistant`&&e.toolCalls)for(let t of e.toolCalls)for(let e of this.subscribers)await e.onNewToolCall?.({toolCall:t,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(e){this.messages.push(...e),(async()=>{for(let t of e){for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role===`assistant`&&t.toolCalls)for(let e of t.toolCalls)for(let t of this.subscribers)await t.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(e){this.messages=_(e),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(e){this.state=_(e),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(e){this.agentId=this.agentId??(0,c.v4)();let t=this.prepareRunAgentInput(e);return(this.middlewares.length===0?this.run(t):this.middlewares.reduceRight((e,t)=>({run:n=>t.run(n,e)}),this).run(t)).pipe(z(this.debug),x(this.debug),R(this.threadId,t.runId,this.agentId),e=>e.pipe((0,f.map)(e=>(this.debug&&console.debug(`[LEGACY]:`,JSON.stringify(e)),e))))}},ie=class extends Z{requestInit(e){return{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e,t){return this.abortController=e?.abortController??new AbortController,super.runAgent(e,t)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(e){super(e),this.abortController=new AbortController,this.url=e.url,this.headers=_(e.headers??{})}run(e){return E(C(this.url,this.requestInit(e)))}clone(){let e=super.clone();e.url=this.url,e.headers=_(this.headers??{});let t=new AbortController,n=this.abortController.signal;return n.aborted&&t.abort(n.reason),e.abortController=t,e}};function ae(e){let t=[],n=new Map,r=new Map;for(let i of e)if(i.type===l.EventType.TEXT_MESSAGE_START){let e=i,t=e.messageId;n.has(t)||n.set(t,{contents:[],otherEvents:[]});let r=n.get(t);r.start=e}else if(i.type===l.EventType.TEXT_MESSAGE_CONTENT){let e=i,t=e.messageId;n.has(t)||n.set(t,{contents:[],otherEvents:[]}),n.get(t).contents.push(e)}else if(i.type===l.EventType.TEXT_MESSAGE_END){let e=i,r=e.messageId;n.has(r)||n.set(r,{contents:[],otherEvents:[]});let a=n.get(r);a.end=e,Q(r,a,t),n.delete(r)}else if(i.type===l.EventType.TOOL_CALL_START){let e=i,t=e.toolCallId;r.has(t)||r.set(t,{args:[],otherEvents:[]});let n=r.get(t);n.start=e}else if(i.type===l.EventType.TOOL_CALL_ARGS){let e=i,t=e.toolCallId;r.has(t)||r.set(t,{args:[],otherEvents:[]}),r.get(t).args.push(e)}else if(i.type===l.EventType.TOOL_CALL_END){let e=i,n=e.toolCallId;r.has(n)||r.set(n,{args:[],otherEvents:[]});let a=r.get(n);a.end=e,$(n,a,t),r.delete(n)}else{let e=!1;for(let[t,r]of n)if(r.start&&!r.end){r.otherEvents.push(i),e=!0;break}if(!e){for(let[t,n]of r)if(n.start&&!n.end){n.otherEvents.push(i),e=!0;break}}e||t.push(i)}for(let[e,r]of n)Q(e,r,t);for(let[e,n]of r)$(e,n,t);return t}function Q(e,t,n){if(t.start&&n.push(t.start),t.contents.length>0){let r=t.contents.map(e=>e.delta).join(``),i={type:l.EventType.TEXT_MESSAGE_CONTENT,messageId:e,delta:r};n.push(i)}t.end&&n.push(t.end);for(let e of t.otherEvents)n.push(e)}function $(e,t,n){if(t.start&&n.push(t.start),t.args.length>0){let r=t.args.map(e=>e.delta).join(``),i={type:l.EventType.TOOL_CALL_ARGS,toolCallId:e,delta:r};n.push(i)}t.end&&n.push(t.end);for(let e of t.otherEvents)n.push(e)}exports.AbstractAgent=Z,exports.BackwardCompatibility_0_0_39=W,exports.BackwardCompatibility_0_0_45=X,exports.FilterToolCallsMiddleware=H,exports.FunctionMiddleware=V,exports.HttpAgent=ie,exports.Middleware=B,exports.compactEvents=ae,exports.convertToLegacyEvents=R,exports.defaultApplyEvents=b,exports.parseProtoStream=T,exports.parseSSEStream=w,exports.randomUUID=v,exports.runHttpRequest=C,exports.structuredClone_=_,exports.transformChunks=z,exports.transformHttpEventStream=E,exports.verifyEvents=x,Object.keys(l).forEach(function(e){e!==`default`&&!Object.prototype.hasOwnProperty.call(exports,e)&&Object.defineProperty(exports,e,{enumerable:!0,get:function(){return l[e]}})});
|
|
5
5
|
//# sourceMappingURL=index.js.map
|