@ag-ui/langgraph 0.0.34 → 0.0.35

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.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import{AbstractAgent as e,EventType as t,HttpAgent as n,randomUUID as r}from"@ag-ui/client";import{Observable as i}from"rxjs";import{Client as a}from"@langchain/langgraph-sdk";let o=function(e){return e.OnChainStart=`on_chain_start`,e.OnChainStream=`on_chain_stream`,e.OnChainEnd=`on_chain_end`,e.OnChatModelStart=`on_chat_model_start`,e.OnChatModelStream=`on_chat_model_stream`,e.OnChatModelEnd=`on_chat_model_end`,e.OnToolStart=`on_tool_start`,e.OnToolEnd=`on_tool_end`,e.OnToolError=`on_tool_error`,e.OnCustomEvent=`on_custom_event`,e.OnInterrupt=`on_interrupt`,e}({}),s=function(e){return e.ManuallyEmitMessage=`manually_emit_message`,e.ManuallyEmitToolCall=`manually_emit_tool_call`,e.ManuallyEmitState=`manually_emit_state`,e.Exit=`exit`,e}({});const c=[`messages`,`tools`];function l(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}function u({mode:e,state:t,schemaKeys:n}){let r=e===`start`?t:null;return r&&n?.input&&(r=l(r,[...c,...n.input])),r}const d=new Set([`image`,`audio`,`video`,`document`]);function f(e){return e.type===`data`?`data:${e.mimeType};base64,${e.value}`:e.type===`url`?e.value:null}function p(e){let t=[];for(let n of e)if(n.type===`text`&&n.text)t.push({type:`text`,text:n.text});else if(n.type===`image_url`){let e=typeof n.image_url==`string`?n.image_url:n.image_url?.url;if(!e)continue;if(e.startsWith(`data:`)){let[n,r]=e.split(`,`,2),i=n.includes(`:`)?n.split(`:`)[1].split(`;`)[0]:`image/png`;t.push({type:`image`,source:{type:`data`,value:r||``,mimeType:i}})}else t.push({type:`image`,source:{type:`url`,value:e}})}return t}function m(e){let t=[];for(let n of e)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(d.has(n.type)){let e=f(n.source);e?t.push({type:`image_url`,image_url:{url:e}}):console.warn(`[convertAguiMultimodalToLangchain] Dropping ${n.type} content: source could not be converted to URL`)}else if(n.type===`binary`){let e;if(n.url)e=n.url;else if(n.data)e=`data:${n.mimeType};base64,${n.data}`;else if(n.id)e=n.id;else{console.warn(`[convertAguiMultimodalToLangchain] Dropping BinaryInputContent: no url, data, or id provided`);continue}t.push({type:`image_url`,image_url:{url:e}})}return t}function h(e){return e.map(e=>{switch(e.type){case`human`:let t;return t=Array.isArray(e.content)?p(e.content):_(b(e.content)),{id:e.id,role:`user`,content:t};case`generic`:case`ai`:let n=b(e.content);return{id:e.id,role:`assistant`,content:n?_(n):``,toolCalls:e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.args)}}))};case`system`:return{id:e.id,role:`system`,content:_(b(e.content))};case`tool`:return{id:e.id,role:`tool`,content:_(b(e.content)),toolCallId:e.tool_call_id};default:throw Error(`message type returned from LangGraph is not supported.`)}})}function g(e){return e.filter(e=>e.role!==`reasoning`&&e.role!==`developer`).map((e,t)=>{switch(e.role){case`user`:let t;return t=typeof e.content==`string`?e.content:Array.isArray(e.content)?m(e.content):String(e.content),{id:e.id,role:e.role,content:t,type:`human`};case`assistant`:return{id:e.id,type:`ai`,role:e.role,content:e.content??``,tool_calls:(e.toolCalls??[]).map(e=>({id:e.id,name:e.function.name,args:JSON.parse(e.function.arguments),type:`tool_call`}))};case`system`:return{id:e.id,role:e.role,content:e.content,type:`system`};case`tool`:return{content:e.content,role:e.role,type:e.role,tool_call_id:e.toolCallId,id:e.id};default:throw console.error(`Message role ${e.role} is not implemented`),Error(`message role is not supported.`)}})}function _(e){return typeof e==`string`?e:JSON.stringify(e)}function v(e){let t=e.chunk?.content;if(t&&Array.isArray(t)&&t.length&&t[0]){let e=t[0];if(e.type===`thinking`&&e.thinking){let t={text:e.thinking,type:`text`,index:e.index??0};return e.signature&&(t.signature=e.signature),t}if(e.type===`reasoning`&&e.reasoning)return{text:e.reasoning,type:`text`,index:e.index??0};if(e.type===`reasoning`&&e.summary?.[0]?.text)return{type:`text`,text:e.summary[0].text,index:e.summary[0].index??0};if(e.type===`reasoning_content`&&e.reasoning_content?.text)return{type:`text`,text:e.reasoning_content.text,index:e.reasoning_content.index??0}}if(e.chunk?.additional_kwargs?.reasoning?.summary?.[0]){let t=e.chunk.additional_kwargs.reasoning.summary[0];return!t||!t.text?null:{type:`text`,text:t.text,index:t.index??0}}return null}function y(e){let t=e.chunk?.content;return!t||!Array.isArray(t)||!t.length||!t[0]?null:t[0].type===`redacted_thinking`&&t[0].data?t[0].data:null}function b(e){return e?typeof e==`string`?e:Array.isArray(e)&&e.length?e.find(e=>e.type===`text`)?.text??null:null:null}const x=`root`;var S=class extends e{constructor(e){super(e),this.headers={},this.emittedToolCallStartIds=new Set,this.subgraphs=new Set,this.currentSubgraph=x,this.cancelRequested=!1,this.cancelSent=!1,this.eventsStreamActive=!1,this.constantSchemaKeys=c,this.config=e,this.messagesInProcess={},this.agentName=e.agentName,this.graphId=e.graphId,this.assistantConfig=e.assistantConfig,this.reasoningProcess=null;let t=this,n=e.headerFactory??(()=>t.headers);e?.client&&e.headerFactory&&console.debug("[@ag-ui/langgraph] Both `config.client` and `config.headerFactory` were set. Custom clients bypass the adapter's onRequest hook — `headerFactory` will not be invoked. Either omit `client` to enable adapter-managed header forwarding, or wire headers into your custom client directly."),this.client=e?.client??new a({apiUrl:e.deploymentUrl,apiKey:e.langsmithApiKey,defaultHeaders:{...e.propertyHeaders??{}},onRequest:(e,t)=>{let r=n();return!r||Object.keys(r).length===0?t:{...t,headers:{...t.headers,...r}}}})}clone(){let e=Object.assign(super.clone(),{config:this.config,messagesInProcess:structuredClone(this.messagesInProcess),agentName:this.agentName,graphId:this.graphId,assistantConfig:this.assistantConfig,reasoningProcess:this.reasoningProcess?structuredClone(this.reasoningProcess):null,constantSchemaKeys:[...this.constantSchemaKeys],headers:{...this.headers},client:this.client,assistant:this.assistant,activeRun:this.activeRun?structuredClone(this.activeRun):void 0,cancelRequested:this.cancelRequested,cancelSent:this.cancelSent,subgraphs:this.subgraphs?new Set(this.subgraphs):new Set,currentSubgraph:x});if(!this.config.client){let t=this.config.headerFactory??(()=>e.headers);e.client=new a({apiUrl:this.config.deploymentUrl,apiKey:this.config.langsmithApiKey,defaultHeaders:{...this.config.propertyHeaders??{}},onRequest:(e,n)=>{let r=t();return!r||Object.keys(r).length===0?n:{...n,headers:{...n.headers,...r}}}})}return e}dispatchEvent(e){return this.subscriber.next(e),!0}run(e){return new i(t=>(this.runAgentStream(e,t).catch(e=>{console.error(`[LangGraph] runAgentStream error:`,e),t.closed||t.error(e)}),()=>{}))}async runAgentStream(e,t){this.activeRun={id:e.runId,threadId:e.threadId,hasFunctionStreaming:!1,modelMadeToolCall:!1},this.cancelRequested=!1,this.cancelSent=!1,this.eventsStreamActive=!1,this.subscriber=t,this.assistant||=await this.getAssistant();let n=e.threadId??r(),i=e.forwardedProps?.streamMode??[`events`,`values`,`updates`,`messages-tuple`],a=await this.prepareStream({...e,threadId:n},i);if(!a)return t.error(`No stream to regenerate`);await this.handleStreamEvents(a,n,t,e,Array.isArray(i)?i:[i])}async prepareRegenerateStream(e,t){let{threadId:n,messageCheckpoint:r,forwardedProps:i}=e,a=await this.getCheckpointByMessage(r.id,n);if(this.assistant||=await this.getAssistant(),!a)return this.subscriber.error(`No checkpoint found for message`);let o=await this.client.threads.updateState(n,{values:this.langGraphDefaultMergeState(a.values,[],e),checkpointId:a.checkpoint.checkpoint_id,asNode:a.next?.[0]??`__start__`}),s,c=[this.assistantConfig,i?.config].filter(Boolean);c.length&&(s=await this.mergeConfigs({configs:c,assistant:this.assistant,schemaKeys:this.activeRun.schemaKeys??null}));let l={...e.forwardedProps??{},input:this.langGraphDefaultMergeState(a.values,[r],e),checkpointId:o.checkpoint.checkpoint_id,streamMode:t,config:s};return{streamResponse:this.client.runs.stream(n,this.assistant.assistant_id,l),state:a,streamMode:t}}async prepareStream(e,n){let{threadId:i,state:a,messages:s,tools:c,context:l,forwardedProps:d}=e;this.activeRun.manuallyEmittedState=null;let f=d?.nodeName,p=i??r();this.assistant||=await this.getAssistant();let m=await this.getOrCreateThread(p,d?.threadMetadata);this.activeRun.threadId=m.thread_id;let h=await this.client.threads.getState(m.thread_id)??{values:{}},_=h.values.messages??[],v=g(s),y=this.langGraphDefaultMergeState({...a,messages:_},v,e),b={...h,values:{...y,messages:[..._,...y.messages??[]]}},x=b.values;if(this.activeRun.schemaKeys=await this.getSchemaKeys(),_.filter(e=>e.type!==`system`).length>s.filter(e=>e.role!==`system`).length){let t=null;for(let e=s.length-1;e>=0;e--)if(s[e].role===`user`){t=g([s[e]])[0];break}return t?this.prepareRegenerateStream({...e,messageCheckpoint:t},n):this.subscriber.error(`No user message found in messages to regenerate`)}this.activeRun.graphInfo=await this.client.assistants.getGraph(this.assistant.assistant_id);let S=!d?.command?.resume&&p&&this.activeRun.nodeName!=`__end__`&&this.activeRun.nodeName?`continue`:`start`;if(S===`continue`){let e=this.activeRun.graphInfo.edges.find(e=>e.target===this.activeRun.nodeName);await this.client.threads.updateState(p,{values:a,asNode:e?.source})}let C=u({mode:S,state:x,schemaKeys:this.activeRun.schemaKeys}),w,T=[this.assistantConfig,d?.config].filter(Boolean);T.length&&(w=await this.mergeConfigs({configs:T,assistant:this.assistant,schemaKeys:this.activeRun.schemaKeys}));let{command:E,...D}=d;if(E?.resume&&typeof E.resume==`string`)try{E.resume=JSON.parse(E.resume)}catch{}let O=new Set(this.activeRun.schemaKeys?.context??[]),k=w?.configurable??{},A={},j={};for(let[e,t]of Object.entries(k))O.has(e)?A[e]=t:j[e]=t;let M={...A},N=w?{...w,configurable:Object.keys(j).length>0?j:void 0}:void 0,P=Object.keys(M).length>0,F=N?.configurable!=null&&Object.keys(N.configurable).length>0;if(P&&F){let e=Object.keys(j);e.length>0&&console.warn(`[@ag-ui/langgraph] Dropping configurable keys not in context_schema: [${e.join(`, `)}]. Use context instead.`)}let I=(()=>{if(!N)return;if(F&&!P)return N;let{configurable:e,...t}=N;return Object.keys(t).length>0?t:void 0})(),L=Object.fromEntries(Object.entries(this.headers??{}).filter(([e])=>e.toLowerCase().startsWith(`x-`))),R=Object.keys(L).length>0?{...I??{},configurable:{...I?.configurable??{},copilotkit_forwarded_headers:L}}:I,z={...D,command:E,streamMode:n,input:C,config:R,...P?{context:M}:{}},B=(h.tasks??[]).flatMap(e=>e.interrupts??[]);return B?.length&&!d?.command?.resume?(this.dispatchEvent({type:t.RUN_STARTED,threadId:p,runId:e.runId}),this.handleNodeChange(f),B.forEach(e=>{this.dispatchEvent({type:t.CUSTOM,name:o.OnInterrupt,value:typeof e.value==`string`?e.value:JSON.stringify(e.value),rawEvent:e})}),this.dispatchEvent({type:t.RUN_FINISHED,threadId:p,runId:e.runId}),this.subscriber.complete()):{streamResponse:this.client.runs.stream(p,this.assistant.assistant_id,z),state:b}}async handleStreamEvents(e,n,r,i,a){let{forwardedProps:c}=i,l=c?.nodeName;this.subscriber=r;let u=!1;if(!e)return;this.emittedToolCallStartIds=new Set;let{streamResponse:d,state:f}=e;this.activeRun.prevNodeName=null;let p={},m=f;try{this.dispatchEvent({type:t.RUN_STARTED,threadId:n,runId:this.activeRun.id}),this.handleNodeChange(l);for await(let e of d){if(this.cancelRequested&&!this.cancelSent&&this.activeRun?.threadId&&this.activeRun?.id){try{await this.client.runs.cancel(this.activeRun.threadId,this.activeRun.id)}catch{}finally{this.cancelSent=!0}try{await d?.return?.()}catch{}break}let r=i.forwardedProps?.streamSubgraphs??!0,c=r&&(e.event.startsWith(`events`)||e.event.startsWith(`values`)),l=e.event===`messages`&&(Array.isArray(a)?a:[a]).includes(`messages-tuple`);if(!a.includes(e.event)&&!c&&!l&&e.event!==`error`)continue;let h=e;if(e.event===`error`){this.dispatchEvent({type:t.RUN_ERROR,message:e.data.message,rawEvent:e});break}if(e.event===`updates`)continue;if(e.event===`values`){p={...p,...h.data};continue}else if(r&&h.event.startsWith(`values|`)){p={...p,...h.data};continue}let g=h.data,_=g.metadata??{},v=_.langgraph_node,y=g.event,b=_.langgraph_checkpoint_ns??``,S=b.split(`|`)[0].split(`:`)[0];b.includes(`|`)&&S&&this.subgraphs.add(S);let C=S&&this.subgraphs.has(S)?S:x;if(C!==this.currentSubgraph&&(this.currentSubgraph=C,await this.getStateAndMessagesSnapshots(n)),_.run_id&&(this.activeRun.id=_.run_id,this.activeRun.serverRunIdKnown=!0,this.cancelRequested&&!this.cancelSent&&this.activeRun?.threadId))try{await this.client.runs.cancel(this.activeRun.threadId,this.activeRun.id)}catch{}finally{this.cancelSent=!0}if(v&&v!==this.activeRun.nodeName&&this.handleNodeChange(v),u||=y===o.OnCustomEvent&&g.name===s.Exit,y===o.OnChainEnd&&g.data?.output!=null){let e=g.data.output;if(typeof e==`object`&&!Array.isArray(e))p={...p,...e};else if(Array.isArray(e))for(let t of e)t&&typeof t==`object`&&t.lg_name===`Command`&&t.update&&typeof t.update==`object`&&(p={...p,...t.update})}if(y===o.OnChainEnd&&this.activeRun.nodeName===v&&(this.activeRun.exitingNode=!0),this.activeRun.exitingNode&&(this.activeRun.manuallyEmittedState&&typeof this.activeRun.manuallyEmittedState==`object`&&(p={...p,...this.activeRun.manuallyEmittedState}),this.activeRun.manuallyEmittedState=null),this.activeRun.graphInfo?.nodes.some(e=>e.id===v)&&this.handleNodeChange(v),m.values=this.activeRun.manuallyEmittedState??p,!this.activeRun.nodeName)continue;let w=JSON.stringify(m)!==JSON.stringify(f);!this.activeRun.modelMadeToolCall&&(w||this.activeRun.prevNodeName!=this.activeRun.nodeName||this.activeRun.exitingNode)&&!this.getMessageInProgress(this.activeRun.id)&&(f=m,this.activeRun.prevNodeName=this.activeRun.nodeName,this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(f),rawEvent:h})),this.dispatchEvent({type:t.RAW,event:g}),this.handleSingleEvent(g)}f=await this.client.threads.getState(n);let e=(f.tasks??[]).flatMap(e=>e.interrupts??[]),c=f.next.length===0,h=f.metadata?.writes??{},g=this.activeRun.nodeName;return e?.length||(g=c?`__end__`:f.next[0]??Object.keys(h)[0]),e.forEach(e=>{this.dispatchEvent({type:t.CUSTOM,name:o.OnInterrupt,value:typeof e.value==`string`?e.value:JSON.stringify(e.value),rawEvent:e})}),this.handleNodeChange(g),this.handleNodeChange(void 0),await this.getStateAndMessagesSnapshots(n),this.dispatchEvent({type:t.RUN_FINISHED,threadId:n,runId:this.activeRun.id}),this.cancelRequested=!1,this.cancelSent=!1,this.activeRun=void 0,r.complete()}catch(e){return r.error(e)}}async getStateAndMessagesSnapshots(e){let n=await this.client.threads.getState(e);this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(n)});let r=n.values.messages??[];this.dispatchEvent({type:t.MESSAGES_SNAPSHOT,messages:h(r)})}handleSingleEvent(e){if(Array.isArray(e)){this.eventsStreamActive||this.handleMessagesTupleEvent(e);return}switch(e.event===o.OnChatModelStream&&(this.eventsStreamActive=!0),e.event){case o.OnChatModelStream:let n=e.metadata[`emit-messages`]??!0,i=e.metadata[`emit-tool-calls`]??!0;if(e.data.chunk.response_metadata.finish_reason)return;let a=this.getMessageInProgress(this.activeRun.id),c=!!a?.id,l=e.data.chunk.tool_call_chunks?.[0],u=e.metadata.predict_state?.some(e=>e.tool===l?.name),d=!c&&l?.name,f=c&&a?.toolCallId&&l?.args,p=c&&a?.toolCallId&&!l;(p||f||d)&&(this.activeRun.hasFunctionStreaming=!0);let m=v(e.data),h=y(e.data),g=b(e.data.chunk.content),_=!!(!l&&g),x=c&&!a?.toolCallId&&!_;if(m){this.handleReasoningEvent(m);break}if(h&&this.reasoningProcess){this.dispatchEvent({type:t.REASONING_ENCRYPTED_VALUE,subtype:`message`,entityId:this.reasoningProcess.messageId,encryptedValue:h});break}if(!m&&this.reasoningProcess&&(this.reasoningProcess.signature&&this.dispatchEvent({type:t.REASONING_ENCRYPTED_VALUE,subtype:`message`,entityId:this.reasoningProcess.messageId,encryptedValue:this.reasoningProcess.signature}),this.dispatchEvent({type:t.REASONING_MESSAGE_END,messageId:this.reasoningProcess.messageId}),this.dispatchEvent({type:t.REASONING_END,messageId:this.reasoningProcess.messageId}),this.reasoningProcess=null),u&&(this.activeRun.modelMadeToolCall=!0,this.dispatchEvent({type:t.CUSTOM,name:`PredictState`,value:e.metadata.predict_state})),p){this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:a?.toolCallId,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(x){this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:a.id,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(d&&i){this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:l.id,toolCallName:l.name,parentMessageId:e.data.chunk.id,rawEvent:e})&&(this.emittedToolCallStartIds.add(l.id),this.setMessageInProgress(this.activeRun.id,{id:e.data.chunk.id,toolCallId:l.id,toolCallName:l.name}));break}if(f&&i){this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:a?.toolCallId,delta:l.args,rawEvent:e});break}if(_&&n){a||=(this.dispatchEvent({type:t.TEXT_MESSAGE_START,role:`assistant`,messageId:e.data.chunk.id,rawEvent:e}),this.setMessageInProgress(this.activeRun.id,{id:e.data.chunk.id,toolCallId:null,toolCallName:null}),this.getMessageInProgress(this.activeRun.id)),this.dispatchEvent({type:t.TEXT_MESSAGE_CONTENT,messageId:a.id,delta:g,rawEvent:e});break}break;case o.OnChatModelEnd:if(this.getMessageInProgress(this.activeRun.id)?.toolCallId){this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:this.getMessageInProgress(this.activeRun.id).toolCallId,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(this.getMessageInProgress(this.activeRun.id)?.id){this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:this.getMessageInProgress(this.activeRun.id).id,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}break;case o.OnCustomEvent:if(e.name===s.ManuallyEmitMessage){this.dispatchEvent({type:t.TEXT_MESSAGE_START,role:`assistant`,messageId:e.data.message_id,rawEvent:e}),this.dispatchEvent({type:t.TEXT_MESSAGE_CONTENT,messageId:e.data.message_id,delta:e.data.message,rawEvent:e}),this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:e.data.message_id,rawEvent:e});break}if(e.name===s.ManuallyEmitToolCall){this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:e.data.id,toolCallName:e.data.name,parentMessageId:e.data.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:e.data.id,delta:e.data.args,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:e.data.id,rawEvent:e});break}e.name===s.ManuallyEmitState&&(this.activeRun.manuallyEmittedState=e.data,this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot({values:this.activeRun.manuallyEmittedState}),rawEvent:e})),this.dispatchEvent({type:t.CUSTOM,name:e.name,value:e.data,rawEvent:e});break;case o.OnToolEnd:let S=e.data?.output;if(S&&!S.tool_call_id&&S.update?.messages?.find(e=>e.type===`tool`)&&(S=S.update?.messages?.find(e=>e.type===`tool`)),S&&S.update?.messages?.length){S.update?.messages.filter(e=>e.type===`tool`).forEach(n=>{this.activeRun.hasFunctionStreaming||(this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:n.tool_call_id,toolCallName:n.name??``,parentMessageId:n.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:n.tool_call_id,delta:JSON.stringify(e.data.input),rawEvent:e})),this.dispatchEvent({type:t.TOOL_CALL_RESULT,toolCallId:n.tool_call_id,content:typeof n?.content==`string`?n?.content:JSON.stringify(n?.content),messageId:r(),rawEvent:e,role:`tool`})}),this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break}this.emittedToolCallStartIds.has(S.tool_call_id)||(this.emittedToolCallStartIds.add(S.tool_call_id),this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:S.tool_call_id,toolCallName:S.name,parentMessageId:S.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:S.tool_call_id,delta:JSON.stringify(e.data.input),rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:S.tool_call_id,rawEvent:e}));let C=Array.isArray(S.content)?S.content.map(e=>typeof e==`string`?e:e.type===`text`?e.text:JSON.stringify(e)).join(``):S.content;this.dispatchEvent({type:t.TOOL_CALL_RESULT,toolCallId:S.tool_call_id,content:C,messageId:r(),role:`tool`,rawEvent:e}),this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break;case o.OnToolError:this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break}}handleMessagesTupleEvent(e){let n=e[0];if(n.type&&n.type!==`AIMessageChunk`)return;let r=typeof n.content==`string`?n.content:Array.isArray(n.content)?n.content.find(e=>e.type===`text`)?.text:null,i=n.tool_call_chunks,a=n.response_metadata?.finish_reason===`stop`,o=this.getMessageInProgress(this.activeRun.id);if(i?.length>0){let e=i[0];e.name?(o?.id&&!o?.toolCallId&&(this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:o.id}),this.messagesInProcess[this.activeRun.id]=null),this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:e.id||n.id,toolCallName:e.name,parentMessageId:n.id}),this.setMessageInProgress(this.activeRun.id,{id:n.id,toolCallId:e.id||n.id,toolCallName:e.name}),this.activeRun.hasFunctionStreaming=!0):e.args&&o?.toolCallId&&this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:e.args});return}if(a){o?.toolCallId?this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:o.toolCallId}):o?.id&&this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:o.id}),this.messagesInProcess[this.activeRun.id]=null;return}!r&&!i?.length||r&&(o||(this.dispatchEvent({type:t.TEXT_MESSAGE_START,role:`assistant`,messageId:n.id}),this.setMessageInProgress(this.activeRun.id,{id:n.id,toolCallId:null,toolCallName:null})),this.dispatchEvent({type:t.TEXT_MESSAGE_CONTENT,messageId:(this.getMessageInProgress(this.activeRun.id)??{id:n.id}).id,delta:r}))}abortRun(){this.cancelRequested=!0;let e=this.activeRun?.threadId,t=this.activeRun?.id;e&&t&&!this.cancelSent&&this.client.runs.cancel(e,t).then(()=>{this.cancelSent=!0}).catch(()=>{}),super.abortRun()}handleReasoningEvent(e){if(!e||!e.type||!e.text)return;let n=e.index;if(this.reasoningProcess?.index&&this.reasoningProcess.index!==n&&(this.reasoningProcess.type&&this.dispatchEvent({type:t.REASONING_MESSAGE_END,messageId:this.reasoningProcess.messageId}),this.dispatchEvent({type:t.REASONING_END,messageId:this.reasoningProcess.messageId}),this.reasoningProcess=null),!this.reasoningProcess){let e=r();this.dispatchEvent({type:t.REASONING_START,messageId:e}),this.reasoningProcess={index:n,messageId:e}}this.reasoningProcess.type!==e.type&&(this.dispatchEvent({type:t.REASONING_MESSAGE_START,messageId:this.reasoningProcess.messageId,role:`reasoning`}),this.reasoningProcess.type=e.type),e.signature&&(this.reasoningProcess.signature=e.signature),this.reasoningProcess.type&&this.dispatchEvent({type:t.REASONING_MESSAGE_CONTENT,messageId:this.reasoningProcess.messageId,delta:e.text})}getStateSnapshot(e){let t=e.values,n=this.activeRun.schemaKeys;return n?.output&&(t=l(t,[...this.constantSchemaKeys,...n.output])),t}async getOrCreateThread(e,t){let n;try{try{n=await this.getThread(e)}catch{n=await this.createThread({threadId:e,metadata:t})}}catch(e){throw Error(`Failed to create thread: ${e.message}`)}return n}async getThread(e){return this.client.threads.get(e)}async createThread(e){return this.client.threads.create(e)}async mergeConfigs({configs:e,assistant:t,schemaKeys:n}){return e.reduce((e,t)=>{let r=e.configurable;t.configurable&&(r=n?.config?l(t?.configurable,[...this.constantSchemaKeys,...n?.config??[],...n?.context??[]]):t?.configurable);let i={...e,...t,configurable:r},a=e.recursion_limit==null&&t.recursion_limit===25,o=JSON.stringify(i)!==JSON.stringify(e),s=a&&JSON.stringify({...i,recursion_limit:null})===JSON.stringify({...e,recursion_limit:null});return o&&!s?{...e,...i}:e},t.config)}getMessageInProgress(e){return this.messagesInProcess[e]}setMessageInProgress(e,t){this.messagesInProcess={...this.messagesInProcess,[e]:{...this.messagesInProcess[e],...t}}}async getAssistant(){try{let e=await this.client.assistants.search({graphId:this.graphId,limit:1}),t=e.find(e=>e.graph_id===this.graphId);if(!t){let t=`
1
+ import{AbstractAgent as e,EventType as t,HttpAgent as n,randomUUID as r}from"@ag-ui/client";import{Observable as i}from"rxjs";import{Client as a}from"@langchain/langgraph-sdk";import{tool as o}from"@langchain/core/tools";import{SystemMessage as s}from"@langchain/core/messages";import{A2UI_OPERATIONS_KEY as c,BASIC_CATALOG_ID as l,DEFAULT_SURFACE_ID as u,GENERATE_A2UI_ARG_DESCRIPTIONS as d,GENERATE_A2UI_TOOL_DESCRIPTION as f,GENERATE_A2UI_TOOL_NAME as p,RENDER_A2UI_TOOL_DEF as m,buildA2UIEnvelope as h,prepareA2UIRequest as g,wrapErrorEnvelope as _}from"@ag-ui/a2ui-toolkit";let v=function(e){return e.OnChainStart=`on_chain_start`,e.OnChainStream=`on_chain_stream`,e.OnChainEnd=`on_chain_end`,e.OnChatModelStart=`on_chat_model_start`,e.OnChatModelStream=`on_chat_model_stream`,e.OnChatModelEnd=`on_chat_model_end`,e.OnToolStart=`on_tool_start`,e.OnToolEnd=`on_tool_end`,e.OnToolError=`on_tool_error`,e.OnCustomEvent=`on_custom_event`,e.OnInterrupt=`on_interrupt`,e}({}),y=function(e){return e.ManuallyEmitMessage=`manually_emit_message`,e.ManuallyEmitToolCall=`manually_emit_tool_call`,e.ManuallyEmitState=`manually_emit_state`,e.Exit=`exit`,e}({});const b=[`messages`,`tools`];function x(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}function S({mode:e,state:t,schemaKeys:n}){let r=e===`start`?t:null;return r&&n?.input&&(r=x(r,[...b,...n.input])),r}const C=new Set([`image`,`audio`,`video`,`document`]);function w(e){return e.type===`data`?`data:${e.mimeType};base64,${e.value}`:e.type===`url`?e.value:null}function T(e){let t=[];for(let n of e)if(n.type===`text`&&n.text)t.push({type:`text`,text:n.text});else if(n.type===`image_url`){let e=typeof n.image_url==`string`?n.image_url:n.image_url?.url;if(!e)continue;if(e.startsWith(`data:`)){let[n,r]=e.split(`,`,2),i=n.includes(`:`)?n.split(`:`)[1].split(`;`)[0]:`image/png`;t.push({type:`image`,source:{type:`data`,value:r||``,mimeType:i}})}else t.push({type:`image`,source:{type:`url`,value:e}})}return t}function E(e){let t=[];for(let n of e)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(C.has(n.type)){let e=w(n.source);e?t.push({type:`image_url`,image_url:{url:e}}):console.warn(`[convertAguiMultimodalToLangchain] Dropping ${n.type} content: source could not be converted to URL`)}else if(n.type===`binary`){let e;if(n.url)e=n.url;else if(n.data)e=`data:${n.mimeType};base64,${n.data}`;else if(n.id)e=n.id;else{console.warn(`[convertAguiMultimodalToLangchain] Dropping BinaryInputContent: no url, data, or id provided`);continue}t.push({type:`image_url`,image_url:{url:e}})}return t}function D(e){return e.map(e=>{switch(e.type){case`human`:let t;return t=Array.isArray(e.content)?T(e.content):k(M(e.content)),{id:e.id,role:`user`,content:t};case`generic`:case`ai`:let n=M(e.content);return{id:e.id,role:`assistant`,content:n?k(n):``,toolCalls:e.tool_calls?.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.args)}}))};case`system`:return{id:e.id,role:`system`,content:k(M(e.content))};case`tool`:return{id:e.id,role:`tool`,content:k(M(e.content)),toolCallId:e.tool_call_id};default:throw Error(`message type returned from LangGraph is not supported.`)}})}function O(e){return e.filter(e=>e.role!==`reasoning`&&e.role!==`developer`).map((e,t)=>{switch(e.role){case`user`:let t;return t=typeof e.content==`string`?e.content:Array.isArray(e.content)?E(e.content):String(e.content),{id:e.id,role:e.role,content:t,type:`human`};case`assistant`:return{id:e.id,type:`ai`,role:e.role,content:e.content??``,tool_calls:(e.toolCalls??[]).map(e=>({id:e.id,name:e.function.name,args:JSON.parse(e.function.arguments),type:`tool_call`}))};case`system`:return{id:e.id,role:e.role,content:e.content,type:`system`};case`tool`:return{content:e.content,role:e.role,type:e.role,tool_call_id:e.toolCallId,id:e.id};default:throw console.error(`Message role ${e.role} is not implemented`),Error(`message role is not supported.`)}})}function k(e){return typeof e==`string`?e:JSON.stringify(e)}function A(e){let t=e.chunk?.content;if(t&&Array.isArray(t)&&t.length&&t[0]){let e=t[0];if(e.type===`thinking`&&e.thinking){let t={text:e.thinking,type:`text`,index:e.index??0};return e.signature&&(t.signature=e.signature),t}if(e.type===`reasoning`&&e.reasoning)return{text:e.reasoning,type:`text`,index:e.index??0};if(e.type===`reasoning`&&e.summary?.[0]?.text)return{type:`text`,text:e.summary[0].text,index:e.summary[0].index??0};if(e.type===`reasoning_content`&&e.reasoning_content?.text)return{type:`text`,text:e.reasoning_content.text,index:e.reasoning_content.index??0}}if(e.chunk?.additional_kwargs?.reasoning?.summary?.[0]){let t=e.chunk.additional_kwargs.reasoning.summary[0];return!t||!t.text?null:{type:`text`,text:t.text,index:t.index??0}}return null}function j(e){let t=e.chunk?.content;return!t||!Array.isArray(t)||!t.length||!t[0]?null:t[0].type===`redacted_thinking`&&t[0].data?t[0].data:null}function M(e){return e?typeof e==`string`?e:Array.isArray(e)&&e.length?e.find(e=>e.type===`text`)?.text??null:null:null}const N=`root`;var P=class extends e{constructor(e){super(e),this.headers={},this.emittedToolCallStartIds=new Set,this.subgraphs=new Set,this.currentSubgraph=N,this.cancelRequested=!1,this.cancelSent=!1,this.eventsStreamActive=!1,this.constantSchemaKeys=b,this.config=e,this.messagesInProcess={},this.agentName=e.agentName,this.graphId=e.graphId,this.assistantConfig=e.assistantConfig,this.reasoningProcess=null;let t=this,n=e.headerFactory??(()=>t.headers);e?.client&&e.headerFactory&&console.debug("[@ag-ui/langgraph] Both `config.client` and `config.headerFactory` were set. Custom clients bypass the adapter's onRequest hook — `headerFactory` will not be invoked. Either omit `client` to enable adapter-managed header forwarding, or wire headers into your custom client directly."),this.client=e?.client??new a({apiUrl:e.deploymentUrl,apiKey:e.langsmithApiKey,defaultHeaders:{...e.propertyHeaders??{}},onRequest:(e,t)=>{let r=n();return!r||Object.keys(r).length===0?t:{...t,headers:{...t.headers,...r}}}})}clone(){let e=Object.assign(super.clone(),{config:this.config,messagesInProcess:structuredClone(this.messagesInProcess),agentName:this.agentName,graphId:this.graphId,assistantConfig:this.assistantConfig,reasoningProcess:this.reasoningProcess?structuredClone(this.reasoningProcess):null,constantSchemaKeys:[...this.constantSchemaKeys],headers:{...this.headers},client:this.client,assistant:this.assistant,activeRun:this.activeRun?structuredClone(this.activeRun):void 0,cancelRequested:this.cancelRequested,cancelSent:this.cancelSent,subgraphs:this.subgraphs?new Set(this.subgraphs):new Set,currentSubgraph:N});if(!this.config.client){let t=this.config.headerFactory??(()=>e.headers);e.client=new a({apiUrl:this.config.deploymentUrl,apiKey:this.config.langsmithApiKey,defaultHeaders:{...this.config.propertyHeaders??{}},onRequest:(e,n)=>{let r=t();return!r||Object.keys(r).length===0?n:{...n,headers:{...n.headers,...r}}}})}return e}dispatchEvent(e){return this.subscriber.next(e),!0}run(e){return new i(t=>(this.runAgentStream(e,t).catch(e=>{console.error(`[LangGraph] runAgentStream error:`,e),t.closed||t.error(e)}),()=>{}))}async runAgentStream(e,t){this.activeRun={id:e.runId,threadId:e.threadId,hasFunctionStreaming:!1,modelMadeToolCall:!1},this.cancelRequested=!1,this.cancelSent=!1,this.eventsStreamActive=!1,this.subscriber=t,this.assistant||=await this.getAssistant();let n=e.threadId??r(),i=e.forwardedProps?.streamMode??[`events`,`values`,`updates`,`messages-tuple`],a=await this.prepareStream({...e,threadId:n},i);if(!a)return t.error(`No stream to regenerate`);await this.handleStreamEvents(a,n,t,e,Array.isArray(i)?i:[i])}async prepareRegenerateStream(e,t){let{threadId:n,messageCheckpoint:r,forwardedProps:i}=e,a=await this.getCheckpointByMessage(r.id,n);if(this.assistant||=await this.getAssistant(),!a)return this.subscriber.error(`No checkpoint found for message`);let o=await this.client.threads.updateState(n,{values:this.langGraphDefaultMergeState(a.values,[],e),checkpointId:a.checkpoint.checkpoint_id,asNode:a.next?.[0]??`__start__`}),s,c=[this.assistantConfig,i?.config].filter(Boolean);c.length&&(s=await this.mergeConfigs({configs:c,assistant:this.assistant,schemaKeys:this.activeRun.schemaKeys??null}));let l={...e.forwardedProps??{},input:this.langGraphDefaultMergeState(a.values,[r],e),checkpointId:o.checkpoint.checkpoint_id,streamMode:t,config:s};return{streamResponse:this.client.runs.stream(n,this.assistant.assistant_id,l),state:a,streamMode:t}}async prepareStream(e,n){let{threadId:i,state:a,messages:o,tools:s,context:c,forwardedProps:l}=e;this.activeRun.manuallyEmittedState=null;let u=l?.nodeName,d=i??r();this.assistant||=await this.getAssistant();let f=await this.getOrCreateThread(d,l?.threadMetadata);this.activeRun.threadId=f.thread_id;let p=await this.client.threads.getState(f.thread_id)??{values:{}},m=p.values.messages??[],h=O(o),g=this.langGraphDefaultMergeState({...a,messages:m},h,e),_={...p,values:{...g,messages:[...m,...g.messages??[]]}},y=_.values;if(this.activeRun.schemaKeys=await this.getSchemaKeys(),m.filter(e=>e.type!==`system`).length>o.filter(e=>e.role!==`system`).length){let t=null;for(let e=o.length-1;e>=0;e--)if(o[e].role===`user`){t=O([o[e]])[0];break}return t?this.prepareRegenerateStream({...e,messageCheckpoint:t},n):this.subscriber.error(`No user message found in messages to regenerate`)}this.activeRun.graphInfo=await this.client.assistants.getGraph(this.assistant.assistant_id);let b=!l?.command?.resume&&d&&this.activeRun.nodeName!=`__end__`&&this.activeRun.nodeName?`continue`:`start`;if(b===`continue`){let e=this.activeRun.graphInfo.edges.find(e=>e.target===this.activeRun.nodeName);await this.client.threads.updateState(d,{values:a,asNode:e?.source})}let x=S({mode:b,state:y,schemaKeys:this.activeRun.schemaKeys}),C,w=[this.assistantConfig,l?.config].filter(Boolean);w.length&&(C=await this.mergeConfigs({configs:w,assistant:this.assistant,schemaKeys:this.activeRun.schemaKeys}));let{command:T,...E}=l;if(T?.resume&&typeof T.resume==`string`)try{T.resume=JSON.parse(T.resume)}catch{}let D=new Set(this.activeRun.schemaKeys?.context??[]),k=C?.configurable??{},A={},j={};for(let[e,t]of Object.entries(k))D.has(e)?A[e]=t:j[e]=t;let M={...A},N=C?{...C,configurable:Object.keys(j).length>0?j:void 0}:void 0,P=Object.keys(M).length>0,F=N?.configurable!=null&&Object.keys(N.configurable).length>0;if(P&&F){let e=Object.keys(j);e.length>0&&console.warn(`[@ag-ui/langgraph] Dropping configurable keys not in context_schema: [${e.join(`, `)}]. Use context instead.`)}let I=(()=>{if(!N)return;if(F&&!P)return N;let{configurable:e,...t}=N;return Object.keys(t).length>0?t:void 0})(),L=Object.fromEntries(Object.entries(this.headers??{}).filter(([e])=>e.toLowerCase().startsWith(`x-`))),R=Object.keys(L).length>0?{...I??{},configurable:{...I?.configurable??{},copilotkit_forwarded_headers:L}}:I,z={...E,command:T,streamMode:n,input:x,config:R,...P?{context:M}:{}},B=(p.tasks??[]).flatMap(e=>e.interrupts??[]);return B?.length&&!l?.command?.resume?(this.dispatchEvent({type:t.RUN_STARTED,threadId:d,runId:e.runId}),this.handleNodeChange(u),B.forEach(e=>{this.dispatchEvent({type:t.CUSTOM,name:v.OnInterrupt,value:typeof e.value==`string`?e.value:JSON.stringify(e.value),rawEvent:e})}),this.dispatchEvent({type:t.RUN_FINISHED,threadId:d,runId:e.runId}),this.subscriber.complete()):{streamResponse:this.client.runs.stream(d,this.assistant.assistant_id,z),state:_}}async handleStreamEvents(e,n,r,i,a){let{forwardedProps:o}=i,s=o?.nodeName;this.subscriber=r;let c=!1;if(!e)return;this.emittedToolCallStartIds=new Set;let{streamResponse:l,state:u}=e;this.activeRun.prevNodeName=null;let d={},f=u;try{this.dispatchEvent({type:t.RUN_STARTED,threadId:n,runId:this.activeRun.id}),this.handleNodeChange(s);for await(let e of l){if(this.cancelRequested&&!this.cancelSent&&this.activeRun?.threadId&&this.activeRun?.id){try{await this.client.runs.cancel(this.activeRun.threadId,this.activeRun.id)}catch{}finally{this.cancelSent=!0}try{await l?.return?.()}catch{}break}let r=i.forwardedProps?.streamSubgraphs??!0,o=r&&(e.event.startsWith(`events`)||e.event.startsWith(`values`)),s=e.event===`messages`&&(Array.isArray(a)?a:[a]).includes(`messages-tuple`);if(!a.includes(e.event)&&!o&&!s&&e.event!==`error`)continue;let p=e;if(e.event===`error`){this.dispatchEvent({type:t.RUN_ERROR,message:e.data.message,rawEvent:e});break}if(e.event===`updates`)continue;if(e.event===`values`){d={...d,...p.data};continue}else if(r&&p.event.startsWith(`values|`)){d={...d,...p.data};continue}let m=p.data,h=m.metadata??{},g=h.langgraph_node,_=m.event,b=h.langgraph_checkpoint_ns??``,x=b.split(`|`)[0].split(`:`)[0];b.includes(`|`)&&x&&this.subgraphs.add(x);let S=x&&this.subgraphs.has(x)?x:N;if(S!==this.currentSubgraph&&(this.currentSubgraph=S,await this.getStateAndMessagesSnapshots(n)),h.run_id&&(this.activeRun.id=h.run_id,this.activeRun.serverRunIdKnown=!0,this.cancelRequested&&!this.cancelSent&&this.activeRun?.threadId))try{await this.client.runs.cancel(this.activeRun.threadId,this.activeRun.id)}catch{}finally{this.cancelSent=!0}if(g&&g!==this.activeRun.nodeName&&this.handleNodeChange(g),c||=_===v.OnCustomEvent&&m.name===y.Exit,_===v.OnChainEnd&&m.data?.output!=null){let e=m.data.output;if(typeof e==`object`&&!Array.isArray(e))d={...d,...e};else if(Array.isArray(e))for(let t of e)t&&typeof t==`object`&&t.lg_name===`Command`&&t.update&&typeof t.update==`object`&&(d={...d,...t.update})}if(_===v.OnChainEnd&&this.activeRun.nodeName===g&&(this.activeRun.exitingNode=!0),this.activeRun.exitingNode&&(this.activeRun.manuallyEmittedState&&typeof this.activeRun.manuallyEmittedState==`object`&&(d={...d,...this.activeRun.manuallyEmittedState}),this.activeRun.manuallyEmittedState=null),this.activeRun.graphInfo?.nodes.some(e=>e.id===g)&&this.handleNodeChange(g),f.values=this.activeRun.manuallyEmittedState??d,!this.activeRun.nodeName)continue;let C=JSON.stringify(f)!==JSON.stringify(u);!this.activeRun.modelMadeToolCall&&(C||this.activeRun.prevNodeName!=this.activeRun.nodeName||this.activeRun.exitingNode)&&!this.getMessageInProgress(this.activeRun.id)&&(u=f,this.activeRun.prevNodeName=this.activeRun.nodeName,this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(u),rawEvent:p})),this.dispatchEvent({type:t.RAW,event:m}),this.handleSingleEvent(m)}u=await this.client.threads.getState(n);let e=(u.tasks??[]).flatMap(e=>e.interrupts??[]),o=u.next.length===0,p=u.metadata?.writes??{},m=this.activeRun.nodeName;return e?.length||(m=o?`__end__`:u.next[0]??Object.keys(p)[0]),e.forEach(e=>{this.dispatchEvent({type:t.CUSTOM,name:v.OnInterrupt,value:typeof e.value==`string`?e.value:JSON.stringify(e.value),rawEvent:e})}),this.handleNodeChange(m),this.handleNodeChange(void 0),await this.getStateAndMessagesSnapshots(n),this.dispatchEvent({type:t.RUN_FINISHED,threadId:n,runId:this.activeRun.id}),this.cancelRequested=!1,this.cancelSent=!1,this.activeRun=void 0,r.complete()}catch(e){return r.error(e)}}async getStateAndMessagesSnapshots(e){let n=await this.client.threads.getState(e);this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot(n)});let r=n.values.messages??[];this.dispatchEvent({type:t.MESSAGES_SNAPSHOT,messages:D(r)})}handleSingleEvent(e){if(Array.isArray(e)){this.eventsStreamActive||this.handleMessagesTupleEvent(e);return}switch(e.event===v.OnChatModelStream&&(this.eventsStreamActive=!0),e.event){case v.OnChatModelStream:let n=e.metadata[`emit-messages`]??!0,i=e.metadata[`emit-tool-calls`]??!0;if(e.data.chunk.response_metadata.finish_reason)return;let a=this.getMessageInProgress(this.activeRun.id),o=!!a?.id,s=e.data.chunk.tool_call_chunks?.[0],c=e.metadata.predict_state?.some(e=>e.tool===s?.name),l=!o&&s?.name,u=o&&a?.toolCallId&&s?.args,d=o&&a?.toolCallId&&!s;(d||u||l)&&(this.activeRun.hasFunctionStreaming=!0);let f=A(e.data),p=j(e.data),m=M(e.data.chunk.content),h=!!(!s&&m),g=o&&!a?.toolCallId&&!h;if(f){this.handleReasoningEvent(f);break}if(p&&this.reasoningProcess){this.dispatchEvent({type:t.REASONING_ENCRYPTED_VALUE,subtype:`message`,entityId:this.reasoningProcess.messageId,encryptedValue:p});break}if(!f&&this.reasoningProcess&&(this.reasoningProcess.signature&&this.dispatchEvent({type:t.REASONING_ENCRYPTED_VALUE,subtype:`message`,entityId:this.reasoningProcess.messageId,encryptedValue:this.reasoningProcess.signature}),this.dispatchEvent({type:t.REASONING_MESSAGE_END,messageId:this.reasoningProcess.messageId}),this.dispatchEvent({type:t.REASONING_END,messageId:this.reasoningProcess.messageId}),this.reasoningProcess=null),c&&(this.activeRun.modelMadeToolCall=!0,this.dispatchEvent({type:t.CUSTOM,name:`PredictState`,value:e.metadata.predict_state})),d){this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:a?.toolCallId,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(g){this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:a.id,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(l&&i){this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:s.id,toolCallName:s.name,parentMessageId:e.data.chunk.id,rawEvent:e})&&(this.emittedToolCallStartIds.add(s.id),this.setMessageInProgress(this.activeRun.id,{id:e.data.chunk.id,toolCallId:s.id,toolCallName:s.name}));break}if(u&&i){this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:a?.toolCallId,delta:s.args,rawEvent:e});break}if(h&&n){a||=(this.dispatchEvent({type:t.TEXT_MESSAGE_START,role:`assistant`,messageId:e.data.chunk.id,rawEvent:e}),this.setMessageInProgress(this.activeRun.id,{id:e.data.chunk.id,toolCallId:null,toolCallName:null}),this.getMessageInProgress(this.activeRun.id)),this.dispatchEvent({type:t.TEXT_MESSAGE_CONTENT,messageId:a.id,delta:m,rawEvent:e});break}break;case v.OnChatModelEnd:if(this.getMessageInProgress(this.activeRun.id)?.toolCallId){this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:this.getMessageInProgress(this.activeRun.id).toolCallId,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}if(this.getMessageInProgress(this.activeRun.id)?.id){this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:this.getMessageInProgress(this.activeRun.id).id,rawEvent:e})&&(this.messagesInProcess[this.activeRun.id]=null);break}break;case v.OnCustomEvent:if(e.name===y.ManuallyEmitMessage){this.dispatchEvent({type:t.TEXT_MESSAGE_START,role:`assistant`,messageId:e.data.message_id,rawEvent:e}),this.dispatchEvent({type:t.TEXT_MESSAGE_CONTENT,messageId:e.data.message_id,delta:e.data.message,rawEvent:e}),this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:e.data.message_id,rawEvent:e});break}if(e.name===y.ManuallyEmitToolCall){this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:e.data.id,toolCallName:e.data.name,parentMessageId:e.data.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:e.data.id,delta:e.data.args,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:e.data.id,rawEvent:e});break}e.name===y.ManuallyEmitState&&(this.activeRun.manuallyEmittedState=e.data,this.dispatchEvent({type:t.STATE_SNAPSHOT,snapshot:this.getStateSnapshot({values:this.activeRun.manuallyEmittedState}),rawEvent:e})),this.dispatchEvent({type:t.CUSTOM,name:e.name,value:e.data,rawEvent:e});break;case v.OnToolEnd:let _=e.data?.output;if(_&&!_.tool_call_id&&_.update?.messages?.find(e=>e.type===`tool`)&&(_=_.update?.messages?.find(e=>e.type===`tool`)),_&&_.update?.messages?.length){_.update?.messages.filter(e=>e.type===`tool`).forEach(n=>{this.activeRun.hasFunctionStreaming||(this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:n.tool_call_id,toolCallName:n.name??``,parentMessageId:n.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:n.tool_call_id,delta:JSON.stringify(e.data.input),rawEvent:e})),this.dispatchEvent({type:t.TOOL_CALL_RESULT,toolCallId:n.tool_call_id,content:typeof n?.content==`string`?n?.content:JSON.stringify(n?.content),messageId:r(),rawEvent:e,role:`tool`})}),this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break}this.emittedToolCallStartIds.has(_.tool_call_id)||(this.emittedToolCallStartIds.add(_.tool_call_id),this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:_.tool_call_id,toolCallName:_.name,parentMessageId:_.id,rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:_.tool_call_id,delta:JSON.stringify(e.data.input),rawEvent:e}),this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:_.tool_call_id,rawEvent:e}));let b=Array.isArray(_.content)?_.content.map(e=>typeof e==`string`?e:e.type===`text`?e.text:JSON.stringify(e)).join(``):_.content;this.dispatchEvent({type:t.TOOL_CALL_RESULT,toolCallId:_.tool_call_id,content:b,messageId:r(),role:`tool`,rawEvent:e}),this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break;case v.OnToolError:this.activeRun.modelMadeToolCall=!1,this.activeRun.hasFunctionStreaming=!1;break}}handleMessagesTupleEvent(e){let n=e[0];if(n.type&&n.type!==`AIMessageChunk`)return;let r=typeof n.content==`string`?n.content:Array.isArray(n.content)?n.content.find(e=>e.type===`text`)?.text:null,i=n.tool_call_chunks,a=n.response_metadata?.finish_reason===`stop`,o=this.getMessageInProgress(this.activeRun.id);if(i?.length>0){let e=i[0];e.name?(o?.id&&!o?.toolCallId&&(this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:o.id}),this.messagesInProcess[this.activeRun.id]=null),this.dispatchEvent({type:t.TOOL_CALL_START,toolCallId:e.id||n.id,toolCallName:e.name,parentMessageId:n.id}),this.setMessageInProgress(this.activeRun.id,{id:n.id,toolCallId:e.id||n.id,toolCallName:e.name}),this.activeRun.hasFunctionStreaming=!0):e.args&&o?.toolCallId&&this.dispatchEvent({type:t.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:e.args});return}if(a){o?.toolCallId?this.dispatchEvent({type:t.TOOL_CALL_END,toolCallId:o.toolCallId}):o?.id&&this.dispatchEvent({type:t.TEXT_MESSAGE_END,messageId:o.id}),this.messagesInProcess[this.activeRun.id]=null;return}!r&&!i?.length||r&&(o||(this.dispatchEvent({type:t.TEXT_MESSAGE_START,role:`assistant`,messageId:n.id}),this.setMessageInProgress(this.activeRun.id,{id:n.id,toolCallId:null,toolCallName:null})),this.dispatchEvent({type:t.TEXT_MESSAGE_CONTENT,messageId:(this.getMessageInProgress(this.activeRun.id)??{id:n.id}).id,delta:r}))}abortRun(){this.cancelRequested=!0;let e=this.activeRun?.threadId,t=this.activeRun?.id;e&&t&&!this.cancelSent&&this.client.runs.cancel(e,t).then(()=>{this.cancelSent=!0}).catch(()=>{}),super.abortRun()}handleReasoningEvent(e){if(!e||!e.type||!e.text)return;let n=e.index;if(this.reasoningProcess?.index&&this.reasoningProcess.index!==n&&(this.reasoningProcess.type&&this.dispatchEvent({type:t.REASONING_MESSAGE_END,messageId:this.reasoningProcess.messageId}),this.dispatchEvent({type:t.REASONING_END,messageId:this.reasoningProcess.messageId}),this.reasoningProcess=null),!this.reasoningProcess){let e=r();this.dispatchEvent({type:t.REASONING_START,messageId:e}),this.reasoningProcess={index:n,messageId:e}}this.reasoningProcess.type!==e.type&&(this.dispatchEvent({type:t.REASONING_MESSAGE_START,messageId:this.reasoningProcess.messageId,role:`reasoning`}),this.reasoningProcess.type=e.type),e.signature&&(this.reasoningProcess.signature=e.signature),this.reasoningProcess.type&&this.dispatchEvent({type:t.REASONING_MESSAGE_CONTENT,messageId:this.reasoningProcess.messageId,delta:e.text})}getStateSnapshot(e){let t=e.values,n=this.activeRun.schemaKeys;return n?.output&&(t=x(t,[...this.constantSchemaKeys,...n.output])),t}async getOrCreateThread(e,t){let n;try{try{n=await this.getThread(e)}catch{n=await this.createThread({threadId:e,metadata:t})}}catch(e){throw Error(`Failed to create thread: ${e.message}`)}return n}async getThread(e){return this.client.threads.get(e)}async createThread(e){return this.client.threads.create(e)}async mergeConfigs({configs:e,assistant:t,schemaKeys:n}){return e.reduce((e,t)=>{let r=e.configurable;t.configurable&&(r=n?.config?x(t?.configurable,[...this.constantSchemaKeys,...n?.config??[],...n?.context??[]]):t?.configurable);let i={...e,...t,configurable:r},a=e.recursion_limit==null&&t.recursion_limit===25,o=JSON.stringify(i)!==JSON.stringify(e),s=a&&JSON.stringify({...i,recursion_limit:null})===JSON.stringify({...e,recursion_limit:null});return o&&!s?{...e,...i}:e},t.config)}getMessageInProgress(e){return this.messagesInProcess[e]}setMessageInProgress(e,t){this.messagesInProcess={...this.messagesInProcess,[e]:{...this.messagesInProcess[e],...t}}}async getAssistant(){try{let e=await this.client.assistants.search({graphId:this.graphId,limit:1}),t=e.find(e=>e.graph_id===this.graphId);if(!t){let t=`
2
2
  No agent found with graph ID ${this.graphId} found..\n
3
3
 
4
4
  These are the available agents: [${e.map(e=>`${e.graph_id} (ID: ${e.assistant_id})`).join(`, `)}]
5
- `;throw console.error(t),Error(t)}return t}catch(e){let n=Error(`Failed to retrieve assistant: ${e.message}`);throw this.dispatchEvent({type:t.RUN_ERROR,message:n.message}),this.subscriber.error(),n}}async getSchemaKeys(){try{let e=await this.client.assistants.getSchemas(this.assistant.assistant_id),t=null,n=[];if(`context_schema`in e&&e.context_schema?.properties&&(n=Object.keys(e.context_schema.properties)),e.config_schema?.properties&&(t=Object.keys(e.config_schema.properties)),!e.input_schema?.properties||!e.output_schema?.properties)return{config:[],input:null,output:null,context:n};let r=Object.keys(e.input_schema.properties),i=Object.keys(e.output_schema.properties);return{input:r&&r.length?[...r,...this.constantSchemaKeys]:null,output:i&&i.length?[...i,...this.constantSchemaKeys]:null,context:n,config:t}}catch{return{config:[],input:this.constantSchemaKeys,output:this.constantSchemaKeys,context:[]}}}langGraphDefaultMergeState(e,t,n){t.length>0&&`role`in t[0]&&t[0].role===`system`&&(t=t.slice(1));let r=e.messages||[],i=new Set(r.map(e=>e.id)),a=t.filter(e=>!i.has(e.id)),o=[...n.tools??[],...e.tools??[]].reduce((e,t)=>{let n=t;return t.type||(n={type:`function`,name:t.name,function:{name:t.name,description:t.description,parameters:t.parameters}}),e.find(e=>e.name===n.name||e.function.name===n.function.name)?e:[...e,n]},[]);return{...e,messages:a,tools:o,"ag-ui":{tools:o,context:n.context},copilotkit:{...e.copilotkit,actions:o}}}handleNodeChange(e){e===`__end__`&&(e=void 0),e!==this.activeRun?.nodeName&&(this.activeRun?.nodeName&&this.endStep(),e&&this.startStep(e)),this.activeRun.nodeName=e}startStep(e){this.dispatchEvent({type:t.STEP_STARTED,stepName:e})}endStep(){this.dispatchEvent({type:t.STEP_FINISHED,stepName:this.activeRun.nodeName})}async getCheckpointByMessage(e,t,n){let r=n?.checkpoint_id?{checkpoint:{checkpoint_id:n.checkpoint_id}}:void 0,i=[...await this.client.threads.getHistory(t,r)].reverse(),a=i.find(t=>t.values.messages?.some(t=>t.id===e));if(!a)throw Error(`Message not found`);let o=a.values.messages??[],s=o.findIndex(t=>t.id===e);if(o.slice(s+1).length)return this.getCheckpointByMessage(e,t,a.parent_checkpoint);let c=i.indexOf(a),{messages:l,...u}=a.values,d=i[c-1]??{...a,values:{}};return{...d,values:{...d.values,...u}}}},C=class extends n{};export{s as CustomEventNames,S as LangGraphAgent,o as LangGraphEventTypes,C as LangGraphHttpAgent};
5
+ `;throw console.error(t),Error(t)}return t}catch(e){let n=Error(`Failed to retrieve assistant: ${e.message}`);throw this.dispatchEvent({type:t.RUN_ERROR,message:n.message}),this.subscriber.error(),n}}async getSchemaKeys(){try{let e=await this.client.assistants.getSchemas(this.assistant.assistant_id),t=null,n=[];if(`context_schema`in e&&e.context_schema?.properties&&(n=Object.keys(e.context_schema.properties)),e.config_schema?.properties&&(t=Object.keys(e.config_schema.properties)),!e.input_schema?.properties||!e.output_schema?.properties)return{config:[],input:null,output:null,context:n};let r=Object.keys(e.input_schema.properties),i=Object.keys(e.output_schema.properties);return{input:r&&r.length?[...r,...this.constantSchemaKeys]:null,output:i&&i.length?[...i,...this.constantSchemaKeys]:null,context:n,config:t}}catch{return{config:[],input:this.constantSchemaKeys,output:this.constantSchemaKeys,context:[]}}}langGraphDefaultMergeState(e,t,n){t.length>0&&`role`in t[0]&&t[0].role===`system`&&(t=t.slice(1));let r=e.messages||[],i=new Set(r.map(e=>e.id)),a=t.filter(e=>!i.has(e.id)),o=[...n.tools??[],...e.tools??[]].reduce((e,t)=>{let n=t;return t.type||(n={type:`function`,name:t.name,function:{name:t.name,description:t.description,parameters:t.parameters}}),e.find(e=>e.name===n.name||e.function.name===n.function.name)?e:[...e,n]},[]);return{...e,messages:a,tools:o,"ag-ui":{tools:o,context:n.context},copilotkit:{...e.copilotkit,actions:o}}}handleNodeChange(e){e===`__end__`&&(e=void 0),e!==this.activeRun?.nodeName&&(this.activeRun?.nodeName&&this.endStep(),e&&this.startStep(e)),this.activeRun.nodeName=e}startStep(e){this.dispatchEvent({type:t.STEP_STARTED,stepName:e})}endStep(){this.dispatchEvent({type:t.STEP_FINISHED,stepName:this.activeRun.nodeName})}async getCheckpointByMessage(e,t,n){let r=n?.checkpoint_id?{checkpoint:{checkpoint_id:n.checkpoint_id}}:void 0,i=[...await this.client.threads.getHistory(t,r)].reverse(),a=i.find(t=>t.values.messages?.some(t=>t.id===e));if(!a)throw Error(`Message not found`);let o=a.values.messages??[],s=o.findIndex(t=>t.id===e);if(o.slice(s+1).length)return this.getCheckpointByMessage(e,t,a.parent_checkpoint);let c=i.indexOf(a),{messages:l,...u}=a.values,d=i[c-1]??{...a,values:{}};return{...d,values:{...d.values,...u}}}};function F(e,t={}){let{compositionGuide:n,defaultSurfaceId:r,defaultCatalogId:i,toolName:a,toolDescription:c}=t,v=r||u,y=i||l;return o(async(t,r)=>{let i=r.state,a=(i.messages??[]).slice(0,-1),o=g({intent:t.intent,targetSurfaceId:t.target_surface_id,changes:t.changes,messages:a,state:i,compositionGuide:n});if(o.error)return _(o.error);if(!e.bindTools)return _(`Provided model does not support bindTools`);let c=(await e.bindTools([m],{tool_choice:{type:`function`,function:{name:`render_a2ui`}}}).invoke([new s(o.prompt),...a])).tool_calls??[];return c.length===0?_(`LLM did not call render_a2ui`):h({args:c[0].args??{},isUpdate:o.isUpdate,targetSurfaceId:t.target_surface_id,prior:o.prior,defaultSurfaceId:v,defaultCatalogId:y})},{name:a||p,description:c||f,schema:{type:`object`,properties:{intent:{type:`string`,enum:[`create`,`update`],description:d.intent},target_surface_id:{type:`string`,description:d.target_surface_id},changes:{type:`string`,description:d.changes}}}})}var I=class extends n{};export{c as A2UI_OPERATIONS_KEY,l as BASIC_CATALOG_ID,y as CustomEventNames,P as LangGraphAgent,v as LangGraphEventTypes,I as LangGraphHttpAgent,F as getA2UITools};
6
6
  //# sourceMappingURL=index.mjs.map