@ag-ui/client 0.0.41 → 0.0.42-alpha.1
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 +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Rt=Object.defineProperty,xt=Object.defineProperties;var It=Object.getOwnPropertyDescriptors;var Y=Object.getOwnPropertySymbols;var ot=Object.prototype.hasOwnProperty,rt=Object.prototype.propertyIsEnumerable;var at=(g,a,e)=>a in g?Rt(g,a,{enumerable:!0,configurable:!0,writable:!0,value:e}):g[a]=e,N=(g,a)=>{for(var e in a||(a={}))ot.call(a,e)&&at(g,e,a[e]);if(Y)for(var e of Y(a))rt.call(a,e)&&at(g,e,a[e]);return g},G=(g,a)=>xt(g,It(a));var it=(g,a)=>{var e={};for(var n in g)ot.call(g,n)&&a.indexOf(n)<0&&(e[n]=g[n]);if(g!=null&&Y)for(var n of Y(g))a.indexOf(n)<0&&rt.call(g,n)&&(e[n]=g[n]);return e};import{EventType as R}from"@ag-ui/core";import{mergeAll as Nt,defaultIfEmpty as Lt,concatMap as wt}from"rxjs/operators";import{of as Ot,EMPTY as Pt}from"rxjs";import{v4 as _t}from"uuid";var y=g=>{if(typeof structuredClone=="function")return structuredClone(g);try{return JSON.parse(JSON.stringify(g))}catch(a){return N({},g)}};function ye(){return _t()}import{applyPatch as lt}from"fast-json-patch";async function I(g,a,e,n){let t=a,s=e,r;for(let o of g)try{let i=await n(o,y(t),y(s));if(i===void 0)continue;if(i.messages!==void 0&&(t=i.messages),i.state!==void 0&&(s=i.state),r=i.stopPropagation,r===!0)break}catch(i){process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0||console.error("Subscriber error:",i);continue}return N(N(N({},JSON.stringify(t)!==JSON.stringify(a)?{messages:t}:{}),JSON.stringify(s)!==JSON.stringify(e)?{state:s}:{}),r!==void 0?{stopPropagation:r}:{})}import Dt from"untruncate-json";var $=(g,a,e,n)=>{let t=y(e.messages),s=y(g.state),r={},o=p=>{p.messages!==void 0&&(t=p.messages,r.messages=p.messages),p.state!==void 0&&(s=p.state,r.state=p.state)},i=()=>{let p=y(r);return r={},p.messages!==void 0||p.state!==void 0?Ot(p):Pt};return a.pipe(wt(async p=>{var S,v,c,b,U;let x=await I(n,t,s,(E,l,d)=>{var m;return(m=E.onEvent)==null?void 0:m.call(E,{event:p,agent:e,input:g,messages:l,state:d})});if(o(x),x.stopPropagation===!0)return i();switch(p.type){case R.TEXT_MESSAGE_START:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onTextMessageStartEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let{messageId:l,role:d="assistant"}=p,m={id:l,role:d,content:""};t.push(m),o({messages:t})}return i()}case R.TEXT_MESSAGE_CONTENT:{let{messageId:E,delta:l}=p,d=t.find(u=>u.id===E);if(!d)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${E}'`),i();let m=await I(n,t,s,(u,A,h)=>{var _;return(_=u.onTextMessageContentEvent)==null?void 0:_.call(u,{event:p,messages:A,state:h,agent:e,input:g,textMessageBuffer:typeof d.content=="string"?d.content:""})});if(o(m),m.stopPropagation!==!0){let u=typeof d.content=="string"?d.content:"";d.content=`${u}${l}`,o({messages:t})}return i()}case R.TEXT_MESSAGE_END:{let{messageId:E}=p,l=t.find(m=>m.id===E);if(!l)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${E}'`),i();let d=await I(n,t,s,(m,u,A)=>{var h;return(h=m.onTextMessageEndEvent)==null?void 0:h.call(m,{event:p,messages:u,state:A,agent:e,input:g,textMessageBuffer:typeof l.content=="string"?l.content:""})});return o(d),await Promise.all(n.map(m=>{var u;(u=m.onNewMessage)==null||u.call(m,{message:l,messages:t,state:s,agent:e,input:g})})),i()}case R.TOOL_CALL_START:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onToolCallStartEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let{toolCallId:l,toolCallName:d,parentMessageId:m}=p,u;m&&t.length>0&&t[t.length-1].id===m?u=t[t.length-1]:(u={id:m||l,role:"assistant",toolCalls:[]},t.push(u)),(S=u.toolCalls)!=null||(u.toolCalls=[]),u.toolCalls.push({id:l,type:"function",function:{name:d,arguments:""}}),o({messages:t})}return i()}case R.TOOL_CALL_ARGS:{let{toolCallId:E,delta:l}=p,d=t.find(A=>{var h;return(h=A.toolCalls)==null?void 0:h.some(_=>_.id===E)});if(!d)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${E}'`),i();let m=d.toolCalls.find(A=>A.id===E);if(!m)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${E}'`),i();let u=await I(n,t,s,(A,h,_)=>{var q;let H=m.function.arguments,F=m.function.name,X={};try{X=Dt(H)}catch(ve){}return(q=A.onToolCallArgsEvent)==null?void 0:q.call(A,{event:p,messages:h,state:_,agent:e,input:g,toolCallBuffer:H,toolCallName:F,partialToolCallArgs:X})});return o(u),u.stopPropagation!==!0&&(m.function.arguments+=l,o({messages:t})),i()}case R.TOOL_CALL_END:{let{toolCallId:E}=p,l=t.find(u=>{var A;return(A=u.toolCalls)==null?void 0:A.some(h=>h.id===E)});if(!l)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${E}'`),i();let d=l.toolCalls.find(u=>u.id===E);if(!d)return console.warn(`TOOL_CALL_END: No tool call found with ID '${E}'`),i();let m=await I(n,t,s,(u,A,h)=>{var X;let _=d.function.arguments,H=d.function.name,F={};try{F=JSON.parse(_)}catch(q){}return(X=u.onToolCallEndEvent)==null?void 0:X.call(u,{event:p,messages:A,state:h,agent:e,input:g,toolCallName:H,toolCallArgs:F})});return o(m),await Promise.all(n.map(u=>{var A;(A=u.onNewToolCall)==null||A.call(u,{toolCall:d,messages:t,state:s,agent:e,input:g})})),i()}case R.TOOL_CALL_RESULT:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onToolCallResultEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let{messageId:l,toolCallId:d,content:m,role:u}=p,A={id:l,toolCallId:d,role:u||"tool",content:m};t.push(A),await Promise.all(n.map(h=>{var _;(_=h.onNewMessage)==null||_.call(h,{message:A,messages:t,state:s,agent:e,input:g})})),o({messages:t})}return i()}case R.STATE_SNAPSHOT:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onStateSnapshotEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let{snapshot:l}=p;s=l,o({state:s})}return i()}case R.STATE_DELTA:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onStateDeltaEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let{delta:l}=p;try{s=lt(s,l,!0,!1).newDocument,o({state:s})}catch(d){let m=d instanceof Error?d.message:String(d);console.warn(`Failed to apply state patch:
|
|
2
2
|
Current state: ${JSON.stringify(s,null,2)}
|
|
3
3
|
Patch operations: ${JSON.stringify(l,null,2)}
|
|
4
|
-
Error: ${m}`)}}return i()}case R.MESSAGES_SNAPSHOT:{let E=await
|
|
4
|
+
Error: ${m}`)}}return i()}case R.MESSAGES_SNAPSHOT:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onMessagesSnapshotEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let{messages:l}=p;t=l,o({messages:t})}return i()}case R.ACTIVITY_SNAPSHOT:{let E=p,l=t.findIndex(h=>h.id===E.messageId),d=l>=0?t[l]:void 0,m=(d==null?void 0:d.role)==="activity"?d:void 0,u=(v=E.replace)!=null?v:!0,A=await I(n,t,s,(h,_,H)=>{var F;return(F=h.onActivitySnapshotEvent)==null?void 0:F.call(h,{event:E,messages:_,state:H,agent:e,input:g,activityMessage:m,existingMessage:d})});if(o(A),A.stopPropagation!==!0){let h={id:E.messageId,role:"activity",activityType:E.activityType,content:y(E.content)},_;l===-1?(t.push(h),_=h):m?u&&(t[l]=G(N({},m),{activityType:E.activityType,content:y(E.content)})):u&&(t[l]=h,_=h),o({messages:t}),_&&await Promise.all(n.map(H=>{var F;return(F=H.onNewMessage)==null?void 0:F.call(H,{message:_,messages:t,state:s,agent:e,input:g})}))}return i()}case R.ACTIVITY_DELTA:{let E=p,l=t.findIndex(A=>A.id===E.messageId);if(l===-1)return console.warn(`ACTIVITY_DELTA: No message found with ID '${E.messageId}' to apply patch`),i();let d=t[l];if(d.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${E.messageId}' is not an activity message`),i();let m=d,u=await I(n,t,s,(A,h,_)=>{var H;return(H=A.onActivityDeltaEvent)==null?void 0:H.call(A,{event:E,messages:h,state:_,agent:e,input:g,activityMessage:m})});if(o(u),u.stopPropagation!==!0)try{let A=y((c=m.content)!=null?c:{}),_=lt(A,(b=E.patch)!=null?b:[],!0,!1).newDocument;t[l]=G(N({},m),{content:y(_),activityType:E.activityType}),o({messages:t})}catch(A){let h=A instanceof Error?A.message:String(A);console.warn(`Failed to apply activity patch for '${E.messageId}': ${h}`)}return i()}case R.RAW:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onRawEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g})});return o(E),i()}case R.CUSTOM:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onCustomEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g})});return o(E),i()}case R.RUN_STARTED:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onRunStartedEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g})});if(o(E),E.stopPropagation!==!0){let l=p;if((U=l.input)!=null&&U.messages){for(let d of l.input.messages)t.find(u=>u.id===d.id)||t.push(d);o({messages:t})}}return i()}case R.RUN_FINISHED:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onRunFinishedEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g,result:p.result})});return o(E),i()}case R.RUN_ERROR:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onRunErrorEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g})});return o(E),i()}case R.STEP_STARTED:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onStepStartedEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g})});return o(E),i()}case R.STEP_FINISHED:{let E=await I(n,t,s,(l,d,m)=>{var u;return(u=l.onStepFinishedEvent)==null?void 0:u.call(l,{event:p,messages:d,state:m,agent:e,input:g})});return o(E),i()}case R.TEXT_MESSAGE_CHUNK:throw new Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case R.TOOL_CALL_CHUNK:throw new Error("TOOL_CALL_CHUNK must be tranformed before being applied");case R.THINKING_START:return i();case R.THINKING_END:return i();case R.THINKING_TEXT_MESSAGE_START:return i();case R.THINKING_TEXT_MESSAGE_CONTENT:return i();case R.THINKING_TEXT_MESSAGE_END:return i()}let T=p.type;return i()}),Nt(),n.length>0?Lt({}):p=>p)};import{EventType as L,AGUIError as w}from"@ag-ui/core";import{throwError as O,of as P}from"rxjs";import{mergeMap as Ht}from"rxjs/operators";var z=g=>a=>{let e=new Map,n=new Map,t=!1,s=!1,r=!1,o=new Map,i=!1,p=!1,x=!1,T=()=>{e.clear(),n.clear(),o.clear(),i=!1,p=!1,t=!1,s=!1,x=!0};return a.pipe(Ht(S=>{let v=S.type;if(g&&console.debug("[VERIFY]:",JSON.stringify(S)),s)return O(()=>new w(`Cannot send event type '${v}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(t&&v!==L.RUN_ERROR&&v!==L.RUN_STARTED)return O(()=>new w(`Cannot send event type '${v}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(r){if(v===L.RUN_STARTED){if(x&&!t)return O(()=>new w("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));t&&T()}}else if(r=!0,v!==L.RUN_STARTED&&v!==L.RUN_ERROR)return O(()=>new w("First event must be 'RUN_STARTED'"));switch(v){case L.TEXT_MESSAGE_START:{let c=S.messageId;return e.has(c)?O(()=>new w(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${c}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(e.set(c,!0),P(S))}case L.TEXT_MESSAGE_CONTENT:{let c=S.messageId;return e.has(c)?P(S):O(()=>new w(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${c}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case L.TEXT_MESSAGE_END:{let c=S.messageId;return e.has(c)?(e.delete(c),P(S)):O(()=>new w(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${c}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case L.TOOL_CALL_START:{let c=S.toolCallId;return n.has(c)?O(()=>new w(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${c}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(n.set(c,!0),P(S))}case L.TOOL_CALL_ARGS:{let c=S.toolCallId;return n.has(c)?P(S):O(()=>new w(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${c}'. Start a tool call with 'TOOL_CALL_START' first.`))}case L.TOOL_CALL_END:{let c=S.toolCallId;return n.has(c)?(n.delete(c),P(S)):O(()=>new w(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${c}'. A 'TOOL_CALL_START' event must be sent first.`))}case L.STEP_STARTED:{let c=S.stepName;return o.has(c)?O(()=>new w(`Step "${c}" is already active for 'STEP_STARTED'`)):(o.set(c,!0),P(S))}case L.STEP_FINISHED:{let c=S.stepName;return o.has(c)?(o.delete(c),P(S)):O(()=>new w(`Cannot send 'STEP_FINISHED' for step "${c}" that was not started`))}case L.RUN_STARTED:return x=!0,P(S);case L.RUN_FINISHED:{if(o.size>0){let c=Array.from(o.keys()).join(", ");return O(()=>new w(`Cannot send 'RUN_FINISHED' while steps are still active: ${c}`))}if(e.size>0){let c=Array.from(e.keys()).join(", ");return O(()=>new w(`Cannot send 'RUN_FINISHED' while text messages are still active: ${c}`))}if(n.size>0){let c=Array.from(n.keys()).join(", ");return O(()=>new w(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${c}`))}return t=!0,P(S)}case L.RUN_ERROR:return s=!0,P(S);case L.CUSTOM:return P(S);case L.THINKING_TEXT_MESSAGE_START:return i?p?O(()=>new w("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(p=!0,P(S)):O(()=>new w("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case L.THINKING_TEXT_MESSAGE_CONTENT:return p?P(S):O(()=>new w("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case L.THINKING_TEXT_MESSAGE_END:return p?(p=!1,P(S)):O(()=>new w("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case L.THINKING_START:return i?O(()=>new w("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(i=!0,P(S));case L.THINKING_END:return i?(i=!1,P(S)):O(()=>new w("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return P(S)}}))};import{EventSchemas as jt}from"@ag-ui/core";import{Subject as Xt,ReplaySubject as $t}from"rxjs";import{Observable as Gt,from as gt,defer as bt,throwError as ct}from"rxjs";import{mergeMap as Ft,switchMap as kt}from"rxjs/operators";var Q=(g,a)=>bt(()=>gt(fetch(g,a))).pipe(kt(e=>{var s;if(!e.ok){let r=e.headers.get("content-type")||"";return gt(e.text()).pipe(Ft(o=>{let i=o;if(r.includes("application/json"))try{i=JSON.parse(o)}catch(x){}let p=new Error(`HTTP ${e.status}: ${typeof i=="string"?i:JSON.stringify(i)}`);return p.status=e.status,p.payload=i,ct(()=>p)}))}let n={type:"headers",status:e.status,headers:e.headers},t=(s=e.body)==null?void 0:s.getReader();return t?new Gt(r=>(r.next(n),(async()=>{try{for(;;){let{done:o,value:i}=await t.read();if(o)break;let p={type:"data",data:i};r.next(p)}r.complete()}catch(o){r.error(o)}})(),()=>{t.cancel().catch(o=>{if((o==null?void 0:o.name)!=="AbortError")throw o})})):ct(()=>new Error("Failed to getReader() from response"))}));import{Subject as Ut}from"rxjs";var Z=g=>{let a=new Ut,e=new TextDecoder("utf-8",{fatal:!1}),n="";g.subscribe({next:s=>{if(s.type!=="headers"&&s.type==="data"&&s.data){let r=e.decode(s.data,{stream:!0});n+=r;let o=n.split(/\n\n/);n=o.pop()||"";for(let i of o)t(i)}},error:s=>a.error(s),complete:()=>{n&&(n+=e.decode(),t(n)),a.complete()}});function t(s){let r=s.split(`
|
|
5
5
|
`),o=[];for(let i of r)i.startsWith("data: ")&&o.push(i.slice(6));if(o.length>0)try{let i=o.join(`
|
|
6
|
-
`),p=JSON.parse(i);a.next(p)}catch(i){a.error(i)}}return a.asObservable()};import{Subject as
|
|
7
|
-
`)},nt=(g,a,e)=>n=>{let t={},s=!0,r=!0,o="",i=null,p=null,S=[],H={},T=A=>{typeof A=="object"&&A!==null&&("messages"in A&&delete A.messages,t=A)};return n.pipe(ee(A=>{switch(A.type){case P.TEXT_MESSAGE_START:{let c=A;return[{type:C.enum.TextMessageStart,messageId:c.messageId,role:c.role}]}case P.TEXT_MESSAGE_CONTENT:{let c=A;return[{type:C.enum.TextMessageContent,messageId:c.messageId,content:c.delta}]}case P.TEXT_MESSAGE_END:{let c=A;return[{type:C.enum.TextMessageEnd,messageId:c.messageId}]}case P.TOOL_CALL_START:{let c=A;return S.push({id:c.toolCallId,type:"function",function:{name:c.toolCallName,arguments:""}}),r=!0,H[c.toolCallId]=c.toolCallName,[{type:C.enum.ActionExecutionStart,actionExecutionId:c.toolCallId,actionName:c.toolCallName,parentMessageId:c.parentMessageId}]}case P.TOOL_CALL_ARGS:{let c=A,F=S.find(E=>E.id===c.toolCallId);if(!F)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c.toolCallId}'`),[];F.function.arguments+=c.delta;let U=!1;if(p){let E=p.find(l=>l.tool==F.function.name);if(E)try{let l=JSON.parse(se(F.function.arguments));E.tool_argument&&E.tool_argument in l?(T(G(_({},t),{[E.state_key]:l[E.tool_argument]})),U=!0):E.tool_argument||(T(G(_({},t),{[E.state_key]:l})),U=!0)}catch(l){}}return[{type:C.enum.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...U?[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}]:[]]}case P.TOOL_CALL_END:{let c=A;return[{type:C.enum.ActionExecutionEnd,actionExecutionId:c.toolCallId}]}case P.TOOL_CALL_RESULT:{let c=A;return[{type:C.enum.ActionExecutionResult,actionExecutionId:c.toolCallId,result:c.content,actionName:H[c.toolCallId]||"unknown"}]}case P.RAW:return[];case P.CUSTOM:{let c=A;switch(c.name){case"Exit":s=!1;break;case"PredictState":p=c.value;break}return[{type:C.enum.MetaEvent,name:c.name,value:c.value}]}case P.STATE_SNAPSHOT:return T(A.snapshot),[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}];case P.STATE_DELTA:{let F=ne(t,A.delta,!0,!1);return F?(T(F.newDocument),[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}]):[]}case P.MESSAGES_SNAPSHOT:return i=A.messages,[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(_(_({},t),i?{messages:i}:{})),active:!0}];case P.RUN_STARTED:return[];case P.RUN_FINISHED:return i&&(t.messages=i),Object.keys(t).length===0?[]:[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(_(_({},t),i?{messages:oe(i)}:{})),active:!1}];case P.RUN_ERROR:{let c=A;return[{type:C.enum.RunError,message:c.message,code:c.code}]}case P.STEP_STARTED:return o=A.stepName,S=[],p=null,[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!0}];case P.STEP_FINISHED:return S=[],p=null,[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!1}];default:return[]}}))};function oe(g){var e;let a=[];for(let n of g)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let t=ae(n.content);if(t){let s={id:n.id,role:n.role,content:t};a.push(s)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let s of n.toolCalls){let r={id:s.id,name:s.function.name,arguments:JSON.parse(s.function.arguments),parentMessageId:n.id};a.push(r)}}else if(n.role==="tool"){let t="unknown";for(let r of g)if(r.role==="assistant"&&((e=r.toolCalls)!=null&&e.length)){for(let o of r.toolCalls)if(o.id===n.toolCallId){t=o.function.name;break}}let s={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:t};a.push(s)}return a}import{v4 as V}from"uuid";import{compareVersions as Ee}from"compare-versions";import{catchError as dt,map as mt,tap as pe}from"rxjs/operators";import{finalize as ft}from"rxjs/operators";import{pipe as Tt,from as de,of as St,EMPTY as me}from"rxjs";import{lastValueFrom as At}from"rxjs";import{mergeMap as re,finalize as ie}from"rxjs";import{EventType as M}from"@ag-ui/core";var B=g=>a=>{let e,n,t,s=()=>{if(!e||t!=="text")throw new Error("No text message to close");let i={type:M.TEXT_MESSAGE_END,messageId:e.messageId};return t=void 0,e=void 0,g&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(i)),i},r=()=>{if(!n||t!=="tool")throw new Error("No tool call to close");let i={type:M.TOOL_CALL_END,toolCallId:n.toolCallId};return t=void 0,n=void 0,g&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(i)),i},o=()=>t==="text"?[s()]:t==="tool"?[r()]:[];return a.pipe(re(i=>{switch(i.type){case M.TEXT_MESSAGE_START:case M.TEXT_MESSAGE_CONTENT:case M.TEXT_MESSAGE_END:case M.TOOL_CALL_START:case M.TOOL_CALL_ARGS:case M.TOOL_CALL_END:case M.TOOL_CALL_RESULT:case M.STATE_SNAPSHOT:case M.STATE_DELTA:case M.MESSAGES_SNAPSHOT:case M.CUSTOM:case M.RUN_STARTED:case M.RUN_FINISHED:case M.RUN_ERROR:case M.STEP_STARTED:case M.STEP_FINISHED:case M.THINKING_START:case M.THINKING_END:case M.THINKING_TEXT_MESSAGE_START:case M.THINKING_TEXT_MESSAGE_CONTENT:case M.THINKING_TEXT_MESSAGE_END:return[...o(),i];case M.RAW:case M.ACTIVITY_SNAPSHOT:case M.ACTIVITY_DELTA:return[i];case M.TEXT_MESSAGE_CHUNK:let S=i,H=[];if((t!=="text"||S.messageId!==void 0&&S.messageId!==(e==null?void 0:e.messageId))&&H.push(...o()),t!=="text"){if(S.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:S.messageId},t="text";let c={type:M.TEXT_MESSAGE_START,messageId:S.messageId,role:S.role||"assistant"};H.push(c),g&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(c))}if(S.delta!==void 0){let c={type:M.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:S.delta};H.push(c),g&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(c))}return H;case M.TOOL_CALL_CHUNK:let T=i,A=[];if((t!=="tool"||T.toolCallId!==void 0&&T.toolCallId!==(n==null?void 0:n.toolCallId))&&A.push(...o()),t!=="tool"){if(T.toolCallId===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallId");if(T.toolCallName===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallName");n={toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId},t="tool";let c={type:M.TOOL_CALL_START,toolCallId:T.toolCallId,toolCallName:T.toolCallName,parentMessageId:T.parentMessageId};A.push(c),g&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(c))}if(T.delta!==void 0){let c={type:M.TOOL_CALL_ARGS,toolCallId:n.toolCallId,delta:T.delta};A.push(c),g&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(c))}return A}let p=i.type;return[]}),ie(()=>{o()}))};import{AGUIConnectNotImplementedError as vt}from"@ag-ui/core";import{ReplaySubject as le}from"rxjs";import{concatMap as ge}from"rxjs/operators";var X=class{runNext(a,e){return e.run(a).pipe(B(!1))}runNextWithState(a,e){let n=y(a.messages||[]),t=y(a.state||{}),s=new le;return z(a,s,e,[]).subscribe(o=>{o.messages!==void 0&&(n=o.messages),o.state!==void 0&&(t=o.state)}),this.runNext(a,e).pipe(ge(async o=>(s.next(o),await new Promise(i=>setTimeout(i,0)),{event:o,messages:y(n),state:y(t)})))}},J=class extends X{constructor(e){super();this.fn=e}run(e,n){return this.fn(e,n)}};function ce(g){let a=g.content;if(Array.isArray(a)){let e=a.filter(n=>typeof n=="object"&&n!==null&&"type"in n&&n.type==="text"&&typeof n.text=="string").map(n=>n.text).join("");return G(_({},g),{content:e})}return typeof a=="string"?g:G(_({},g),{content:""})}var $=class extends X{run(a,e){let r=a,{parentRunId:n}=r,t=it(r,["parentRunId"]),s=G(_({},t),{messages:t.messages.map(ce)});return this.runNext(s,e)}};var pt={name:"@ag-ui/client",author:"Markus Ecker <markus.ecker@gmail.com>",version:"0.0.41",private:!1,publishConfig:{access:"public"},main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",sideEffects:!1,files:["dist/**","README.md"],scripts:{build:"tsup",dev:"tsup --watch",clean:"rm -rf dist .turbo node_modules",typecheck:"tsc --noEmit",test:"jest","link:global":"pnpm link --global","unlink:global":"pnpm unlink --global"},dependencies:{"@ag-ui/core":"workspace:*","@ag-ui/encoder":"workspace:*","@ag-ui/proto":"workspace:*","@types/uuid":"^10.0.0","compare-versions":"^6.1.1","fast-json-patch":"^3.1.1",rxjs:"7.8.1","untruncate-json":"^0.0.1",uuid:"^11.1.0",zod:"^3.22.4"},devDependencies:{"@types/jest":"^29.5.14","@types/node":"^20.11.19",jest:"^29.7.0","ts-jest":"^29.1.2",tsup:"^8.0.2",typescript:"^5.3.3"}};var W=class{constructor({agentId:a,description:e,threadId:n,initialMessages:t,initialState:s,debug:r}={}){this.debug=!1;this.subscribers=[];this.isRunning=!1;this.middlewares=[];this.agentId=a,this.description=e!=null?e:"",this.threadId=n!=null?n:V(),this.messages=y(t!=null?t:[]),this.state=y(s!=null?s:{}),this.debug=r!=null?r:!1,Ee(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new $)}get maxVersion(){return pt.version}subscribe(a){return this.subscribers.push(a),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==a)}}}use(...a){let e=a.map(n=>typeof n=="function"?new J(n):n);return this.middlewares.push(...e),this}async runAgent(a,e){var n;try{this.isRunning=!0,this.agentId=(n=this.agentId)!=null?n:V();let t=this.prepareRunAgentInput(a),s,r=new Set(this.messages.map(S=>S.id)),o=[{onRunFinishedEvent:S=>{s=S.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o);let i=Tt(()=>this.middlewares.length===0?this.run(t):this.middlewares.reduceRight((H,T)=>({run:A=>T.run(A,H)}),this).run(t),B(this.debug),K(this.debug),S=>this.apply(t,S,o),S=>this.processApplyEvents(t,S,o),dt(S=>(this.isRunning=!1,this.onError(t,S,o))),ft(()=>{this.isRunning=!1,this.onFinalize(t,o)}));await At(i(St(null)));let p=y(this.messages).filter(S=>!r.has(S.id));return{result:s,newMessages:p}}finally{this.isRunning=!1}}connect(a){throw new vt}async connectAgent(a,e){var n;try{this.isRunning=!0,this.agentId=(n=this.agentId)!=null?n:V();let t=this.prepareRunAgentInput(a),s,r=new Set(this.messages.map(S=>S.id)),o=[{onRunFinishedEvent:S=>{s=S.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o);let i=Tt(()=>this.connect(t),B(this.debug),K(this.debug),S=>this.apply(t,S,o),S=>this.processApplyEvents(t,S,o),dt(S=>(this.isRunning=!1,S instanceof vt?me:this.onError(t,S,o))),ft(()=>{this.isRunning=!1,this.onFinalize(t,o)}));await At(i(St(null)));let p=y(this.messages).filter(S=>!r.has(S.id));return{result:s,newMessages:p}}finally{this.isRunning=!1}}abortRun(){}apply(a,e,n){return z(a,e,this,n)}processApplyEvents(a,e,n){return e.pipe(pe(t=>{t.messages&&(this.messages=t.messages,n.forEach(s=>{var r;(r=s.onMessagesChanged)==null||r.call(s,{messages:this.messages,state:this.state,agent:this,input:a})})),t.state&&(this.state=t.state,n.forEach(s=>{var r;(r=s.onStateChanged)==null||r.call(s,{state:this.state,messages:this.messages,agent:this,input:a})}))}))}prepareRunAgentInput(a){var t,s,r;let n=y(this.messages).filter(o=>o.role!=="activity");return{threadId:this.threadId,runId:(a==null?void 0:a.runId)||V(),tools:y((t=a==null?void 0:a.tools)!=null?t:[]),context:y((s=a==null?void 0:a.context)!=null?s:[]),forwardedProps:y((r=a==null?void 0:a.forwardedProps)!=null?r:{}),state:y(this.state),messages:n}}async onInitialize(a,e){let n=await x(e,this.messages,this.state,(t,s,r)=>{var o;return(o=t.onRunInitialized)==null?void 0:o.call(t,{messages:s,state:r,agent:this,input:a})});(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,a.messages=n.messages,e.forEach(t=>{var s;(s=t.onMessagesChanged)==null||s.call(t,{messages:this.messages,state:this.state,agent:this,input:a})})),n.state&&(this.state=n.state,a.state=n.state,e.forEach(t=>{var s;(s=t.onStateChanged)==null||s.call(t,{state:this.state,messages:this.messages,agent:this,input:a})})))}onError(a,e,n){return de(x(n,this.messages,this.state,(t,s,r)=>{var o;return(o=t.onRunFailed)==null?void 0:o.call(t,{error:e,messages:s,state:r,agent:this,input:a})})).pipe(mt(t=>{let s=t;if((s.messages!==void 0||s.state!==void 0)&&(s.messages!==void 0&&(this.messages=s.messages,n.forEach(r=>{var o;(o=r.onMessagesChanged)==null||o.call(r,{messages:this.messages,state:this.state,agent:this,input:a})})),s.state!==void 0&&(this.state=s.state,n.forEach(r=>{var o;(o=r.onStateChanged)==null||o.call(r,{state:this.state,messages:this.messages,agent:this,input:a})}))),s.stopPropagation!==!0)throw console.error("Agent execution failed:",e),e;return{}}))}async onFinalize(a,e){let n=await x(e,this.messages,this.state,(t,s,r)=>{var o;return(o=t.onRunFinalized)==null?void 0:o.call(t,{messages:s,state:r,agent:this,input:a})});(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(t=>{var s;(s=t.onMessagesChanged)==null||s.call(t,{messages:this.messages,state:this.state,agent:this,input:a})})),n.state!==void 0&&(this.state=n.state,e.forEach(t=>{var s;(s=t.onStateChanged)==null||s.call(t,{state:this.state,messages:this.messages,agent:this,input:a})})))}clone(){let a=Object.create(Object.getPrototypeOf(this));return a.agentId=this.agentId,a.description=this.description,a.threadId=this.threadId,a.messages=y(this.messages),a.state=y(this.state),a.debug=this.debug,a.isRunning=this.isRunning,a.subscribers=[...this.subscribers],a}addMessage(a){this.messages.push(a),(async()=>{var e,n,t;for(let s of this.subscribers)await((e=s.onNewMessage)==null?void 0:e.call(s,{message:a,messages:this.messages,state:this.state,agent:this}));if(a.role==="assistant"&&a.toolCalls)for(let s of a.toolCalls)for(let r of this.subscribers)await((n=r.onNewToolCall)==null?void 0:n.call(r,{toolCall:s,messages:this.messages,state:this.state,agent:this}));for(let s of this.subscribers)await((t=s.onMessagesChanged)==null?void 0:t.call(s,{messages:this.messages,state:this.state,agent:this}))})()}addMessages(a){this.messages.push(...a),(async()=>{var e,n,t;for(let s of a){for(let r of this.subscribers)await((e=r.onNewMessage)==null?void 0:e.call(r,{message:s,messages:this.messages,state:this.state,agent:this}));if(s.role==="assistant"&&s.toolCalls)for(let r of s.toolCalls)for(let o of this.subscribers)await((n=o.onNewToolCall)==null?void 0:n.call(o,{toolCall:r,messages:this.messages,state:this.state,agent:this}))}for(let s of this.subscribers)await((t=s.onMessagesChanged)==null?void 0:t.call(s,{messages:this.messages,state:this.state,agent:this}))})()}setMessages(a){this.messages=y(a),(async()=>{var e;for(let n of this.subscribers)await((e=n.onMessagesChanged)==null?void 0:e.call(n,{messages:this.messages,state:this.state,agent:this}))})()}setState(a){this.state=y(a),(async()=>{var e;for(let n of this.subscribers)await((e=n.onStateChanged)==null?void 0:e.call(n,{messages:this.messages,state:this.state,agent:this}))})()}legacy_to_be_removed_runAgentBridged(a){var t;this.agentId=(t=this.agentId)!=null?t:V();let e=this.prepareRunAgentInput(a);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((r,o)=>({run:i=>o.run(i,r)}),this).run(e)).pipe(B(this.debug),K(this.debug),nt(this.threadId,e.runId,this.agentId),s=>s.pipe(mt(r=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(r)),r))))}};var st=class extends W{constructor(e){var n;super(e);this.abortController=new AbortController;this.url=e.url,this.headers=y((n=e.headers)!=null?n:{})}requestInit(e){return{method:"POST",headers:G(_({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e,n){var t;return this.abortController=(t=e==null?void 0:e.abortController)!=null?t:new AbortController,super.runAgent(e,n)}abortRun(){this.abortController.abort(),super.abortRun()}run(e){let n=Q(this.url,this.requestInit(e));return et(n)}clone(){var s;let e=super.clone();e.url=this.url,e.headers=y((s=this.headers)!=null?s:{});let n=new AbortController,t=this.abortController.signal;return t.aborted&&n.abort(t.reason),e.abortController=n,e}};import{EventType as k}from"@ag-ui/core";function fe(g){let a=[],e=new Map,n=new Map;for(let t of g)if(t.type===k.TEXT_MESSAGE_START){let s=t,r=s.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]});let o=e.get(r);o.start=s}else if(t.type===k.TEXT_MESSAGE_CONTENT){let s=t,r=s.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]}),e.get(r).contents.push(s)}else if(t.type===k.TEXT_MESSAGE_END){let s=t,r=s.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]});let o=e.get(r);o.end=s,ht(r,o,a),e.delete(r)}else if(t.type===k.TOOL_CALL_START){let s=t,r=s.toolCallId;n.has(r)||n.set(r,{args:[],otherEvents:[]});let o=n.get(r);o.start=s}else if(t.type===k.TOOL_CALL_ARGS){let s=t,r=s.toolCallId;n.has(r)||n.set(r,{args:[],otherEvents:[]}),n.get(r).args.push(s)}else if(t.type===k.TOOL_CALL_END){let s=t,r=s.toolCallId;n.has(r)||n.set(r,{args:[],otherEvents:[]});let o=n.get(r);o.end=s,yt(r,o,a),n.delete(r)}else{let s=!1;for(let[r,o]of e)if(o.start&&!o.end){o.otherEvents.push(t),s=!0;break}if(!s){for(let[r,o]of n)if(o.start&&!o.end){o.otherEvents.push(t),s=!0;break}}s||a.push(t)}for(let[t,s]of e)ht(t,s,a);for(let[t,s]of n)yt(t,s,a);return a}function ht(g,a,e){if(a.start&&e.push(a.start),a.contents.length>0){let n=a.contents.map(s=>s.delta).join(""),t={type:k.TEXT_MESSAGE_CONTENT,messageId:g,delta:n};e.push(t)}a.end&&e.push(a.end);for(let n of a.otherEvents)e.push(n)}function yt(g,a,e){if(a.start&&e.push(a.start),a.args.length>0){let n=a.args.map(s=>s.delta).join(""),t={type:k.TOOL_CALL_ARGS,toolCallId:g,delta:n};e.push(t)}a.end&&e.push(a.end);for(let n of a.otherEvents)e.push(n)}export*from"@ag-ui/core";export{W as AbstractAgent,st as HttpAgent,fe as compactEvents,nt as convertToLegacyEvents,z as defaultApplyEvents,tt as parseProtoStream,Z as parseSSEStream,ve as randomUUID,Q as runHttpRequest,y as structuredClone_,B as transformChunks,et as transformHttpEventStream,K as verifyEvents};
|
|
6
|
+
`),p=JSON.parse(i);a.next(p)}catch(i){a.error(i)}}return a.asObservable()};import{Subject as Bt}from"rxjs";import*as ut from"@ag-ui/proto";var tt=g=>{let a=new Bt,e=new Uint8Array(0);g.subscribe({next:t=>{if(t.type!=="headers"&&t.type==="data"&&t.data){let s=new Uint8Array(e.length+t.data.length);s.set(e,0),s.set(t.data,e.length),e=s,n()}},error:t=>a.error(t),complete:()=>{if(e.length>0)try{n()}catch(t){console.warn("Incomplete or invalid protocol buffer data at stream end")}a.complete()}});function n(){for(;e.length>=4;){let r=4+new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1);if(e.length<r)break;try{let o=e.slice(4,r),i=ut.decode(o);a.next(i),e=e.slice(r)}catch(o){let i=o instanceof Error?o.message:String(o);a.error(new Error(`Failed to decode protocol buffer message: ${i}`));return}}}return a.asObservable()};import*as Et from"@ag-ui/proto";import{EventType as zt}from"@ag-ui/core";var et=g=>{let a=new Xt,e=new $t,n=!1;return g.subscribe({next:t=>{e.next(t),t.type==="headers"&&!n?(n=!0,t.headers.get("content-type")===Et.AGUI_MEDIA_TYPE?tt(e).subscribe({next:r=>a.next(r),error:r=>a.error(r),complete:()=>a.complete()}):Z(e).subscribe({next:r=>{try{let o=jt.parse(r);a.next(o)}catch(o){a.error(o)}},error:r=>{if((r==null?void 0:r.name)==="AbortError"){a.next({type:zt.RUN_ERROR,rawEvent:r}),a.complete();return}return a.error(r)},complete:()=>a.complete()})):n||a.error(new Error("No headers event received before data events"))},error:t=>{e.error(t),a.error(t)},complete:()=>{e.complete()}}),a.asObservable()};import{mergeMap as se}from"rxjs/operators";import{applyPatch as ae}from"fast-json-patch";import{EventType as D}from"@ag-ui/core";import{z as f}from"zod";var C=f.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Kt=f.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Jt=f.object({type:f.literal(C.enum.TextMessageStart),messageId:f.string(),parentMessageId:f.string().optional(),role:f.string().optional()}),Vt=f.object({type:f.literal(C.enum.TextMessageContent),messageId:f.string(),content:f.string()}),Wt=f.object({type:f.literal(C.enum.TextMessageEnd),messageId:f.string()}),Yt=f.object({type:f.literal(C.enum.ActionExecutionStart),actionExecutionId:f.string(),actionName:f.string(),parentMessageId:f.string().optional()}),qt=f.object({type:f.literal(C.enum.ActionExecutionArgs),actionExecutionId:f.string(),args:f.string()}),Qt=f.object({type:f.literal(C.enum.ActionExecutionEnd),actionExecutionId:f.string()}),Zt=f.object({type:f.literal(C.enum.ActionExecutionResult),actionName:f.string(),actionExecutionId:f.string(),result:f.string()}),te=f.object({type:f.literal(C.enum.AgentStateMessage),threadId:f.string(),agentName:f.string(),nodeName:f.string(),runId:f.string(),active:f.boolean(),role:f.string(),state:f.string(),running:f.boolean()}),ee=f.object({type:f.literal(C.enum.MetaEvent),name:Kt,value:f.any()}),ne=f.object({type:f.literal(C.enum.RunError),message:f.string(),code:f.string().optional()}),Wn=f.discriminatedUnion("type",[Jt,Vt,Wt,Yt,qt,Qt,Zt,te,ee,ne]),Yn=f.object({id:f.string(),role:f.string(),content:f.string(),parentMessageId:f.string().optional()}),qn=f.object({id:f.string(),name:f.string(),arguments:f.any(),parentMessageId:f.string().optional()}),Qn=f.object({id:f.string(),result:f.any(),actionExecutionId:f.string(),actionName:f.string()});import oe from"untruncate-json";var re=g=>{if(typeof g=="string")return g;if(!Array.isArray(g))return;let a=g.filter(e=>e.type==="text").map(e=>e.text).filter(e=>e.length>0);if(a.length!==0)return a.join(`
|
|
7
|
+
`)},nt=(g,a,e)=>n=>{let t={},s=!0,r=!0,o="",i=null,p=null,x=[],T={},S=v=>{typeof v=="object"&&v!==null&&("messages"in v&&delete v.messages,t=v)};return n.pipe(se(v=>{switch(v.type){case D.TEXT_MESSAGE_START:{let c=v;return[{type:C.enum.TextMessageStart,messageId:c.messageId,role:c.role}]}case D.TEXT_MESSAGE_CONTENT:{let c=v;return[{type:C.enum.TextMessageContent,messageId:c.messageId,content:c.delta}]}case D.TEXT_MESSAGE_END:{let c=v;return[{type:C.enum.TextMessageEnd,messageId:c.messageId}]}case D.TOOL_CALL_START:{let c=v;return x.push({id:c.toolCallId,type:"function",function:{name:c.toolCallName,arguments:""}}),r=!0,T[c.toolCallId]=c.toolCallName,[{type:C.enum.ActionExecutionStart,actionExecutionId:c.toolCallId,actionName:c.toolCallName,parentMessageId:c.parentMessageId}]}case D.TOOL_CALL_ARGS:{let c=v,b=x.find(E=>E.id===c.toolCallId);if(!b)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${c.toolCallId}'`),[];b.function.arguments+=c.delta;let U=!1;if(p){let E=p.find(l=>l.tool==b.function.name);if(E)try{let l=JSON.parse(oe(b.function.arguments));E.tool_argument&&E.tool_argument in l?(S(G(N({},t),{[E.state_key]:l[E.tool_argument]})),U=!0):E.tool_argument||(S(G(N({},t),{[E.state_key]:l})),U=!0)}catch(l){}}return[{type:C.enum.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...U?[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}]:[]]}case D.TOOL_CALL_END:{let c=v;return[{type:C.enum.ActionExecutionEnd,actionExecutionId:c.toolCallId}]}case D.TOOL_CALL_RESULT:{let c=v;return[{type:C.enum.ActionExecutionResult,actionExecutionId:c.toolCallId,result:c.content,actionName:T[c.toolCallId]||"unknown"}]}case D.RAW:return[];case D.CUSTOM:{let c=v;switch(c.name){case"Exit":s=!1;break;case"PredictState":p=c.value;break}return[{type:C.enum.MetaEvent,name:c.name,value:c.value}]}case D.STATE_SNAPSHOT:return S(v.snapshot),[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}];case D.STATE_DELTA:{let b=ae(t,v.delta,!0,!1);return b?(S(b.newDocument),[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:r}]):[]}case D.MESSAGES_SNAPSHOT:return i=v.messages,[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(N(N({},t),i?{messages:i}:{})),active:!0}];case D.RUN_STARTED:return[];case D.RUN_FINISHED:return i&&(t.messages=i),Object.keys(t).length===0?[]:[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(N(N({},t),i?{messages:ie(i)}:{})),active:!1}];case D.RUN_ERROR:{let c=v;return[{type:C.enum.RunError,message:c.message,code:c.code}]}case D.STEP_STARTED:return o=v.stepName,x=[],p=null,[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!0}];case D.STEP_FINISHED:return x=[],p=null,[{type:C.enum.AgentStateMessage,threadId:g,agentName:e,nodeName:o,runId:a,running:s,role:"assistant",state:JSON.stringify(t),active:!1}];default:return[]}}))};function ie(g){var e;let a=[];for(let n of g)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let t=re(n.content);if(t){let s={id:n.id,role:n.role,content:t};a.push(s)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let s of n.toolCalls){let r={id:s.id,name:s.function.name,arguments:JSON.parse(s.function.arguments),parentMessageId:n.id};a.push(r)}}else if(n.role==="tool"){let t="unknown";for(let r of g)if(r.role==="assistant"&&((e=r.toolCalls)!=null&&e.length)){for(let o of r.toolCalls)if(o.id===n.toolCallId){t=o.function.name;break}}let s={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:t};a.push(s)}return a}import{v4 as V}from"uuid";import{compareVersions as de}from"compare-versions";import{catchError as dt,map as mt,tap as me}from"rxjs/operators";import{finalize as ft}from"rxjs/operators";import{takeUntil as St}from"rxjs/operators";import{pipe as Tt,from as fe,of as vt,EMPTY as Se,Subject as At}from"rxjs";import{lastValueFrom as ht}from"rxjs";import{mergeMap as le,finalize as ge}from"rxjs";import{EventType as M}from"@ag-ui/core";var B=g=>a=>{let e,n,t,s=()=>{if(!e||t!=="text")throw new Error("No text message to close");let i={type:M.TEXT_MESSAGE_END,messageId:e.messageId};return t=void 0,e=void 0,g&&console.debug("[TRANSFORM]: TEXT_MESSAGE_END",JSON.stringify(i)),i},r=()=>{if(!n||t!=="tool")throw new Error("No tool call to close");let i={type:M.TOOL_CALL_END,toolCallId:n.toolCallId};return t=void 0,n=void 0,g&&console.debug("[TRANSFORM]: TOOL_CALL_END",JSON.stringify(i)),i},o=()=>t==="text"?[s()]:t==="tool"?[r()]:[];return a.pipe(le(i=>{switch(i.type){case M.TEXT_MESSAGE_START:case M.TEXT_MESSAGE_CONTENT:case M.TEXT_MESSAGE_END:case M.TOOL_CALL_START:case M.TOOL_CALL_ARGS:case M.TOOL_CALL_END:case M.TOOL_CALL_RESULT:case M.STATE_SNAPSHOT:case M.STATE_DELTA:case M.MESSAGES_SNAPSHOT:case M.CUSTOM:case M.RUN_STARTED:case M.RUN_FINISHED:case M.RUN_ERROR:case M.STEP_STARTED:case M.STEP_FINISHED:case M.THINKING_START:case M.THINKING_END:case M.THINKING_TEXT_MESSAGE_START:case M.THINKING_TEXT_MESSAGE_CONTENT:case M.THINKING_TEXT_MESSAGE_END:return[...o(),i];case M.RAW:case M.ACTIVITY_SNAPSHOT:case M.ACTIVITY_DELTA:return[i];case M.TEXT_MESSAGE_CHUNK:let x=i,T=[];if((t!=="text"||x.messageId!==void 0&&x.messageId!==(e==null?void 0:e.messageId))&&T.push(...o()),t!=="text"){if(x.messageId===void 0)throw new Error("First TEXT_MESSAGE_CHUNK must have a messageId");e={messageId:x.messageId},t="text";let c={type:M.TEXT_MESSAGE_START,messageId:x.messageId,role:x.role||"assistant"};T.push(c),g&&console.debug("[TRANSFORM]: TEXT_MESSAGE_START",JSON.stringify(c))}if(x.delta!==void 0){let c={type:M.TEXT_MESSAGE_CONTENT,messageId:e.messageId,delta:x.delta};T.push(c),g&&console.debug("[TRANSFORM]: TEXT_MESSAGE_CONTENT",JSON.stringify(c))}return T;case M.TOOL_CALL_CHUNK:let S=i,v=[];if((t!=="tool"||S.toolCallId!==void 0&&S.toolCallId!==(n==null?void 0:n.toolCallId))&&v.push(...o()),t!=="tool"){if(S.toolCallId===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallId");if(S.toolCallName===void 0)throw new Error("First TOOL_CALL_CHUNK must have a toolCallName");n={toolCallId:S.toolCallId,toolCallName:S.toolCallName,parentMessageId:S.parentMessageId},t="tool";let c={type:M.TOOL_CALL_START,toolCallId:S.toolCallId,toolCallName:S.toolCallName,parentMessageId:S.parentMessageId};v.push(c),g&&console.debug("[TRANSFORM]: TOOL_CALL_START",JSON.stringify(c))}if(S.delta!==void 0){let c={type:M.TOOL_CALL_ARGS,toolCallId:n.toolCallId,delta:S.delta};v.push(c),g&&console.debug("[TRANSFORM]: TOOL_CALL_ARGS",JSON.stringify(c))}return v}let p=i.type;return[]}),ge(()=>{o()}))};import{AGUIConnectNotImplementedError as yt}from"@ag-ui/core";import{ReplaySubject as ce}from"rxjs";import{concatMap as ue}from"rxjs/operators";var j=class{runNext(a,e){return e.run(a).pipe(B(!1))}runNextWithState(a,e){let n=y(a.messages||[]),t=y(a.state||{}),s=new ce;return $(a,s,e,[]).subscribe(o=>{o.messages!==void 0&&(n=o.messages),o.state!==void 0&&(t=o.state)}),this.runNext(a,e).pipe(ue(async o=>(s.next(o),await new Promise(i=>setTimeout(i,0)),{event:o,messages:y(n),state:y(t)})))}},K=class extends j{constructor(e){super();this.fn=e}run(e,n){return this.fn(e,n)}};function Ee(g){let a=g.content;if(Array.isArray(a)){let e=a.filter(n=>typeof n=="object"&&n!==null&&"type"in n&&n.type==="text"&&typeof n.text=="string").map(n=>n.text).join("");return G(N({},g),{content:e})}return typeof a=="string"?g:G(N({},g),{content:""})}var J=class extends j{run(a,e){let r=a,{parentRunId:n}=r,t=it(r,["parentRunId"]),s=G(N({},t),{messages:t.messages.map(Ee)});return this.runNext(s,e)}};var pt={name:"@ag-ui/client",author:"Markus Ecker <markus.ecker@gmail.com>",version:"0.0.42-alpha.1",private:!1,publishConfig:{access:"public"},main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",sideEffects:!1,files:["dist/**","README.md"],scripts:{build:"tsup",dev:"tsup --watch",clean:"rm -rf dist .turbo node_modules",typecheck:"tsc --noEmit",test:"jest","link:global":"pnpm link --global","unlink:global":"pnpm unlink --global"},dependencies:{"@ag-ui/core":"workspace:*","@ag-ui/encoder":"workspace:*","@ag-ui/proto":"workspace:*","@types/uuid":"^10.0.0","compare-versions":"^6.1.1","fast-json-patch":"^3.1.1",rxjs:"7.8.1","untruncate-json":"^0.0.1",uuid:"^11.1.0",zod:"^3.22.4"},devDependencies:{"@types/jest":"^29.5.14","@types/node":"^20.11.19",jest:"^29.7.0","ts-jest":"^29.1.2",tsup:"^8.0.2",typescript:"^5.3.3"}};var W=class{constructor({agentId:a,description:e,threadId:n,initialMessages:t,initialState:s,debug:r}={}){this.debug=!1;this.subscribers=[];this.isRunning=!1;this.middlewares=[];this.agentId=a,this.description=e!=null?e:"",this.threadId=n!=null?n:V(),this.messages=y(t!=null?t:[]),this.state=y(s!=null?s:{}),this.debug=r!=null?r:!1,de(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new J)}get maxVersion(){return pt.version}subscribe(a){return this.subscribers.push(a),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==a)}}}use(...a){let e=a.map(n=>typeof n=="function"?new K(n):n);return this.middlewares.push(...e),this}async runAgent(a,e){var n;try{this.isRunning=!0,this.agentId=(n=this.agentId)!=null?n:V();let t=this.prepareRunAgentInput(a),s,r=new Set(this.messages.map(T=>T.id)),o=[{onRunFinishedEvent:T=>{s=T.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o),this.activeRunDetach$=new At;let i;this.activeRunCompletionPromise=new Promise(T=>{i=T});let p=Tt(()=>this.middlewares.length===0?this.run(t):this.middlewares.reduceRight((S,v)=>({run:c=>v.run(c,S)}),this).run(t),B(this.debug),z(this.debug),T=>T.pipe(St(this.activeRunDetach$)),T=>this.apply(t,T,o),T=>this.processApplyEvents(t,T,o),dt(T=>(this.isRunning=!1,this.onError(t,T,o))),ft(()=>{this.isRunning=!1,this.onFinalize(t,o),i==null||i(),i=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}));await ht(p(vt(null)));let x=y(this.messages).filter(T=>!r.has(T.id));return{result:s,newMessages:x}}finally{this.isRunning=!1}}connect(a){throw new yt}async connectAgent(a,e){var n;try{this.isRunning=!0,this.agentId=(n=this.agentId)!=null?n:V();let t=this.prepareRunAgentInput(a),s,r=new Set(this.messages.map(T=>T.id)),o=[{onRunFinishedEvent:T=>{s=T.result}},...this.subscribers,e!=null?e:{}];await this.onInitialize(t,o),this.activeRunDetach$=new At;let i;this.activeRunCompletionPromise=new Promise(T=>{i=T});let p=Tt(()=>this.connect(t),B(this.debug),z(this.debug),T=>T.pipe(St(this.activeRunDetach$)),T=>this.apply(t,T,o),T=>this.processApplyEvents(t,T,o),dt(T=>(this.isRunning=!1,T instanceof yt?Se:this.onError(t,T,o))),ft(()=>{this.isRunning=!1,this.onFinalize(t,o),i==null||i(),i=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}));await ht(p(vt(null)));let x=y(this.messages).filter(T=>!r.has(T.id));return{result:s,newMessages:x}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){var e,n;if(!this.activeRunDetach$)return;let a=(e=this.activeRunCompletionPromise)!=null?e:Promise.resolve();this.activeRunDetach$.next(),(n=this.activeRunDetach$)==null||n.complete(),await a}apply(a,e,n){return $(a,e,this,n)}processApplyEvents(a,e,n){return e.pipe(me(t=>{t.messages&&(this.messages=t.messages,n.forEach(s=>{var r;(r=s.onMessagesChanged)==null||r.call(s,{messages:this.messages,state:this.state,agent:this,input:a})})),t.state&&(this.state=t.state,n.forEach(s=>{var r;(r=s.onStateChanged)==null||r.call(s,{state:this.state,messages:this.messages,agent:this,input:a})}))}))}prepareRunAgentInput(a){var t,s,r;let n=y(this.messages).filter(o=>o.role!=="activity");return{threadId:this.threadId,runId:(a==null?void 0:a.runId)||V(),tools:y((t=a==null?void 0:a.tools)!=null?t:[]),context:y((s=a==null?void 0:a.context)!=null?s:[]),forwardedProps:y((r=a==null?void 0:a.forwardedProps)!=null?r:{}),state:y(this.state),messages:n}}async onInitialize(a,e){let n=await I(e,this.messages,this.state,(t,s,r)=>{var o;return(o=t.onRunInitialized)==null?void 0:o.call(t,{messages:s,state:r,agent:this,input:a})});(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,a.messages=n.messages,e.forEach(t=>{var s;(s=t.onMessagesChanged)==null||s.call(t,{messages:this.messages,state:this.state,agent:this,input:a})})),n.state&&(this.state=n.state,a.state=n.state,e.forEach(t=>{var s;(s=t.onStateChanged)==null||s.call(t,{state:this.state,messages:this.messages,agent:this,input:a})})))}onError(a,e,n){return fe(I(n,this.messages,this.state,(t,s,r)=>{var o;return(o=t.onRunFailed)==null?void 0:o.call(t,{error:e,messages:s,state:r,agent:this,input:a})})).pipe(mt(t=>{let s=t;if((s.messages!==void 0||s.state!==void 0)&&(s.messages!==void 0&&(this.messages=s.messages,n.forEach(r=>{var o;(o=r.onMessagesChanged)==null||o.call(r,{messages:this.messages,state:this.state,agent:this,input:a})})),s.state!==void 0&&(this.state=s.state,n.forEach(r=>{var o;(o=r.onStateChanged)==null||o.call(r,{state:this.state,messages:this.messages,agent:this,input:a})}))),s.stopPropagation!==!0)throw console.error("Agent execution failed:",e),e;return{}}))}async onFinalize(a,e){let n=await I(e,this.messages,this.state,(t,s,r)=>{var o;return(o=t.onRunFinalized)==null?void 0:o.call(t,{messages:s,state:r,agent:this,input:a})});(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(t=>{var s;(s=t.onMessagesChanged)==null||s.call(t,{messages:this.messages,state:this.state,agent:this,input:a})})),n.state!==void 0&&(this.state=n.state,e.forEach(t=>{var s;(s=t.onStateChanged)==null||s.call(t,{state:this.state,messages:this.messages,agent:this,input:a})})))}clone(){let a=Object.create(Object.getPrototypeOf(this));return a.agentId=this.agentId,a.description=this.description,a.threadId=this.threadId,a.messages=y(this.messages),a.state=y(this.state),a.debug=this.debug,a.isRunning=this.isRunning,a.subscribers=[...this.subscribers],a.middlewares=[...this.middlewares],a}addMessage(a){this.messages.push(a),(async()=>{var e,n,t;for(let s of this.subscribers)await((e=s.onNewMessage)==null?void 0:e.call(s,{message:a,messages:this.messages,state:this.state,agent:this}));if(a.role==="assistant"&&a.toolCalls)for(let s of a.toolCalls)for(let r of this.subscribers)await((n=r.onNewToolCall)==null?void 0:n.call(r,{toolCall:s,messages:this.messages,state:this.state,agent:this}));for(let s of this.subscribers)await((t=s.onMessagesChanged)==null?void 0:t.call(s,{messages:this.messages,state:this.state,agent:this}))})()}addMessages(a){this.messages.push(...a),(async()=>{var e,n,t;for(let s of a){for(let r of this.subscribers)await((e=r.onNewMessage)==null?void 0:e.call(r,{message:s,messages:this.messages,state:this.state,agent:this}));if(s.role==="assistant"&&s.toolCalls)for(let r of s.toolCalls)for(let o of this.subscribers)await((n=o.onNewToolCall)==null?void 0:n.call(o,{toolCall:r,messages:this.messages,state:this.state,agent:this}))}for(let s of this.subscribers)await((t=s.onMessagesChanged)==null?void 0:t.call(s,{messages:this.messages,state:this.state,agent:this}))})()}setMessages(a){this.messages=y(a),(async()=>{var e;for(let n of this.subscribers)await((e=n.onMessagesChanged)==null?void 0:e.call(n,{messages:this.messages,state:this.state,agent:this}))})()}setState(a){this.state=y(a),(async()=>{var e;for(let n of this.subscribers)await((e=n.onStateChanged)==null?void 0:e.call(n,{messages:this.messages,state:this.state,agent:this}))})()}legacy_to_be_removed_runAgentBridged(a){var t;this.agentId=(t=this.agentId)!=null?t:V();let e=this.prepareRunAgentInput(a);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((r,o)=>({run:i=>o.run(i,r)}),this).run(e)).pipe(B(this.debug),z(this.debug),nt(this.threadId,e.runId,this.agentId),s=>s.pipe(mt(r=>(this.debug&&console.debug("[LEGACY]:",JSON.stringify(r)),r))))}};var st=class extends W{constructor(e){var n;super(e);this.abortController=new AbortController;this.url=e.url,this.headers=y((n=e.headers)!=null?n:{})}requestInit(e){return{method:"POST",headers:G(N({},this.headers),{"Content-Type":"application/json",Accept:"text/event-stream"}),body:JSON.stringify(e),signal:this.abortController.signal}}runAgent(e,n){var t;return this.abortController=(t=e==null?void 0:e.abortController)!=null?t:new AbortController,super.runAgent(e,n)}abortRun(){this.abortController.abort(),super.abortRun()}run(e){let n=Q(this.url,this.requestInit(e));return et(n)}clone(){var s;let e=super.clone();e.url=this.url,e.headers=y((s=this.headers)!=null?s:{});let n=new AbortController,t=this.abortController.signal;return t.aborted&&n.abort(t.reason),e.abortController=n,e}};import{EventType as k}from"@ag-ui/core";function Te(g){let a=[],e=new Map,n=new Map;for(let t of g)if(t.type===k.TEXT_MESSAGE_START){let s=t,r=s.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]});let o=e.get(r);o.start=s}else if(t.type===k.TEXT_MESSAGE_CONTENT){let s=t,r=s.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]}),e.get(r).contents.push(s)}else if(t.type===k.TEXT_MESSAGE_END){let s=t,r=s.messageId;e.has(r)||e.set(r,{contents:[],otherEvents:[]});let o=e.get(r);o.end=s,Mt(r,o,a),e.delete(r)}else if(t.type===k.TOOL_CALL_START){let s=t,r=s.toolCallId;n.has(r)||n.set(r,{args:[],otherEvents:[]});let o=n.get(r);o.start=s}else if(t.type===k.TOOL_CALL_ARGS){let s=t,r=s.toolCallId;n.has(r)||n.set(r,{args:[],otherEvents:[]}),n.get(r).args.push(s)}else if(t.type===k.TOOL_CALL_END){let s=t,r=s.toolCallId;n.has(r)||n.set(r,{args:[],otherEvents:[]});let o=n.get(r);o.end=s,Ct(r,o,a),n.delete(r)}else{let s=!1;for(let[r,o]of e)if(o.start&&!o.end){o.otherEvents.push(t),s=!0;break}if(!s){for(let[r,o]of n)if(o.start&&!o.end){o.otherEvents.push(t),s=!0;break}}s||a.push(t)}for(let[t,s]of e)Mt(t,s,a);for(let[t,s]of n)Ct(t,s,a);return a}function Mt(g,a,e){if(a.start&&e.push(a.start),a.contents.length>0){let n=a.contents.map(s=>s.delta).join(""),t={type:k.TEXT_MESSAGE_CONTENT,messageId:g,delta:n};e.push(t)}a.end&&e.push(a.end);for(let n of a.otherEvents)e.push(n)}function Ct(g,a,e){if(a.start&&e.push(a.start),a.args.length>0){let n=a.args.map(s=>s.delta).join(""),t={type:k.TOOL_CALL_ARGS,toolCallId:g,delta:n};e.push(t)}a.end&&e.push(a.end);for(let n of a.otherEvents)e.push(n)}export*from"@ag-ui/core";export{W as AbstractAgent,st as HttpAgent,Te as compactEvents,nt as convertToLegacyEvents,$ as defaultApplyEvents,tt as parseProtoStream,Z as parseSSEStream,ye as randomUUID,Q as runHttpRequest,y as structuredClone_,B as transformChunks,et as transformHttpEventStream,z as verifyEvents};
|
|
8
8
|
//# sourceMappingURL=index.mjs.map
|