@ag-ui/client 0.0.46 → 0.0.48-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{v4 as e}from"uuid";import{AGUIConnectNotImplementedError as t,AGUIError as n,EventSchemas as r,EventType as i}from"@ag-ui/core";import*as a from"fast-json-patch";import{EMPTY as o,Observable as s,ReplaySubject as c,Subject as l,defer as u,finalize as d,from as f,lastValueFrom as p,mergeMap as m,of as h,pipe as g,throwError as _}from"rxjs";import{catchError as v,concatMap as y,defaultIfEmpty as ee,filter as te,finalize as b,map as x,mergeAll as ne,mergeMap as S,switchMap as re,takeUntil as C,tap as ie}from"rxjs/operators";import w from"untruncate-json";import*as T from"@ag-ui/proto";import{z as E}from"zod";import{compareVersions as D}from"compare-versions";export*from"@ag-ui/core";const O=e=>{if(typeof structuredClone==`function`)return structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch{return{...e}}};function k(){return e()}async function A(e,t,n,r){let i=t,a=n,o;for(let t of e)try{let e=await r(t,O(i),O(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 j=(e,t,n,r)=>{let s=O(n.messages),c=O(e.state),l={},u=e=>{e.messages!==void 0&&(s=e.messages,l.messages=e.messages),e.state!==void 0&&(c=e.state,l.state=e.state)},d=()=>{let e=O(l);return l={},e.messages!==void 0||e.state!==void 0?h(e):o};return t.pipe(y(async t=>{let o=await A(r,s,c,(r,i,a)=>r.onEvent?.({event:t,agent:n,input:e,messages:i,state:a}));if(u(o),o.stopPropagation===!0)return d();switch(t.type){case i.TEXT_MESSAGE_START:{let i=await A(r,s,c,(r,i,a)=>r.onTextMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{messageId:e,role:n=`assistant`}=t;if(!s.find(t=>t.id===e)){let t={id:e,role:n,content:``};s.push(t),u({messages:s})}}return d()}case i.TEXT_MESSAGE_CONTENT:{let{messageId:i,delta:a}=t,o=s.find(e=>e.id===i);if(!o)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${i}'`),d();let l=await A(r,s,c,(r,i,a)=>r.onTextMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,textMessageBuffer:typeof o.content==`string`?o.content:``}));return u(l),l.stopPropagation!==!0&&(o.content=`${typeof o.content==`string`?o.content:``}${a}`,u({messages:s})),d()}case i.TEXT_MESSAGE_END:{let{messageId:i}=t,a=s.find(e=>e.id===i);return a?(u(await A(r,s,c,(r,i,o)=>r.onTextMessageEndEvent?.({event:t,messages:i,state:o,agent:n,input:e,textMessageBuffer:typeof a.content==`string`?a.content:``}))),await Promise.all(r.map(t=>{t.onNewMessage?.({message:a,messages:s,state:c,agent:n,input:e})})),d()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${i}'`),d())}case i.TOOL_CALL_START:{let i=await A(r,s,c,(r,i,a)=>r.onToolCallStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{toolCallId:e,toolCallName:n,parentMessageId:r}=t,i;r&&s.length>0&&s[s.length-1].id===r?i=s[s.length-1]:(i={id:r||e,role:`assistant`,toolCalls:[]},s.push(i)),i.toolCalls??=[],i.toolCalls.push({id:e,type:`function`,function:{name:n,arguments:``}}),u({messages:s})}return d()}case i.TOOL_CALL_ARGS:{let{toolCallId:i,delta:a}=t,o=s.find(e=>e.toolCalls?.some(e=>e.id===i));if(!o)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${i}'`),d();let l=o.toolCalls?.find(e=>e.id===i);if(!l)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${i}'`),d();let f=await A(r,s,c,(r,i,a)=>{let o=l.function.arguments,s=l.function.name,c={};try{c=w(o)}catch{}return r.onToolCallArgsEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallBuffer:o,toolCallName:s,partialToolCallArgs:c})});return u(f),f.stopPropagation!==!0&&(l.function.arguments+=a,u({messages:s})),d()}case i.TOOL_CALL_END:{let{toolCallId:i}=t,a=s.find(e=>e.toolCalls?.some(e=>e.id===i));if(!a)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${i}'`),d();let o=a.toolCalls?.find(e=>e.id===i);return o?(u(await A(r,s,c,(r,i,a)=>{let s=o.function.arguments,c=o.function.name,l={};try{l=JSON.parse(s)}catch{}return r.onToolCallEndEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallName:c,toolCallArgs:l})})),await Promise.all(r.map(t=>{t.onNewToolCall?.({toolCall:o,messages:s,state:c,agent:n,input:e})})),d()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${i}'`),d())}case i.TOOL_CALL_RESULT:{let i=await A(r,s,c,(r,i,a)=>r.onToolCallResultEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{messageId:i,toolCallId:a,content:o,role:l}=t,d={id:i,toolCallId:a,role:l||`tool`,content:o};s.push(d),await Promise.all(r.map(t=>{t.onNewMessage?.({message:d,messages:s,state:c,agent:n,input:e})})),u({messages:s})}return d()}case i.STATE_SNAPSHOT:{let i=await A(r,s,c,(r,i,a)=>r.onStateSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{snapshot:e}=t;c=e,u({state:c})}return d()}case i.STATE_DELTA:{let i=await A(r,s,c,(r,i,a)=>r.onStateDeltaEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{delta:e}=t;try{c=a.applyPatch(c,e,!0,!1).newDocument,u({state:c})}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Failed to apply state patch:\nCurrent state: ${JSON.stringify(c,null,2)}\nPatch operations: ${JSON.stringify(e,null,2)}\nError: ${n}`)}}return d()}case i.MESSAGES_SNAPSHOT:{let i=await A(r,s,c,(r,i,a)=>r.onMessagesSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{messages:e}=t,n=new Map(e.map(e=>[e.id,e]));s=s.filter(e=>e.role===`activity`||n.has(e.id)).map(e=>e.role===`activity`?e:n.get(e.id));let r=new Set(s.map(e=>e.id));for(let t of e)r.has(t.id)||s.push(t);u({messages:s})}return d()}case i.ACTIVITY_SNAPSHOT:{let i=t,a=s.findIndex(e=>e.id===i.messageId),o=a>=0?s[a]:void 0,l=o?.role===`activity`?o:void 0,f=i.replace??!0,p=await A(r,s,c,(t,r,a)=>t.onActivitySnapshotEvent?.({event:i,messages:r,state:a,agent:n,input:e,activityMessage:l,existingMessage:o}));if(u(p),p.stopPropagation!==!0){let t={id:i.messageId,role:`activity`,activityType:i.activityType,content:O(i.content)},o;a===-1?(s.push(t),o=t):l?f&&(s[a]={...l,activityType:i.activityType,content:O(i.content)}):f&&(s[a]=t,o=t),u({messages:s}),o&&await Promise.all(r.map(t=>t.onNewMessage?.({message:o,messages:s,state:c,agent:n,input:e})))}return d()}case i.ACTIVITY_DELTA:{let i=t,o=s.findIndex(e=>e.id===i.messageId);if(o===-1)return d();let l=s[o];if(l.role!==`activity`)return console.warn(`ACTIVITY_DELTA: Message '${i.messageId}' is not an activity message`),d();let f=l,p=await A(r,s,c,(t,r,a)=>t.onActivityDeltaEvent?.({event:i,messages:r,state:a,agent:n,input:e,activityMessage:f}));if(u(p),p.stopPropagation!==!0)try{let e=O(f.content??{}),t=a.applyPatch(e,i.patch??[],!0,!1).newDocument;s[o]={...f,content:O(t),activityType:i.activityType},u({messages:s})}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`Failed to apply activity patch for '${i.messageId}': ${t}`)}return d()}case i.RAW:return u(await A(r,s,c,(r,i,a)=>r.onRawEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.CUSTOM:return u(await A(r,s,c,(r,i,a)=>r.onCustomEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.RUN_STARTED:{let i=await A(r,s,c,(r,i,a)=>r.onRunStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let e=t;if(e.input?.messages){for(let t of e.input.messages)s.find(e=>e.id===t.id)||s.push(t);u({messages:s})}}return d()}case i.RUN_FINISHED:return u(await A(r,s,c,(r,i,a)=>r.onRunFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e,result:t.result}))),d();case i.RUN_ERROR:return u(await A(r,s,c,(r,i,a)=>r.onRunErrorEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.STEP_STARTED:return u(await A(r,s,c,(r,i,a)=>r.onStepStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.STEP_FINISHED:return u(await A(r,s,c,(r,i,a)=>r.onStepFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.TEXT_MESSAGE_CHUNK:throw Error(`TEXT_MESSAGE_CHUNK must be tranformed before being applied`);case i.TOOL_CALL_CHUNK:throw Error(`TOOL_CALL_CHUNK must be tranformed before being applied`);case i.THINKING_START:return d();case i.THINKING_END:return d();case i.THINKING_TEXT_MESSAGE_START:return d();case i.THINKING_TEXT_MESSAGE_CONTENT:return d();case i.THINKING_TEXT_MESSAGE_END:return d();case i.REASONING_START:return u(await A(r,s,c,(r,i,a)=>r.onReasoningStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.REASONING_MESSAGE_START:{let i=await A(r,s,c,(r,i,a)=>r.onReasoningMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(i),i.stopPropagation!==!0){let{messageId:e}=t;if(!s.find(t=>t.id===e)){let t={id:e,role:`reasoning`,content:``};s.push(t),u({messages:s})}}return d()}case i.REASONING_MESSAGE_CONTENT:{let{messageId:i,delta:a}=t,o=s.find(e=>e.id===i);if(!o)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${i}'`),d();let l=await A(r,s,c,(r,i,a)=>r.onReasoningMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,reasoningMessageBuffer:typeof o.content==`string`?o.content:``}));return u(l),l.stopPropagation!==!0&&(o.content=`${typeof o.content==`string`?o.content:``}${a}`,u({messages:s})),d()}case i.REASONING_MESSAGE_END:{let{messageId:i}=t,a=s.find(e=>e.id===i);return a?(u(await A(r,s,c,(r,i,o)=>r.onReasoningMessageEndEvent?.({event:t,messages:i,state:o,agent:n,input:e,reasoningMessageBuffer:typeof a.content==`string`?a.content:``}))),await Promise.all(r.map(t=>{t.onNewMessage?.({message:a,messages:s,state:c,agent:n,input:e})})),d()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${i}'`),d())}case i.REASONING_MESSAGE_CHUNK:throw Error(`REASONING_MESSAGE_CHUNK must be transformed before being applied`);case i.REASONING_END:return u(await A(r,s,c,(r,i,a)=>r.onReasoningEndEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),d();case i.REASONING_ENCRYPTED_VALUE:{let{subtype:i,entityId:a,encryptedValue:o}=t,f=await A(r,s,c,(r,i,a)=>r.onReasoningEncryptedValueEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(u(f),f.stopPropagation!==!0){let e=!1;if(i===`tool-call`){for(let t of s)if(t.role===`assistant`&&t.toolCalls){let n=t.toolCalls.find(e=>e.id===a);if(n){n.encryptedValue=o,e=!0;break}}}else{let t=s.find(e=>e.id===a);t?.role!==`activity`&&t&&(t.encryptedValue=o,e=!0)}e&&(l.messages=s)}return d()}}return t.type,d()}),ne(),r.length>0?ee({}):e=>e)},M=e=>t=>{let r=new Map,a=new Map,o=!1,s=!1,c=!1,l=new Map,u=!1,d=!1,f=!1,p=()=>{r.clear(),a.clear(),l.clear(),u=!1,d=!1,o=!1,s=!1,f=!0};return t.pipe(S(t=>{let m=t.type;if(e&&console.debug(`[VERIFY]:`,JSON.stringify(t)),s)return _(()=>new n(`Cannot send event type '${m}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(o&&m!==i.RUN_ERROR&&m!==i.RUN_STARTED)return _(()=>new n(`Cannot send event type '${m}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(!c){if(c=!0,m!==i.RUN_STARTED&&m!==i.RUN_ERROR)return _(()=>new n(`First event must be 'RUN_STARTED'`))}else if(m===i.RUN_STARTED){if(f&&!o)return _(()=>new n(`Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run.`));o&&p()}switch(m){case i.TEXT_MESSAGE_START:{let e=t.messageId;return r.has(e)?_(()=>new n(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${e}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(r.set(e,!0),h(t))}case i.TEXT_MESSAGE_CONTENT:{let e=t.messageId;return r.has(e)?h(t):_(()=>new n(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${e}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case i.TEXT_MESSAGE_END:{let e=t.messageId;return r.has(e)?(r.delete(e),h(t)):_(()=>new n(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${e}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case i.TOOL_CALL_START:{let e=t.toolCallId;return a.has(e)?_(()=>new n(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${e}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(a.set(e,!0),h(t))}case i.TOOL_CALL_ARGS:{let e=t.toolCallId;return a.has(e)?h(t):_(()=>new n(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${e}'. Start a tool call with 'TOOL_CALL_START' first.`))}case i.TOOL_CALL_END:{let e=t.toolCallId;return a.has(e)?(a.delete(e),h(t)):_(()=>new n(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${e}'. A 'TOOL_CALL_START' event must be sent first.`))}case i.STEP_STARTED:{let e=t.stepName;return l.has(e)?_(()=>new n(`Step "${e}" is already active for 'STEP_STARTED'`)):(l.set(e,!0),h(t))}case i.STEP_FINISHED:{let e=t.stepName;return l.has(e)?(l.delete(e),h(t)):_(()=>new n(`Cannot send 'STEP_FINISHED' for step "${e}" that was not started`))}case i.RUN_STARTED:return f=!0,h(t);case i.RUN_FINISHED:if(l.size>0){let e=Array.from(l.keys()).join(`, `);return _(()=>new n(`Cannot send 'RUN_FINISHED' while steps are still active: ${e}`))}if(r.size>0){let e=Array.from(r.keys()).join(`, `);return _(()=>new n(`Cannot send 'RUN_FINISHED' while text messages are still active: ${e}`))}if(a.size>0){let e=Array.from(a.keys()).join(`, `);return _(()=>new n(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${e}`))}return o=!0,h(t);case i.RUN_ERROR:return s=!0,h(t);case i.CUSTOM:return h(t);case i.THINKING_TEXT_MESSAGE_START:return u?d?_(()=>new n(`Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.`)):(d=!0,h(t)):_(()=>new n(`Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first.`));case i.THINKING_TEXT_MESSAGE_CONTENT:return d?h(t):_(()=>new n(`Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first.`));case i.THINKING_TEXT_MESSAGE_END:return d?(d=!1,h(t)):_(()=>new n(`Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first.`));case i.THINKING_START:return u?_(()=>new n(`Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.`)):(u=!0,h(t));case i.THINKING_END:return u?(u=!1,h(t)):_(()=>new n(`Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first.`));default:return h(t)}}))};let N=function(e){return e.HEADERS=`headers`,e.DATA=`data`,e}({});const P=(e,t)=>u(()=>f(fetch(e,t))).pipe(re(e=>{if(!e.ok){let t=e.headers.get(`content-type`)||``;return f(e.text()).pipe(S(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,_(()=>i)}))}let t={type:N.HEADERS,status:e.status,headers:e.headers},n=e.body?.getReader();return n?new s(e=>(e.next(t),(async()=>{try{for(;;){let{done:t,value:r}=await n.read();if(t)break;let i={type:N.DATA,data:r};e.next(i)}e.complete()}catch(t){e.error(t)}})(),()=>{n.cancel().catch(e=>{if(e?.name!==`AbortError`)throw e})})):_(()=>Error(`Failed to getReader() from response`))})),F=e=>{let t=new l,n=new TextDecoder(`utf-8`,{fatal:!1}),r=``;e.subscribe({next:e=>{if(e.type!==N.HEADERS&&e.type===N.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()},I=e=>{let t=new l,n=new Uint8Array;e.subscribe({next:e=>{if(e.type!==N.HEADERS&&e.type===N.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=T.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()},L=e=>{let t=new l,n=new c,a=!1;return e.subscribe({next:e=>{n.next(e),e.type===N.HEADERS&&!a?(a=!0,e.headers.get(`content-type`)===T.AGUI_MEDIA_TYPE?I(n).subscribe({next:e=>t.next(e),error:e=>t.error(e),complete:()=>t.complete()}):F(n).subscribe({next:e=>{try{let n=r.parse(e);t.next(n)}catch(e){t.error(e)}},error:e=>{if(e?.name===`AbortError`){t.next({type:i.RUN_ERROR,message:e.message||`Request aborted`,code:`abort`,rawEvent:e}),t.complete();return}return t.error(e)},complete:()=>t.complete()})):a||t.error(Error(`No headers event received before data events`))},error:e=>{n.error(e),t.error(e)},complete:()=>{n.complete()}}),t.asObservable()},R=E.enum([`TextMessageStart`,`TextMessageContent`,`TextMessageEnd`,`ActionExecutionStart`,`ActionExecutionArgs`,`ActionExecutionEnd`,`ActionExecutionResult`,`AgentStateMessage`,`MetaEvent`,`RunStarted`,`RunFinished`,`RunError`,`NodeStarted`,`NodeFinished`]),ae=E.enum([`LangGraphInterruptEvent`,`PredictState`,`Exit`]),oe=E.object({type:E.literal(R.enum.TextMessageStart),messageId:E.string(),parentMessageId:E.string().optional(),role:E.string().optional()}),se=E.object({type:E.literal(R.enum.TextMessageContent),messageId:E.string(),content:E.string()}),ce=E.object({type:E.literal(R.enum.TextMessageEnd),messageId:E.string()}),le=E.object({type:E.literal(R.enum.ActionExecutionStart),actionExecutionId:E.string(),actionName:E.string(),parentMessageId:E.string().optional()}),ue=E.object({type:E.literal(R.enum.ActionExecutionArgs),actionExecutionId:E.string(),args:E.string()}),z=E.object({type:E.literal(R.enum.ActionExecutionEnd),actionExecutionId:E.string()}),de=E.object({type:E.literal(R.enum.ActionExecutionResult),actionName:E.string(),actionExecutionId:E.string(),result:E.string()}),fe=E.object({type:E.literal(R.enum.AgentStateMessage),threadId:E.string(),agentName:E.string(),nodeName:E.string(),runId:E.string(),active:E.boolean(),role:E.string(),state:E.string(),running:E.boolean()}),pe=E.object({type:E.literal(R.enum.MetaEvent),name:ae,value:E.any()}),me=E.object({type:E.literal(R.enum.RunError),message:E.string(),code:E.string().optional()});E.discriminatedUnion(`type`,[oe,se,ce,le,ue,z,de,fe,pe,me]),E.object({id:E.string(),role:E.string(),content:E.string(),parentMessageId:E.string().optional()}),E.object({id:E.string(),name:E.string(),arguments:E.any(),parentMessageId:E.string().optional()}),E.object({id:E.string(),result:E.any(),actionExecutionId:E.string(),actionName:E.string()});const he=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
|
-
`)},B=(e,t,n)=>r=>{let o={},s=!0,c=!0,l=``,u=null,d=null,f=[],p={},m=e=>{typeof e==`object`&&e&&(`messages`in e&&delete e.messages,o=e)};return r.pipe(S(r=>{switch(r.type){case i.TEXT_MESSAGE_START:{let e=r;return[{type:R.enum.TextMessageStart,messageId:e.messageId,role:e.role}]}case i.TEXT_MESSAGE_CONTENT:{let e=r;return[{type:R.enum.TextMessageContent,messageId:e.messageId,content:e.delta}]}case i.TEXT_MESSAGE_END:{let e=r;return[{type:R.enum.TextMessageEnd,messageId:e.messageId}]}case i.TOOL_CALL_START:{let e=r;return f.push({id:e.toolCallId,type:`function`,function:{name:e.toolCallName,arguments:``}}),c=!0,p[e.toolCallId]=e.toolCallName,[{type:R.enum.ActionExecutionStart,actionExecutionId:e.toolCallId,actionName:e.toolCallName,parentMessageId:e.parentMessageId}]}case i.TOOL_CALL_ARGS:{let i=r,a=f.find(e=>e.id===i.toolCallId);if(!a)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${i.toolCallId}'`),[];a.function.arguments+=i.delta;let u=!1;if(d){let e=d.find(e=>e.tool==a.function.name);if(e)try{let t=JSON.parse(w(a.function.arguments));e.tool_argument&&e.tool_argument in t?(m({...o,[e.state_key]:t[e.tool_argument]}),u=!0):e.tool_argument||(m({...o,[e.state_key]:t}),u=!0)}catch{}}return[{type:R.enum.ActionExecutionArgs,actionExecutionId:i.toolCallId,args:i.delta},...u?[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:c}]:[]]}case i.TOOL_CALL_END:{let e=r;return[{type:R.enum.ActionExecutionEnd,actionExecutionId:e.toolCallId}]}case i.TOOL_CALL_RESULT:{let e=r;return[{type:R.enum.ActionExecutionResult,actionExecutionId:e.toolCallId,result:e.content,actionName:p[e.toolCallId]||`unknown`}]}case i.RAW:return[];case i.CUSTOM:{let e=r;switch(e.name){case`Exit`:s=!1;break;case`PredictState`:d=e.value;break}return[{type:R.enum.MetaEvent,name:e.name,value:e.value}]}case i.STATE_SNAPSHOT:return m(r.snapshot),[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:c}];case i.STATE_DELTA:{let i=r,u=a.applyPatch(o,i.delta,!0,!1);return u?(m(u.newDocument),[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:c}]):[]}case i.MESSAGES_SNAPSHOT:return u=r.messages,[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify({...o,...u?{messages:u}:{}}),active:!0}];case i.RUN_STARTED:return[];case i.RUN_FINISHED:return u&&(o.messages=u),Object.keys(o).length===0?[]:[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify({...o,...u?{messages:ge(u)}:{}}),active:!1}];case i.RUN_ERROR:{let e=r;return[{type:R.enum.RunError,message:e.message,code:e.code}]}case i.STEP_STARTED:return l=r.stepName,f=[],d=null,[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:!0}];case i.STEP_FINISHED:return f=[],d=null,[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:!1}];default:return[]}}))};function ge(e){let t=[];for(let n of e)if(n.role===`assistant`||n.role===`user`||n.role===`system`){let e=he(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 V=e=>t=>{let n,r,a,o,s=()=>{if(!n||o!==`text`)throw Error(`No text message to close`);let t={type:i.TEXT_MESSAGE_END,messageId:n.messageId};return o=void 0,n=void 0,e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_END`,JSON.stringify(t)),t},c=()=>{if(!r||o!==`tool`)throw Error(`No tool call to close`);let t={type:i.TOOL_CALL_END,toolCallId:r.toolCallId};return o=void 0,r=void 0,e&&console.debug(`[TRANSFORM]: TOOL_CALL_END`,JSON.stringify(t)),t},l=()=>{if(!a||o!==`reasoning`)throw Error(`No reasoning message to close`);let t={type:i.REASONING_MESSAGE_END,messageId:a.messageId};return o=void 0,a=void 0,e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_END`,JSON.stringify(t)),t},u=()=>o===`text`?[s()]:o===`tool`?[c()]:o===`reasoning`?[l()]:[];return t.pipe(m(t=>{switch(t.type){case i.TEXT_MESSAGE_START:case i.TEXT_MESSAGE_CONTENT:case i.TEXT_MESSAGE_END:case i.TOOL_CALL_START:case i.TOOL_CALL_ARGS:case i.TOOL_CALL_END:case i.TOOL_CALL_RESULT:case i.STATE_SNAPSHOT:case i.STATE_DELTA:case i.MESSAGES_SNAPSHOT:case i.CUSTOM:case i.RUN_STARTED:case i.RUN_FINISHED:case i.RUN_ERROR:case i.STEP_STARTED:case i.STEP_FINISHED:case i.THINKING_START:case i.THINKING_END:case i.THINKING_TEXT_MESSAGE_START:case i.THINKING_TEXT_MESSAGE_CONTENT:case i.THINKING_TEXT_MESSAGE_END:case i.REASONING_START:case i.REASONING_MESSAGE_START:case i.REASONING_MESSAGE_CONTENT:case i.REASONING_MESSAGE_END:case i.REASONING_END:return[...u(),t];case i.RAW:case i.ACTIVITY_SNAPSHOT:case i.ACTIVITY_DELTA:case i.REASONING_ENCRYPTED_VALUE:return[t];case i.TEXT_MESSAGE_CHUNK:let s=t,c=[];if((o!==`text`||s.messageId!==void 0&&s.messageId!==n?.messageId)&&c.push(...u()),o!==`text`){if(s.messageId===void 0)throw Error(`First TEXT_MESSAGE_CHUNK must have a messageId`);n={messageId:s.messageId},o=`text`;let t={type:i.TEXT_MESSAGE_START,messageId:s.messageId,role:s.role||`assistant`};c.push(t),e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_START`,JSON.stringify(t))}if(s.delta!==void 0){let t={type:i.TEXT_MESSAGE_CONTENT,messageId:n.messageId,delta:s.delta};c.push(t),e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_CONTENT`,JSON.stringify(t))}return c;case i.TOOL_CALL_CHUNK:let l=t,d=[];if((o!==`tool`||l.toolCallId!==void 0&&l.toolCallId!==r?.toolCallId)&&d.push(...u()),o!==`tool`){if(l.toolCallId===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallId`);if(l.toolCallName===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallName`);r={toolCallId:l.toolCallId,toolCallName:l.toolCallName,parentMessageId:l.parentMessageId},o=`tool`;let t={type:i.TOOL_CALL_START,toolCallId:l.toolCallId,toolCallName:l.toolCallName,parentMessageId:l.parentMessageId};d.push(t),e&&console.debug(`[TRANSFORM]: TOOL_CALL_START`,JSON.stringify(t))}if(l.delta!==void 0){let t={type:i.TOOL_CALL_ARGS,toolCallId:r.toolCallId,delta:l.delta};d.push(t),e&&console.debug(`[TRANSFORM]: TOOL_CALL_ARGS`,JSON.stringify(t))}return d;case i.REASONING_MESSAGE_CHUNK:let f=t,p=[];if((o!==`reasoning`||f.messageId&&f.messageId!==a?.messageId)&&p.push(...u()),o!==`reasoning`){if(f.messageId===void 0)throw Error(`First REASONING_MESSAGE_CHUNK must have a messageId`);a={messageId:f.messageId},o=`reasoning`;let t={type:i.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:i.REASONING_MESSAGE_CONTENT,messageId:a.messageId,delta:f.delta};p.push(t),e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_CONTENT`,JSON.stringify(t))}return p}return t.type,[]}),d(()=>{u()}))};var H=class{runNext(e,t){return t.run(e).pipe(V(!1))}runNextWithState(e,t){let n=O(e.messages||[]),r=O(e.state||{}),i=new c;return j(e,i,t,[]).subscribe(e=>{e.messages!==void 0&&(n=e.messages),e.state!==void 0&&(r=e.state)}),this.runNext(e,t).pipe(y(async e=>(i.next(e),await new Promise(e=>setTimeout(e,0)),{event:e,messages:O(n),state:O(r)})))}},U=class extends H{constructor(e){super(),this.fn=e}run(e,t){return this.fn(e,t)}},_e=class extends H{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(te(e=>{if(e.type===i.TOOL_CALL_START){let t=e;return this.shouldFilterTool(t.toolCallName)?(this.blockedToolCallIds.add(t.toolCallId),!1):!0}if(e.type===i.TOOL_CALL_ARGS){let t=e;return!this.blockedToolCallIds.has(t.toolCallId)}if(e.type===i.TOOL_CALL_END){let t=e;return!this.blockedToolCallIds.has(t.toolCallId)}if(e.type===i.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 ve(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 H{run(e,t){let{parentRunId:n,...r}=e,i={...r,messages:r.messages.map(ve)};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 H{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(x(e=>this.transformEvent(e)))}transformEvent(e){switch(e.type){case G:{this.currentReasoningId=k();let{title:t,...n}=e;return this.warnAboutTransformation(G,i.REASONING_START),{...n,type:i.REASONING_START,messageId:this.currentReasoningId}}case q:return this.currentMessageId=k(),this.warnAboutTransformation(q,i.REASONING_MESSAGE_START),{...e,type:i.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:`assistant`};case J:{let{delta:t,...n}=e;return this.warnAboutTransformation(J,i.REASONING_MESSAGE_CONTENT),{...n,type:i.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??k(),delta:t}}case Y:{let t=this.currentMessageId??k();return this.warnAboutTransformation(Y,i.REASONING_MESSAGE_END),{...e,type:i.REASONING_MESSAGE_END,messageId:t}}case K:{let t=this.currentReasoningId??k();return this.warnAboutTransformation(K,i.REASONING_END),{...e,type:i.REASONING_END,messageId:t}}default:return e}}},ye=`0.0.46`,Z=class{get maxVersion(){return ye}constructor({agentId:t,description:n,threadId:r,initialMessages:i,initialState:a,debug:o}={}){this.debug=!1,this.subscribers=[],this.isRunning=!1,this.middlewares=[],this.agentId=t,this.description=n??``,this.threadId=r??e(),this.messages=O(i??[]),this.state=O(a??{}),this.debug=o??!1,D(this.maxVersion,`0.0.39`)<=0&&this.middlewares.unshift(new W),D(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 U(e):e);return this.middlewares.push(...t),this}async runAgent(t,n){try{this.isRunning=!0,this.agentId=this.agentId??e();let r=this.prepareRunAgentInput(t),i,a=new Set(this.messages.map(e=>e.id)),o=[{onRunFinishedEvent:e=>{i=e.result}},...this.subscribers,n??{}];await this.onInitialize(r,o),this.activeRunDetach$=new l;let s;this.activeRunCompletionPromise=new Promise(e=>{s=e}),await p(g(()=>this.middlewares.length===0?this.run(r):this.middlewares.reduceRight((e,t)=>({run:n=>t.run(n,e)}),this).run(r),V(this.debug),M(this.debug),e=>e.pipe(C(this.activeRunDetach$)),e=>this.apply(r,e,o),e=>this.processApplyEvents(r,e,o),v(e=>(this.isRunning=!1,this.onError(r,e,o))),b(()=>{this.isRunning=!1,this.onFinalize(r,o),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(h(null)));let c=O(this.messages).filter(e=>!a.has(e.id));return{result:i,newMessages:c}}finally{this.isRunning=!1}}connect(e){throw new t}async connectAgent(n,r){try{this.isRunning=!0,this.agentId=this.agentId??e();let i=this.prepareRunAgentInput(n),a,s=new Set(this.messages.map(e=>e.id)),c=[{onRunFinishedEvent:e=>{a=e.result}},...this.subscribers,r??{}];await this.onInitialize(i,c),this.activeRunDetach$=new l;let u;this.activeRunCompletionPromise=new Promise(e=>{u=e}),await p(g(()=>this.connect(i),V(this.debug),M(this.debug),e=>e.pipe(C(this.activeRunDetach$)),e=>this.apply(i,e,c),e=>this.processApplyEvents(i,e,c),v(e=>(this.isRunning=!1,e instanceof t?o:this.onError(i,e,c))),b(()=>{this.isRunning=!1,this.onFinalize(i,c),u?.(),u=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(h(null)));let d=O(this.messages).filter(e=>!s.has(e.id));return{result:a,newMessages:d}}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 j(e,t,this,n)}processApplyEvents(e,t,n){return t.pipe(ie(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(t){let n=O(this.messages).filter(e=>e.role!==`activity`);return{threadId:this.threadId,runId:t?.runId||e(),tools:O(t?.tools??[]),context:O(t?.context??[]),forwardedProps:O(t?.forwardedProps??{}),state:O(this.state),messages:n}}async onInitialize(e,t){let n=await A(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 f(A(n,this.messages,this.state,(n,r,i)=>n.onRunFailed?.({error:t,messages:r,state:i,agent:this,input:e}))).pipe(x(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 A(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=O(this.messages),e.state=O(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=O(e),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(e){this.state=O(e),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??e();let n=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((e,t)=>({run:n=>t.run(n,e)}),this).run(n)).pipe(V(this.debug),M(this.debug),B(this.threadId,n.runId,this.agentId),e=>e.pipe(x(e=>(this.debug&&console.debug(`[LEGACY]:`,JSON.stringify(e)),e))))}},be=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=O(e.headers??{})}run(e){return L(P(this.url,this.requestInit(e)))}clone(){let e=super.clone();e.url=this.url,e.headers=O(this.headers??{});let t=new AbortController,n=this.abortController.signal;return n.aborted&&t.abort(n.reason),e.abortController=t,e}};function xe(e){let t=[],n=new Map,r=new Map;for(let a of e)if(a.type===i.TEXT_MESSAGE_START){let e=a,t=e.messageId;n.has(t)||n.set(t,{contents:[],otherEvents:[]});let r=n.get(t);r.start=e}else if(a.type===i.TEXT_MESSAGE_CONTENT){let e=a,t=e.messageId;n.has(t)||n.set(t,{contents:[],otherEvents:[]}),n.get(t).contents.push(e)}else if(a.type===i.TEXT_MESSAGE_END){let e=a,r=e.messageId;n.has(r)||n.set(r,{contents:[],otherEvents:[]});let i=n.get(r);i.end=e,Q(r,i,t),n.delete(r)}else if(a.type===i.TOOL_CALL_START){let e=a,t=e.toolCallId;r.has(t)||r.set(t,{args:[],otherEvents:[]});let n=r.get(t);n.start=e}else if(a.type===i.TOOL_CALL_ARGS){let e=a,t=e.toolCallId;r.has(t)||r.set(t,{args:[],otherEvents:[]}),r.get(t).args.push(e)}else if(a.type===i.TOOL_CALL_END){let e=a,n=e.toolCallId;r.has(n)||r.set(n,{args:[],otherEvents:[]});let i=r.get(n);i.end=e,$(n,i,t),r.delete(n)}else{let e=!1;for(let[t,r]of n)if(r.start&&!r.end){r.otherEvents.push(a),e=!0;break}if(!e){for(let[t,n]of r)if(n.start&&!n.end){n.otherEvents.push(a),e=!0;break}}e||t.push(a)}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(``),a={type:i.TEXT_MESSAGE_CONTENT,messageId:e,delta:r};n.push(a)}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(``),a={type:i.TOOL_CALL_ARGS,toolCallId:e,delta:r};n.push(a)}t.end&&n.push(t.end);for(let e of t.otherEvents)n.push(e)}export{Z as AbstractAgent,W as BackwardCompatibility_0_0_39,X as BackwardCompatibility_0_0_45,_e as FilterToolCallsMiddleware,U as FunctionMiddleware,be as HttpAgent,H as Middleware,xe as compactEvents,B as convertToLegacyEvents,j as defaultApplyEvents,I as parseProtoStream,F as parseSSEStream,k as randomUUID,P as runHttpRequest,O as structuredClone_,V as transformChunks,L as transformHttpEventStream,M as verifyEvents};
|
|
4
|
+
`)},B=(e,t,n)=>r=>{let o={},s=!0,c=!0,l=``,u=null,d=null,f=[],p={},m=e=>{typeof e==`object`&&e&&(`messages`in e&&delete e.messages,o=e)};return r.pipe(S(r=>{switch(r.type){case i.TEXT_MESSAGE_START:{let e=r;return[{type:R.enum.TextMessageStart,messageId:e.messageId,role:e.role}]}case i.TEXT_MESSAGE_CONTENT:{let e=r;return[{type:R.enum.TextMessageContent,messageId:e.messageId,content:e.delta}]}case i.TEXT_MESSAGE_END:{let e=r;return[{type:R.enum.TextMessageEnd,messageId:e.messageId}]}case i.TOOL_CALL_START:{let e=r;return f.push({id:e.toolCallId,type:`function`,function:{name:e.toolCallName,arguments:``}}),c=!0,p[e.toolCallId]=e.toolCallName,[{type:R.enum.ActionExecutionStart,actionExecutionId:e.toolCallId,actionName:e.toolCallName,parentMessageId:e.parentMessageId}]}case i.TOOL_CALL_ARGS:{let i=r,a=f.find(e=>e.id===i.toolCallId);if(!a)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${i.toolCallId}'`),[];a.function.arguments+=i.delta;let u=!1;if(d){let e=d.find(e=>e.tool==a.function.name);if(e)try{let t=JSON.parse(w(a.function.arguments));e.tool_argument&&e.tool_argument in t?(m({...o,[e.state_key]:t[e.tool_argument]}),u=!0):e.tool_argument||(m({...o,[e.state_key]:t}),u=!0)}catch{}}return[{type:R.enum.ActionExecutionArgs,actionExecutionId:i.toolCallId,args:i.delta},...u?[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:c}]:[]]}case i.TOOL_CALL_END:{let e=r;return[{type:R.enum.ActionExecutionEnd,actionExecutionId:e.toolCallId}]}case i.TOOL_CALL_RESULT:{let e=r;return[{type:R.enum.ActionExecutionResult,actionExecutionId:e.toolCallId,result:e.content,actionName:p[e.toolCallId]||`unknown`}]}case i.RAW:return[];case i.CUSTOM:{let e=r;switch(e.name){case`Exit`:s=!1;break;case`PredictState`:d=e.value;break}return[{type:R.enum.MetaEvent,name:e.name,value:e.value}]}case i.STATE_SNAPSHOT:return m(r.snapshot),[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:c}];case i.STATE_DELTA:{let i=r,u=a.applyPatch(o,i.delta,!0,!1);return u?(m(u.newDocument),[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:c}]):[]}case i.MESSAGES_SNAPSHOT:return u=r.messages,[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify({...o,...u?{messages:u}:{}}),active:!0}];case i.RUN_STARTED:return[];case i.RUN_FINISHED:return u&&(o.messages=u),Object.keys(o).length===0?[]:[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify({...o,...u?{messages:ge(u)}:{}}),active:!1}];case i.RUN_ERROR:{let e=r;return[{type:R.enum.RunError,message:e.message,code:e.code}]}case i.STEP_STARTED:return l=r.stepName,f=[],d=null,[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:!0}];case i.STEP_FINISHED:return f=[],d=null,[{type:R.enum.AgentStateMessage,threadId:e,agentName:n,nodeName:l,runId:t,running:s,role:`assistant`,state:JSON.stringify(o),active:!1}];default:return[]}}))};function ge(e){let t=[];for(let n of e)if(n.role===`assistant`||n.role===`user`||n.role===`system`){let e=he(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 V=e=>t=>{let n,r,a,o,s=()=>{if(!n||o!==`text`)throw Error(`No text message to close`);let t={type:i.TEXT_MESSAGE_END,messageId:n.messageId};return o=void 0,n=void 0,e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_END`,JSON.stringify(t)),t},c=()=>{if(!r||o!==`tool`)throw Error(`No tool call to close`);let t={type:i.TOOL_CALL_END,toolCallId:r.toolCallId};return o=void 0,r=void 0,e&&console.debug(`[TRANSFORM]: TOOL_CALL_END`,JSON.stringify(t)),t},l=()=>{if(!a||o!==`reasoning`)throw Error(`No reasoning message to close`);let t={type:i.REASONING_MESSAGE_END,messageId:a.messageId};return o=void 0,a=void 0,e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_END`,JSON.stringify(t)),t},u=()=>o===`text`?[s()]:o===`tool`?[c()]:o===`reasoning`?[l()]:[];return t.pipe(m(t=>{switch(t.type){case i.TEXT_MESSAGE_START:case i.TEXT_MESSAGE_CONTENT:case i.TEXT_MESSAGE_END:case i.TOOL_CALL_START:case i.TOOL_CALL_ARGS:case i.TOOL_CALL_END:case i.TOOL_CALL_RESULT:case i.STATE_SNAPSHOT:case i.STATE_DELTA:case i.MESSAGES_SNAPSHOT:case i.CUSTOM:case i.RUN_STARTED:case i.RUN_FINISHED:case i.RUN_ERROR:case i.STEP_STARTED:case i.STEP_FINISHED:case i.THINKING_START:case i.THINKING_END:case i.THINKING_TEXT_MESSAGE_START:case i.THINKING_TEXT_MESSAGE_CONTENT:case i.THINKING_TEXT_MESSAGE_END:case i.REASONING_START:case i.REASONING_MESSAGE_START:case i.REASONING_MESSAGE_CONTENT:case i.REASONING_MESSAGE_END:case i.REASONING_END:return[...u(),t];case i.RAW:case i.ACTIVITY_SNAPSHOT:case i.ACTIVITY_DELTA:case i.REASONING_ENCRYPTED_VALUE:return[t];case i.TEXT_MESSAGE_CHUNK:let s=t,c=[];if((o!==`text`||s.messageId!==void 0&&s.messageId!==n?.messageId)&&c.push(...u()),o!==`text`){if(s.messageId===void 0)throw Error(`First TEXT_MESSAGE_CHUNK must have a messageId`);n={messageId:s.messageId},o=`text`;let t={type:i.TEXT_MESSAGE_START,messageId:s.messageId,role:s.role||`assistant`};c.push(t),e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_START`,JSON.stringify(t))}if(s.delta!==void 0){let t={type:i.TEXT_MESSAGE_CONTENT,messageId:n.messageId,delta:s.delta};c.push(t),e&&console.debug(`[TRANSFORM]: TEXT_MESSAGE_CONTENT`,JSON.stringify(t))}return c;case i.TOOL_CALL_CHUNK:let l=t,d=[];if((o!==`tool`||l.toolCallId!==void 0&&l.toolCallId!==r?.toolCallId)&&d.push(...u()),o!==`tool`){if(l.toolCallId===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallId`);if(l.toolCallName===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallName`);r={toolCallId:l.toolCallId,toolCallName:l.toolCallName,parentMessageId:l.parentMessageId},o=`tool`;let t={type:i.TOOL_CALL_START,toolCallId:l.toolCallId,toolCallName:l.toolCallName,parentMessageId:l.parentMessageId};d.push(t),e&&console.debug(`[TRANSFORM]: TOOL_CALL_START`,JSON.stringify(t))}if(l.delta!==void 0){let t={type:i.TOOL_CALL_ARGS,toolCallId:r.toolCallId,delta:l.delta};d.push(t),e&&console.debug(`[TRANSFORM]: TOOL_CALL_ARGS`,JSON.stringify(t))}return d;case i.REASONING_MESSAGE_CHUNK:let f=t,p=[];if((o!==`reasoning`||f.messageId&&f.messageId!==a?.messageId)&&p.push(...u()),o!==`reasoning`){if(f.messageId===void 0)throw Error(`First REASONING_MESSAGE_CHUNK must have a messageId`);a={messageId:f.messageId},o=`reasoning`;let t={type:i.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:i.REASONING_MESSAGE_CONTENT,messageId:a.messageId,delta:f.delta};p.push(t),e&&console.debug(`[TRANSFORM]: REASONING_MESSAGE_CONTENT`,JSON.stringify(t))}return p}return t.type,[]}),d(()=>{u()}))};var H=class{runNext(e,t){return t.run(e).pipe(V(!1))}runNextWithState(e,t){let n=O(e.messages||[]),r=O(e.state||{}),i=new c;return j(e,i,t,[]).subscribe(e=>{e.messages!==void 0&&(n=e.messages),e.state!==void 0&&(r=e.state)}),this.runNext(e,t).pipe(y(async e=>(i.next(e),await new Promise(e=>setTimeout(e,0)),{event:e,messages:O(n),state:O(r)})))}},U=class extends H{constructor(e){super(),this.fn=e}run(e,t){return this.fn(e,t)}},_e=class extends H{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(te(e=>{if(e.type===i.TOOL_CALL_START){let t=e;return this.shouldFilterTool(t.toolCallName)?(this.blockedToolCallIds.add(t.toolCallId),!1):!0}if(e.type===i.TOOL_CALL_ARGS){let t=e;return!this.blockedToolCallIds.has(t.toolCallId)}if(e.type===i.TOOL_CALL_END){let t=e;return!this.blockedToolCallIds.has(t.toolCallId)}if(e.type===i.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 ve(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 H{run(e,t){let{parentRunId:n,...r}=e,i={...r,messages:r.messages.map(ve)};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 H{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(x(e=>this.transformEvent(e)))}transformEvent(e){switch(e.type){case G:{this.currentReasoningId=k();let{title:t,...n}=e;return this.warnAboutTransformation(G,i.REASONING_START),{...n,type:i.REASONING_START,messageId:this.currentReasoningId}}case q:return this.currentMessageId=k(),this.warnAboutTransformation(q,i.REASONING_MESSAGE_START),{...e,type:i.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:`assistant`};case J:{let{delta:t,...n}=e;return this.warnAboutTransformation(J,i.REASONING_MESSAGE_CONTENT),{...n,type:i.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??k(),delta:t}}case Y:{let t=this.currentMessageId??k();return this.warnAboutTransformation(Y,i.REASONING_MESSAGE_END),{...e,type:i.REASONING_MESSAGE_END,messageId:t}}case K:{let t=this.currentReasoningId??k();return this.warnAboutTransformation(K,i.REASONING_END),{...e,type:i.REASONING_END,messageId:t}}default:return e}}},ye=`0.0.48-alpha.0`,Z=class{get maxVersion(){return ye}constructor({agentId:t,description:n,threadId:r,initialMessages:i,initialState:a,debug:o}={}){this.debug=!1,this.subscribers=[],this.isRunning=!1,this.middlewares=[],this.agentId=t,this.description=n??``,this.threadId=r??e(),this.messages=O(i??[]),this.state=O(a??{}),this.debug=o??!1,D(this.maxVersion,`0.0.39`)<=0&&this.middlewares.unshift(new W),D(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 U(e):e);return this.middlewares.push(...t),this}async runAgent(t,n){try{this.isRunning=!0,this.agentId=this.agentId??e();let r=this.prepareRunAgentInput(t),i,a=new Set(this.messages.map(e=>e.id)),o=[{onRunFinishedEvent:e=>{i=e.result}},...this.subscribers,n??{}];await this.onInitialize(r,o),this.activeRunDetach$=new l;let s;this.activeRunCompletionPromise=new Promise(e=>{s=e}),await p(g(()=>this.middlewares.length===0?this.run(r):this.middlewares.reduceRight((e,t)=>({run:n=>t.run(n,e),get messages(){return e.messages},get state(){return e.state}}),this).run(r),V(this.debug),M(this.debug),e=>e.pipe(C(this.activeRunDetach$)),e=>this.apply(r,e,o),e=>this.processApplyEvents(r,e,o),v(e=>(this.isRunning=!1,this.onError(r,e,o))),b(()=>{this.isRunning=!1,this.onFinalize(r,o),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(h(null)));let c=O(this.messages).filter(e=>!a.has(e.id));return{result:i,newMessages:c}}finally{this.isRunning=!1}}connect(e){throw new t}fetchRunHistory(e){return Promise.resolve(void 0)}async connectAgent(n,r){try{this.isRunning=!0,this.agentId=this.agentId??e();let i=this.prepareRunAgentInput(n),a,s=new Set(this.messages.map(e=>e.id)),c=[{onRunFinishedEvent:e=>{a=e.result}},...this.subscribers,r??{}];await this.onInitialize(i,c),this.activeRunDetach$=new l;let u;this.activeRunCompletionPromise=new Promise(e=>{u=e}),await p(g(()=>this.connect(i),V(this.debug),M(this.debug),e=>e.pipe(C(this.activeRunDetach$)),e=>this.apply(i,e,c),e=>this.processApplyEvents(i,e,c),v(e=>(this.isRunning=!1,e instanceof t?o:this.onError(i,e,c))),b(()=>{this.isRunning=!1,this.onFinalize(i,c),u?.(),u=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(h(null)));let d=O(this.messages).filter(e=>!s.has(e.id));return{result:a,newMessages:d}}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 j(e,t,this,n)}processApplyEvents(e,t,n){return t.pipe(ie(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(t){let n=O(this.messages).filter(e=>e.role!==`activity`);return{threadId:this.threadId,runId:t?.runId||e(),tools:O(t?.tools??[]),context:O(t?.context??[]),forwardedProps:O(t?.forwardedProps??{}),state:O(this.state),messages:n}}async onInitialize(e,t){let n=await A(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 f(A(n,this.messages,this.state,(n,r,i)=>n.onRunFailed?.({error:t,messages:r,state:i,agent:this,input:e}))).pipe(x(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 A(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=O(this.messages),e.state=O(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=O(e),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(e){this.state=O(e),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??e();let n=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((e,t)=>({run:n=>t.run(n,e),get messages(){return e.messages},get state(){return e.state}}),this).run(n)).pipe(V(this.debug),M(this.debug),B(this.threadId,n.runId,this.agentId),e=>e.pipe(x(e=>(this.debug&&console.debug(`[LEGACY]:`,JSON.stringify(e)),e))))}},be=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=O(e.headers??{})}run(e){return L(P(this.url,this.requestInit(e)))}clone(){let e=super.clone();e.url=this.url,e.headers=O(this.headers??{});let t=new AbortController,n=this.abortController.signal;return n.aborted&&t.abort(n.reason),e.abortController=t,e}};function xe(e){let t=[],n=new Map,r=new Map;for(let a of e)if(a.type===i.TEXT_MESSAGE_START){let e=a,t=e.messageId;n.has(t)||n.set(t,{contents:[],otherEvents:[]});let r=n.get(t);r.start=e}else if(a.type===i.TEXT_MESSAGE_CONTENT){let e=a,t=e.messageId;n.has(t)||n.set(t,{contents:[],otherEvents:[]}),n.get(t).contents.push(e)}else if(a.type===i.TEXT_MESSAGE_END){let e=a,r=e.messageId;n.has(r)||n.set(r,{contents:[],otherEvents:[]});let i=n.get(r);i.end=e,Q(r,i,t),n.delete(r)}else if(a.type===i.TOOL_CALL_START){let e=a,t=e.toolCallId;r.has(t)||r.set(t,{args:[],otherEvents:[]});let n=r.get(t);n.start=e}else if(a.type===i.TOOL_CALL_ARGS){let e=a,t=e.toolCallId;r.has(t)||r.set(t,{args:[],otherEvents:[]}),r.get(t).args.push(e)}else if(a.type===i.TOOL_CALL_END){let e=a,n=e.toolCallId;r.has(n)||r.set(n,{args:[],otherEvents:[]});let i=r.get(n);i.end=e,$(n,i,t),r.delete(n)}else{let e=!1;for(let[t,r]of n)if(r.start&&!r.end){r.otherEvents.push(a),e=!0;break}if(!e){for(let[t,n]of r)if(n.start&&!n.end){n.otherEvents.push(a),e=!0;break}}e||t.push(a)}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(``),a={type:i.TEXT_MESSAGE_CONTENT,messageId:e,delta:r};n.push(a)}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(``),a={type:i.TOOL_CALL_ARGS,toolCallId:e,delta:r};n.push(a)}t.end&&n.push(t.end);for(let e of t.otherEvents)n.push(e)}export{Z as AbstractAgent,W as BackwardCompatibility_0_0_39,X as BackwardCompatibility_0_0_45,_e as FilterToolCallsMiddleware,U as FunctionMiddleware,be as HttpAgent,H as Middleware,xe as compactEvents,B as convertToLegacyEvents,j as defaultApplyEvents,I as parseProtoStream,F as parseSSEStream,k as randomUUID,P as runHttpRequest,O as structuredClone_,V as transformChunks,L as transformHttpEventStream,M as verifyEvents};
|
|
5
5
|
//# sourceMappingURL=index.mjs.map
|