@mcp-use/inspector 0.12.5 → 0.12.6

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.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-BX11cXGe.js","assets/index-BZHKq4Gu.js","assets/index-beDRbW3x.css"])))=>i.map(i=>d[i]);
2
- import{_ as j,q as ve,Z as Sl,s as Cl,p as Bi,u as Tl,T as ei,v as kl,w as y,a as an,t as An,x as Ye,y as vs,z as vr,A as Sr,B as El,C as xl,D as Ml,E as Al}from"./index-BZHKq4Gu.js";import{F as qm,G as Ym,H as Xm,I as Zm,L as Qm,J as eg,M as tg,H as ng,V as rg,W as sg,K as ig,N as og,N as ag}from"./index-BZHKq4Gu.js";import{L as zi,S as fr,t as Pl,o as Ol,l as Nl,a as Wi,T as Il,D as Rl,b as Hi}from"./index-VGF5GoM6.js";import{h as bn,s as $l,g as Gi,B as jl,k as Ll,l as Dl,I as Fl,C as Ul,m as Vl,t as Bl,n as zl,o as Wl,p as Hl,q as Gl,r as Kl,u as Jl,v as ql,w as Yl,x as Xl,y as Zl,R as Ql,z as ec,a as tc}from"./index-Dh_Vxoku.js";import{aO as nc,aP as Ss,aQ as rc,at as Ee,e as Zt,aR as sc,aS as ln,a0 as de,x as nt,aT as Ki,g as ic,aU as Hr,_ as q,ag as Kt,ae as fe,z as O,ad as ee,d as oc,C as ac,aV as lc,p as ti,aA as Ji,aW as be,ai as cn,aX as nn,E as qi,y as Oe,aY as Cs,B as Gr,D as Lt,am as Dt,aZ as cc,a_ as uc,a$ as hc,b0 as dc,b1 as fc,b2 as pc,b3 as mc,b4 as gc,b5 as yc,b6 as wc,b7 as bc,b8 as _c,b9 as vc,ba as Sc,bb as Cc,bc as Tc,bd as kc,K as Ec,be as xc,bf as Mc,bg as Ac,t as je,r as rn,m as Re,L as Xe,aq as Ft,bh as Pc,F as Oc,aB as ni,ar as Nc,bi as ri,bj as si,ab as Ts,aa as ii,a9 as Kr,ac as Ic,S as Rc,a5 as ks,a8 as Ge,bk as Jn,o as z,bl as ae,bm as $c,bn as Me,bo as _t,bp as jc,bq as Es,l as F,a6 as Lc,i as Dc,T as Fc,br as qn,bs as Fe,bt as U,bu as Yi,s as ne,a7 as Uc,bv as Pn,bw as Xi,bx as Ut,by as un,bz as Yn,bA as Xn,bB as Vc,aK as Bc,aI as zc,aH as Wc,bC as Hc}from"./index-CYBG3mWU.js";import{E as Zi,c as Gc,e as Kc}from"./embeddings-Azb3VHue.js";import"./index-DRz5BQNA.js";var Cr,Cn,Tr=0,kr=0;function Jc(t,e,n){var r=0,s=e||new Array(16);t=t||{};var i=t.node,o=t.clockseq;if(t._v6||(i||(i=Cr),o==null&&(o=Cn)),i==null||o==null){var a=t.random||(t.rng||nc)();i==null&&(i=[a[0],a[1],a[2],a[3],a[4],a[5]],!Cr&&!t._v6&&(i[0]|=1,Cr=i)),o==null&&(o=(a[6]<<8|a[7])&16383,Cn===void 0&&!t._v6&&(Cn=o))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:kr+1,u=l-Tr+(c-kr)/1e4;if(u<0&&t.clockseq===void 0&&(o=o+1&16383),(u<0||l>Tr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Tr=l,kr=c,Cn=o,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=l/4294967296*1e4&268435455;s[r++]=d>>>8&255,s[r++]=d&255,s[r++]=d>>>24&15|16,s[r++]=d>>>16&255,s[r++]=o>>>8|128,s[r++]=o&255;for(var f=0;f<6;++f)s[r+f]=i[f];return e||Ss(s)}function qc(t){var e=typeof t=="string"?rc(t):t,n=Yc(e);return typeof t=="string"?Ss(n):n}function Yc(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function oi(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function ai(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?oi(Object(n),!0).forEach(function(r){Xc(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):oi(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Xc(t,e,n){return(e=Zc(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Zc(t){var e=Qc(t,"string");return typeof e=="symbol"?e:e+""}function Qc(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function eu(t={},e,n=0){var r=Jc(ai(ai({},t),{},{_v6:!0}),new Uint8Array(16));return r=qc(r),Ss(r)}async function*tu(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}j(tu,"streamEventsToAISDK");function nu(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}j(nu,"createReadableStreamFromGenerator");async function*ru(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-A5IEINAP-CKX4vEt9.js","assets/index-ubmd7JRV.js","assets/index-beDRbW3x.css"])))=>i.map(i=>d[i]);
2
+ import{_ as j,q as ve,Z as Sl,s as Cl,p as Bi,u as Tl,T as ei,v as kl,w as y,a as an,t as An,x as Ye,y as vs,z as vr,A as Sr,B as El,C as xl,D as Ml,E as Al}from"./index-ubmd7JRV.js";import{F as qm,G as Ym,H as Xm,I as Zm,L as Qm,J as eg,M as tg,H as ng,V as rg,W as sg,K as ig,N as og,N as ag}from"./index-ubmd7JRV.js";import{L as zi,S as fr,t as Pl,o as Ol,l as Nl,a as Wi,T as Il,D as Rl,b as Hi}from"./index-BZVDzI3u.js";import{h as bn,s as $l,g as Gi,B as jl,k as Ll,l as Dl,I as Fl,C as Ul,m as Vl,t as Bl,n as zl,o as Wl,p as Hl,q as Gl,r as Kl,u as Jl,v as ql,w as Yl,x as Xl,y as Zl,R as Ql,z as ec,a as tc}from"./index-B8valPom.js";import{aO as nc,aP as Ss,aQ as rc,at as Ee,e as Zt,aR as sc,aS as ln,a0 as de,x as nt,aT as Ki,g as ic,aU as Hr,_ as q,ag as Kt,ae as fe,z as O,ad as ee,d as oc,C as ac,aV as lc,p as ti,aA as Ji,aW as be,ai as cn,aX as nn,E as qi,y as Oe,aY as Cs,B as Gr,D as Lt,am as Dt,aZ as cc,a_ as uc,a$ as hc,b0 as dc,b1 as fc,b2 as pc,b3 as mc,b4 as gc,b5 as yc,b6 as wc,b7 as bc,b8 as _c,b9 as vc,ba as Sc,bb as Cc,bc as Tc,bd as kc,K as Ec,be as xc,bf as Mc,bg as Ac,t as je,r as rn,m as Re,L as Xe,aq as Ft,bh as Pc,F as Oc,aB as ni,ar as Nc,bi as ri,bj as si,ab as Ts,aa as ii,a9 as Kr,ac as Ic,S as Rc,a5 as ks,a8 as Ge,bk as Jn,o as z,bl as ae,bm as $c,bn as Me,bo as _t,bp as jc,bq as Es,l as F,a6 as Lc,i as Dc,T as Fc,br as qn,bs as Fe,bt as U,bu as Yi,s as ne,a7 as Uc,bv as Pn,bw as Xi,bx as Ut,by as un,bz as Yn,bA as Xn,bB as Vc,aK as Bc,aI as zc,aH as Wc,bC as Hc}from"./index-C9gKZsxC.js";import{E as Zi,c as Gc,e as Kc}from"./embeddings-_gd8Ybda.js";import"./index-DRz5BQNA.js";var Cr,Cn,Tr=0,kr=0;function Jc(t,e,n){var r=0,s=e||new Array(16);t=t||{};var i=t.node,o=t.clockseq;if(t._v6||(i||(i=Cr),o==null&&(o=Cn)),i==null||o==null){var a=t.random||(t.rng||nc)();i==null&&(i=[a[0],a[1],a[2],a[3],a[4],a[5]],!Cr&&!t._v6&&(i[0]|=1,Cr=i)),o==null&&(o=(a[6]<<8|a[7])&16383,Cn===void 0&&!t._v6&&(Cn=o))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:kr+1,u=l-Tr+(c-kr)/1e4;if(u<0&&t.clockseq===void 0&&(o=o+1&16383),(u<0||l>Tr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Tr=l,kr=c,Cn=o,l+=122192928e5;var h=((l&268435455)*1e4+c)%4294967296;s[r++]=h>>>24&255,s[r++]=h>>>16&255,s[r++]=h>>>8&255,s[r++]=h&255;var d=l/4294967296*1e4&268435455;s[r++]=d>>>8&255,s[r++]=d&255,s[r++]=d>>>24&15|16,s[r++]=d>>>16&255,s[r++]=o>>>8|128,s[r++]=o&255;for(var f=0;f<6;++f)s[r+f]=i[f];return e||Ss(s)}function qc(t){var e=typeof t=="string"?rc(t):t,n=Yc(e);return typeof t=="string"?Ss(n):n}function Yc(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function oi(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function ai(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?oi(Object(n),!0).forEach(function(r){Xc(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):oi(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Xc(t,e,n){return(e=Zc(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Zc(t){var e=Qc(t,"string");return typeof e=="symbol"?e:e+""}function Qc(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function eu(t={},e,n=0){var r=Jc(ai(ai({},t),{},{_v6:!0}),new Uint8Array(16));return r=qc(r),Ss(r)}async function*tu(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}j(tu,"streamEventsToAISDK");function nu(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}j(nu,"createReadableStreamFromGenerator");async function*ru(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
3
3
  🔧 Using tool: ${e.name}
4
4
  `;break;case"on_tool_end":yield`
5
5
  ✅ Tool completed: ${e.name}
@@ -372,7 +372,7 @@ You can then use these server-specific tools in subsequent steps.
372
372
  Here are the tools *currently* available to you (this list includes server management tools and will
373
373
  change when you connect to a server):
374
374
  {tool_descriptions}
375
- `,jt,Gm=(jt=class{static getPackageVersion(){return Tl()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new Nm({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new mt,this.telemetry=ei.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Ui({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,!this.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new mt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Am(this.client,this.adapter)}else this.adapter=e.adapter??new mt(this.disallowedTools);if(this.telemetry=ei.getInstance(),this.llm){const[n,r]=kl(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Ui({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:j(()=>this.getMetadata(),"metadataProvider"),tagsProvider:j(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:j(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:j(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:j(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}y.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),y.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),y.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await mt.createTools(this.client),y.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{y.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const r of this.connectors)r.isClientConnected||await r.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),y.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}y.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Im;this.systemMessage=bl(e,n,Rm,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof be))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(i=>i.name);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[ml({runLimit:this.maxSteps})],s=sl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new be(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof be)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new mt(this.disallowedTools),this._initialized&&y.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},y.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],y.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){y.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const i=r.replace(/[^\w-]/g,"_");if(s==null)n[i]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[i]=s;else if(Array.isArray(s)){const o=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");o.length>0&&(n[i]=o)}else if(typeof s=="object")try{const o=JSON.stringify(s);o.length>1e3?(y.warn(`Metadata value for key '${i}' is too large. Truncating.`),n[i]=`${o.substring(0,1e3)}...`):n[i]=s}catch(o){y.warn(`Failed to serialize metadata value for key '${i}': ${o}. Skipping.`)}else y.warn(`Unsupported metadata value type for key '${i}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const i=this.client.getServerConfig(s);if(i){let o="unknown";i.command?o="command":i.url?o="http":i.ws_url&&(o="websocket"),r[s]={type:o,has_args:!!i.args,has_env:!!i.env,has_headers:!!i.headers,url:i.url||null,command:i.command||null}}}catch(i){y.warn(`Failed to get config for server '${s}': ${i}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){y.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const i=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(i))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof O)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof fe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof F)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof O||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,i){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(e,n,r,s,i);const o=this.stream(e,n,r,s,i);return this._consumeAndReturn(o)}async*stream(e,n,r=!0,s,i){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(e,n,r,s,i);let o=!1;const a=Date.now();let l=!1,c=null,u=0;try{if(r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const S=this.serverManager.tools,m=new Set(S.map(_=>_.name)),w=new Set(this._tools.map(_=>_.name));(m.size!==w.size||[...m].some(_=>!w.has(_)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...m].join(", ")}`),this._tools=S,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const h=s??this.conversationHistory,d=[];for(const S of h)(this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S))&&d.push(S);const f=e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:e.replace(/\n/g," ");y.info(`💬 Received query: '${f}'`),y.info("🏁 Starting agent execution");const g=3;let p=0;const C=[...d,new fe(e)];for(;p<=g;){const S={messages:C};let m=!1;const w=await this._agentExecutor.stream(S,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const _ of w){for(const[T,x]of Object.entries(_))if(y.debug(`📦 Node '${T}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let b=x.messages;Array.isArray(b)||(b=[b]);for(const v of b)C.includes(v)||C.push(v);for(const v of b){if("tool_calls"in v&&Array.isArray(v.tool_calls)&&v.tool_calls.length>0)for(const M of v.tool_calls){const E=M.name||"unknown",P=M.args||{};this.toolsUsedNames.push(E),u++;let I=JSON.stringify(P);I.length>100&&(I=`${I.slice(0,97)}...`),y.info(`🔧 Tool call: ${E} with input: ${I}`),yield{action:{tool:E,toolInput:P,log:`Calling tool ${E}`},observation:""}}if(this._isToolMessageLike(v)){const M=v.content;let E=String(M);if(E.length>100&&(E=`${E.slice(0,97)}...`),E=E.replace(/\n/g," "),y.info(`📄 Tool result: ${E}`),this.useServerManager&&this.serverManager){const P=this.serverManager.tools,I=new Set(P.map(X=>X.name)),V=new Set(this._tools.map(X=>X.name));if(I.size!==V.size||[...I].some(X=>!V.has(X))){y.info(`🔄 Tools changed during execution. New tools: ${[...I].join(", ")}`),this._tools=P,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),m=!0,p++,y.info(`🔃 Restarting execution with updated tools (restart ${p}/${g})`);break}}}this._isAIMessageLike(v)&&!this._messageHasToolCalls(v)&&(c=this._normalizeOutput(this._getMessageContent(v)),y.info("✅ Agent finished with output"))}if(m)break}if(m)break}if(!m)break;if(p>g){y.warn(`⚠️ Max restarts (${g}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const S=C.slice(d.length);for(const m of S)this.addToHistory(m)}if(i&&c)try{y.info("🔧 Attempting structured output...");const S=await this._attemptStructuredOutput(c,this.llm,i);return this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(S)}`)),y.info("✅ Structured output successful"),l=!0,S}catch(S){throw y.error(`❌ Structured output failed: ${S}`),new Error(`Failed to generate structured output: ${S instanceof Error?S.message:String(S)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-a)/1e3).toFixed(2)} seconds`),l=!0,c||"No output generated"}catch(h){throw y.error(`❌ Error running query: ${h}`),o&&r&&(y.info("🧹 Cleaning up resources after error"),await this.close()),h}finally{const h=Date.now()-a;let d=0;this.client?d=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(d=this.connectors.length);const f=this.memoryEnabled?this.conversationHistory.length:0,g=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:d,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:g.length,toolsAvailableNames:g.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:c||"",executionTimeMs:h,errorType:l?null:"execution_error",conversationHistoryLength:f}),r&&!this.client&&o&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new mt)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,i){const{prettyStreamEvents:o}=await an(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-BX11cXGe.js");return{prettyStreamEvents:l}},__vite__mapDeps([0,1,2])),a="";for await(const l of o(this.streamEvents(e,n,r,s,i)))yield;return a}async*streamEvents(e,n,r=!0,s,i){let o=!1;const a=Date.now();let l=!1,c=0,u=0,h="";i&&(e=this._enhanceQueryWithSchema(e,i));try{r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0);const d=this._agentExecutor;if(!d)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const f=typeof e=="string"&&e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:typeof e=="string"?e.replace(/\n/g," "):String(e);y.info(`💬 Received query for streamEvents: '${f}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${f}`),this.addToHistory(new fe({content:e})));const g=s??this.conversationHistory,p=[];for(const m of g)this._isHumanMessageLike(m)||this._isAIMessageLike(m)||this._isToolMessageLike(m)?p.push(m):y.info(`⚠️ Skipped message of type: ${m.constructor?.name||typeof m}`);const C=[...p,new fe(e)];y.info("callbacks",this.callbacks);const S=d.streamEvents({messages:C},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const m of S)if(c++,!(!m||typeof m!="object")){if(m.event==="on_chat_model_stream"&&m.data?.chunk?.content&&(u+=m.data.chunk.content.length),m.event==="on_chat_model_stream"&&m.data?.chunk){const w=m.data.chunk;if(w.content){h||(h="");const _=this._normalizeOutput(w.content);h+=_,y.debug(`📝 Accumulated response length: ${h.length}`)}}if(yield m,m.event==="on_chain_end"&&m.data?.output&&!h){const w=m.data.output;Array.isArray(w)&&w.length>0&&w[0]?.text?h=w[0].text:typeof w=="string"?h=w:w&&typeof w=="object"&&"output"in w&&(h=w.output)}}if(i&&h){y.info("🔧 Attempting structured output conversion...");try{let m=!1,w=null,_=null;this._attemptStructuredOutput(h,this.llm,i).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,_=x,x});let T=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(T++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${T*2}s)`,elapsed:T*2}});if(_)throw _;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(w)}`)),y.info("✅ Structured output successful"))}catch(m){y.warn(`⚠️ Structured output failed: ${m}`),yield{event:"on_structured_output_error",data:{error:m instanceof Error?m.message:String(m)}}}}else this.memoryEnabled&&h&&this.addToHistory(new O(h));console.log(`
375
+ `,jt,Gm=(jt=class{static getPackageVersion(){return Tl()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new Nm({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new mt,this.telemetry=ei.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Ui({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,!this.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new mt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new Am(this.client,this.adapter)}else this.adapter=e.adapter??new mt(this.disallowedTools);if(this.telemetry=ei.getInstance(),this.llm){const[n,r]=kl(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Ui({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:j(()=>this.getMetadata(),"metadataProvider"),tagsProvider:j(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:j(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:j(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:j(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}y.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),y.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),y.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await mt.createTools(this.client),y.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{y.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const r of this.connectors)r.isClientConnected||await r.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),y.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}y.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Im;this.systemMessage=bl(e,n,Rm,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof be))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(i=>i.name);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[ml({runLimit:this.maxSteps})],s=sl({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new be(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof be)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new mt(this.disallowedTools),this._initialized&&y.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},y.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],y.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){y.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const i=r.replace(/[^\w-]/g,"_");if(s==null)n[i]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[i]=s;else if(Array.isArray(s)){const o=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");o.length>0&&(n[i]=o)}else if(typeof s=="object")try{const o=JSON.stringify(s);o.length>1e3?(y.warn(`Metadata value for key '${i}' is too large. Truncating.`),n[i]=`${o.substring(0,1e3)}...`):n[i]=s}catch(o){y.warn(`Failed to serialize metadata value for key '${i}': ${o}. Skipping.`)}else y.warn(`Unsupported metadata value type for key '${i}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const i=this.client.getServerConfig(s);if(i){let o="unknown";i.command?o="command":i.url?o="http":i.ws_url&&(o="websocket"),r[s]={type:o,has_args:!!i.args,has_env:!!i.env,has_headers:!!i.headers,url:i.url||null,command:i.command||null}}}catch(i){y.warn(`Failed to get config for server '${s}': ${i}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){y.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const i=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(i))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof O)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof fe)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof F)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof O||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,i){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(e,n,r,s,i);const o=this.stream(e,n,r,s,i);return this._consumeAndReturn(o)}async*stream(e,n,r=!0,s,i){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(e,n,r,s,i);let o=!1;const a=Date.now();let l=!1,c=null,u=0;try{if(r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const S=this.serverManager.tools,m=new Set(S.map(_=>_.name)),w=new Set(this._tools.map(_=>_.name));(m.size!==w.size||[...m].some(_=>!w.has(_)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...m].join(", ")}`),this._tools=S,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const h=s??this.conversationHistory,d=[];for(const S of h)(this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S))&&d.push(S);const f=e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:e.replace(/\n/g," ");y.info(`💬 Received query: '${f}'`),y.info("🏁 Starting agent execution");const g=3;let p=0;const C=[...d,new fe(e)];for(;p<=g;){const S={messages:C};let m=!1;const w=await this._agentExecutor.stream(S,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const _ of w){for(const[T,x]of Object.entries(_))if(y.debug(`📦 Node '${T}' output: ${JSON.stringify(x)}`),x&&typeof x=="object"&&"messages"in x){let b=x.messages;Array.isArray(b)||(b=[b]);for(const v of b)C.includes(v)||C.push(v);for(const v of b){if("tool_calls"in v&&Array.isArray(v.tool_calls)&&v.tool_calls.length>0)for(const M of v.tool_calls){const E=M.name||"unknown",P=M.args||{};this.toolsUsedNames.push(E),u++;let I=JSON.stringify(P);I.length>100&&(I=`${I.slice(0,97)}...`),y.info(`🔧 Tool call: ${E} with input: ${I}`),yield{action:{tool:E,toolInput:P,log:`Calling tool ${E}`},observation:""}}if(this._isToolMessageLike(v)){const M=v.content;let E=String(M);if(E.length>100&&(E=`${E.slice(0,97)}...`),E=E.replace(/\n/g," "),y.info(`📄 Tool result: ${E}`),this.useServerManager&&this.serverManager){const P=this.serverManager.tools,I=new Set(P.map(X=>X.name)),V=new Set(this._tools.map(X=>X.name));if(I.size!==V.size||[...I].some(X=>!V.has(X))){y.info(`🔄 Tools changed during execution. New tools: ${[...I].join(", ")}`),this._tools=P,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),m=!0,p++,y.info(`🔃 Restarting execution with updated tools (restart ${p}/${g})`);break}}}this._isAIMessageLike(v)&&!this._messageHasToolCalls(v)&&(c=this._normalizeOutput(this._getMessageContent(v)),y.info("✅ Agent finished with output"))}if(m)break}if(m)break}if(!m)break;if(p>g){y.warn(`⚠️ Max restarts (${g}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const S=C.slice(d.length);for(const m of S)this.addToHistory(m)}if(i&&c)try{y.info("🔧 Attempting structured output...");const S=await this._attemptStructuredOutput(c,this.llm,i);return this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(S)}`)),y.info("✅ Structured output successful"),l=!0,S}catch(S){throw y.error(`❌ Structured output failed: ${S}`),new Error(`Failed to generate structured output: ${S instanceof Error?S.message:String(S)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-a)/1e3).toFixed(2)} seconds`),l=!0,c||"No output generated"}catch(h){throw y.error(`❌ Error running query: ${h}`),o&&r&&(y.info("🧹 Cleaning up resources after error"),await this.close()),h}finally{const h=Date.now()-a;let d=0;this.client?d=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(d=this.connectors.length);const f=this.memoryEnabled?this.conversationHistory.length:0,g=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:d,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:g.length,toolsAvailableNames:g.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:c||"",executionTimeMs:h,errorType:l?null:"execution_error",conversationHistoryLength:f}),r&&!this.client&&o&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new mt)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,i){const{prettyStreamEvents:o}=await an(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-CKX4vEt9.js");return{prettyStreamEvents:l}},__vite__mapDeps([0,1,2])),a="";for await(const l of o(this.streamEvents(e,n,r,s,i)))yield;return a}async*streamEvents(e,n,r=!0,s,i){let o=!1;const a=Date.now();let l=!1,c=0,u=0,h="";i&&(e=this._enhanceQueryWithSchema(e,i));try{r&&!this._initialized?(await this.initialize(),o=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),o=!0);const d=this._agentExecutor;if(!d)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const f=typeof e=="string"&&e.length>50?`${e.slice(0,50).replace(/\n/g," ")}...`:typeof e=="string"?e.replace(/\n/g," "):String(e);y.info(`💬 Received query for streamEvents: '${f}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${f}`),this.addToHistory(new fe({content:e})));const g=s??this.conversationHistory,p=[];for(const m of g)this._isHumanMessageLike(m)||this._isAIMessageLike(m)||this._isToolMessageLike(m)?p.push(m):y.info(`⚠️ Skipped message of type: ${m.constructor?.name||typeof m}`);const C=[...p,new fe(e)];y.info("callbacks",this.callbacks);const S=d.streamEvents({messages:C},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const m of S)if(c++,!(!m||typeof m!="object")){if(m.event==="on_chat_model_stream"&&m.data?.chunk?.content&&(u+=m.data.chunk.content.length),m.event==="on_chat_model_stream"&&m.data?.chunk){const w=m.data.chunk;if(w.content){h||(h="");const _=this._normalizeOutput(w.content);h+=_,y.debug(`📝 Accumulated response length: ${h.length}`)}}if(yield m,m.event==="on_chain_end"&&m.data?.output&&!h){const w=m.data.output;Array.isArray(w)&&w.length>0&&w[0]?.text?h=w[0].text:typeof w=="string"?h=w:w&&typeof w=="object"&&"output"in w&&(h=w.output)}}if(i&&h){y.info("🔧 Attempting structured output conversion...");try{let m=!1,w=null,_=null;this._attemptStructuredOutput(h,this.llm,i).then(x=>(m=!0,w=x,x)).catch(x=>{throw m=!0,_=x,x});let T=0;for(;!m;)await new Promise(x=>setTimeout(x,2e3)),m||(T++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${T*2}s)`,elapsed:T*2}});if(_)throw _;w&&(yield{event:"on_structured_output",data:{output:w}},this.memoryEnabled&&this.addToHistory(new O(`Structured result: ${JSON.stringify(w)}`)),y.info("✅ Structured output successful"))}catch(m){y.warn(`⚠️ Structured output failed: ${m}`),yield{event:"on_structured_output_error",data:{error:m instanceof Error?m.message:String(m)}}}}else this.memoryEnabled&&h&&this.addToHistory(new O(h));console.log(`
376
376
 
377
377
  `),y.info(`🎉 StreamEvents complete - ${c} events emitted`),l=!0}catch(d){throw y.error(`❌ Error during streamEvents: ${d}`),o&&r&&(y.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),d}finally{const d=Date.now()-a;let f=0;this.client?f=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(f=this.connectors.length);const g=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:e,success:l,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:f,serverIdentifiers:this.connectors.map(p=>p.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(p=>p.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,response:`[STREAMED RESPONSE - ${u} chars]`,executionTimeMs:d,errorType:l?null:"streaming_error",conversationHistoryLength:g}),r&&!this.client&&o&&(y.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){y.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),y.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,i="";if(y.debug(`🔄 Structured output requested, schema: ${JSON.stringify(An(r),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")s=n.withStructuredOutput(r);else if(n)s=n;else throw new Error("LLM is required for structured output");const o=An(r),{$schema:a,additionalProperties:l,...c}=o;i=JSON.stringify(c,null,2),y.info(`🔄 Schema description: ${i}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),y.info("rawResult",e),u||(u=JSON.stringify(e));const h=3;let d="";for(let f=1;f<=h;f++){y.info(`🔄 Structured output attempt ${f}/${h}`);let g=`
378
378
  Please format the following information according to the EXACT schema specified below.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CbvsEzXT.js","assets/index-BZHKq4Gu.js","assets/index-beDRbW3x.css"])))=>i.map(i=>d[i]);
2
- import{_ as a,a as k}from"./index-BZHKq4Gu.js";var y=null,L=null,O=null,J=!1,V=typeof process<"u"&&process.versions?.node;(async()=>{if(V)try{O=(await k(()=>import("./util-t-trnxQI.js").then(e=>e.u),[])).stripVTControlCharacters}catch{}try{y=(await k(()=>import("./index-JiKw9JSs.js"),[])).default}catch{}try{L=(await k(()=>import("./index-CbvsEzXT.js").then(e=>e.i),__vite__mapDeps([0,1,2]))).highlight}catch{}V&&(!y||!L)&&(J||(J=!0,console.warn(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BKbSGlCI.js","assets/index-ubmd7JRV.js","assets/index-beDRbW3x.css"])))=>i.map(i=>d[i]);
2
+ import{_ as a,a as k}from"./index-ubmd7JRV.js";var y=null,L=null,O=null,J=!1,V=typeof process<"u"&&process.versions?.node;(async()=>{if(V)try{O=(await k(()=>import("./util-t-trnxQI.js").then(e=>e.u),[])).stripVTControlCharacters}catch{}try{y=(await k(()=>import("./index-JiKw9JSs.js"),[])).default}catch{}try{L=(await k(()=>import("./index-BKbSGlCI.js").then(e=>e.i),__vite__mapDeps([0,1,2]))).highlight}catch{}V&&(!y||!L)&&(J||(J=!0,console.warn(`
3
3
  ✨ For enhanced console output with colors and syntax highlighting, install:
4
4
 
5
5
  npm install chalk cli-highlight
@@ -1 +1 @@
1
- import{_ as c,A as d}from"./index-CYBG3mWU.js";var l={};c(l,{chunkArray:()=>u});const u=(r,s)=>r.reduce((a,n,o)=>{const e=Math.floor(o/s),t=a[e]||[];return a[e]=t.concat([n]),a},[]);var _={};c(_,{Embeddings:()=>h});var h=class{caller;constructor(r){this.caller=new d(r??{})}};export{h as E,l as c,_ as e};
1
+ import{_ as c,A as d}from"./index-C9gKZsxC.js";var l={};c(l,{chunkArray:()=>u});const u=(r,s)=>r.reduce((a,n,o)=>{const e=Math.floor(o/s),t=a[e]||[];return a[e]=t.concat([n]),a},[]);var _={};c(_,{Embeddings:()=>h});var h=class{caller;constructor(r){this.caller=new d(r??{})}};export{h as E,l as c,_ as e};
@@ -1,4 +1,4 @@
1
- import{g as $n,O as bt,h as jn,f as Bn,e as Ln,R as xt}from"./index-Dh_Vxoku.js";import{i as Un,J as nn,a as St,ae as kt,H as qn,I as Wn,D as A,z as Mt,K as Fn,x as be,g as Tt,B as Dn,L as Hn}from"./index-CYBG3mWU.js";import"./index-BZHKq4Gu.js";import"./index-DRz5BQNA.js";var Rt=class extends $n{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(s){throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const n=await Un(this.zodSchema,e);if(n.success)return n.data;throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:i}=r;return Array.isArray(i.content)?sn(i.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}};function sn(t){const e=[];for(const n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}function Kn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}function Jn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Xn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function zn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function Vn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const Qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=nn({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Gn=t=>t();function Yn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Zn(t){function*e(){for(const n of t)Yn(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function G(t){return typeof t=="string"?t:es(t)}function es(t){const e=[];for(let n=0,{length:s}=t;n<s;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function Ve(t){return(t??"").split(";")[0].toLowerCase()}function he(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function H(t,e){const n=he(e,"cache_control");n!==void 0&&(t.cache_control=n);const s=he(e,"citations");s!==void 0&&(t.citations=s);const r=he(e,"context");r!==void 0&&(t.context=r);const i=he(e,"title");return i!==void 0&&(t.title=i),t}function Qe(t,e){const n=he(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function At(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function ts(t){const e=[],n=t.response_metadata,s="model_provider"in n&&n?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Zn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const i=Gn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:i})}else if(r.type==="reasoning"&&s)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&s)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&s)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const i=r.output.urls.map(a=>({type:"web_search_result",title:"",encrypted_content:"",url:a}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:i})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const i=r.metadata;if(r.fileId){e.push(H({type:"document",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){const a=Ve(r.mimeType);if(a==="application/pdf"||a===""){e.push(H({type:"document",source:{type:"url",url:r.url}},i));continue}}if(r.data){const a=Ve(r.mimeType);if(a===""||a==="application/pdf")e.push(H({type:"document",source:{type:"base64",data:G(r.data),media_type:"application/pdf"}},i));else if(a==="text/plain")e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},i));else if(At(a))e.push(H({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:G(r.data),media_type:a}}]}},i));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${a}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const i=r.metadata;if(r.fileId){e.push(Qe({type:"image",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){e.push(Qe({type:"image",source:{type:"url",url:r.url}},i));continue}if(r.data){const a=Ve(r.mimeType)||"image/png";At(a)&&e.push(Qe({type:"image",source:{type:"base64",data:G(r.data),media_type:a}},i));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&s&&e.push(r.value))}return e}function vt(t){const e=nn({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
1
+ import{g as $n,O as bt,h as jn,f as Bn,e as Ln,R as xt}from"./index-B8valPom.js";import{i as Un,J as nn,a as St,ae as kt,H as qn,I as Wn,D as A,z as Mt,K as Fn,x as be,g as Tt,B as Dn,L as Hn}from"./index-C9gKZsxC.js";import"./index-ubmd7JRV.js";import"./index-DRz5BQNA.js";var Rt=class extends $n{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(s){throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(s.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const n=await Un(this.zodSchema,e);if(n.success)return n.data;throw new bt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(r=>{const{message:i}=r;return Array.isArray(i.content)?sn(i.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}};function sn(t){const e=[];for(const n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}function Kn(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}function Jn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Xn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function zn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function Vn(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const Qn={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=nn({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Gn=t=>t();function Yn(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Zn(t){function*e(){for(const n of t)Yn(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function G(t){return typeof t=="string"?t:es(t)}function es(t){const e=[];for(let n=0,{length:s}=t;n<s;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function Ve(t){return(t??"").split(";")[0].toLowerCase()}function he(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function H(t,e){const n=he(e,"cache_control");n!==void 0&&(t.cache_control=n);const s=he(e,"citations");s!==void 0&&(t.citations=s);const r=he(e,"context");r!==void 0&&(t.context=r);const i=he(e,"title");return i!==void 0&&(t.title=i),t}function Qe(t,e){const n=he(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function At(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function ts(t){const e=[],n=t.response_metadata,s="model_provider"in n&&n?.model_provider==="anthropic";for(const r of t.contentBlocks)if(r.type==="text")r.annotations?e.push({type:"text",text:r.text,citations:Zn(r.annotations)}):e.push({type:"text",text:r.text});else if(r.type==="tool_call")e.push({type:"tool_use",id:r.id??"",name:r.name,input:r.args});else if(r.type==="tool_call_chunk"){const i=Gn(()=>{if(typeof r.args!="string")return r.args;try{return JSON.parse(r.args)}catch{return{}}});e.push({type:"tool_use",id:r.id??"",name:r.name??"",input:i})}else if(r.type==="reasoning"&&s)e.push({type:"thinking",thinking:r.reasoning,signature:String(r.signature)});else if(r.type==="server_tool_call"&&s)r.name==="web_search"?e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args}):r.name==="code_execution"&&e.push({type:"server_tool_use",name:r.name,id:r.id??"",input:r.args});else if(r.type==="server_tool_call_result"&&s)if(r.name==="web_search"&&Array.isArray(r.output.urls)){const i=r.output.urls.map(a=>({type:"web_search_result",title:"",encrypted_content:"",url:a}));e.push({type:"web_search_tool_result",tool_use_id:r.toolCallId??"",content:i})}else r.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:r.toolCallId??"",content:r.output}):r.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:r.toolCallId??"",content:r.output});else{if(r.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(r.type==="file"){const i=r.metadata;if(r.fileId){e.push(H({type:"document",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){const a=Ve(r.mimeType);if(a==="application/pdf"||a===""){e.push(H({type:"document",source:{type:"url",url:r.url}},i));continue}}if(r.data){const a=Ve(r.mimeType);if(a===""||a==="application/pdf")e.push(H({type:"document",source:{type:"base64",data:G(r.data),media_type:"application/pdf"}},i));else if(a==="text/plain")e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},i));else if(At(a))e.push(H({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:G(r.data),media_type:a}}]}},i));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${a}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(r.type==="image"){const i=r.metadata;if(r.fileId){e.push(Qe({type:"image",source:{type:"file",file_id:r.fileId}},i));continue}if(r.url){e.push(Qe({type:"image",source:{type:"url",url:r.url}},i));continue}if(r.data){const a=Ve(r.mimeType)||"image/png";At(a)&&e.push(Qe({type:"image",source:{type:"base64",data:G(r.data),media_type:a}},i));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else r.type==="video"||(r.type==="text-plain"?r.data&&e.push(H({type:"document",source:{type:"text",data:G(r.data),media_type:"text/plain"}},r.metadata)):r.type==="non_standard"&&s&&e.push(r.value))}return e}function vt(t){const e=nn({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
2
2
 
3
3
  `))}if(n.protocol==="http:"||n.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
4
4
 
@@ -1,4 +1,4 @@
1
- import{M as Be,N as Ue,O as X,P as te,_ as U,Q as At,S as Ot,U as Nt,V as kt,W as xt,X as Pt,Y as Mt,Z as Rt,n as Dt,$ as Lt,g as Ce,a0 as Ft,a1 as Bt,a2 as Ut,a3 as jt,a4 as Vt,a5 as zt,a6 as Gt,i as $t,a7 as Zt,h as Ge,a8 as Ht,a9 as $e,aa as Wt,ab as Xt,ac as Yt,ad as H,x as ue,ae as Se,af as Jt,ag as Kt,ah as qt,A as Ze,ai as ne,e as ie,aj as He,ak as We,b as oe,K as Qt,C as be,al as je,c as ea,R as Ve,y as Y,a as ta,am as Ie,D as aa,L as Xe,an as sa,ao as na,ap as ra,z as Ye,aq as re,r as G,ar as Je,as as ia,at as Ke,u as oa,m as ca,au as ua,av as la,aw as ha,ax as pa,ay as ga,az as ma,aA as fa,aB as da,B as ze,aC as ba,G as _a,aD as ya,o as qe,s as Qe,aE as Ta,aF as Te,p as va}from"./index-CYBG3mWU.js";import{g as Ea}from"./index-BZHKq4Gu.js";import{r as wa}from"./index-DRz5BQNA.js";function et(e,a,n,r,i){if(a!==e){typeof a.toJSON=="function"&&(a=a.toJSON());for(var c=Be(a),h=Be(e),l=!1,m=h.length-1;m>=0;m--){var g=h[m],T=e[g];if(Ue(a,g)&&!(a[g]===void 0&&T!==void 0&&Array.isArray(a)===!1)){var _=a[g];typeof T=="object"&&T!=null&&typeof _=="object"&&_!=null&&Array.isArray(T)===Array.isArray(_)?et(T,_,n,r+"/"+X(g),i):T!==_&&(i&&n.push({op:"test",path:r+"/"+X(g),value:te(T)}),n.push({op:"replace",path:r+"/"+X(g),value:te(_)}))}else Array.isArray(e)===Array.isArray(a)?(i&&n.push({op:"test",path:r+"/"+X(g),value:te(T)}),n.push({op:"remove",path:r+"/"+X(g)}),l=!0):(i&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:a}))}if(!(!l&&c.length==h.length))for(var m=0;m<c.length;m++){var g=c[m];!Ue(e,g)&&a[g]!==void 0&&n.push({op:"add",path:r+"/"+X(g),value:te(a[g])})}}}function Ae(e,a,n=!1){var r=[];return et(e,a,r,"",n),r}var Ca={};U(Ca,{extendInteropZodObject:()=>Yt,getInteropZodDefaultGetter:()=>Xt,getInteropZodObjectShape:()=>Wt,getSchemaDescription:()=>$e,interopParse:()=>Ht,interopParseAsync:()=>Ge,interopSafeParse:()=>Zt,interopSafeParseAsync:()=>$t,interopZodObjectMakeFieldsOptional:()=>Gt,interopZodObjectPartial:()=>zt,interopZodObjectPassthrough:()=>Vt,interopZodObjectStrict:()=>jt,interopZodTransformInputSchema:()=>Ut,isInteropZodLiteral:()=>Bt,isInteropZodObject:()=>Ft,isInteropZodSchema:()=>Ce,isShapelessZodSchema:()=>Lt,isSimpleStringZodSchema:()=>Dt,isZodArrayV4:()=>Rt,isZodLiteralV3:()=>Mt,isZodLiteralV4:()=>Pt,isZodObjectV3:()=>xt,isZodObjectV4:()=>kt,isZodSchema:()=>Nt,isZodSchemaV3:()=>Ot,isZodSchemaV4:()=>At});function tt(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function at(e){return e!==void 0&&H.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function st(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Ce(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function nt(e){return st(e)||at(e)||tt(e)}var Sa={};U(Sa,{convertToOpenAIFunction:()=>rt,convertToOpenAITool:()=>Ia,isLangChainTool:()=>nt,isRunnableToolLike:()=>at,isStructuredTool:()=>tt,isStructuredToolParams:()=>st});function rt(e,a){const n=typeof a=="number"?void 0:a;return{name:e.name,description:e.description,parameters:ue(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function Ia(e,a){const n=typeof a=="number"?void 0:a;let r;return nt(e)?r={type:"function",function:rt(e)}:r=e,n?.strict!==void 0&&(r.function.strict=n.strict),r}var Aa={};U(Aa,{BasePromptValue:()=>le,ChatPromptValue:()=>ot,ImagePromptValue:()=>Oa,StringPromptValue:()=>it});var le=class extends Kt{},it=class extends le{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new Se(this.value)]}},ot=class extends le{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return Jt(this.messages)}toChatMessages(){return this.messages}},Oa=class extends le{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Se({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},b="0123456789abcdef".split(""),Na=[-2147483648,8388608,32768,128],F=[24,16,8,0],ae=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],k=[];function B(e,a){a?(k[0]=k[16]=k[1]=k[2]=k[3]=k[4]=k[5]=k[6]=k[7]=k[8]=k[9]=k[10]=k[11]=k[12]=k[13]=k[14]=k[15]=0,this.blocks=k):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}B.prototype.update=function(e){if(!this.finalized){var a,n=typeof e;if(n!=="string"){if(n==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);a=!0}for(var r,i=0,c,h=e.length,l=this.blocks;i<h;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),a)for(c=this.start;i<h&&c<64;++i)l[c>>>2]|=e[i]<<F[c++&3];else for(c=this.start;i<h&&c<64;++i)r=e.charCodeAt(i),r<128?l[c>>>2]|=r<<F[c++&3]:r<2048?(l[c>>>2]|=(192|r>>>6)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]):r<55296||r>=57344?(l[c>>>2]|=(224|r>>>12)<<F[c++&3],l[c>>>2]|=(128|r>>>6&63)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),l[c>>>2]|=(240|r>>>18)<<F[c++&3],l[c>>>2]|=(128|r>>>12&63)<<F[c++&3],l[c>>>2]|=(128|r>>>6&63)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]);this.lastByteIndex=c,this.bytes+=c-this.start,c>=64?(this.block=l[16],this.start=c-64,this.hash(),this.hashed=!0):this.start=c}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};B.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,a=this.lastByteIndex;e[16]=this.block,e[a>>>2]|=Na[a&3],this.block=e[16],a>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};B.prototype.hash=function(){var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=this.blocks,g,T,_,v,d,y,f,E,w,P,I;for(g=16;g<64;++g)d=m[g-15],T=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3,d=m[g-2],_=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,m[g]=m[g-16]+T+m[g-7]+_<<0;for(I=a&n,g=0;g<64;g+=4)this.first?(this.is224?(E=300032,d=m[0]-1413257819,l=d-150054599<<0,r=d+24177077<<0):(E=704751109,d=m[0]-210244248,l=d-1521486534<<0,r=d+143694565<<0),this.first=!1):(T=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),_=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),E=e&a,v=E^e&n^I,f=i&c^~i&h,d=l+_+f+ae[g]+m[g],y=T+v,l=r+d<<0,r=d+y<<0),T=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),_=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),w=r&e,v=w^r&a^E,f=h&l^~h&i,d=c+_+f+ae[g+1]+m[g+1],y=T+v,h=n+d<<0,n=d+y<<0,T=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),_=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),P=n&r,v=P^n&e^w,f=c&h^~c&l,d=i+_+f+ae[g+2]+m[g+2],y=T+v,c=a+d<<0,a=d+y<<0,T=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),_=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),I=a&n,v=I^a&r^P,f=c&h^~c&l,d=i+_+f+ae[g+3]+m[g+3],y=T+v,i=e+d<<0,e=d+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+a<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+c<<0,this.h6=this.h6+h<<0,this.h7=this.h7+l<<0};B.prototype.hex=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=b[e>>>28&15]+b[e>>>24&15]+b[e>>>20&15]+b[e>>>16&15]+b[e>>>12&15]+b[e>>>8&15]+b[e>>>4&15]+b[e&15]+b[a>>>28&15]+b[a>>>24&15]+b[a>>>20&15]+b[a>>>16&15]+b[a>>>12&15]+b[a>>>8&15]+b[a>>>4&15]+b[a&15]+b[n>>>28&15]+b[n>>>24&15]+b[n>>>20&15]+b[n>>>16&15]+b[n>>>12&15]+b[n>>>8&15]+b[n>>>4&15]+b[n&15]+b[r>>>28&15]+b[r>>>24&15]+b[r>>>20&15]+b[r>>>16&15]+b[r>>>12&15]+b[r>>>8&15]+b[r>>>4&15]+b[r&15]+b[i>>>28&15]+b[i>>>24&15]+b[i>>>20&15]+b[i>>>16&15]+b[i>>>12&15]+b[i>>>8&15]+b[i>>>4&15]+b[i&15]+b[c>>>28&15]+b[c>>>24&15]+b[c>>>20&15]+b[c>>>16&15]+b[c>>>12&15]+b[c>>>8&15]+b[c>>>4&15]+b[c&15]+b[h>>>28&15]+b[h>>>24&15]+b[h>>>20&15]+b[h>>>16&15]+b[h>>>12&15]+b[h>>>8&15]+b[h>>>4&15]+b[h&15];return this.is224||(m+=b[l>>>28&15]+b[l>>>24&15]+b[l>>>20&15]+b[l>>>16&15]+b[l>>>12&15]+b[l>>>8&15]+b[l>>>4&15]+b[l&15]),m};B.prototype.toString=B.prototype.hex;B.prototype.digest=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||m.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),m};B.prototype.array=B.prototype.digest;B.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),a=new DataView(e);return a.setUint32(0,this.h0),a.setUint32(4,this.h1),a.setUint32(8,this.h2),a.setUint32(12,this.h3),a.setUint32(16,this.h4),a.setUint32(20,this.h5),a.setUint32(24,this.h6),this.is224||a.setUint32(28,this.h7),e};const ct=(...e)=>new B(!1,!0).update(e.join("")).hex();var ka={};U(ka,{sha256:()=>ct});var xa={};U(xa,{BaseCache:()=>lt,InMemoryCache:()=>ht,defaultHashKeyEncoder:()=>ut,deserializeStoredGeneration:()=>Pa,serializeGeneration:()=>Ma});const ut=(...e)=>ct(e.join("_"));function Pa(e){return e.message!==void 0?{text:e.text,message:qt(e.message)}:{text:e.text}}function Ma(e){const a={text:e.text};return e.message!==void 0&&(a.message=e.message.toDict()),a}var lt=class{keyEncoder=ut;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const Ra=new Map;var ht=class pt extends lt{cache;constructor(a){super(),this.cache=a??new Map}lookup(a,n){return Promise.resolve(this.cache.get(this.keyEncoder(a,n))??null)}async update(a,n,r){this.cache.set(this.keyEncoder(a,n),r)}static global(){return new pt(Ra)}},Da=wa();const La=Ea(Da);var Fa=Object.defineProperty,Ba=(e,a,n)=>a in e?Fa(e,a,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[a]=n,Ua=(e,a,n)=>(Ba(e,a+"",n),n);function ja(e,a){let n=Array.from({length:e.length},(r,i)=>({start:i,end:i+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){const c=e.slice(n[i].start,n[i+1].end),h=a.get(c.join(","));h!=null&&(r==null||h<r[0])&&(r=[h,i])}if(r!=null){const i=r[1];n[i]={start:n[i].start,end:n[i+1].end},n.splice(i+1,1)}else break}return n}function Va(e,a){return e.length===1?[a.get(e.join(","))]:ja(e,a).map(n=>a.get(e.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function za(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var ve=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,a){this.patStr=e.pat_str;const n=e.bpe_ranks.split(`
1
+ import{M as Be,N as Ue,O as X,P as te,_ as U,Q as At,S as Ot,U as Nt,V as kt,W as xt,X as Pt,Y as Mt,Z as Rt,n as Dt,$ as Lt,g as Ce,a0 as Ft,a1 as Bt,a2 as Ut,a3 as jt,a4 as Vt,a5 as zt,a6 as Gt,i as $t,a7 as Zt,h as Ge,a8 as Ht,a9 as $e,aa as Wt,ab as Xt,ac as Yt,ad as H,x as ue,ae as Se,af as Jt,ag as Kt,ah as qt,A as Ze,ai as ne,e as ie,aj as He,ak as We,b as oe,K as Qt,C as be,al as je,c as ea,R as Ve,y as Y,a as ta,am as Ie,D as aa,L as Xe,an as sa,ao as na,ap as ra,z as Ye,aq as re,r as G,ar as Je,as as ia,at as Ke,u as oa,m as ca,au as ua,av as la,aw as ha,ax as pa,ay as ga,az as ma,aA as fa,aB as da,B as ze,aC as ba,G as _a,aD as ya,o as qe,s as Qe,aE as Ta,aF as Te,p as va}from"./index-C9gKZsxC.js";import{g as Ea}from"./index-ubmd7JRV.js";import{r as wa}from"./index-DRz5BQNA.js";function et(e,a,n,r,i){if(a!==e){typeof a.toJSON=="function"&&(a=a.toJSON());for(var c=Be(a),h=Be(e),l=!1,m=h.length-1;m>=0;m--){var g=h[m],T=e[g];if(Ue(a,g)&&!(a[g]===void 0&&T!==void 0&&Array.isArray(a)===!1)){var _=a[g];typeof T=="object"&&T!=null&&typeof _=="object"&&_!=null&&Array.isArray(T)===Array.isArray(_)?et(T,_,n,r+"/"+X(g),i):T!==_&&(i&&n.push({op:"test",path:r+"/"+X(g),value:te(T)}),n.push({op:"replace",path:r+"/"+X(g),value:te(_)}))}else Array.isArray(e)===Array.isArray(a)?(i&&n.push({op:"test",path:r+"/"+X(g),value:te(T)}),n.push({op:"remove",path:r+"/"+X(g)}),l=!0):(i&&n.push({op:"test",path:r,value:e}),n.push({op:"replace",path:r,value:a}))}if(!(!l&&c.length==h.length))for(var m=0;m<c.length;m++){var g=c[m];!Ue(e,g)&&a[g]!==void 0&&n.push({op:"add",path:r+"/"+X(g),value:te(a[g])})}}}function Ae(e,a,n=!1){var r=[];return et(e,a,r,"",n),r}var Ca={};U(Ca,{extendInteropZodObject:()=>Yt,getInteropZodDefaultGetter:()=>Xt,getInteropZodObjectShape:()=>Wt,getSchemaDescription:()=>$e,interopParse:()=>Ht,interopParseAsync:()=>Ge,interopSafeParse:()=>Zt,interopSafeParseAsync:()=>$t,interopZodObjectMakeFieldsOptional:()=>Gt,interopZodObjectPartial:()=>zt,interopZodObjectPassthrough:()=>Vt,interopZodObjectStrict:()=>jt,interopZodTransformInputSchema:()=>Ut,isInteropZodLiteral:()=>Bt,isInteropZodObject:()=>Ft,isInteropZodSchema:()=>Ce,isShapelessZodSchema:()=>Lt,isSimpleStringZodSchema:()=>Dt,isZodArrayV4:()=>Rt,isZodLiteralV3:()=>Mt,isZodLiteralV4:()=>Pt,isZodObjectV3:()=>xt,isZodObjectV4:()=>kt,isZodSchema:()=>Nt,isZodSchemaV3:()=>Ot,isZodSchemaV4:()=>At});function tt(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function at(e){return e!==void 0&&H.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function st(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(Ce(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function nt(e){return st(e)||at(e)||tt(e)}var Sa={};U(Sa,{convertToOpenAIFunction:()=>rt,convertToOpenAITool:()=>Ia,isLangChainTool:()=>nt,isRunnableToolLike:()=>at,isStructuredTool:()=>tt,isStructuredToolParams:()=>st});function rt(e,a){const n=typeof a=="number"?void 0:a;return{name:e.name,description:e.description,parameters:ue(e.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function Ia(e,a){const n=typeof a=="number"?void 0:a;let r;return nt(e)?r={type:"function",function:rt(e)}:r=e,n?.strict!==void 0&&(r.function.strict=n.strict),r}var Aa={};U(Aa,{BasePromptValue:()=>le,ChatPromptValue:()=>ot,ImagePromptValue:()=>Oa,StringPromptValue:()=>it});var le=class extends Kt{},it=class extends le{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new Se(this.value)]}},ot=class extends le{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return Jt(this.messages)}toChatMessages(){return this.messages}},Oa=class extends le{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new Se({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},b="0123456789abcdef".split(""),Na=[-2147483648,8388608,32768,128],F=[24,16,8,0],ae=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],k=[];function B(e,a){a?(k[0]=k[16]=k[1]=k[2]=k[3]=k[4]=k[5]=k[6]=k[7]=k[8]=k[9]=k[10]=k[11]=k[12]=k[13]=k[14]=k[15]=0,this.blocks=k):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}B.prototype.update=function(e){if(!this.finalized){var a,n=typeof e;if(n!=="string"){if(n==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);a=!0}for(var r,i=0,c,h=e.length,l=this.blocks;i<h;){if(this.hashed&&(this.hashed=!1,l[0]=this.block,this.block=l[16]=l[1]=l[2]=l[3]=l[4]=l[5]=l[6]=l[7]=l[8]=l[9]=l[10]=l[11]=l[12]=l[13]=l[14]=l[15]=0),a)for(c=this.start;i<h&&c<64;++i)l[c>>>2]|=e[i]<<F[c++&3];else for(c=this.start;i<h&&c<64;++i)r=e.charCodeAt(i),r<128?l[c>>>2]|=r<<F[c++&3]:r<2048?(l[c>>>2]|=(192|r>>>6)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]):r<55296||r>=57344?(l[c>>>2]|=(224|r>>>12)<<F[c++&3],l[c>>>2]|=(128|r>>>6&63)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]):(r=65536+((r&1023)<<10|e.charCodeAt(++i)&1023),l[c>>>2]|=(240|r>>>18)<<F[c++&3],l[c>>>2]|=(128|r>>>12&63)<<F[c++&3],l[c>>>2]|=(128|r>>>6&63)<<F[c++&3],l[c>>>2]|=(128|r&63)<<F[c++&3]);this.lastByteIndex=c,this.bytes+=c-this.start,c>=64?(this.block=l[16],this.start=c-64,this.hash(),this.hashed=!0):this.start=c}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};B.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,a=this.lastByteIndex;e[16]=this.block,e[a>>>2]|=Na[a&3],this.block=e[16],a>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};B.prototype.hash=function(){var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=this.blocks,g,T,_,v,d,y,f,E,w,P,I;for(g=16;g<64;++g)d=m[g-15],T=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3,d=m[g-2],_=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,m[g]=m[g-16]+T+m[g-7]+_<<0;for(I=a&n,g=0;g<64;g+=4)this.first?(this.is224?(E=300032,d=m[0]-1413257819,l=d-150054599<<0,r=d+24177077<<0):(E=704751109,d=m[0]-210244248,l=d-1521486534<<0,r=d+143694565<<0),this.first=!1):(T=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),_=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),E=e&a,v=E^e&n^I,f=i&c^~i&h,d=l+_+f+ae[g]+m[g],y=T+v,l=r+d<<0,r=d+y<<0),T=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),_=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),w=r&e,v=w^r&a^E,f=h&l^~h&i,d=c+_+f+ae[g+1]+m[g+1],y=T+v,h=n+d<<0,n=d+y<<0,T=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),_=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),P=n&r,v=P^n&e^w,f=c&h^~c&l,d=i+_+f+ae[g+2]+m[g+2],y=T+v,c=a+d<<0,a=d+y<<0,T=(a>>>2|a<<30)^(a>>>13|a<<19)^(a>>>22|a<<10),_=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),I=a&n,v=I^a&r^P,f=c&h^~c&l,d=i+_+f+ae[g+3]+m[g+3],y=T+v,i=e+d<<0,e=d+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+a<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+c<<0,this.h6=this.h6+h<<0,this.h7=this.h7+l<<0};B.prototype.hex=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=b[e>>>28&15]+b[e>>>24&15]+b[e>>>20&15]+b[e>>>16&15]+b[e>>>12&15]+b[e>>>8&15]+b[e>>>4&15]+b[e&15]+b[a>>>28&15]+b[a>>>24&15]+b[a>>>20&15]+b[a>>>16&15]+b[a>>>12&15]+b[a>>>8&15]+b[a>>>4&15]+b[a&15]+b[n>>>28&15]+b[n>>>24&15]+b[n>>>20&15]+b[n>>>16&15]+b[n>>>12&15]+b[n>>>8&15]+b[n>>>4&15]+b[n&15]+b[r>>>28&15]+b[r>>>24&15]+b[r>>>20&15]+b[r>>>16&15]+b[r>>>12&15]+b[r>>>8&15]+b[r>>>4&15]+b[r&15]+b[i>>>28&15]+b[i>>>24&15]+b[i>>>20&15]+b[i>>>16&15]+b[i>>>12&15]+b[i>>>8&15]+b[i>>>4&15]+b[i&15]+b[c>>>28&15]+b[c>>>24&15]+b[c>>>20&15]+b[c>>>16&15]+b[c>>>12&15]+b[c>>>8&15]+b[c>>>4&15]+b[c&15]+b[h>>>28&15]+b[h>>>24&15]+b[h>>>20&15]+b[h>>>16&15]+b[h>>>12&15]+b[h>>>8&15]+b[h>>>4&15]+b[h&15];return this.is224||(m+=b[l>>>28&15]+b[l>>>24&15]+b[l>>>20&15]+b[l>>>16&15]+b[l>>>12&15]+b[l>>>8&15]+b[l>>>4&15]+b[l&15]),m};B.prototype.toString=B.prototype.hex;B.prototype.digest=function(){this.finalize();var e=this.h0,a=this.h1,n=this.h2,r=this.h3,i=this.h4,c=this.h5,h=this.h6,l=this.h7,m=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||m.push(l>>>24&255,l>>>16&255,l>>>8&255,l&255),m};B.prototype.array=B.prototype.digest;B.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),a=new DataView(e);return a.setUint32(0,this.h0),a.setUint32(4,this.h1),a.setUint32(8,this.h2),a.setUint32(12,this.h3),a.setUint32(16,this.h4),a.setUint32(20,this.h5),a.setUint32(24,this.h6),this.is224||a.setUint32(28,this.h7),e};const ct=(...e)=>new B(!1,!0).update(e.join("")).hex();var ka={};U(ka,{sha256:()=>ct});var xa={};U(xa,{BaseCache:()=>lt,InMemoryCache:()=>ht,defaultHashKeyEncoder:()=>ut,deserializeStoredGeneration:()=>Pa,serializeGeneration:()=>Ma});const ut=(...e)=>ct(e.join("_"));function Pa(e){return e.message!==void 0?{text:e.text,message:qt(e.message)}:{text:e.text}}function Ma(e){const a={text:e.text};return e.message!==void 0&&(a.message=e.message.toDict()),a}var lt=class{keyEncoder=ut;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const Ra=new Map;var ht=class pt extends lt{cache;constructor(a){super(),this.cache=a??new Map}lookup(a,n){return Promise.resolve(this.cache.get(this.keyEncoder(a,n))??null)}async update(a,n,r){this.cache.set(this.keyEncoder(a,n),r)}static global(){return new pt(Ra)}},Da=wa();const La=Ea(Da);var Fa=Object.defineProperty,Ba=(e,a,n)=>a in e?Fa(e,a,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[a]=n,Ua=(e,a,n)=>(Ba(e,a+"",n),n);function ja(e,a){let n=Array.from({length:e.length},(r,i)=>({start:i,end:i+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){const c=e.slice(n[i].start,n[i+1].end),h=a.get(c.join(","));h!=null&&(r==null||h<r[0])&&(r=[h,i])}if(r!=null){const i=r[1];n[i]={start:n[i].start,end:n[i+1].end},n.splice(i+1,1)}else break}return n}function Va(e,a){return e.length===1?[a.get(e.join(","))]:ja(e,a).map(n=>a.get(e.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function za(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var ve=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,a){this.patStr=e.pat_str;const n=e.bpe_ranks.split(`
2
2
  `).filter(Boolean).reduce((r,i)=>{const[c,h,...l]=i.split(" "),m=Number.parseInt(h,10);return l.forEach((g,T)=>r[g]=m+T),r},{});for(const[r,i]of Object.entries(n)){const c=La.toByteArray(r);this.rankMap.set(c.join(","),i),this.textMap.set(i,c)}this.specialTokens={...e.special_tokens,...a},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[i,c])=>(r[c]=this.textEncoder.encode(i),r),{})}encode(e,a=[],n="all"){const r=new RegExp(this.patStr,"ug"),i=ve.specialTokenRegex(Object.keys(this.specialTokens)),c=[],h=new Set(a==="all"?Object.keys(this.specialTokens):a),l=new Set(n==="all"?Object.keys(this.specialTokens).filter(g=>!h.has(g)):n);if(l.size>0){const g=ve.specialTokenRegex([...l]),T=e.match(g);if(T!=null)throw new Error(`The text contains a special token that is not allowed: ${T[0]}`)}let m=0;for(;;){let g=null,T=m;for(;i.lastIndex=T,g=i.exec(e),!(g==null||h.has(g[0]));)T=g.index+1;const _=g?.index??e.length;for(const d of e.substring(m,_).matchAll(r)){const y=this.textEncoder.encode(d[0]),f=this.rankMap.get(y.join(","));if(f!=null){c.push(f);continue}c.push(...Va(y,this.rankMap))}if(g==null)break;let v=this.specialTokens[g[0]];c.push(v),m=g.index+g[0].length}return c}decode(e){const a=[];let n=0;for(let c=0;c<e.length;++c){const h=e[c],l=this.textMap.get(h)??this.inverseSpecialTokens[h];l!=null&&(a.push(l),n+=l.length)}const r=new Uint8Array(n);let i=0;for(const c of a)r.set(c,i),i+=c.length;return this.textDecoder.decode(r)}},gt=ve;Ua(gt,"specialTokenRegex",e=>new RegExp(e.map(a=>za(a)).join("|"),"g"));function Ga(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var $a={};U($a,{encodingForModel:()=>Oe,getEncoding:()=>mt});const se={},Za=new Ze({});async function mt(e){return e in se||(se[e]=Za.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(a=>a.json()).then(a=>new gt(a)).catch(a=>{throw delete se[e],a})),await se[e]}async function Oe(e){return mt(Ga(e))}var Ha={};U(Ha,{BaseLangChain:()=>dt,BaseLanguageModel:()=>bt,calculateMaxTokens:()=>Ya,getEmbeddingContextSize:()=>Wa,getModelContextSize:()=>ft,getModelNameForTiktoken:()=>he,isOpenAITool:()=>Xa});const he=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,Wa=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},ft=e=>{switch(he(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Xa(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}const Ya=async({prompt:e,modelName:a})=>{let n;try{n=(await Oe(he(a))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),n=Math.ceil(e.length/4)}return ft(a)-n},Ja=()=>!1;var dt=class extends H{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??Ja(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},bt=class extends dt{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:a,...n}){const{cache:r,...i}=n;super({callbacks:e??a,...i}),typeof r=="object"?this.cache=r:r?this.cache=ht.global():this.cache=void 0,this.caller=new Ze(n??{})}_encoding;async getNumTokens(e){let a;typeof e=="string"?a=e:a=e.map(r=>typeof r=="string"?r:r.type==="text"&&"text"in r?r.text:"").join("");let n=Math.ceil(a.length/4);if(!this._encoding)try{this._encoding=await Oe("modelName"in this?he(this.modelName):"gpt2")}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}if(this._encoding)try{n=this._encoding.encode(a).length}catch(r){console.warn("Failed to calculate number of tokens, falling back to approximate count",r)}return n}static _convertInputToPromptValue(e){return typeof e=="string"?new it(e):Array.isArray(e)?new ot(e.map(ne)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...a}){const n={...this._identifyingParams(),...a,_type:this._llmType(),_model:this._modelType()};return Object.entries(n).filter(([c,h])=>h!==void 0).map(([c,h])=>`${c}:${JSON.stringify(h)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}},ce=class extends H{static lc_name(){return"RunnablePassthrough"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;func;constructor(e){super(e),e&&(this.func=e.func)}async invoke(e,a){const n=ie(a);return this.func&&await this.func(e,n),this._callWithConfig(r=>Promise.resolve(r),e,n)}async*transform(e,a){const n=ie(a);let r,i=!0;for await(const c of this._transformStreamWithConfig(e,h=>h,n))if(yield c,i)if(r===void 0)r=c;else try{r=oe(r,c)}catch{r=void 0,i=!1}this.func&&r!==void 0&&await this.func(r,n)}static assign(e){return new He(new We({steps:e}))}};const Ka=e=>e();function _e(e){const a=e.constructor;return new a({...e,content:e.contentBlocks,response_metadata:{...e.response_metadata,output_version:"v1"}})}var qa={};U(qa,{BaseChatModel:()=>_t,SimpleChatModel:()=>Qa});function ye(e){const a=[];for(const n of e){let r=n;if(Array.isArray(n.content))for(let i=0;i<n.content.length;i++){const c=n.content[i];(sa(c)||na(c))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,i),ra(c),...n.content.slice(i+1)]}))}a.push(r)}return a}var _t=class $ extends bt{lc_namespace=["langchain","chat_models",this._llmType()];disableStreaming=!1;outputVersion;get callKeys(){return[...super.callKeys,"outputVersion"]}constructor(a){super(a),this.outputVersion=Ka(()=>{const n=a.outputVersion??Qt("LC_OUTPUT_VERSION");return n&&["v0","v1"].includes(n)?n:"v0"})}_separateRunnableConfigFromCallOptionsCompat(a){const[n,r]=super._separateRunnableConfigFromCallOptions(a);return r.signal=n.signal,[n,r]}async invoke(a,n){const r=$._convertInputToPromptValue(a);return(await this.generatePrompt([r],n,n?.callbacks)).generations[0][0].message}async*_streamResponseChunks(a,n,r){throw new Error("Not implemented.")}async*_streamIterator(a,n){if(this._streamResponseChunks===$.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(a,n);else{const i=$._convertInputToPromptValue(a).toChatMessages(),[c,h]=this._separateRunnableConfigFromCallOptionsCompat(n),l={...c.metadata,...this.getLsParams(h)},m=await be.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose}),g={options:h,invocation_params:this?.invocationParams(h),batch_size:1},T=h.outputVersion??this.outputVersion,_=await m?.handleChatModelStart(this.toJSON(),[ye(i)],c.runId,void 0,g,void 0,void 0,c.runName);let v,d;try{for await(const y of this._streamResponseChunks(i,h,_?.[0])){if(y.message.id==null){const f=_?.at(0)?.runId;f!=null&&y.message._updateId(`run-${f}`)}y.message.response_metadata={...y.generationInfo,...y.message.response_metadata},T==="v1"?yield _e(y.message):yield y.message,v?v=v.concat(y):v=y,je(y.message)&&y.message.usage_metadata!==void 0&&(d={tokenUsage:{promptTokens:y.message.usage_metadata.input_tokens,completionTokens:y.message.usage_metadata.output_tokens,totalTokens:y.message.usage_metadata.total_tokens}})}}catch(y){throw await Promise.all((_??[]).map(f=>f?.handleLLMError(y))),y}await Promise.all((_??[]).map(y=>y?.handleLLMEnd({generations:[[v]],llmOutput:d})))}}getLsParams(a){const n=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:a.stop,ls_provider:n}}async _generateUncached(a,n,r,i){const c=a.map(v=>v.map(ne));let h;if(i!==void 0&&i.length===c.length)h=i;else{const v={...r.metadata,...this.getLsParams(n)},d=await be.configure(r.callbacks,this.callbacks,r.tags,this.tags,v,this.metadata,{verbose:this.verbose}),y={options:n,invocation_params:this?.invocationParams(n),batch_size:1};h=await d?.handleChatModelStart(this.toJSON(),c.map(ye),r.runId,void 0,y,void 0,void 0,r.runName)}const l=n.outputVersion??this.outputVersion,m=[],g=[];if(!!h?.[0].handlers.find(ea)&&!this.disableStreaming&&c.length===1&&this._streamResponseChunks!==$.prototype._streamResponseChunks)try{const v=await this._streamResponseChunks(c[0],n,h?.[0]);let d,y;for await(const f of v){if(f.message.id==null){const E=h?.at(0)?.runId;E!=null&&f.message._updateId(`run-${E}`)}d===void 0?d=f:d=oe(d,f),je(f.message)&&f.message.usage_metadata!==void 0&&(y={tokenUsage:{promptTokens:f.message.usage_metadata.input_tokens,completionTokens:f.message.usage_metadata.output_tokens,totalTokens:f.message.usage_metadata.total_tokens}})}if(d===void 0)throw new Error("Received empty response from chat model call.");m.push([d]),await h?.[0].handleLLMEnd({generations:m,llmOutput:y})}catch(v){throw await h?.[0].handleLLMError(v),v}else{const v=await Promise.allSettled(c.map(async(d,y)=>{const f=await this._generate(d,{...n,promptIndex:y},h?.[y]);if(l==="v1")for(const E of f.generations)E.message=_e(E.message);return f}));await Promise.all(v.map(async(d,y)=>{if(d.status==="fulfilled"){const f=d.value;for(const E of f.generations){if(E.message.id==null){const w=h?.at(0)?.runId;w!=null&&E.message._updateId(`run-${w}`)}E.message.response_metadata={...E.generationInfo,...E.message.response_metadata}}return f.generations.length===1&&(f.generations[0].message.response_metadata={...f.llmOutput,...f.generations[0].message.response_metadata}),m[y]=f.generations,g[y]=f.llmOutput,h?.[y]?.handleLLMEnd({generations:[f.generations],llmOutput:f.llmOutput})}else return await h?.[y]?.handleLLMError(d.reason),Promise.reject(d.reason)}))}const _={generations:m,llmOutput:g.length?this._combineLLMOutput?.(...g):void 0};return Object.defineProperty(_,Ve,{value:h?{runIds:h?.map(v=>v.runId)}:void 0,configurable:!0}),_}async _generateCached({messages:a,cache:n,llmStringKey:r,parsedOptions:i,handledOptions:c}){const h=a.map(w=>w.map(ne)),l={...c.metadata,...this.getLsParams(i)},m=await be.configure(c.callbacks,this.callbacks,c.tags,this.tags,l,this.metadata,{verbose:this.verbose}),g={options:i,invocation_params:this?.invocationParams(i),batch_size:1},T=await m?.handleChatModelStart(this.toJSON(),h.map(ye),c.runId,void 0,g,void 0,void 0,c.runName),_=[],d=(await Promise.allSettled(h.map(async(w,P)=>{const I=$._convertInputToPromptValue(w).toString(),R=await n.lookup(I,r);return R==null&&_.push(P),R}))).map((w,P)=>({result:w,runManager:T?.[P]})).filter(({result:w})=>w.status==="fulfilled"&&w.value!=null||w.status==="rejected"),y=i.outputVersion??this.outputVersion,f=[];await Promise.all(d.map(async({result:w,runManager:P},I)=>{if(w.status==="fulfilled"){const R=w.value;return f[I]=R.map(L=>("message"in L&&Y(L.message)&&ta(L.message)&&(L.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},y==="v1"&&(L.message=_e(L.message))),L.generationInfo={...L.generationInfo,tokenUsage:{}},L)),R.length&&await P?.handleLLMNewToken(R[0].text),P?.handleLLMEnd({generations:[R]},void 0,void 0,void 0,{cached:!0})}else return await P?.handleLLMError(w.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(w.reason)}));const E={generations:f,missingPromptIndices:_,startedRunManagers:T};return Object.defineProperty(E,Ve,{value:T?{runIds:T?.map(w=>w.runId)}:void 0,configurable:!0}),E}async generate(a,n,r){let i;Array.isArray(n)?i={stop:n}:i=n;const c=a.map(y=>y.map(ne)),[h,l]=this._separateRunnableConfigFromCallOptionsCompat(i);if(h.callbacks=h.callbacks??r,!this.cache)return this._generateUncached(c,l,h);const{cache:m}=this,g=this._getSerializedCacheKeyParametersForCall(l),{generations:T,missingPromptIndices:_,startedRunManagers:v}=await this._generateCached({messages:c,cache:m,llmStringKey:g,parsedOptions:l,handledOptions:h});let d={};if(_.length>0){const y=await this._generateUncached(_.map(f=>c[f]),l,h,v!==void 0?_.map(f=>v?.[f]):void 0);await Promise.all(y.generations.map(async(f,E)=>{const w=_[E];T[w]=f;const P=$._convertInputToPromptValue(c[w]).toString();return m.update(P,g,f)})),d=y.llmOutput??{}}return{generations:T,llmOutput:d}}invocationParams(a){return{}}_modelType(){return"base_chat_model"}async generatePrompt(a,n,r){const i=a.map(c=>c.toChatMessages());return this.generate(i,n,r)}withStructuredOutput(a,n){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(n?.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=a,i=n?.name,c=$e(r)??"A function available to call.",h=n?.method,l=n?.includeRaw;if(h==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let m=i??"extract",g;Ce(r)?g=[{type:"function",function:{name:m,description:c,parameters:ue(r)}}]:("name"in r&&(m=r.name),g=[{type:"function",function:{name:m,description:c,parameters:r}}]);const T=this.bindTools(g),_=Ie.from(f=>{if(!aa.isInstance(f))throw new Error("Input is not an AIMessageChunk.");if(!f.tool_calls||f.tool_calls.length===0)throw new Error("No tool calls found in the response.");const E=f.tool_calls.find(w=>w.name===m);if(!E)throw new Error(`No tool call found with name ${m}.`);return E.args});if(!l)return T.pipe(_).withConfig({runName:"StructuredOutput"});const v=ce.assign({parsed:(f,E)=>_.invoke(f.raw,E)}),d=ce.assign({parsed:()=>null}),y=v.withFallbacks({fallbacks:[d]});return Xe.from([{raw:T},y]).withConfig({runName:"StructuredOutputRunnable"})}},Qa=class extends _t{async _generate(e,a,n){const r=await this._call(e,a,n),i=new Ye(r);if(typeof i.content!="string")throw new Error("Cannot generate with a simple chat model when output is not a string.");return{generations:[{text:i.content,message:i}]}}},es=class extends H{static lc_name(){return"RouterRunnable"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;runnables;constructor(e){super(e),this.runnables=e.runnables}async invoke(e,a){const{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw new Error(`No runnable associated with key "${n}".`);return i.invoke(r,ie(a))}async batch(e,a,n){const r=e.map(_=>_.key),i=e.map(_=>_.input);if(r.find(_=>this.runnables[_]===void 0)!==void 0)throw new Error("One or more keys do not have a corresponding runnable.");const h=r.map(_=>this.runnables[_]),l=this._getOptionsList(a??{},e.length),m=l[0]?.maxConcurrency??n?.maxConcurrency,g=m&&m>0?m:e.length,T=[];for(let _=0;_<i.length;_+=g){const v=i.slice(_,_+g).map((y,f)=>h[f].invoke(y,l[f])),d=await Promise.all(v);T.push(d)}return T.flat()}async stream(e,a){const{key:n,input:r}=e,i=this.runnables[n];if(i===void 0)throw new Error(`No runnable associated with key "${n}".`);return i.stream(r,a)}},ts=class extends H{static lc_name(){return"RunnableBranch"}lc_namespace=["langchain_core","runnables"];lc_serializable=!0;default;branches;constructor(e){super(e),this.branches=e.branches,this.default=e.default}static from(e){if(e.length<1)throw new Error("RunnableBranch requires at least one branch");const n=e.slice(0,-1).map(([i,c])=>[re(i),re(c)]),r=re(e[e.length-1]);return new this({branches:n,default:r})}async _invoke(e,a,n){let r;for(let i=0;i<this.branches.length;i+=1){const[c,h]=this.branches[i];if(await c.invoke(e,G(a,{callbacks:n?.getChild(`condition:${i+1}`)}))){r=await h.invoke(e,G(a,{callbacks:n?.getChild(`branch:${i+1}`)}));break}}return r||(r=await this.default.invoke(e,G(a,{callbacks:n?.getChild("branch:default")}))),r}async invoke(e,a={}){return this._callWithConfig(this._invoke,e,a)}async*_streamIterator(e,a){const r=await(await Je(a))?.handleChainStart(this.toJSON(),ia(e,"input"),a?.runId,void 0,void 0,void 0,a?.runName);let i,c=!0,h;try{for(let l=0;l<this.branches.length;l+=1){const[m,g]=this.branches[l];if(await m.invoke(e,G(a,{callbacks:r?.getChild(`condition:${l+1}`)}))){h=await g.stream(e,G(a,{callbacks:r?.getChild(`branch:${l+1}`)}));for await(const _ of h)if(yield _,c)if(i===void 0)i=_;else try{i=oe(i,_)}catch{i=void 0,c=!1}break}}if(h===void 0){h=await this.default.stream(e,G(a,{callbacks:r?.getChild("branch:default")}));for await(const l of h)if(yield l,c)if(i===void 0)i=l;else try{i=oe(i,l)}catch{i=void 0,c=!1}}}catch(l){throw await r?.handleChainError(l),l}await r?.handleChainEnd(i??{})}},as=class extends Ke{runnable;inputMessagesKey;outputMessagesKey;historyMessagesKey;getMessageHistory;constructor(e){let a=Ie.from((c,h)=>this._enterHistory(c,h??{})).withConfig({runName:"loadHistory"});const n=e.historyMessagesKey??e.inputMessagesKey;n&&(a=ce.assign({[n]:a}).withConfig({runName:"insertHistory"}));const r=a.pipe(e.runnable.withListeners({onEnd:(c,h)=>this._exitHistory(c,h??{})})).withConfig({runName:"RunnableWithMessageHistory"}),i=e.config??{};super({...e,config:i,bound:r}),this.runnable=e.runnable,this.getMessageHistory=e.getMessageHistory,this.inputMessagesKey=e.inputMessagesKey,this.outputMessagesKey=e.outputMessagesKey,this.historyMessagesKey=e.historyMessagesKey}_getInputMessages(e){let a;if(typeof e=="object"&&!Array.isArray(e)&&!Y(e)){let n;this.inputMessagesKey?n=this.inputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="input",Array.isArray(e[n])&&Array.isArray(e[n][0])?a=e[n][0]:a=e[n]}else a=e;if(typeof a=="string")return[new Se(a)];if(Array.isArray(a))return a;if(Y(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.
3
3
  Got ${JSON.stringify(a,null,2)}`)}_getOutputMessages(e){let a;if(!Array.isArray(e)&&!Y(e)&&typeof e!="string"){let n;this.outputMessagesKey!==void 0?n=this.outputMessagesKey:Object.keys(e).length===1?n=Object.keys(e)[0]:n="output",e.generations!==void 0?a=e.generations[0][0].message:a=e[n]}else a=e;if(typeof a=="string")return[new Ye(a)];if(Array.isArray(a))return a;if(Y(a))return[a];throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(a,null,2)}`)}async _enterHistory(e,a){const r=await(a?.configurable?.messageHistory).getMessages();return this.historyMessagesKey===void 0?r.concat(this._getInputMessages(e)):r}async _exitHistory(e,a){const n=a.configurable?.messageHistory;let r;Array.isArray(e.inputs)&&Array.isArray(e.inputs[0])?r=e.inputs[0]:r=e.inputs;let i=this._getInputMessages(r);if(this.historyMessagesKey===void 0){const l=await n.getMessages();i=i.slice(l.length)}const c=e.outputs;if(!c)throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(e,null,2)}`);const h=this._getOutputMessages(c);await n.addMessages([...i,...h])}async _mergeConfig(...e){const a=await super._mergeConfig(...e);if(!a.configurable||!a.configurable.sessionId){const r={[this.inputMessagesKey??"input"]:"foo"},i={configurable:{sessionId:"123"}};throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()
4
4
  eg. chain.invoke(${JSON.stringify(r)}, ${JSON.stringify(i)})`)}const{sessionId:n}=a.configurable;return a.configurable.messageHistory=await this.getMessageHistory(n),a}},ss={};U(ss,{RouterRunnable:()=>es,Runnable:()=>H,RunnableAssign:()=>He,RunnableBinding:()=>Ke,RunnableBranch:()=>ts,RunnableEach:()=>ma,RunnableLambda:()=>Ie,RunnableMap:()=>We,RunnableParallel:()=>ga,RunnablePassthrough:()=>ce,RunnablePick:()=>pa,RunnableRetry:()=>ha,RunnableSequence:()=>Xe,RunnableToolLike:()=>la,RunnableWithFallbacks:()=>ua,RunnableWithMessageHistory:()=>as,_coerceToRunnable:()=>re,ensureConfig:()=>ie,getCallbackManagerForConfig:()=>Je,mergeConfigs:()=>ca,patchConfig:()=>G,pickRunnableConfigKeys:()=>oa});var yt=class extends H{parseResultWithPrompt(e,a,n){return this.parseResult(e,n)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,a){return typeof e=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r?.callbacks),e,{...a,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r?.callbacks),e,{...a,runType:"parser"})}},pe=class extends yt{parseResult(e,a){return this.parse(e[0].text,a)}async parseWithPrompt(e,a,n){return this.parse(e,n)}_type(){throw new Error("_type not implemented")}},Z=class extends Error{llmOutput;observation;sendToLLM;constructor(e,a,n,r=!1){if(super(e),this.llmOutput=a,this.observation=n,this.sendToLLM=r,r&&(n===void 0||a===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");fa(this,"OUTPUT_PARSING_FAILURE")}},q=class extends pe{async*_transform(e){for await(const a of e)typeof a=="string"?yield this.parseResult([{text:a}]):yield this.parseResult([{message:a,text:this._baseMessageToString(a)}])}async*transform(e,a){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...a,runType:"parser"})}},Ne=class extends q{diff=!1;constructor(e){super(e),this.diff=e?.diff??this.diff}async*_transform(e){let a,n;for await(const r of e){if(typeof r!="string"&&typeof r.content!="string")throw new Error("Cannot handle non-string output.");let i;if(da(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");i=new ze({message:r,text:r.content})}else if(Y(r)){if(typeof r.content!="string")throw new Error("Cannot handle non-string message output.");i=new ze({message:ba(r),text:r.content})}else i=new _a({text:r});n===void 0?n=i:n=n.concat(i);const c=await this.parsePartialResult([n]);c!=null&&!ya(c,a)&&(this.diff?yield this._diff(a,c):yield c,a=c)}}getFormatInstructions(){return""}},ns=class extends q{static lc_name(){return"BytesOutputParser"}lc_namespace=["langchain_core","output_parsers","bytes"];lc_serializable=!0;textEncoder=new TextEncoder;parse(e){return Promise.resolve(this.textEncoder.encode(e))}getFormatInstructions(){return""}},Q=class extends q{re;async*_transform(e){let a="";for await(const n of e)if(typeof n=="string"?a+=n:a+=n.content,this.re){const r=[...a.matchAll(this.re)];if(r.length>1){let i=0;for(const c of r.slice(0,-1))yield[c[1]],i+=(c.index??0)+c[0].length;a=a.slice(i)}}else{const r=await this.parse(a);if(r.length>1){for(const i of r.slice(0,-1))yield[i];a=r[r.length-1]}}for(const n of await this.parse(a))yield[n]}},rs=class extends Q{static lc_name(){return"CommaSeparatedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;async parse(e){try{return e.trim().split(",").map(a=>a.trim())}catch{throw new Z(`Could not parse output: ${e}`,e)}}getFormatInstructions(){return"Your response should be a list of comma separated values, eg: `foo, bar, baz`"}},is=class extends Q{lc_namespace=["langchain_core","output_parsers","list"];length;separator;constructor({length:e,separator:a}){super(...arguments),this.length=e,this.separator=a||","}async parse(e){try{const a=e.trim().split(this.separator).map(n=>n.trim());if(this.length!==void 0&&a.length!==this.length)throw new Z(`Incorrect number of items. Expected ${this.length}, got ${a.length}.`);return a}catch(a){throw Object.getPrototypeOf(a)===Z.prototype?a:new Z(`Could not parse output: ${e}`)}}getFormatInstructions(){return`Your response should be a list of ${this.length===void 0?"":`${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`}},os=class extends Q{static lc_name(){return"NumberedListOutputParser"}lc_namespace=["langchain_core","output_parsers","list"];lc_serializable=!0;getFormatInstructions(){return`Your response should be a numbered list with each item on a new line. For example: