@mcp-use/inspector 0.26.1 → 0.26.2-canary.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdn/inspector.js +64 -54
- package/dist/client/index.js +31 -31
- package/dist/web/assets/{browser-CUjguYn6.js → browser-BmLBExar.js} +3 -3
- package/dist/web/assets/{chunk-6E445R5C-ny1rw8Le.js → chunk-PQMRWHFE-CV30_nBm.js} +1 -1
- package/dist/web/assets/{chunk-RPN2XO5I-_4a18lz2.js → chunk-RPN2XO5I-BI2C4Mwo.js} +1 -1
- package/dist/web/assets/{chunk_array-cMM4je5w.js → chunk_array-Dt8Wg6B_.js} +1 -1
- package/dist/web/assets/{client-DEFMLVFC.js → client-6SIHYz8o.js} +1 -1
- package/dist/web/assets/{client-S6L7XHLF-Dqmt1wRx.js → client-H7MR3VAF-CO-aN8Vj.js} +3 -3
- package/dist/web/assets/{dist-BG8NAFfu.js → dist-E6FGji6q.js} +1 -1
- package/dist/web/assets/{dist-CKth7ANk.js → dist-NjrowN6N.js} +1 -1
- package/dist/web/assets/{dist-YxwKnKYL.js → dist-XbUgwOND.js} +1 -1
- package/dist/web/assets/{function_calling-XyGNNvjR.js → function_calling-BocD-RuD.js} +1 -1
- package/dist/web/assets/{index-zqVFP8t5.js → index-B2Y-NYsA.js} +10 -10
- package/dist/web/assets/{llms-DmE4p8kW.js → llms-DKXMVXWf.js} +1 -1
- package/dist/web/assets/messages-DQOeGdbS.js +1 -0
- package/dist/web/assets/react-ksVTeyRI.js +1 -0
- package/dist/web/assets/{rpc-logger-TPNV75J4-BPgEimJH.js → rpc-logger-TPNV75J4-BdFmawYU.js} +1 -1
- package/dist/web/assets/{stdio-LLTXMSZH-CQ-zxwTS.js → stdio-ZCW4I5XD-CmtXCvzt.js} +1 -1
- package/dist/web/assets/{tools-DWDA-ZTt.js → tools-DdqMuNxj.js} +1 -1
- package/dist/web/index.html +4 -4
- package/package.json +3 -3
- package/dist/web/assets/messages-DmWRSzWI.js +0 -1
- package/dist/web/assets/react-Cg35ZZKt.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/langfuse-U2OEF7K7-UPVEn4-O.js","assets/chunk-QWQYAQCK-CyFuZlX8.js","assets/chunk-3GQAWCBQ-C-9Cm0Np.js","assets/chunk-zsgVPwQN.js","assets/chunk-UJPHRNQP-C81GjauI.js","assets/preload-helper-XLr9-hSf.js","assets/client-
|
|
2
|
-
import{t as e}from"./chunk-3GQAWCBQ-C-9Cm0Np.js";import{n as t}from"./chunk-QWQYAQCK-CyFuZlX8.js";import{It as n,S as r,er as i}from"./json-schema-processors-DSIsU0go.js";import{a,c as o,s}from"./client-DEFMLVFC.js";import{a as c,c as l,m as u,n as d,v as f}from"./schemas-79owEkeD.js";import"./chunk-6E445R5C-ny1rw8Le.js";import{t as p}from"./preload-helper-XLr9-hSf.js";import{$n as m,A as h,An as g,Ar as _,At as v,Bn as y,Bt as b,C as ee,Ct as x,Dr as S,Dt as te,E as ne,En as re,Er as ie,Et as ae,F as oe,Fr as C,Ft as se,G as ce,Ht as le,I as ue,In as de,Ir as fe,It as pe,Jn as me,Kt as he,L as ge,Lr as _e,M as ve,Mr as ye,Mt as be,N as xe,Nr as Se,Nt as Ce,Or as we,Ot as Te,Pn as Ee,Pr as w,Pt as De,Qn as Oe,R as ke,Rr as T,Rt as Ae,S as je,St as Me,Tr as Ne,Tt as Pe,Ut as Fe,Vt as Ie,W as E,Wt as Le,Xt as Re,Zn as ze,_n as Be,at as Ve,b as He,bt as Ue,d as We,dn as Ge,dt as Ke,er as qe,fn as Je,g as Ye,gt as Xe,i as Ze,j as Qe,jn as $e,jr as et,jt as tt,k as nt,kr as rt,kt as it,l as at,lt as ot,mn as st,mr as D,mt as ct,nn as lt,nr as ut,nt as dt,o as ft,on as pt,ot as mt,pn as O,pt as ht,qn as gt,qt as _t,rr as vt,rt as yt,s as k,sn as bt,t as xt,tn as A,tr as St,ut as Ct,vn as j,vt as wt,w as Tt,wt as Et,x as Dt,xt as Ot,yn as kt,yt as At,zn as jt,zr as Mt,zt as Nt}from"./index-zqVFP8t5.js";import{C as Pt,D as Ft,M as It,O as Lt,S as Rt,T as zt,_ as Bt,b as Vt,c as Ht,d as Ut,f as Wt,g as Gt,h as Kt,j as qt,k as Jt,m as Yt,n as Xt,s as Zt,u as Qt,v as $t,x as en,y as tn}from"./function_calling-XyGNNvjR.js";import{a as nn,i as rn,n as an,o as on,r as sn,t as cn}from"./tools-DWDA-ZTt.js";import{n as ln,r as un,t as dn}from"./chunk_array-cMM4je5w.js";import{n as fn,r as pn,t as mn}from"./llms-DmE4p8kW.js";import{t as hn}from"./chunk-RPN2XO5I-_4a18lz2.js";import"./chunk-UJPHRNQP-C81GjauI.js";var gn,_n,vn=0,yn=0;function bn(e,t,n){var r=t&&n||0,i=t||Array(16);e||={};var a=e.node,o=e.clockseq;if(e._v6||(a||=gn,o??=_n),a==null||o==null){var s=e.random||(e.rng||b)();a??(a=[s[0],s[1],s[2],s[3],s[4],s[5]],!gn&&!e._v6&&(a[0]|=1,gn=a)),o??(o=(s[6]<<8|s[7])&16383,_n===void 0&&!e._v6&&(_n=o))}var c=e.msecs===void 0?Date.now():e.msecs,l=e.nsecs===void 0?yn+1:e.nsecs,u=c-vn+(l-yn)/1e4;if(u<0&&e.clockseq===void 0&&(o=o+1&16383),(u<0||c>vn)&&e.nsecs===void 0&&(l=0),l>=1e4)throw Error(`uuid.v1(): Can't create more than 10M uuids/sec`);vn=c,yn=l,_n=o,c+=0xb1d069b5400;var d=((c&268435455)*1e4+l)%4294967296;i[r++]=d>>>24&255,i[r++]=d>>>16&255,i[r++]=d>>>8&255,i[r++]=d&255;var f=c/4294967296*1e4&268435455;i[r++]=f>>>8&255,i[r++]=f&255,i[r++]=f>>>24&15|16,i[r++]=f>>>16&255,i[r++]=o>>>8|128,i[r++]=o&255;for(var p=0;p<6;++p)i[r+p]=a[p];return t||Ie(i)}function xn(e){var t=Sn(typeof e==`string`?le(e):e);return typeof e==`string`?Ie(t):t}function Sn(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function Cn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Cn(Object(n),!0).forEach(function(t){Tn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Cn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Tn(e,t,n){return(t=En(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function En(e){var t=Dn(e,`string`);return typeof t==`symbol`?t:t+``}function Dn(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function On(e={},t,n=0){var r=bn(wn(wn({},e),{},{_v6:!0}),new Uint8Array(16));if(r=xn(r),t){for(var i=0;i<16;i++)t[n+i]=r[i];return t}return Ie(r)}var kn=Object.defineProperty,An=(e,t)=>{for(var n in t)kn(e,n,{get:t[n],enumerable:!0})};An({},{ConfigurableModel:()=>In,MODEL_PROVIDER_CONFIG:()=>jn,_inferModelProvider:()=>Fn,getChatModelByClassName:()=>Nn,initChatModel:()=>Ln});var jn={openai:{package:`@langchain/openai`,className:`ChatOpenAI`},anthropic:{package:`@langchain/anthropic`,className:`ChatAnthropic`},azure_openai:{package:`@langchain/openai`,className:`AzureChatOpenAI`},cohere:{package:`@langchain/cohere`,className:`ChatCohere`},"google-vertexai":{package:`@langchain/google-vertexai`,className:`ChatVertexAI`},"google-vertexai-web":{package:`@langchain/google-vertexai-web`,className:`ChatVertexAI`},"google-genai":{package:`@langchain/google-genai`,className:`ChatGoogleGenerativeAI`},ollama:{package:`@langchain/ollama`,className:`ChatOllama`},mistralai:{package:`@langchain/mistralai`,className:`ChatMistralAI`},mistral:{package:`@langchain/mistralai`,className:`ChatMistralAI`},groq:{package:`@langchain/groq`,className:`ChatGroq`},cerebras:{package:`@langchain/cerebras`,className:`ChatCerebras`},bedrock:{package:`@langchain/aws`,className:`ChatBedrockConverse`},deepseek:{package:`@langchain/deepseek`,className:`ChatDeepSeek`},xai:{package:`@langchain/xai`,className:`ChatXAI`},fireworks:{package:`@langchain/community/chat_models/fireworks`,className:`ChatFireworks`,hasCircularDependency:!0},together:{package:`@langchain/community/chat_models/togetherai`,className:`ChatTogetherAI`,hasCircularDependency:!0},perplexity:{package:`@langchain/community/chat_models/perplexity`,className:`ChatPerplexity`,hasCircularDependency:!0}},Mn=Object.keys(jn);async function Nn(e){let t=Object.entries(jn).find(([,t])=>t.className===e);if(!t)return;let[,n]=t;try{return(await p(()=>import(n.package),[]))[n.className]}catch(e){let t=e;if(`code`in t&&t.code?.toString().includes(`ERR_MODULE_NOT_FOUND`)&&`message`in t&&typeof t.message==`string`){let e=(t.message.startsWith(`Error: `)?t.message.slice(7):t.message).split(`Cannot find package '`)[1].split(`'`)[0];throw Error(`Unable to import ${e}. Please install with \`npm install ${e}\` or \`pnpm install ${e}\``)}throw e}}async function Pn(e,t,n={}){let r=t||Fn(e);if(!r)throw Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let i=jn[r];if(!i){let e=Mn.join(`, `);throw Error(`Unsupported { modelProvider: ${r} }.\n\nSupported model providers are: ${e}`)}let{modelProvider:a,...o}=n;return new(await(Nn(i.className)))({model:e,...o})}function Fn(e){if(e.startsWith(`gpt-3`)||e.startsWith(`gpt-4`)||e.startsWith(`gpt-5`)||e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`))return`openai`;if(e.startsWith(`claude`))return`anthropic`;if(e.startsWith(`command`))return`cohere`;if(e.startsWith(`accounts/fireworks`))return`fireworks`;if(e.startsWith(`gemini`))return`google-vertexai`;if(e.startsWith(`amazon.`))return`bedrock`;if(e.startsWith(`mistral`))return`mistralai`;if(e.startsWith(`sonar`)||e.startsWith(`pplx`))return`perplexity`}var In=class e extends Zt{_llmType(){return`chat_model`}lc_namespace=[`langchain`,`chat_models`];_defaultConfig={};_configurableFields=`any`;_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields===`any`?this._configurableFields=`any`:this._configurableFields=e.configurableFields??[`model`,`modelProvider`],e.configPrefix?this._configPrefix=e.configPrefix.endsWith(`_`)?e.configPrefix:`${e.configPrefix}_`:this._configPrefix=``,this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations,this._profile=e.profile??void 0}async _getModelInstance(e){let t=this._getCacheKey(e),n=this._modelInstanceCache.get(t);if(n)return n;let r={...this._defaultConfig,...this._modelParams(e)},i=await Pn(r.model,r.modelProvider,r);for(let[e,t]of Object.entries(this._queuedMethodOperations))e in i&&typeof i[e]==`function`&&(i=await i[e](...t));return this._modelInstanceCache.set(t,i),i}async _generate(e,t,n){return(await this._getModelInstance(t))._generate(e,t??{},n)}bindTools(t,n){let r={...this._queuedMethodOperations};return r.bindTools=[t,n],new e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(t,...n)=>{let r={...this._queuedMethodOperations};return r.withStructuredOutput=[t,...n],new e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})};_modelParams(e){let t=e?.configurable??{},n={};for(let[e,r]of Object.entries(t))if(e.startsWith(this._configPrefix)){let t=this._removePrefix(e,this._configPrefix);n[t]=r}return this._configurableFields!==`any`&&(n=Object.fromEntries(Object.entries(n).filter(([e])=>this._configurableFields.includes(e)))),n}_removePrefix(e,t){return e.startsWith(t)?e.slice(t.length):e}withConfig(t){let n={...t||{}},r=this._modelParams(n),i=Object.fromEntries(Object.entries(n).filter(([e])=>e!==`configurable`));return i.configurable=Object.fromEntries(Object.entries(n.configurable||{}).filter(([e])=>this._configPrefix&&!Object.keys(r).includes(this._removePrefix(e,this._configPrefix)))),new at({config:n,bound:new e({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(e,t){let n=await this._getModelInstance(t),r=At(t);return n.invoke(e,r)}async stream(e,t){let n=new ht({generator:await(await this._getModelInstance(t)).stream(e,t),config:t});return await n.setup,ct.fromAsyncGenerator(n)}async batch(e,t,n){return super.batch(e,t,n)}async*transform(e,t){let n=await this._getModelInstance(t),r=At(t);yield*n.transform(e,r)}async*streamLog(e,t,n){let r=await this._getModelInstance(t),i=At(t);yield*r.streamLog(e,i,{...n,_schemaFormat:`original`,includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(e,t,n){let r=this;async function*i(){let i=await r._getModelInstance(t),a=At(t),o=i.streamEvents(e,a,n);for await(let e of o)yield e}return ct.fromAsyncGenerator(i())}get profile(){if(this._profile)return this._profile;let e=this._getCacheKey({});return this._modelInstanceCache.get(e)?.profile??{}}_getCacheKey(e){let t=e??{};if(t.configurable){let{configurable:e}=t,n={};for(let[t,r]of Object.entries(e))t.startsWith(`__pregel_`)||(n[t]=r);t={...t,configurable:n}}return JSON.stringify(t)}};async function Ln(e,t){let{configurableFields:n,configPrefix:r,modelProvider:i,profile:a,...o}={configPrefix:``,...t??{}};if(i===void 0&&e?.includes(`:`)){let[t,...n]=e.split(`:`),r=n.length===0?[t]:[t,n.join(`:`)];Mn.includes(r[0])&&([i,e]=r)}let s=Array.isArray(n)?[...n]:n;!e&&s===void 0&&(s=[`model`,`modelProvider`]),r&&s===void 0&&console.warn(`{ configPrefix: ${r} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let c={...o},l;return s===void 0?l=new In({defaultConfig:{...c,model:e,modelProvider:i},configPrefix:r,profile:a}):(e&&(c.model=e),i&&(c.modelProvider=i),l=new In({defaultConfig:c,configPrefix:r,configurableFields:s,profile:a})),await l._getModelInstance(),l}var Rn=class{constructor(){this.store=void 0}getStore(){return this.store}run(e,t,...n){this.store=e;try{return t(...n)}finally{this.store=void 0}}exit(e,...t){let n=this.store;this.store=void 0;try{return e(...t)}finally{this.store=n}}enterWith(e){this.store=e}disable(){this.store=void 0}};function zn(){Pe.initializeGlobalInstance(new Rn)}var Bn=class extends Error{lc_error_code;constructor(e,t){let n=e??``;t?.lc_error_code&&(n=`${n}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/\n`),super(n),this.lc_error_code=t?.lc_error_code}},Vn=class extends Bn{get is_bubble_up(){return!0}},Hn=class extends Bn{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},Un=class extends Bn{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},Wn=class extends Vn{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},Gn=class extends Wn{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},Kn=class extends Vn{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function qn(e){return e!==void 0&&e.name===Kn.unminifiable_name}function Jn(e){return e!==void 0&&e.is_bubble_up===!0}function Yn(e){return e!==void 0&&[Wn.unminifiable_name,Gn.unminifiable_name].includes(e.name)}var Xn=class extends Bn{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},M=class extends Bn{constructor(e,t){super(e,t),this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},N=class extends Bn{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},Zn=class extends Bn{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},Qn=class extends Bn{constructor(e,t){super(e,t),this.name=`StateGraphInputError`,this.message=`Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema.`}static get unminifiable_name(){return`StateGraphInputError`}};function $n(e){return On({clockseq:e})}function er(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return Ae(e,new Uint8Array(n))}var tr=`__error__`,nr=`__scheduled__`,rr=`__interrupt__`,ir=`__resume__`,ar=`[...]`,or=`[Circular]`,sr=[],cr=[];function lr(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function ur(e,t,n,r){r===void 0&&(r=lr()),fr(e,``,0,[],void 0,0,r);var i;try{i=cr.length===0?JSON.stringify(e,t,n):JSON.stringify(e,pr(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;sr.length!==0;){var a=sr.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function dr(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,sr.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),sr.push([r,n,t,i])):cr.push([t,n,e])}function fr(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){dr(or,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){dr(ar,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){dr(ar,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)fr(e[s],s,s,r,e,a,o);else{var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];fr(e[l],l,s,r,e,a,o)}}r.pop()}}function pr(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(cr.length>0)for(var r=0;r<cr.length;r++){var i=cr[r];if(i[1]===t&&i[0]===n){n=i[2],cr.splice(r,1);break}}return e.call(this,t,n)}}var mr=[],hr={},gr={};D(gr,{BaseChatMessageHistory:()=>_r,BaseListChatMessageHistory:()=>vr,InMemoryChatMessageHistory:()=>yr});var _r=class extends ze{async addMessages(e){for(let t of e)await this.addMessage(t)}},vr=class extends ze{addUserMessage(e){return this.addMessage(new j(e))}addAIMessage(e){return this.addMessage(new A(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},yr=class extends vr{lc_namespace=[`langchain`,`stores`,`message`,`in_memory`];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},br={},xr={};D(xr,{BaseMemory:()=>Sr,getInputValue:()=>wr,getOutputValue:()=>Tr,getPromptInputKey:()=>Er});var Sr=class{},Cr=(e,t)=>{if(t!==void 0)return e[t];let n=Object.keys(e);if(n.length===1)return e[n[0]]},wr=(e,t)=>{let n=Cr(e,t);if(!n){let t=Object.keys(e);throw Error(`input values have ${t.length} keys, you must specify an input key or pass only 1 key as input`)}return n},Tr=(e,t)=>{let n=Cr(e,t);if(!n&&n!==``){let t=Object.keys(e);throw Error(`output values have ${t.length} keys, you must specify an output key or pass only 1 key as output`)}return n};function Er(e,t){let n=Object.keys(e).filter(e=>!t.includes(e)&&e!==`stop`);if(n.length!==1)throw Error(`One input key expected, but got ${n.length}`);return n[0]}var Dr={};D(Dr,{BaseStore:()=>Or,InMemoryStore:()=>kr});var Or=class extends ze{},kr=class extends Or{lc_namespace=[`langchain`,`storage`];store={};async mget(e){return e.map(e=>this.store[e])}async mset(e){for(let[t,n]of e)this.store[t]=n}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let n of t)(e===void 0||n.startsWith(e))&&(yield n)}},Ar={};D(Ar,{BaseRetriever:()=>jr});var jr=class extends k{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw Error(`Not implemented!`)}async invoke(e,t){let n=At(Te(t)),r=await(await ae.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let t=await this._getRelevantDocuments(e,r);return await r?.handleRetrieverEnd(t),t}catch(e){throw await r?.handleRetrieverError(e),e}}},Mr={};D(Mr,{SaveableVectorStore:()=>Fr,VectorStore:()=>Pr,VectorStoreRetriever:()=>Nr});var Nr=class extends jr{static lc_name(){return`VectorStoreRetriever`}get lc_namespace(){return[`langchain_core`,`vectorstores`]}vectorStore;k=4;searchType=`similarity`;searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType===`mmr`&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType===`mmr`){if(typeof this.vectorStore.maxMarginalRelevanceSearch!=`function`)throw Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild(`vectorstore`))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild(`vectorstore`))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},Pr=class extends ze{lc_namespace=[`langchain`,`vectorstores`,this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw Error(`Not implemented.`)}async similaritySearch(e,t=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)).map(e=>e[0])}async similaritySearchWithScore(e,t=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)}static fromTexts(e,t,n,r){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}static fromDocuments(e,t,n){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}asRetriever(e,t,n,r,i,a){if(typeof e==`number`)return new Nr({vectorStore:this,k:e,filter:t,tags:[...r??[],this._vectorstoreType()],metadata:i,verbose:a,callbacks:n});{let t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType===`mmr`?new Nr({...t,searchKwargs:e.searchKwargs}):new Nr({...t})}}},Fr=class extends Pr{static load(e,t){throw Error(`Not implemented`)}},Ir={};D(Ir,{BaseDocumentLoader:()=>Lr});var Lr=class{},Rr={};D(Rr,{LangSmithLoader:()=>zr});var zr=class extends Lr{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw Error(`client and clientConfig cannot both be provided.`);this.client=e.client??new De(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??Br,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){let e=[];for await(let t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=t.inputs;for(let e of this.contentKey)n=n[e];let r=this.formatContent(n),i=t;[`created_at`,`modified_at`].forEach(e=>{e in i&&typeof i[e]==`object`&&(i[e]=i[e].toString())}),e.push({pageContent:r,metadata:i})}return e}};function Br(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var Vr=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},Hr=class extends k{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},Ur=class extends Hr{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},Wr={};D(Wr,{BaseDocumentTransformer:()=>Hr,Document:()=>Vr,MappingDocumentTransformer:()=>Ur});var Gr=class extends ze{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},Kr=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},qr=class extends Kr{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,n]of this.conditionals)if(t(e))return n;return this.defaultPrompt}};function Jr(e){return e._modelType()===`base_llm`}function Yr(e){return e._modelType()===`base_chat_model`}function Xr(e){return e.split(/\n| /).length}var Zr=class e extends Gr{examples=[];examplePrompt;getTextLength=Xr;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Xr}async addExample(e){this.examples.push(e);let t=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(t))}async calculateExampleTextLengths(e,t){if(e.length>0)return e;let{examples:n,examplePrompt:r}=t;return(await Promise.all(n.map(e=>r.format(e)))).map(e=>this.getTextLength(e))}async selectExamples(e){let t=Object.values(e).join(` `),n=this.maxLength-this.getTextLength(t),r=0,i=[];for(;n>0&&r<this.examples.length;){let e=n-this.exampleTextLengths[r];if(e<0)break;i.push(this.examples[r]),n=e,r+=1}return i}static async fromExamples(t,n){let r=new e(n);return await Promise.all(t.map(e=>r.addExample(e))),r}};function Qr(e){return Object.keys(e).sort().map(t=>e[t])}var $r=class e extends Gr{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`)}async addExample(e){let t=Qr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new Vr({pageContent:t,metadata:e})])}async selectExamples(e){let t=Qr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `),n=(await this.vectorStoreRetriever.invoke(t)).map(e=>e.metadata);return this.exampleKeys?n.map(e=>this.exampleKeys.reduce((t,n)=>({...t,[n]:e[n]}),{})):n}static async fromExamples(t,n,r,i={}){let a=i.inputKeys??null,o=t.map(e=>Qr(a?a.reduce((t,n)=>({...t,[n]:e[n]}),{}):e).join(` `));return new e({vectorStore:await r.fromTexts(o,t,n,i),k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}},ei={};D(ei,{BaseExampleSelector:()=>Gr,BasePromptSelector:()=>Kr,ConditionalPromptSelector:()=>qr,LengthBasedExampleSelector:()=>Zr,SemanticSimilarityExampleSelector:()=>$r,isChatModel:()=>Yr,isLLM:()=>Jr});var ti=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,ni=class extends ze{lc_namespace=[`langchain`,`recordmanagers`]},ri=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Bt;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=[`hash_`,`content_hash`,`metadata_hash`];for(let t of e)if(t in this.metadata)throw Error(`Metadata cannot contain key ${t} as it is reserved for internal use. Restricted keys: [${e.join(`, `)}]`);let t=this._hashStringToUUID(this.pageContent);try{let e=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=e}catch(e){throw Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||=this.hash_}toDocument(){return new Vr({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let n=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return n.calculateHashes(),n}_hashStringToUUID(e){return Ae(this.keyEncoder(e),ti)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return Ae(this.keyEncoder(t),ti)}};function ii(e,t){let n=[],r=[];return t.forEach(t=>{r.push(t),r.length>=e&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function ai(e){let t=new Set,n=[];for(let r of e){if(!r.hash_)throw Error(`Hashed document does not have a hash`);t.has(r.hash_)||(t.add(r.hash_),n.push(r))}return n}function oi(e){if(e===null)return e=>null;if(typeof e==`string`)return t=>t.metadata[e];if(typeof e==`function`)return e;throw Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var si=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function ci(e){let{docsSource:t,recordManager:n,vectorStore:r,options:i}=e,{batchSize:a=100,cleanup:o,sourceIdKey:s,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=i??{};if(o===`incremental`&&!s)throw Error(`sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.`);let u=si(t)?await t.load():t,d=oi(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=ii(a??100,u);for(let e of _){let t=ai(e.map(e=>ri.fromDocument(e))),i=t.map(e=>d(e));o===`incremental`&&t.forEach((e,t)=>{if(i[t]===null)throw Error(`sourceIdKey must be provided when cleanup is incremental`)});let a=await n.exists(t.map(e=>e.uid)),s=[],c=[],u=[],_=new Set;if(t.forEach((e,t)=>{if(a[t])if(l)_.add(e.uid);else{u.push(e.uid);return}s.push(e.uid),c.push(e.toDocument())}),u.length>0&&(await n.update(u,{timeAtLeast:f}),g+=u.length),c.length>0&&(await r.addDocuments(c,{ids:s}),p+=c.length-_.size,h+=_.size),await n.update(t.map(e=>e.uid),{timeAtLeast:f,groupIds:i}),o===`incremental`){i.forEach(e=>{if(!e)throw Error(`Source id cannot be null`)});let e=await n.listKeys({before:f,groupIds:i});e.length>0&&(await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length)}}if(o===`full`){let e=await n.listKeys({before:f,limit:c});for(;e.length>0;)await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length,e=await n.listKeys({before:f,limit:c})}return{numAdded:p,numDeleted:m,numUpdated:h,numSkipped:g}}var li={};D(li,{RecordManager:()=>ni,UUIDV5_NAMESPACE:()=>ti,_HashedDocument:()=>ri,_batch:()=>ii,_deduplicateInOrder:()=>ai,_getSourceIdAssigner:()=>oi,_isBaseDocumentLoader:()=>si,index:()=>ci});var ui={},di=class extends Lt{static lc_name(){return`OutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if(`message`in e[0]){let t=e[0].message.additional_kwargs.function_call;if(!t)throw Error(`No function_call in message ${JSON.stringify(e)}`);if(!t.arguments)throw Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?t.arguments:JSON.stringify(t)}else throw Error(`No message in generations ${JSON.stringify(e)}`)}},fi=class extends Ft{static lc_name(){return`JsonOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new di(e)}_diff(e,t){if(t)return Ke(e??{},t)}async parsePartialResult(e){let t=e[0];if(!t.message)return;let{message:n}=t,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?pt(r.arguments):{...r,arguments:pt(r.arguments)}}async parseResult(e){let t=await this.outputParser.parseResult(e);if(!t)throw Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){let t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return``}},pi=class extends Lt{static lc_name(){return`JsonKeyOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser=new fi;attrName;get lc_aliases(){return{attrName:`key_name`}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},mi={};D(mi,{JsonKeyOutputFunctionsParser:()=>pi,JsonOutputFunctionsParser:()=>fi,OutputFunctionsParser:()=>di});var hi=class extends k{lc_serializable=!0;lc_namespace=[`langchain_core`,`prompts`,this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);let{inputVariables:t}=e;if(t.includes(`stop`))throw Error(`Cannot have an input variable named 'stop', as it is used internally, please rename.`);Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},n={};for(let[e,r]of Object.entries(t))typeof r==`string`?n[e]=r:n[e]=await r();return{...n,...e}}async invoke(e,t){let n={...this.metadata,...t?.metadata},r=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(e=>this.formatPromptValue(e),e,{...t,tags:r,metadata:n,runType:`prompt`})}},gi=class extends hi{async formatPromptValue(e){return new Vt(await this.format(e))}},_i=Object.prototype.toString,vi=Array.isArray||function(e){return _i.call(e)===`[object Array]`};function yi(e){return typeof e==`function`}function bi(e){return vi(e)?`array`:typeof e}function xi(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function Si(e,t){return typeof e==`object`&&!!e&&t in e}function Ci(e,t){return e!=null&&typeof e!=`object`&&e.hasOwnProperty&&e.hasOwnProperty(t)}var wi=RegExp.prototype.test;function Ti(e,t){return wi.call(e,t)}var Ei=/\S/;function Di(e){return!Ti(Ei,e)}var Oi={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`,"/":`/`,"`":```,"=":`=`};function ki(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return Oi[e]})}var Ai=/\s*/,ji=/\s+/,Mi=/\s*=/,Ni=/\s*\}/,Pi=/#|\^|\/|>|\{|&|=|!/;function Fi(e,t){if(!e)return[];var n=!1,r=[],i=[],a=[],o=!1,s=!1,c=``,l=0;function u(){if(o&&!s)for(;a.length;)delete i[a.pop()];else a=[];o=!1,s=!1}var d,f,p;function m(e){if(typeof e==`string`&&(e=e.split(ji,2)),!vi(e)||e.length!==2)throw Error(`Invalid tags: `+e);d=RegExp(xi(e[0])+`\\s*`),f=RegExp(`\\s*`+xi(e[1])),p=RegExp(`\\s*`+xi(`}`+e[1]))}m(t||F.tags);for(var h=new Ri(e),g,_,v,y,b,ee;!h.eos();){if(g=h.pos,v=h.scanUntil(d),v)for(var x=0,S=v.length;x<S;++x)y=v.charAt(x),Di(y)?(a.push(i.length),c+=y):(s=!0,n=!0,c+=` `),i.push([`text`,y,g,g+1]),g+=1,y===`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/langfuse-U2OEF7K7-UPVEn4-O.js","assets/chunk-QWQYAQCK-CyFuZlX8.js","assets/chunk-3GQAWCBQ-C-9Cm0Np.js","assets/chunk-zsgVPwQN.js","assets/chunk-UJPHRNQP-C81GjauI.js","assets/preload-helper-XLr9-hSf.js","assets/client-H7MR3VAF-CO-aN8Vj.js","assets/client-6SIHYz8o.js","assets/schemas-79owEkeD.js","assets/json-schema-processors-DSIsU0go.js","assets/chunk-PQMRWHFE-CV30_nBm.js","assets/path-BzTN_bR6.js","assets/chunk-RPN2XO5I-BI2C4Mwo.js","assets/display-A5IEINAP-BFwsYEHq.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./chunk-3GQAWCBQ-C-9Cm0Np.js";import{n as t}from"./chunk-QWQYAQCK-CyFuZlX8.js";import{It as n,S as r,er as i}from"./json-schema-processors-DSIsU0go.js";import{a,c as o,s}from"./client-6SIHYz8o.js";import{a as c,c as l,m as u,n as d,v as f}from"./schemas-79owEkeD.js";import"./chunk-PQMRWHFE-CV30_nBm.js";import{t as p}from"./preload-helper-XLr9-hSf.js";import{$n as m,A as h,An as g,Ar as _,At as v,Bn as y,Bt as b,C as ee,Ct as x,Dr as S,Dt as te,E as ne,En as re,Er as ie,Et as ae,F as oe,Fr as C,Ft as se,G as ce,Ht as le,I as ue,In as de,Ir as fe,It as pe,Jn as me,Kt as he,L as ge,Lr as _e,M as ve,Mr as ye,Mt as be,N as xe,Nr as Se,Nt as Ce,Or as we,Ot as Te,Pn as Ee,Pr as w,Pt as De,Qn as Oe,R as ke,Rr as T,Rt as Ae,S as je,St as Me,Tr as Ne,Tt as Pe,Ut as Fe,Vt as Ie,W as E,Wt as Le,Xt as Re,Zn as ze,_n as Be,at as Ve,b as He,bt as Ue,d as We,dn as Ge,dt as Ke,er as qe,fn as Je,g as Ye,gt as Xe,i as Ze,j as Qe,jn as $e,jr as et,jt as tt,k as nt,kr as rt,kt as it,l as at,lt as ot,mn as st,mr as D,mt as ct,nn as lt,nr as ut,nt as dt,o as ft,on as pt,ot as mt,pn as O,pt as ht,qn as gt,qt as _t,rr as vt,rt as yt,s as k,sn as bt,t as xt,tn as A,tr as St,ut as Ct,vn as j,vt as wt,w as Tt,wt as Et,x as Dt,xt as Ot,yn as kt,yt as At,zn as jt,zr as Mt,zt as Nt}from"./index-B2Y-NYsA.js";import{C as Pt,D as Ft,M as It,O as Lt,S as Rt,T as zt,_ as Bt,b as Vt,c as Ht,d as Ut,f as Wt,g as Gt,h as Kt,j as qt,k as Jt,m as Yt,n as Xt,s as Zt,u as Qt,v as $t,x as en,y as tn}from"./function_calling-BocD-RuD.js";import{a as nn,i as rn,n as an,o as on,r as sn,t as cn}from"./tools-DdqMuNxj.js";import{n as ln,r as un,t as dn}from"./chunk_array-Dt8Wg6B_.js";import{n as fn,r as pn,t as mn}from"./llms-DKXMVXWf.js";import{t as hn}from"./chunk-RPN2XO5I-BI2C4Mwo.js";import"./chunk-UJPHRNQP-C81GjauI.js";var gn,_n,vn=0,yn=0;function bn(e,t,n){var r=t&&n||0,i=t||Array(16);e||={};var a=e.node,o=e.clockseq;if(e._v6||(a||=gn,o??=_n),a==null||o==null){var s=e.random||(e.rng||b)();a??(a=[s[0],s[1],s[2],s[3],s[4],s[5]],!gn&&!e._v6&&(a[0]|=1,gn=a)),o??(o=(s[6]<<8|s[7])&16383,_n===void 0&&!e._v6&&(_n=o))}var c=e.msecs===void 0?Date.now():e.msecs,l=e.nsecs===void 0?yn+1:e.nsecs,u=c-vn+(l-yn)/1e4;if(u<0&&e.clockseq===void 0&&(o=o+1&16383),(u<0||c>vn)&&e.nsecs===void 0&&(l=0),l>=1e4)throw Error(`uuid.v1(): Can't create more than 10M uuids/sec`);vn=c,yn=l,_n=o,c+=0xb1d069b5400;var d=((c&268435455)*1e4+l)%4294967296;i[r++]=d>>>24&255,i[r++]=d>>>16&255,i[r++]=d>>>8&255,i[r++]=d&255;var f=c/4294967296*1e4&268435455;i[r++]=f>>>8&255,i[r++]=f&255,i[r++]=f>>>24&15|16,i[r++]=f>>>16&255,i[r++]=o>>>8|128,i[r++]=o&255;for(var p=0;p<6;++p)i[r+p]=a[p];return t||Ie(i)}function xn(e){var t=Sn(typeof e==`string`?le(e):e);return typeof e==`string`?Ie(t):t}function Sn(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function Cn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Cn(Object(n),!0).forEach(function(t){Tn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Cn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Tn(e,t,n){return(t=En(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function En(e){var t=Dn(e,`string`);return typeof t==`symbol`?t:t+``}function Dn(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function On(e={},t,n=0){var r=bn(wn(wn({},e),{},{_v6:!0}),new Uint8Array(16));if(r=xn(r),t){for(var i=0;i<16;i++)t[n+i]=r[i];return t}return Ie(r)}var kn=Object.defineProperty,An=(e,t)=>{for(var n in t)kn(e,n,{get:t[n],enumerable:!0})};An({},{ConfigurableModel:()=>In,MODEL_PROVIDER_CONFIG:()=>jn,_inferModelProvider:()=>Fn,getChatModelByClassName:()=>Nn,initChatModel:()=>Ln});var jn={openai:{package:`@langchain/openai`,className:`ChatOpenAI`},anthropic:{package:`@langchain/anthropic`,className:`ChatAnthropic`},azure_openai:{package:`@langchain/openai`,className:`AzureChatOpenAI`},cohere:{package:`@langchain/cohere`,className:`ChatCohere`},"google-vertexai":{package:`@langchain/google-vertexai`,className:`ChatVertexAI`},"google-vertexai-web":{package:`@langchain/google-vertexai-web`,className:`ChatVertexAI`},"google-genai":{package:`@langchain/google-genai`,className:`ChatGoogleGenerativeAI`},ollama:{package:`@langchain/ollama`,className:`ChatOllama`},mistralai:{package:`@langchain/mistralai`,className:`ChatMistralAI`},mistral:{package:`@langchain/mistralai`,className:`ChatMistralAI`},groq:{package:`@langchain/groq`,className:`ChatGroq`},cerebras:{package:`@langchain/cerebras`,className:`ChatCerebras`},bedrock:{package:`@langchain/aws`,className:`ChatBedrockConverse`},deepseek:{package:`@langchain/deepseek`,className:`ChatDeepSeek`},xai:{package:`@langchain/xai`,className:`ChatXAI`},fireworks:{package:`@langchain/community/chat_models/fireworks`,className:`ChatFireworks`,hasCircularDependency:!0},together:{package:`@langchain/community/chat_models/togetherai`,className:`ChatTogetherAI`,hasCircularDependency:!0},perplexity:{package:`@langchain/community/chat_models/perplexity`,className:`ChatPerplexity`,hasCircularDependency:!0}},Mn=Object.keys(jn);async function Nn(e){let t=Object.entries(jn).find(([,t])=>t.className===e);if(!t)return;let[,n]=t;try{return(await p(()=>import(n.package),[]))[n.className]}catch(e){let t=e;if(`code`in t&&t.code?.toString().includes(`ERR_MODULE_NOT_FOUND`)&&`message`in t&&typeof t.message==`string`){let e=(t.message.startsWith(`Error: `)?t.message.slice(7):t.message).split(`Cannot find package '`)[1].split(`'`)[0];throw Error(`Unable to import ${e}. Please install with \`npm install ${e}\` or \`pnpm install ${e}\``)}throw e}}async function Pn(e,t,n={}){let r=t||Fn(e);if(!r)throw Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let i=jn[r];if(!i){let e=Mn.join(`, `);throw Error(`Unsupported { modelProvider: ${r} }.\n\nSupported model providers are: ${e}`)}let{modelProvider:a,...o}=n;return new(await(Nn(i.className)))({model:e,...o})}function Fn(e){if(e.startsWith(`gpt-3`)||e.startsWith(`gpt-4`)||e.startsWith(`gpt-5`)||e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`))return`openai`;if(e.startsWith(`claude`))return`anthropic`;if(e.startsWith(`command`))return`cohere`;if(e.startsWith(`accounts/fireworks`))return`fireworks`;if(e.startsWith(`gemini`))return`google-vertexai`;if(e.startsWith(`amazon.`))return`bedrock`;if(e.startsWith(`mistral`))return`mistralai`;if(e.startsWith(`sonar`)||e.startsWith(`pplx`))return`perplexity`}var In=class e extends Zt{_llmType(){return`chat_model`}lc_namespace=[`langchain`,`chat_models`];_defaultConfig={};_configurableFields=`any`;_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields===`any`?this._configurableFields=`any`:this._configurableFields=e.configurableFields??[`model`,`modelProvider`],e.configPrefix?this._configPrefix=e.configPrefix.endsWith(`_`)?e.configPrefix:`${e.configPrefix}_`:this._configPrefix=``,this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations,this._profile=e.profile??void 0}async _getModelInstance(e){let t=this._getCacheKey(e),n=this._modelInstanceCache.get(t);if(n)return n;let r={...this._defaultConfig,...this._modelParams(e)},i=await Pn(r.model,r.modelProvider,r);for(let[e,t]of Object.entries(this._queuedMethodOperations))e in i&&typeof i[e]==`function`&&(i=await i[e](...t));return this._modelInstanceCache.set(t,i),i}async _generate(e,t,n){return(await this._getModelInstance(t))._generate(e,t??{},n)}bindTools(t,n){let r={...this._queuedMethodOperations};return r.bindTools=[t,n],new e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(t,...n)=>{let r={...this._queuedMethodOperations};return r.withStructuredOutput=[t,...n],new e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})};_modelParams(e){let t=e?.configurable??{},n={};for(let[e,r]of Object.entries(t))if(e.startsWith(this._configPrefix)){let t=this._removePrefix(e,this._configPrefix);n[t]=r}return this._configurableFields!==`any`&&(n=Object.fromEntries(Object.entries(n).filter(([e])=>this._configurableFields.includes(e)))),n}_removePrefix(e,t){return e.startsWith(t)?e.slice(t.length):e}withConfig(t){let n={...t||{}},r=this._modelParams(n),i=Object.fromEntries(Object.entries(n).filter(([e])=>e!==`configurable`));return i.configurable=Object.fromEntries(Object.entries(n.configurable||{}).filter(([e])=>this._configPrefix&&!Object.keys(r).includes(this._removePrefix(e,this._configPrefix)))),new at({config:n,bound:new e({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(e,t){let n=await this._getModelInstance(t),r=At(t);return n.invoke(e,r)}async stream(e,t){let n=new ht({generator:await(await this._getModelInstance(t)).stream(e,t),config:t});return await n.setup,ct.fromAsyncGenerator(n)}async batch(e,t,n){return super.batch(e,t,n)}async*transform(e,t){let n=await this._getModelInstance(t),r=At(t);yield*n.transform(e,r)}async*streamLog(e,t,n){let r=await this._getModelInstance(t),i=At(t);yield*r.streamLog(e,i,{...n,_schemaFormat:`original`,includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(e,t,n){let r=this;async function*i(){let i=await r._getModelInstance(t),a=At(t),o=i.streamEvents(e,a,n);for await(let e of o)yield e}return ct.fromAsyncGenerator(i())}get profile(){if(this._profile)return this._profile;let e=this._getCacheKey({});return this._modelInstanceCache.get(e)?.profile??{}}_getCacheKey(e){let t=e??{};if(t.configurable){let{configurable:e}=t,n={};for(let[t,r]of Object.entries(e))t.startsWith(`__pregel_`)||(n[t]=r);t={...t,configurable:n}}return JSON.stringify(t)}};async function Ln(e,t){let{configurableFields:n,configPrefix:r,modelProvider:i,profile:a,...o}={configPrefix:``,...t??{}};if(i===void 0&&e?.includes(`:`)){let[t,...n]=e.split(`:`),r=n.length===0?[t]:[t,n.join(`:`)];Mn.includes(r[0])&&([i,e]=r)}let s=Array.isArray(n)?[...n]:n;!e&&s===void 0&&(s=[`model`,`modelProvider`]),r&&s===void 0&&console.warn(`{ configPrefix: ${r} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let c={...o},l;return s===void 0?l=new In({defaultConfig:{...c,model:e,modelProvider:i},configPrefix:r,profile:a}):(e&&(c.model=e),i&&(c.modelProvider=i),l=new In({defaultConfig:c,configPrefix:r,configurableFields:s,profile:a})),await l._getModelInstance(),l}var Rn=class{constructor(){this.store=void 0}getStore(){return this.store}run(e,t,...n){this.store=e;try{return t(...n)}finally{this.store=void 0}}exit(e,...t){let n=this.store;this.store=void 0;try{return e(...t)}finally{this.store=n}}enterWith(e){this.store=e}disable(){this.store=void 0}};function zn(){Pe.initializeGlobalInstance(new Rn)}var Bn=class extends Error{lc_error_code;constructor(e,t){let n=e??``;t?.lc_error_code&&(n=`${n}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/\n`),super(n),this.lc_error_code=t?.lc_error_code}},Vn=class extends Bn{get is_bubble_up(){return!0}},Hn=class extends Bn{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},Un=class extends Bn{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},Wn=class extends Vn{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},Gn=class extends Wn{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},Kn=class extends Vn{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function qn(e){return e!==void 0&&e.name===Kn.unminifiable_name}function Jn(e){return e!==void 0&&e.is_bubble_up===!0}function Yn(e){return e!==void 0&&[Wn.unminifiable_name,Gn.unminifiable_name].includes(e.name)}var Xn=class extends Bn{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},M=class extends Bn{constructor(e,t){super(e,t),this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},N=class extends Bn{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},Zn=class extends Bn{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},Qn=class extends Bn{constructor(e,t){super(e,t),this.name=`StateGraphInputError`,this.message=`Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema.`}static get unminifiable_name(){return`StateGraphInputError`}};function $n(e){return On({clockseq:e})}function er(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return Ae(e,new Uint8Array(n))}var tr=`__error__`,nr=`__scheduled__`,rr=`__interrupt__`,ir=`__resume__`,ar=`[...]`,or=`[Circular]`,sr=[],cr=[];function lr(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function ur(e,t,n,r){r===void 0&&(r=lr()),fr(e,``,0,[],void 0,0,r);var i;try{i=cr.length===0?JSON.stringify(e,t,n):JSON.stringify(e,pr(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;sr.length!==0;){var a=sr.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function dr(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,sr.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),sr.push([r,n,t,i])):cr.push([t,n,e])}function fr(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){dr(or,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){dr(ar,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){dr(ar,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)fr(e[s],s,s,r,e,a,o);else{var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];fr(e[l],l,s,r,e,a,o)}}r.pop()}}function pr(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(cr.length>0)for(var r=0;r<cr.length;r++){var i=cr[r];if(i[1]===t&&i[0]===n){n=i[2],cr.splice(r,1);break}}return e.call(this,t,n)}}var mr=[],hr={},gr={};D(gr,{BaseChatMessageHistory:()=>_r,BaseListChatMessageHistory:()=>vr,InMemoryChatMessageHistory:()=>yr});var _r=class extends ze{async addMessages(e){for(let t of e)await this.addMessage(t)}},vr=class extends ze{addUserMessage(e){return this.addMessage(new j(e))}addAIMessage(e){return this.addMessage(new A(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},yr=class extends vr{lc_namespace=[`langchain`,`stores`,`message`,`in_memory`];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},br={},xr={};D(xr,{BaseMemory:()=>Sr,getInputValue:()=>wr,getOutputValue:()=>Tr,getPromptInputKey:()=>Er});var Sr=class{},Cr=(e,t)=>{if(t!==void 0)return e[t];let n=Object.keys(e);if(n.length===1)return e[n[0]]},wr=(e,t)=>{let n=Cr(e,t);if(!n){let t=Object.keys(e);throw Error(`input values have ${t.length} keys, you must specify an input key or pass only 1 key as input`)}return n},Tr=(e,t)=>{let n=Cr(e,t);if(!n&&n!==``){let t=Object.keys(e);throw Error(`output values have ${t.length} keys, you must specify an output key or pass only 1 key as output`)}return n};function Er(e,t){let n=Object.keys(e).filter(e=>!t.includes(e)&&e!==`stop`);if(n.length!==1)throw Error(`One input key expected, but got ${n.length}`);return n[0]}var Dr={};D(Dr,{BaseStore:()=>Or,InMemoryStore:()=>kr});var Or=class extends ze{},kr=class extends Or{lc_namespace=[`langchain`,`storage`];store={};async mget(e){return e.map(e=>this.store[e])}async mset(e){for(let[t,n]of e)this.store[t]=n}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let n of t)(e===void 0||n.startsWith(e))&&(yield n)}},Ar={};D(Ar,{BaseRetriever:()=>jr});var jr=class extends k{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw Error(`Not implemented!`)}async invoke(e,t){let n=At(Te(t)),r=await(await ae.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let t=await this._getRelevantDocuments(e,r);return await r?.handleRetrieverEnd(t),t}catch(e){throw await r?.handleRetrieverError(e),e}}},Mr={};D(Mr,{SaveableVectorStore:()=>Fr,VectorStore:()=>Pr,VectorStoreRetriever:()=>Nr});var Nr=class extends jr{static lc_name(){return`VectorStoreRetriever`}get lc_namespace(){return[`langchain_core`,`vectorstores`]}vectorStore;k=4;searchType=`similarity`;searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType===`mmr`&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType===`mmr`){if(typeof this.vectorStore.maxMarginalRelevanceSearch!=`function`)throw Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild(`vectorstore`))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild(`vectorstore`))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},Pr=class extends ze{lc_namespace=[`langchain`,`vectorstores`,this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw Error(`Not implemented.`)}async similaritySearch(e,t=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)).map(e=>e[0])}async similaritySearchWithScore(e,t=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)}static fromTexts(e,t,n,r){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}static fromDocuments(e,t,n){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}asRetriever(e,t,n,r,i,a){if(typeof e==`number`)return new Nr({vectorStore:this,k:e,filter:t,tags:[...r??[],this._vectorstoreType()],metadata:i,verbose:a,callbacks:n});{let t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType===`mmr`?new Nr({...t,searchKwargs:e.searchKwargs}):new Nr({...t})}}},Fr=class extends Pr{static load(e,t){throw Error(`Not implemented`)}},Ir={};D(Ir,{BaseDocumentLoader:()=>Lr});var Lr=class{},Rr={};D(Rr,{LangSmithLoader:()=>zr});var zr=class extends Lr{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw Error(`client and clientConfig cannot both be provided.`);this.client=e.client??new De(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??Br,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){let e=[];for await(let t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=t.inputs;for(let e of this.contentKey)n=n[e];let r=this.formatContent(n),i=t;[`created_at`,`modified_at`].forEach(e=>{e in i&&typeof i[e]==`object`&&(i[e]=i[e].toString())}),e.push({pageContent:r,metadata:i})}return e}};function Br(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var Vr=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},Hr=class extends k{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},Ur=class extends Hr{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},Wr={};D(Wr,{BaseDocumentTransformer:()=>Hr,Document:()=>Vr,MappingDocumentTransformer:()=>Ur});var Gr=class extends ze{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},Kr=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},qr=class extends Kr{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,n]of this.conditionals)if(t(e))return n;return this.defaultPrompt}};function Jr(e){return e._modelType()===`base_llm`}function Yr(e){return e._modelType()===`base_chat_model`}function Xr(e){return e.split(/\n| /).length}var Zr=class e extends Gr{examples=[];examplePrompt;getTextLength=Xr;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Xr}async addExample(e){this.examples.push(e);let t=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(t))}async calculateExampleTextLengths(e,t){if(e.length>0)return e;let{examples:n,examplePrompt:r}=t;return(await Promise.all(n.map(e=>r.format(e)))).map(e=>this.getTextLength(e))}async selectExamples(e){let t=Object.values(e).join(` `),n=this.maxLength-this.getTextLength(t),r=0,i=[];for(;n>0&&r<this.examples.length;){let e=n-this.exampleTextLengths[r];if(e<0)break;i.push(this.examples[r]),n=e,r+=1}return i}static async fromExamples(t,n){let r=new e(n);return await Promise.all(t.map(e=>r.addExample(e))),r}};function Qr(e){return Object.keys(e).sort().map(t=>e[t])}var $r=class e extends Gr{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`)}async addExample(e){let t=Qr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new Vr({pageContent:t,metadata:e})])}async selectExamples(e){let t=Qr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `),n=(await this.vectorStoreRetriever.invoke(t)).map(e=>e.metadata);return this.exampleKeys?n.map(e=>this.exampleKeys.reduce((t,n)=>({...t,[n]:e[n]}),{})):n}static async fromExamples(t,n,r,i={}){let a=i.inputKeys??null,o=t.map(e=>Qr(a?a.reduce((t,n)=>({...t,[n]:e[n]}),{}):e).join(` `));return new e({vectorStore:await r.fromTexts(o,t,n,i),k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}},ei={};D(ei,{BaseExampleSelector:()=>Gr,BasePromptSelector:()=>Kr,ConditionalPromptSelector:()=>qr,LengthBasedExampleSelector:()=>Zr,SemanticSimilarityExampleSelector:()=>$r,isChatModel:()=>Yr,isLLM:()=>Jr});var ti=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,ni=class extends ze{lc_namespace=[`langchain`,`recordmanagers`]},ri=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Bt;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=[`hash_`,`content_hash`,`metadata_hash`];for(let t of e)if(t in this.metadata)throw Error(`Metadata cannot contain key ${t} as it is reserved for internal use. Restricted keys: [${e.join(`, `)}]`);let t=this._hashStringToUUID(this.pageContent);try{let e=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=e}catch(e){throw Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||=this.hash_}toDocument(){return new Vr({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let n=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return n.calculateHashes(),n}_hashStringToUUID(e){return Ae(this.keyEncoder(e),ti)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return Ae(this.keyEncoder(t),ti)}};function ii(e,t){let n=[],r=[];return t.forEach(t=>{r.push(t),r.length>=e&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function ai(e){let t=new Set,n=[];for(let r of e){if(!r.hash_)throw Error(`Hashed document does not have a hash`);t.has(r.hash_)||(t.add(r.hash_),n.push(r))}return n}function oi(e){if(e===null)return e=>null;if(typeof e==`string`)return t=>t.metadata[e];if(typeof e==`function`)return e;throw Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var si=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function ci(e){let{docsSource:t,recordManager:n,vectorStore:r,options:i}=e,{batchSize:a=100,cleanup:o,sourceIdKey:s,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=i??{};if(o===`incremental`&&!s)throw Error(`sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.`);let u=si(t)?await t.load():t,d=oi(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=ii(a??100,u);for(let e of _){let t=ai(e.map(e=>ri.fromDocument(e))),i=t.map(e=>d(e));o===`incremental`&&t.forEach((e,t)=>{if(i[t]===null)throw Error(`sourceIdKey must be provided when cleanup is incremental`)});let a=await n.exists(t.map(e=>e.uid)),s=[],c=[],u=[],_=new Set;if(t.forEach((e,t)=>{if(a[t])if(l)_.add(e.uid);else{u.push(e.uid);return}s.push(e.uid),c.push(e.toDocument())}),u.length>0&&(await n.update(u,{timeAtLeast:f}),g+=u.length),c.length>0&&(await r.addDocuments(c,{ids:s}),p+=c.length-_.size,h+=_.size),await n.update(t.map(e=>e.uid),{timeAtLeast:f,groupIds:i}),o===`incremental`){i.forEach(e=>{if(!e)throw Error(`Source id cannot be null`)});let e=await n.listKeys({before:f,groupIds:i});e.length>0&&(await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length)}}if(o===`full`){let e=await n.listKeys({before:f,limit:c});for(;e.length>0;)await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length,e=await n.listKeys({before:f,limit:c})}return{numAdded:p,numDeleted:m,numUpdated:h,numSkipped:g}}var li={};D(li,{RecordManager:()=>ni,UUIDV5_NAMESPACE:()=>ti,_HashedDocument:()=>ri,_batch:()=>ii,_deduplicateInOrder:()=>ai,_getSourceIdAssigner:()=>oi,_isBaseDocumentLoader:()=>si,index:()=>ci});var ui={},di=class extends Lt{static lc_name(){return`OutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if(`message`in e[0]){let t=e[0].message.additional_kwargs.function_call;if(!t)throw Error(`No function_call in message ${JSON.stringify(e)}`);if(!t.arguments)throw Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?t.arguments:JSON.stringify(t)}else throw Error(`No message in generations ${JSON.stringify(e)}`)}},fi=class extends Ft{static lc_name(){return`JsonOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new di(e)}_diff(e,t){if(t)return Ke(e??{},t)}async parsePartialResult(e){let t=e[0];if(!t.message)return;let{message:n}=t,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?pt(r.arguments):{...r,arguments:pt(r.arguments)}}async parseResult(e){let t=await this.outputParser.parseResult(e);if(!t)throw Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){let t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return``}},pi=class extends Lt{static lc_name(){return`JsonKeyOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser=new fi;attrName;get lc_aliases(){return{attrName:`key_name`}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},mi={};D(mi,{JsonKeyOutputFunctionsParser:()=>pi,JsonOutputFunctionsParser:()=>fi,OutputFunctionsParser:()=>di});var hi=class extends k{lc_serializable=!0;lc_namespace=[`langchain_core`,`prompts`,this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);let{inputVariables:t}=e;if(t.includes(`stop`))throw Error(`Cannot have an input variable named 'stop', as it is used internally, please rename.`);Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},n={};for(let[e,r]of Object.entries(t))typeof r==`string`?n[e]=r:n[e]=await r();return{...n,...e}}async invoke(e,t){let n={...this.metadata,...t?.metadata},r=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(e=>this.formatPromptValue(e),e,{...t,tags:r,metadata:n,runType:`prompt`})}},gi=class extends hi{async formatPromptValue(e){return new Vt(await this.format(e))}},_i=Object.prototype.toString,vi=Array.isArray||function(e){return _i.call(e)===`[object Array]`};function yi(e){return typeof e==`function`}function bi(e){return vi(e)?`array`:typeof e}function xi(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function Si(e,t){return typeof e==`object`&&!!e&&t in e}function Ci(e,t){return e!=null&&typeof e!=`object`&&e.hasOwnProperty&&e.hasOwnProperty(t)}var wi=RegExp.prototype.test;function Ti(e,t){return wi.call(e,t)}var Ei=/\S/;function Di(e){return!Ti(Ei,e)}var Oi={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`,"/":`/`,"`":```,"=":`=`};function ki(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return Oi[e]})}var Ai=/\s*/,ji=/\s+/,Mi=/\s*=/,Ni=/\s*\}/,Pi=/#|\^|\/|>|\{|&|=|!/;function Fi(e,t){if(!e)return[];var n=!1,r=[],i=[],a=[],o=!1,s=!1,c=``,l=0;function u(){if(o&&!s)for(;a.length;)delete i[a.pop()];else a=[];o=!1,s=!1}var d,f,p;function m(e){if(typeof e==`string`&&(e=e.split(ji,2)),!vi(e)||e.length!==2)throw Error(`Invalid tags: `+e);d=RegExp(xi(e[0])+`\\s*`),f=RegExp(`\\s*`+xi(e[1])),p=RegExp(`\\s*`+xi(`}`+e[1]))}m(t||F.tags);for(var h=new Ri(e),g,_,v,y,b,ee;!h.eos();){if(g=h.pos,v=h.scanUntil(d),v)for(var x=0,S=v.length;x<S;++x)y=v.charAt(x),Di(y)?(a.push(i.length),c+=y):(s=!0,n=!0,c+=` `),i.push([`text`,y,g,g+1]),g+=1,y===`
|
|
3
3
|
`&&(u(),c=``,l=0,n=!1);if(!h.scan(d))break;if(o=!0,_=h.scan(Pi)||`name`,h.scan(Ai),_===`=`?(v=h.scanUntil(Mi),h.scan(Mi),h.scanUntil(f)):_===`{`?(v=h.scanUntil(p),h.scan(Ni),h.scanUntil(f),_=`&`):v=h.scanUntil(f),!h.scan(f))throw Error(`Unclosed tag at `+h.pos);if(b=_==`>`?[_,v,g,h.pos,c,l,n]:[_,v,g,h.pos],l++,i.push(b),_===`#`||_===`^`)r.push(b);else if(_===`/`){if(ee=r.pop(),!ee)throw Error(`Unopened section "`+v+`" at `+g);if(ee[1]!==v)throw Error(`Unclosed section "`+ee[1]+`" at `+g)}else _===`name`||_===`{`||_===`&`?s=!0:_===`=`&&m(v)}if(u(),ee=r.pop(),ee)throw Error(`Unclosed section "`+ee[1]+`" at `+h.pos);return Li(Ii(i))}function Ii(e){for(var t=[],n,r,i=0,a=e.length;i<a;++i)n=e[i],n&&(n[0]===`text`&&r&&r[0]===`text`?(r[1]+=n[1],r[3]=n[3]):(t.push(n),r=n));return t}function Li(e){for(var t=[],n=t,r=[],i,a,o=0,s=e.length;o<s;++o)switch(i=e[o],i[0]){case`#`:case`^`:n.push(i),r.push(i),n=i[4]=[];break;case`/`:a=r.pop(),a[5]=i[2],n=r.length>0?r[r.length-1][4]:t;break;default:n.push(i)}return t}function Ri(e){this.string=e,this.tail=e,this.pos=0}Ri.prototype.eos=function(){return this.tail===``},Ri.prototype.scan=function(e){var t=this.tail.match(e);if(!t||t.index!==0)return``;var n=t[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n},Ri.prototype.scanUntil=function(e){var t=this.tail.search(e),n;switch(t){case-1:n=this.tail,this.tail=``;break;case 0:n=``;break;default:n=this.tail.substring(0,t),this.tail=this.tail.substring(t)}return this.pos+=n.length,n};function zi(e,t){this.view=e,this.cache={".":this.view},this.parent=t}zi.prototype.push=function(e){return new zi(e,this)},zi.prototype.lookup=function(e){var t=this.cache,n;if(t.hasOwnProperty(e))n=t[e];else{for(var r=this,i,a,o,s=!1;r;){if(e.indexOf(`.`)>0)for(i=r.view,a=e.split(`.`),o=0;i!=null&&o<a.length;)o===a.length-1&&(s=Si(i,a[o])||Ci(i,a[o])),i=i[a[o++]];else i=r.view[e],s=Si(r.view,e);if(s){n=i;break}r=r.parent}t[e]=n}return yi(n)&&(n=n.call(this.view)),n};function P(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}P.prototype.clearCache=function(){this.templateCache!==void 0&&this.templateCache.clear()},P.prototype.parse=function(e,t){var n=this.templateCache,r=e+`:`+(t||F.tags).join(`:`),i=n!==void 0,a=i?n.get(r):void 0;return a??(a=Fi(e,t),i&&n.set(r,a)),a},P.prototype.render=function(e,t,n,r){var i=this.getConfigTags(r),a=this.parse(e,i),o=t instanceof zi?t:new zi(t,void 0);return this.renderTokens(a,o,n,e,r)},P.prototype.renderTokens=function(e,t,n,r,i){for(var a=``,o,s,c,l=0,u=e.length;l<u;++l)c=void 0,o=e[l],s=o[0],s===`#`?c=this.renderSection(o,t,n,r,i):s===`^`?c=this.renderInverted(o,t,n,r,i):s===`>`?c=this.renderPartial(o,t,n,i):s===`&`?c=this.unescapedValue(o,t):s===`name`?c=this.escapedValue(o,t,i):s===`text`&&(c=this.rawValue(o)),c!==void 0&&(a+=c);return a},P.prototype.renderSection=function(e,t,n,r,i){var a=this,o=``,s=t.lookup(e[1]);function c(e){return a.render(e,t,n,i)}if(s){if(vi(s))for(var l=0,u=s.length;l<u;++l)o+=this.renderTokens(e[4],t.push(s[l]),n,r,i);else if(typeof s==`object`||typeof s==`string`||typeof s==`number`)o+=this.renderTokens(e[4],t.push(s),n,r,i);else if(yi(s)){if(typeof r!=`string`)throw Error(`Cannot use higher-order sections without the original template`);s=s.call(t.view,r.slice(e[3],e[5]),c),s!=null&&(o+=s)}else o+=this.renderTokens(e[4],t,n,r,i);return o}},P.prototype.renderInverted=function(e,t,n,r,i){var a=t.lookup(e[1]);if(!a||vi(a)&&a.length===0)return this.renderTokens(e[4],t,n,r,i)},P.prototype.indentPartial=function(e,t,n){for(var r=t.replace(/[^ \t]/g,``),i=e.split(`
|
|
4
4
|
`),a=0;a<i.length;a++)i[a].length&&(a>0||!n)&&(i[a]=r+i[a]);return i.join(`
|
|
5
5
|
`)},P.prototype.renderPartial=function(e,t,n,r){if(n){var i=this.getConfigTags(r),a=yi(n)?n(e[1]):n[e[1]];if(a!=null){var o=e[6],s=e[5],c=e[4],l=a;s==0&&c&&(l=this.indentPartial(a,c,o));var u=this.parse(l,i);return this.renderTokens(u,t,n,l,r)}}},P.prototype.unescapedValue=function(e,t){var n=t.lookup(e[1]);if(n!=null)return n},P.prototype.escapedValue=function(e,t,n){var r=this.getConfigEscape(n)||F.escape,i=t.lookup(e[1]);if(i!=null)return typeof i==`number`&&r===F.escape?String(i):r(i)},P.prototype.rawValue=function(e){return e[1]},P.prototype.getConfigTags=function(e){if(vi(e))return e;if(e&&typeof e==`object`)return e.tags},P.prototype.getConfigEscape=function(e){if(e&&typeof e==`object`&&!vi(e))return e.escape};var F={name:`mustache.js`,version:`4.2.0`,tags:[`{{`,`}}`],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){Bi.templateCache=e},get templateCache(){return Bi.templateCache}},Bi=new P;F.clearCache=function(){return Bi.clearCache()},F.parse=function(e,t){return Bi.parse(e,t)},F.render=function(e,t,n,r){if(typeof e!=`string`)throw TypeError(`Invalid template! Template should be a "string" but "`+bi(e)+`" was given as the first argument for mustache#render(template, view, partials)`);return Bi.render(e,t,n,r)},F.escape=ki,F.Scanner=Ri,F.Context=zi,F.Writer=P;function Vi(){F.escape=e=>e}var Hi=e=>{let t=e.split(``),n=[],r=(e,n)=>{for(let r=n;r<t.length;r+=1)if(e.includes(t[r]))return r;return-1},i=0;for(;i<t.length;)if(t[i]===`{`&&i+1<t.length&&t[i+1]===`{`)n.push({type:`literal`,text:`{`}),i+=2;else if(t[i]===`}`&&i+1<t.length&&t[i+1]===`}`)n.push({type:`literal`,text:`}`}),i+=2;else if(t[i]===`{`){let e=r(`}`,i);if(e<0)throw Error(`Unclosed '{' in template.`);n.push({type:`variable`,name:t.slice(i+1,e).join(``)}),i=e+1}else if(t[i]===`}`)throw Error(`Single '}' in template.`);else{let e=r(`{}`,i),a=(e<0?t.slice(i):t.slice(i,e)).join(``);n.push({type:`literal`,text:a}),i=e<0?t.length:e}return n},Ui=(e,t=[])=>{let n=[];for(let r of e)if(r[0]===`name`){let e=r[1].includes(`.`)?r[1].split(`.`)[0]:r[1];n.push({type:`variable`,name:e})}else if([`#`,`&`,`^`,`>`].includes(r[0])){if(n.push({type:`variable`,name:r[1]}),r[0]===`#`&&r.length>4&&Array.isArray(r[4])){let e=[...t,r[1]],i=Ui(r[4],e);n.push(...i)}}else n.push({type:`literal`,text:r[1]});return n},Wi=e=>(Vi(),Ui(F.parse(e))),Gi=(e,t)=>Hi(e).reduce((e,n)=>{if(n.type===`variable`){if(n.name in t)return e+(typeof t[n.name]==`string`?t[n.name]:JSON.stringify(t[n.name]));throw Error(`(f-string) Missing value for input ${n.name}`)}return e+n.text},``),Ki=(e,t)=>(Vi(),F.render(e,t)),qi={"f-string":Gi,mustache:Ki},Ji={"f-string":Hi,mustache:Wi},Yi=(e,t,n)=>{try{return qi[t](e,n)}catch(e){throw Ge(e,`INVALID_PROMPT_INPUT`)}},Xi=(e,t)=>Ji[t](e),Zi=(e,t,n)=>{if(!(t in qi)){let e=Object.keys(qi);throw Error(`Invalid template format. Got \`${t}\`;
|
|
@@ -340,7 +340,7 @@ Here are the tools *currently* available to you (this list includes server manag
|
|
|
340
340
|
\u2022 Missing or invalid MCP server configurations
|
|
341
341
|
\u2022 Network connectivity issues with MCP servers
|
|
342
342
|
\u2022 Missing environment variables or credentials
|
|
343
|
-
Raw error: ${c}`)}return l?this.parseStructuredResponse(c,l):typeof c==`object`&&c&&`result`in c?c.result:typeof c==`string`?c:String(c)}catch(e){throw e instanceof Error?e.name===`AbortError`?(t.error(`\u274C Remote execution timed out: ${e}`),Error(`Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.`)):(t.error(`\u274C Remote execution error: ${e}`),Error(`Remote agent execution failed: ${e.message}`)):(t.error(`\u274C Remote execution error: ${e}`),Error(`Remote agent execution failed: ${String(e)}`))}}async*stream(e,t,n,r,i){return await this.run(e,t,n,r,i)}async close(){t.info(`🔌 Remote agent client closed`)}},fh={openai:{package:`@langchain/openai`,className:`ChatOpenAI`,envVars:[`OPENAI_API_KEY`],defaultModel:`gpt-4o`},anthropic:{package:`@langchain/anthropic`,className:`ChatAnthropic`,envVars:[`ANTHROPIC_API_KEY`],defaultModel:`claude-3-5-sonnet-20241022`},google:{package:`@langchain/google-genai`,className:`ChatGoogleGenerativeAI`,envVars:[`GOOGLE_API_KEY`,`GOOGLE_GENERATIVE_AI_API_KEY`],defaultModel:`gemini-pro`},groq:{package:`@langchain/groq`,className:`ChatGroq`,envVars:[`GROQ_API_KEY`],defaultModel:`llama-3.1-70b-versatile`}};function ph(e){let t=e.split(`/`);if(t.length!==2)throw Error(`Invalid LLM string format. Expected 'provider/model', got '${e}'. Examples: 'openai/gpt-4', 'anthropic/claude-3-5-sonnet-20241022', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`);let[n,r]=t;if(!n||!r)throw Error(`Invalid LLM string format. Both provider and model must be non-empty. Got '${e}'`);let i=n.toLowerCase();if(!(i in fh)){let e=Object.keys(fh).join(`, `);throw Error(`Unsupported LLM provider '${n}'. Supported providers: ${e}`)}return{provider:i,model:r}}e(ph,`parseLLMString`);function mh(e,n){if(n?.apiKey)return n.apiKey;let r=fh[e];if(typeof process<`u`)for(let n of r.envVars){let r={}[n];if(r)return t.debug(`Using API key from environment variable ${n} for provider ${e}`),r}let i=r.envVars.join(` or `);throw Error(`API key not found for provider '${e}'. Set ${i} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${e}/model', llmConfig: { apiKey: 'your-key' } })`)}e(mh,`getAPIKey`);async function hh(e,n){t.info(`Creating LLM from string: ${e}`);let{provider:r,model:i}=ph(e),a=fh[r],o=mh(r,n),s;try{t.debug(`Importing package ${a.package}...`),s=await p(()=>import(a.package),[])}catch(e){throw e?.code===`MODULE_NOT_FOUND`||e?.message?.includes(`Cannot find module`)||e?.message?.includes(`Cannot find package`)?Error(`Package '${a.package}' is not installed. Install it with: npm install ${a.package} or yarn add ${a.package}`):Error(`Failed to import ${a.package}: ${e?.message||e}`)}let c=s[a.className];if(!c)throw Error(`Could not find ${a.className} in package ${a.package}. This might be a version compatibility issue.`);let l={model:i,apiKey:o,...n};n?.apiKey&&(delete l.apiKey,l.apiKey=o),(r===`anthropic`||r===`google`||r===`openai`||r===`groq`)&&(l.model=i);try{let e=new c(l);return t.info(`Successfully created ${r} LLM with model ${i}`),e}catch(e){throw Error(`Failed to instantiate ${a.className} with model '${i}': ${e?.message||e}`)}}e(hh,`createLLMFromString`);function gh(e){try{return ph(e),!0}catch{return!1}}e(gh,`isValidLLMString`);function _h(){return Object.keys(fh)}e(_h,`getSupportedProviders`);function vh(e,t,n,r,i,a){if(typeof e==`object`&&e){let t=e;return{query:t.prompt,maxSteps:t.maxSteps,manageConnector:t.manageConnector,externalHistory:t.externalHistory,outputSchema:t.schema,signal:t.signal}}return{query:e,maxSteps:t,manageConnector:n,externalHistory:r,outputSchema:i,signal:a}}e(vh,`normalizeRunOptions`);var yh=class{static{e(this,`MCPAgent`)}static getPackageVersion(){return o()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];exposeResourcesAsTools=!0;exposePromptsAsTools=!0;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;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(n){if(n.agentId){this.isRemote=!0,this.remoteAgent=new dh({agentId:n.agentId,apiKey:n.apiKey,baseUrl:n.baseUrl}),this.maxSteps=n.maxSteps??5,this.memoryEnabled=n.memoryEnabled??!0,this.autoInitialize=n.autoInitialize??!1,this.verbose=n.verbose??!1,this.observe=n.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new Um,this.telemetry=a.getInstance(),this.modelProvider=`remote`,this.modelName=`remote-agent`,this.observabilityManager=new nh({customCallbacks:n.callbacks,agentId:n.agentId}),this.callbacks=[];return}if(!n.llm)throw Error(`llm is required for local execution. For remote execution, provide agentId instead.`);if(typeof n.llm==`string`){if(this.isSimplifiedMode=!0,this.llmString=n.llm,this.llmConfig=n.llmConfig,this.mcpServersConfig=n.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw Error(`Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }`);this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],t.info(`\u{1F3AF} Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=n.llm,this.client=n.client,this.connectors=n.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw Error(`Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.`);if(this.maxSteps=n.maxSteps??5,this.autoInitialize=n.autoInitialize??!1,this.memoryEnabled=n.memoryEnabled??!0,this.systemPrompt=n.systemPrompt??null,this.systemPromptTemplateOverride=n.systemPromptTemplate??null,this.additionalInstructions=n.additionalInstructions??null,this.disallowedTools=n.disallowedTools??[],this.additionalTools=n.additionalTools??[],this.toolsUsedNames=n.toolsUsedNames??[],this.exposeResourcesAsTools=n.exposeResourcesAsTools??!0,this.exposePromptsAsTools=n.exposePromptsAsTools??!0,this.useServerManager=n.useServerManager??!1,this.verbose=n.verbose??!1,this.observe=n.observe??!0,this.isSimplifiedMode)this.adapter=n.adapter??new Um(this.disallowedTools),this.telemetry=a.getInstance(),this.modelProvider=`unknown`,this.modelName=`unknown`;else{if(this.useServerManager){if(!this.client)throw Error(`'client' must be provided when 'useServerManager' is true.`);this.adapter=n.adapter??new Um(this.disallowedTools),this.serverManager=n.serverManagerFactory?.(this.client)??new th(this.client,this.adapter)}else this.adapter=n.adapter??new Um(this.disallowedTools);if(this.telemetry=a.getInstance(),this.llm){let[e,t]=s(this.llm);this.modelProvider=e,this.modelName=t}else this.modelProvider=`unknown`,this.modelName=`unknown`}this.observabilityManager=new nh({customCallbacks:n.callbacks,verbose:this.verbose,observe:this.observe,agentId:n.agentId,metadataProvider:e(()=>this.getMetadata(),`metadataProvider`),tagsProvider:e(()=>this.getTags(),`tagsProvider`)}),Object.defineProperty(this,`agentExecutor`,{get:e(()=>this._agentExecutor,`get`),configurable:!0}),Object.defineProperty(this,`tools`,{get:e(()=>this._tools,`get`),configurable:!0}),Object.defineProperty(this,`initialized`,{get:e(()=>this._initialized,`get`),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(t.info(`🚀 Initializing MCP agent and connecting to services...`),this.isSimplifiedMode){if(t.info(`🎯 Simplified mode: Creating client and LLM from configuration...`),this.mcpServersConfig){t.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);let{MCPClient:e}=await p(async()=>{let{MCPClient:e}=await import(`./client-S6L7XHLF-Dqmt1wRx.js`);return{MCPClient:e}},__vite__mapDeps([6,5,7,3,8,9,2,1,10,11,12]));this.client=new e({mcpServers:this.mcpServersConfig}),t.info(`✅ MCPClient created successfully`)}if(this.llmString){t.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await hh(this.llmString,this.llmConfig),t.info(`✅ LLM created successfully`);let[e,n]=s(this.llm);this.modelProvider=e,this.modelName=n}catch(e){throw Error(`Failed to create LLM from string '${this.llmString}': ${e?.message||e}`)}}if(this.useServerManager){if(!this.client)throw Error(`'client' must be available when 'useServerManager' is true.`);this.serverManager=new th(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();let e=await this.observabilityManager.getHandlerNames();if(e.length>0&&t.info(`\u{1F4CA} Observability enabled with: ${e.join(`, `)}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();let e=this.serverManager.tools;this._tools=e,this._tools.push(...this.additionalTools),t.info(`\u{1F527} Server manager mode active with ${e.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),t.info(`\u{1F50C} Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(e=>e!==`code_mode`).length===0&&(t.info(`🔄 No active sessions found, creating new ones...`),this.sessions=await this.client.createAllSessions(),t.info(`\u2705 Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){let e=this.sessions.code_mode;if(e)this._tools=await this.adapter.createToolsFromConnectors([e.connector]),t.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} code mode tools`);else throw Error(`Code mode enabled but code_mode session not found`)}else{let e=Object.values(this.sessions).map(e=>e.connector),n=await this.adapter.createToolsFromConnectors(e),r=this.exposeResourcesAsTools?await this.adapter.createResourcesFromConnectors(e):[],i=this.exposePromptsAsTools?await this.adapter.createPromptsFromConnectors(e):[];this._tools=[...n,...r,...i],t.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from client: ${n.length} tools, ${r.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{t.info(`\u{1F517} Connecting to ${this.connectors.length} direct connectors...`);for(let e of this.connectors)e.isClientConnected||await e.connect();let e=await this.adapter.createToolsFromConnectors(this.connectors),n=await this.adapter.createResourcesFromConnectors(this.connectors),r=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...e,...n,...r],this._tools.push(...this.additionalTools),t.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from connectors: ${e.length} tools, ${n.length} resources, ${r.length} prompts`)}t.info(`\u{1F9F0} Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;let n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),t.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),t.info(`✨ Agent initialization complete`)}async createSystemMessageFromTools(e){this.systemMessage=ah(e,this.systemPromptTemplateOverride??oh,sh,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(e=>!(e instanceof O))])}createAgent(){if(!this.llm)throw Error(`LLM is required to create agent`);let e=this.systemMessage?.content??`You are a helpful assistant.`,n=this._tools.map(e=>e.name);t.info(`\u{1F9E0} Agent ready with tools: ${n.join(`, `)}`);let r=[bm({runLimit:this.maxSteps})],i=Lf({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return t.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),i}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 O(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(e=>!(e instanceof O)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),t.debug(`Agent recreated with new system message`))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new Um(this.disallowedTools),this._initialized&&t.debug(`Agent already initialized. Changes will take effect on next initialization.`)}getDisallowedTools(){return this.disallowedTools}setMetadata(e){let n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},t.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){let n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],t.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){let n={};for(let[r,i]of Object.entries(e)){if(typeof r!=`string`||r.length===0){t.warn(`Invalid metadata key: ${r}. Skipping.`);continue}let e=r.replace(/[^\w-]/g,`_`);if(i==null)n[e]=i;else if(typeof i==`string`||typeof i==`number`||typeof i==`boolean`)n[e]=i;else if(Array.isArray(i)){let t=i.filter(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`);t.length>0&&(n[e]=t)}else if(typeof i==`object`)try{let r=JSON.stringify(i);r.length>1e3?(t.warn(`Metadata value for key '${e}' is too large. Truncating.`),n[e]=`${r.substring(0,1e3)}...`):n[e]=i}catch(n){t.warn(`Failed to serialize metadata value for key '${e}': ${n}. Skipping.`)}else t.warn(`Unsupported metadata value type for key '${e}': ${typeof i}. Skipping.`)}return n}sanitizeTags(e){return e.filter(e=>typeof e==`string`&&e.length>0).map(e=>e.replace(/[^\w:-]/g,`_`)).filter(e=>e.length<=50)}getMCPServerInfo(){let e={};try{if(this.client){let n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;let r={};for(let e of n)try{let t=this.client.getServerConfig(e);if(t){let n=`unknown`;t.command?n=`command`:t.url?n=`http`:t.ws_url&&(n=`websocket`),r[e]={type:n,has_args:!!t.args,has_env:!!t.env,has_headers:!!t.headers,url:t.url||null,command:t.command||null}}}catch(n){t.warn(`Failed to get config for server '${e}': ${n}`),r[e]={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(e=>e.publicIdentifier),e.mcp_server_types=this.connectors.map(e=>e.constructor.name))}catch(n){t.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)){let t=[];for(let n of e)if(typeof n==`object`&&n)`text`in n&&typeof n.text==`string`?t.push(n.text):`content`in n?t.push(this._normalizeOutput(n.content)):t.push(String(n));else{let e=n&&typeof n==`object`&&`text`in n?n.text:null;if(typeof e==`string`)t.push(e);else{let e=n&&typeof n==`object`&&`content`in n?n.content:n;t.push(this._normalizeOutput(e))}}return t.join(``)}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof A)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{let e=t.getType();if(e===`ai`||e===`assistant`)return!0}catch{}if(typeof t._getType==`function`)try{let e=t._getType();if(e===`ai`||e===`assistant`)return!0}catch{}return`type`in t?t.type===`ai`||t.type===`assistant`:`role`in t?t.role===`ai`||t.role===`assistant`:!1}_messageHasToolCalls(e){return typeof e==`object`&&e&&`tool_calls`in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof j)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{let e=t.getType();if(e===`human`||e===`user`)return!0}catch{}return`type`in t&&(t.type===`human`||t.type===`user`)||`role`in t&&(t.role===`human`||t.role===`user`)}_isToolMessageLike(e){if(e instanceof g)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{if(t.getType()===`tool`)return!0}catch{}return`type`in t&&t.type===`tool`}_getMessageContent(e){if(e instanceof A||e&&typeof e==`object`&&`content`in e)return e.content}async _consumeAndReturn(e){for(;;){let{done:t,value:n}=await e.next();if(t)return n}}async run(e,t,n,r,i,a){let{query:o,maxSteps:s,manageConnector:c,externalHistory:l,outputSchema:u,signal:d}=vh(e,t,n,r,i,a);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(o,s,c,l,u);let f=this.stream(o,s,c,l,u,d);return this._consumeAndReturn(f)}async*stream(e,n,r=!0,i,a,o){let{query:s,maxSteps:c,manageConnector:l,externalHistory:u,outputSchema:d,signal:f}=vh(e,n,r,i,a,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(s,c,l,u,d);let p=!1,m=Date.now(),h=!1,g=null,_=0;try{if((l&&!this._initialized||!this._initialized&&this.autoInitialize)&&(await this.initialize(),p=!0),!this._agentExecutor)throw Error(`MCP agent failed to initialize`);if(this.useServerManager&&this.serverManager){let e=this.serverManager.tools,n=new Set(e.map(e=>e.name)),r=new Set(this._tools.map(e=>e.name));(n.size!==r.size||[...n].some(e=>!r.has(e)))&&(t.info(`\u{1F504} Tools changed before execution, updating agent. New tools: ${[...n].join(`, `)}`),this._tools=e,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}let e=u??this.conversationHistory,n=[];for(let t of e)(this._isHumanMessageLike(t)||this._isAIMessageLike(t)||this._isToolMessageLike(t))&&n.push(t);let r=s.length>50?`${s.slice(0,50).replace(/\n/g,` `)}...`:s.replace(/\n/g,` `);t.info(`\u{1F4AC} Received query: '${r}'`),t.info(`🏁 Starting agent execution`);let i=0,a=[...n,new j(s)];for(;i<=3;){let e={messages:a},n=!1,r=await this._agentExecutor.stream(e,{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},...f&&{signal:f}});for await(let e of r){if(f?.aborted)break;for(let[r,o]of Object.entries(e))if(t.debug(`\u{1F4E6} Node '${r}' output: ${JSON.stringify(o)}`),o&&typeof o==`object`&&`messages`in o){let e=o.messages;Array.isArray(e)||(e=[e]);for(let t of e)a.includes(t)||a.push(t);for(let r of e){if(`tool_calls`in r&&Array.isArray(r.tool_calls)&&r.tool_calls.length>0)for(let e of r.tool_calls){let n=e.name||`unknown`,r=e.args||{};this.toolsUsedNames.push(n),_++;let i=JSON.stringify(r);i.length>100&&(i=`${i.slice(0,97)}...`),t.info(`\u{1F527} Tool call: ${n} with input: ${i}`),yield{action:{tool:n,toolInput:r,log:`Calling tool ${n}`},observation:``}}if(this._isToolMessageLike(r)){let e=r.content,a=String(e);if(a.length>100&&(a=`${a.slice(0,97)}...`),a=a.replace(/\n/g,` `),t.info(`\u{1F4C4} Tool result: ${a}`),this.useServerManager&&this.serverManager){let e=this.serverManager.tools,r=new Set(e.map(e=>e.name)),a=new Set(this._tools.map(e=>e.name));if(r.size!==a.size||[...r].some(e=>!a.has(e))){t.info(`\u{1F504} Tools changed during execution. New tools: ${[...r].join(`, `)}`),this._tools=e,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),n=!0,i++,t.info(`\u{1F503} Restarting execution with updated tools (restart ${i}/3)`);break}}}this._isAIMessageLike(r)&&!this._messageHasToolCalls(r)&&(g=this._normalizeOutput(this._getMessageContent(r)),t.info(`✅ Agent finished with output`))}if(n)break}if(n)break}if(!n)break;if(i>3){t.warn(`⚠️ Max restarts (3) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){let e=a.slice(n.length);for(let t of e)this.addToHistory(t)}if(d&&g)try{t.info(`🔧 Attempting structured output...`);let e=await this._attemptStructuredOutput(g,this.llm,d);return this.memoryEnabled&&this.addToHistory(new A(`Structured result: ${JSON.stringify(e)}`)),t.info(`✅ Structured output successful`),h=!0,e}catch(e){throw t.error(`\u274C Structured output failed: ${e}`),Error(`Failed to generate structured output: ${e instanceof Error?e.message:String(e)}`)}return t.info(`\u{1F389} Agent execution complete in ${((Date.now()-m)/1e3).toFixed(2)} seconds`),h=!0,g||`No output generated`}catch(e){throw t.error(`\u274C Error running query: ${e}`),p&&l&&(t.info(`🧹 Cleaning up resources after error`),await this.close()),e}finally{let e=Date.now()-m,n=0;this.client?n=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(n=this.connectors.length);let r=this.memoryEnabled?this.conversationHistory.length:0,i=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:`stream`,query:s,success:h,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:n,serverIdentifiers:this.connectors.map(e=>e.publicIdentifier),totalToolsAvailable:i.length,toolsAvailableNames:i.map(e=>e.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:c??null,manageConnector:l??!0,externalHistoryUsed:u!==void 0,stepsTaken:_,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||``,executionTimeMs:e,errorType:h?null:`execution_error`,conversationHistoryLength:r}),l&&!this.client&&p&&(t.info(`🧹 Closing agent after stream completion`),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(t.debug(`Flushing observability traces...`),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}t.info(`🔌 Closing MCPAgent resources…`),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(t.info(`🔄 Closing internally-created client (simplified mode) and cleaning up resources`),await this.client.close(),this.sessions={},this.client=void 0):(t.info(`🔄 Closing client and cleaning up resources`),await this.client.close(),this.sessions={});else for(let e of this.connectors)t.info(`🔄 Disconnecting connector`),await e.disconnect();this.isSimplifiedMode&&this.llm&&(t.debug(`🔄 Clearing LLM reference (simplified mode)`),this.llm=void 0),`connectorToolMap`in this.adapter&&(this.adapter=new Um)}finally{this._initialized=!1,t.info(`👋 Agent closed successfully`)}}async*prettyStreamEvents(e,t,n=!0,r,i){let{prettyStreamEvents:a}=await p(async()=>{let{prettyStreamEvents:e}=await import(`./display-A5IEINAP-BFwsYEHq.js`);return{prettyStreamEvents:e}},__vite__mapDeps([13,3,5,2]));for await(let o of a(this.streamEvents(e,t,n,r,i)))yield;return``}async*streamEvents(e,n,r=!0,i,a,o){let s=vh(e,n,r,i,a,o),{query:c}=s,{maxSteps:l,manageConnector:u,externalHistory:d,outputSchema:f,signal:p}=s,m=!1,h=Date.now(),g=!1,_=0,v=0,y=``;f&&(c=this._enhanceQueryWithSchema(c,f));try{(u&&!this._initialized||!this._initialized&&this.autoInitialize)&&(await this.initialize(),m=!0);let e=this._agentExecutor;if(!e)throw Error(`MCP agent failed to initialize`);this.maxSteps=l??this.maxSteps;let n=typeof c==`string`&&c.length>50?`${c.slice(0,50).replace(/\n/g,` `)}...`:typeof c==`string`?c.replace(/\n/g,` `):String(c);t.info(`\u{1F4AC} Received query for streamEvents: '${n}'`),this.memoryEnabled&&(t.info(`\u{1F504} Adding user message to history: ${n}`),this.addToHistory(new j({content:c})));let r=d??this.conversationHistory,i=[];for(let e of r)this._isHumanMessageLike(e)||this._isAIMessageLike(e)||this._isToolMessageLike(e)?i.push(e):t.info(`\u26A0\uFE0F Skipped message of type: ${e.constructor?.name||typeof e}`);let a=[...i,new j(c)];t.info(`callbacks`,this.callbacks);let o=e.streamEvents({messages:a},{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},...p&&{signal:p}});for await(let e of o){if(p?.aborted)break;if(_++,!(!e||typeof e!=`object`)){if(e.event===`on_chat_model_stream`&&e.data?.chunk?.content&&(v+=e.data.chunk.content.length),e.event===`on_chat_model_stream`&&e.data?.chunk){let n=e.data.chunk;if(n.content){y||=``;let e=this._normalizeOutput(n.content);y+=e,t.debug(`\u{1F4DD} Accumulated response length: ${y.length}`)}}if(yield e,e.event===`on_chain_end`&&e.data?.output&&!y){let t=e.data.output;Array.isArray(t)&&t.length>0&&t[0]?.text?y=t[0].text:typeof t==`string`?y=t:t&&typeof t==`object`&&`output`in t&&(y=t.output)}}}if(f&&y){t.info(`🔧 Attempting structured output conversion...`);try{let e=!1,n=null,r=null;this._attemptStructuredOutput(y,this.llm,f).then(t=>(e=!0,n=t,t)).catch(t=>{throw e=!0,r=t,t});let i=0;for(;!e;)await new Promise(e=>setTimeout(e,2e3)),e||(i++,yield{event:`on_structured_output_progress`,data:{message:`Converting to structured output... (${i*2}s)`,elapsed:i*2}});if(r)throw r;n&&(yield{event:`on_structured_output`,data:{output:n}},this.memoryEnabled&&this.addToHistory(new A(`Structured result: ${JSON.stringify(n)}`)),t.info(`✅ Structured output successful`))}catch(e){t.warn(`\u26A0\uFE0F Structured output failed: ${e}`),yield{event:`on_structured_output_error`,data:{error:e instanceof Error?e.message:String(e)}}}}else this.memoryEnabled&&y&&this.addToHistory(new A(y));console.log(`
|
|
343
|
+
Raw error: ${c}`)}return l?this.parseStructuredResponse(c,l):typeof c==`object`&&c&&`result`in c?c.result:typeof c==`string`?c:String(c)}catch(e){throw e instanceof Error?e.name===`AbortError`?(t.error(`\u274C Remote execution timed out: ${e}`),Error(`Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.`)):(t.error(`\u274C Remote execution error: ${e}`),Error(`Remote agent execution failed: ${e.message}`)):(t.error(`\u274C Remote execution error: ${e}`),Error(`Remote agent execution failed: ${String(e)}`))}}async*stream(e,t,n,r,i){return await this.run(e,t,n,r,i)}async close(){t.info(`🔌 Remote agent client closed`)}},fh={openai:{package:`@langchain/openai`,className:`ChatOpenAI`,envVars:[`OPENAI_API_KEY`],defaultModel:`gpt-4o`},anthropic:{package:`@langchain/anthropic`,className:`ChatAnthropic`,envVars:[`ANTHROPIC_API_KEY`],defaultModel:`claude-3-5-sonnet-20241022`},google:{package:`@langchain/google-genai`,className:`ChatGoogleGenerativeAI`,envVars:[`GOOGLE_API_KEY`,`GOOGLE_GENERATIVE_AI_API_KEY`],defaultModel:`gemini-pro`},groq:{package:`@langchain/groq`,className:`ChatGroq`,envVars:[`GROQ_API_KEY`],defaultModel:`llama-3.1-70b-versatile`}};function ph(e){let t=e.split(`/`);if(t.length!==2)throw Error(`Invalid LLM string format. Expected 'provider/model', got '${e}'. Examples: 'openai/gpt-4', 'anthropic/claude-3-5-sonnet-20241022', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`);let[n,r]=t;if(!n||!r)throw Error(`Invalid LLM string format. Both provider and model must be non-empty. Got '${e}'`);let i=n.toLowerCase();if(!(i in fh)){let e=Object.keys(fh).join(`, `);throw Error(`Unsupported LLM provider '${n}'. Supported providers: ${e}`)}return{provider:i,model:r}}e(ph,`parseLLMString`);function mh(e,n){if(n?.apiKey)return n.apiKey;let r=fh[e];if(typeof process<`u`)for(let n of r.envVars){let r={}[n];if(r)return t.debug(`Using API key from environment variable ${n} for provider ${e}`),r}let i=r.envVars.join(` or `);throw Error(`API key not found for provider '${e}'. Set ${i} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${e}/model', llmConfig: { apiKey: 'your-key' } })`)}e(mh,`getAPIKey`);async function hh(e,n){t.info(`Creating LLM from string: ${e}`);let{provider:r,model:i}=ph(e),a=fh[r],o=mh(r,n),s;try{t.debug(`Importing package ${a.package}...`),s=await p(()=>import(a.package),[])}catch(e){throw e?.code===`MODULE_NOT_FOUND`||e?.message?.includes(`Cannot find module`)||e?.message?.includes(`Cannot find package`)?Error(`Package '${a.package}' is not installed. Install it with: npm install ${a.package} or yarn add ${a.package}`):Error(`Failed to import ${a.package}: ${e?.message||e}`)}let c=s[a.className];if(!c)throw Error(`Could not find ${a.className} in package ${a.package}. This might be a version compatibility issue.`);let l={model:i,apiKey:o,...n};n?.apiKey&&(delete l.apiKey,l.apiKey=o),(r===`anthropic`||r===`google`||r===`openai`||r===`groq`)&&(l.model=i);try{let e=new c(l);return t.info(`Successfully created ${r} LLM with model ${i}`),e}catch(e){throw Error(`Failed to instantiate ${a.className} with model '${i}': ${e?.message||e}`)}}e(hh,`createLLMFromString`);function gh(e){try{return ph(e),!0}catch{return!1}}e(gh,`isValidLLMString`);function _h(){return Object.keys(fh)}e(_h,`getSupportedProviders`);function vh(e,t,n,r,i,a){if(typeof e==`object`&&e){let t=e;return{query:t.prompt,maxSteps:t.maxSteps,manageConnector:t.manageConnector,externalHistory:t.externalHistory,outputSchema:t.schema,signal:t.signal}}return{query:e,maxSteps:t,manageConnector:n,externalHistory:r,outputSchema:i,signal:a}}e(vh,`normalizeRunOptions`);var yh=class{static{e(this,`MCPAgent`)}static getPackageVersion(){return o()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];exposeResourcesAsTools=!0;exposePromptsAsTools=!0;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;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(n){if(n.agentId){this.isRemote=!0,this.remoteAgent=new dh({agentId:n.agentId,apiKey:n.apiKey,baseUrl:n.baseUrl}),this.maxSteps=n.maxSteps??5,this.memoryEnabled=n.memoryEnabled??!0,this.autoInitialize=n.autoInitialize??!1,this.verbose=n.verbose??!1,this.observe=n.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new Um,this.telemetry=a.getInstance(),this.modelProvider=`remote`,this.modelName=`remote-agent`,this.observabilityManager=new nh({customCallbacks:n.callbacks,agentId:n.agentId}),this.callbacks=[];return}if(!n.llm)throw Error(`llm is required for local execution. For remote execution, provide agentId instead.`);if(typeof n.llm==`string`){if(this.isSimplifiedMode=!0,this.llmString=n.llm,this.llmConfig=n.llmConfig,this.mcpServersConfig=n.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw Error(`Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }`);this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],t.info(`\u{1F3AF} Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=n.llm,this.client=n.client,this.connectors=n.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw Error(`Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.`);if(this.maxSteps=n.maxSteps??5,this.autoInitialize=n.autoInitialize??!1,this.memoryEnabled=n.memoryEnabled??!0,this.systemPrompt=n.systemPrompt??null,this.systemPromptTemplateOverride=n.systemPromptTemplate??null,this.additionalInstructions=n.additionalInstructions??null,this.disallowedTools=n.disallowedTools??[],this.additionalTools=n.additionalTools??[],this.toolsUsedNames=n.toolsUsedNames??[],this.exposeResourcesAsTools=n.exposeResourcesAsTools??!0,this.exposePromptsAsTools=n.exposePromptsAsTools??!0,this.useServerManager=n.useServerManager??!1,this.verbose=n.verbose??!1,this.observe=n.observe??!0,this.isSimplifiedMode)this.adapter=n.adapter??new Um(this.disallowedTools),this.telemetry=a.getInstance(),this.modelProvider=`unknown`,this.modelName=`unknown`;else{if(this.useServerManager){if(!this.client)throw Error(`'client' must be provided when 'useServerManager' is true.`);this.adapter=n.adapter??new Um(this.disallowedTools),this.serverManager=n.serverManagerFactory?.(this.client)??new th(this.client,this.adapter)}else this.adapter=n.adapter??new Um(this.disallowedTools);if(this.telemetry=a.getInstance(),this.llm){let[e,t]=s(this.llm);this.modelProvider=e,this.modelName=t}else this.modelProvider=`unknown`,this.modelName=`unknown`}this.observabilityManager=new nh({customCallbacks:n.callbacks,verbose:this.verbose,observe:this.observe,agentId:n.agentId,metadataProvider:e(()=>this.getMetadata(),`metadataProvider`),tagsProvider:e(()=>this.getTags(),`tagsProvider`)}),Object.defineProperty(this,`agentExecutor`,{get:e(()=>this._agentExecutor,`get`),configurable:!0}),Object.defineProperty(this,`tools`,{get:e(()=>this._tools,`get`),configurable:!0}),Object.defineProperty(this,`initialized`,{get:e(()=>this._initialized,`get`),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(t.info(`🚀 Initializing MCP agent and connecting to services...`),this.isSimplifiedMode){if(t.info(`🎯 Simplified mode: Creating client and LLM from configuration...`),this.mcpServersConfig){t.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);let{MCPClient:e}=await p(async()=>{let{MCPClient:e}=await import(`./client-H7MR3VAF-CO-aN8Vj.js`);return{MCPClient:e}},__vite__mapDeps([6,5,7,3,8,9,2,1,10,11,12]));this.client=new e({mcpServers:this.mcpServersConfig}),t.info(`✅ MCPClient created successfully`)}if(this.llmString){t.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await hh(this.llmString,this.llmConfig),t.info(`✅ LLM created successfully`);let[e,n]=s(this.llm);this.modelProvider=e,this.modelName=n}catch(e){throw Error(`Failed to create LLM from string '${this.llmString}': ${e?.message||e}`)}}if(this.useServerManager){if(!this.client)throw Error(`'client' must be available when 'useServerManager' is true.`);this.serverManager=new th(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();let e=await this.observabilityManager.getHandlerNames();if(e.length>0&&t.info(`\u{1F4CA} Observability enabled with: ${e.join(`, `)}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();let e=this.serverManager.tools;this._tools=e,this._tools.push(...this.additionalTools),t.info(`\u{1F527} Server manager mode active with ${e.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),t.info(`\u{1F50C} Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(e=>e!==`code_mode`).length===0&&(t.info(`🔄 No active sessions found, creating new ones...`),this.sessions=await this.client.createAllSessions(),t.info(`\u2705 Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){let e=this.sessions.code_mode;if(e)this._tools=await this.adapter.createToolsFromConnectors([e.connector]),t.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} code mode tools`);else throw Error(`Code mode enabled but code_mode session not found`)}else{let e=Object.values(this.sessions).map(e=>e.connector),n=await this.adapter.createToolsFromConnectors(e),r=this.exposeResourcesAsTools?await this.adapter.createResourcesFromConnectors(e):[],i=this.exposePromptsAsTools?await this.adapter.createPromptsFromConnectors(e):[];this._tools=[...n,...r,...i],t.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from client: ${n.length} tools, ${r.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{t.info(`\u{1F517} Connecting to ${this.connectors.length} direct connectors...`);for(let e of this.connectors)e.isClientConnected||await e.connect();let e=await this.adapter.createToolsFromConnectors(this.connectors),n=await this.adapter.createResourcesFromConnectors(this.connectors),r=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...e,...n,...r],this._tools.push(...this.additionalTools),t.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from connectors: ${e.length} tools, ${n.length} resources, ${r.length} prompts`)}t.info(`\u{1F9F0} Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;let n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),t.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),t.info(`✨ Agent initialization complete`)}async createSystemMessageFromTools(e){this.systemMessage=ah(e,this.systemPromptTemplateOverride??oh,sh,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(e=>!(e instanceof O))])}createAgent(){if(!this.llm)throw Error(`LLM is required to create agent`);let e=this.systemMessage?.content??`You are a helpful assistant.`,n=this._tools.map(e=>e.name);t.info(`\u{1F9E0} Agent ready with tools: ${n.join(`, `)}`);let r=[bm({runLimit:this.maxSteps})],i=Lf({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return t.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),i}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 O(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(e=>!(e instanceof O)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),t.debug(`Agent recreated with new system message`))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new Um(this.disallowedTools),this._initialized&&t.debug(`Agent already initialized. Changes will take effect on next initialization.`)}getDisallowedTools(){return this.disallowedTools}setMetadata(e){let n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},t.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){let n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],t.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){let n={};for(let[r,i]of Object.entries(e)){if(typeof r!=`string`||r.length===0){t.warn(`Invalid metadata key: ${r}. Skipping.`);continue}let e=r.replace(/[^\w-]/g,`_`);if(i==null)n[e]=i;else if(typeof i==`string`||typeof i==`number`||typeof i==`boolean`)n[e]=i;else if(Array.isArray(i)){let t=i.filter(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`);t.length>0&&(n[e]=t)}else if(typeof i==`object`)try{let r=JSON.stringify(i);r.length>1e3?(t.warn(`Metadata value for key '${e}' is too large. Truncating.`),n[e]=`${r.substring(0,1e3)}...`):n[e]=i}catch(n){t.warn(`Failed to serialize metadata value for key '${e}': ${n}. Skipping.`)}else t.warn(`Unsupported metadata value type for key '${e}': ${typeof i}. Skipping.`)}return n}sanitizeTags(e){return e.filter(e=>typeof e==`string`&&e.length>0).map(e=>e.replace(/[^\w:-]/g,`_`)).filter(e=>e.length<=50)}getMCPServerInfo(){let e={};try{if(this.client){let n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;let r={};for(let e of n)try{let t=this.client.getServerConfig(e);if(t){let n=`unknown`;t.command?n=`command`:t.url?n=`http`:t.ws_url&&(n=`websocket`),r[e]={type:n,has_args:!!t.args,has_env:!!t.env,has_headers:!!t.headers,url:t.url||null,command:t.command||null}}}catch(n){t.warn(`Failed to get config for server '${e}': ${n}`),r[e]={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(e=>e.publicIdentifier),e.mcp_server_types=this.connectors.map(e=>e.constructor.name))}catch(n){t.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)){let t=[];for(let n of e)if(typeof n==`object`&&n)`text`in n&&typeof n.text==`string`?t.push(n.text):`content`in n?t.push(this._normalizeOutput(n.content)):t.push(String(n));else{let e=n&&typeof n==`object`&&`text`in n?n.text:null;if(typeof e==`string`)t.push(e);else{let e=n&&typeof n==`object`&&`content`in n?n.content:n;t.push(this._normalizeOutput(e))}}return t.join(``)}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof A)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{let e=t.getType();if(e===`ai`||e===`assistant`)return!0}catch{}if(typeof t._getType==`function`)try{let e=t._getType();if(e===`ai`||e===`assistant`)return!0}catch{}return`type`in t?t.type===`ai`||t.type===`assistant`:`role`in t?t.role===`ai`||t.role===`assistant`:!1}_messageHasToolCalls(e){return typeof e==`object`&&e&&`tool_calls`in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof j)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{let e=t.getType();if(e===`human`||e===`user`)return!0}catch{}return`type`in t&&(t.type===`human`||t.type===`user`)||`role`in t&&(t.role===`human`||t.role===`user`)}_isToolMessageLike(e){if(e instanceof g)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{if(t.getType()===`tool`)return!0}catch{}return`type`in t&&t.type===`tool`}_getMessageContent(e){if(e instanceof A||e&&typeof e==`object`&&`content`in e)return e.content}async _consumeAndReturn(e){for(;;){let{done:t,value:n}=await e.next();if(t)return n}}async run(e,t,n,r,i,a){let{query:o,maxSteps:s,manageConnector:c,externalHistory:l,outputSchema:u,signal:d}=vh(e,t,n,r,i,a);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(o,s,c,l,u);let f=this.stream(o,s,c,l,u,d);return this._consumeAndReturn(f)}async*stream(e,n,r=!0,i,a,o){let{query:s,maxSteps:c,manageConnector:l,externalHistory:u,outputSchema:d,signal:f}=vh(e,n,r,i,a,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(s,c,l,u,d);let p=!1,m=Date.now(),h=!1,g=null,_=0;try{if((l&&!this._initialized||!this._initialized&&this.autoInitialize)&&(await this.initialize(),p=!0),!this._agentExecutor)throw Error(`MCP agent failed to initialize`);if(this.useServerManager&&this.serverManager){let e=this.serverManager.tools,n=new Set(e.map(e=>e.name)),r=new Set(this._tools.map(e=>e.name));(n.size!==r.size||[...n].some(e=>!r.has(e)))&&(t.info(`\u{1F504} Tools changed before execution, updating agent. New tools: ${[...n].join(`, `)}`),this._tools=e,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}let e=u??this.conversationHistory,n=[];for(let t of e)(this._isHumanMessageLike(t)||this._isAIMessageLike(t)||this._isToolMessageLike(t))&&n.push(t);let r=s.length>50?`${s.slice(0,50).replace(/\n/g,` `)}...`:s.replace(/\n/g,` `);t.info(`\u{1F4AC} Received query: '${r}'`),t.info(`🏁 Starting agent execution`);let i=0,a=[...n,new j(s)];for(;i<=3;){let e={messages:a},n=!1,r=await this._agentExecutor.stream(e,{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},...f&&{signal:f}});for await(let e of r){if(f?.aborted)break;for(let[r,o]of Object.entries(e))if(t.debug(`\u{1F4E6} Node '${r}' output: ${JSON.stringify(o)}`),o&&typeof o==`object`&&`messages`in o){let e=o.messages;Array.isArray(e)||(e=[e]);for(let t of e)a.includes(t)||a.push(t);for(let r of e){if(`tool_calls`in r&&Array.isArray(r.tool_calls)&&r.tool_calls.length>0)for(let e of r.tool_calls){let n=e.name||`unknown`,r=e.args||{};this.toolsUsedNames.push(n),_++;let i=JSON.stringify(r);i.length>100&&(i=`${i.slice(0,97)}...`),t.info(`\u{1F527} Tool call: ${n} with input: ${i}`),yield{action:{tool:n,toolInput:r,log:`Calling tool ${n}`},observation:``}}if(this._isToolMessageLike(r)){let e=r.content,a=String(e);if(a.length>100&&(a=`${a.slice(0,97)}...`),a=a.replace(/\n/g,` `),t.info(`\u{1F4C4} Tool result: ${a}`),this.useServerManager&&this.serverManager){let e=this.serverManager.tools,r=new Set(e.map(e=>e.name)),a=new Set(this._tools.map(e=>e.name));if(r.size!==a.size||[...r].some(e=>!a.has(e))){t.info(`\u{1F504} Tools changed during execution. New tools: ${[...r].join(`, `)}`),this._tools=e,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),n=!0,i++,t.info(`\u{1F503} Restarting execution with updated tools (restart ${i}/3)`);break}}}this._isAIMessageLike(r)&&!this._messageHasToolCalls(r)&&(g=this._normalizeOutput(this._getMessageContent(r)),t.info(`✅ Agent finished with output`))}if(n)break}if(n)break}if(!n)break;if(i>3){t.warn(`⚠️ Max restarts (3) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){let e=a.slice(n.length);for(let t of e)this.addToHistory(t)}if(d&&g)try{t.info(`🔧 Attempting structured output...`);let e=await this._attemptStructuredOutput(g,this.llm,d);return this.memoryEnabled&&this.addToHistory(new A(`Structured result: ${JSON.stringify(e)}`)),t.info(`✅ Structured output successful`),h=!0,e}catch(e){throw t.error(`\u274C Structured output failed: ${e}`),Error(`Failed to generate structured output: ${e instanceof Error?e.message:String(e)}`)}return t.info(`\u{1F389} Agent execution complete in ${((Date.now()-m)/1e3).toFixed(2)} seconds`),h=!0,g||`No output generated`}catch(e){throw t.error(`\u274C Error running query: ${e}`),p&&l&&(t.info(`🧹 Cleaning up resources after error`),await this.close()),e}finally{let e=Date.now()-m,n=0;this.client?n=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(n=this.connectors.length);let r=this.memoryEnabled?this.conversationHistory.length:0,i=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:`stream`,query:s,success:h,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:n,serverIdentifiers:this.connectors.map(e=>e.publicIdentifier),totalToolsAvailable:i.length,toolsAvailableNames:i.map(e=>e.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:c??null,manageConnector:l??!0,externalHistoryUsed:u!==void 0,stepsTaken:_,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||``,executionTimeMs:e,errorType:h?null:`execution_error`,conversationHistoryLength:r}),l&&!this.client&&p&&(t.info(`🧹 Closing agent after stream completion`),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(t.debug(`Flushing observability traces...`),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}t.info(`🔌 Closing MCPAgent resources…`),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(t.info(`🔄 Closing internally-created client (simplified mode) and cleaning up resources`),await this.client.close(),this.sessions={},this.client=void 0):(t.info(`🔄 Closing client and cleaning up resources`),await this.client.close(),this.sessions={});else for(let e of this.connectors)t.info(`🔄 Disconnecting connector`),await e.disconnect();this.isSimplifiedMode&&this.llm&&(t.debug(`🔄 Clearing LLM reference (simplified mode)`),this.llm=void 0),`connectorToolMap`in this.adapter&&(this.adapter=new Um)}finally{this._initialized=!1,t.info(`👋 Agent closed successfully`)}}async*prettyStreamEvents(e,t,n=!0,r,i){let{prettyStreamEvents:a}=await p(async()=>{let{prettyStreamEvents:e}=await import(`./display-A5IEINAP-BFwsYEHq.js`);return{prettyStreamEvents:e}},__vite__mapDeps([13,3,5,2]));for await(let o of a(this.streamEvents(e,t,n,r,i)))yield;return``}async*streamEvents(e,n,r=!0,i,a,o){let s=vh(e,n,r,i,a,o),{query:c}=s,{maxSteps:l,manageConnector:u,externalHistory:d,outputSchema:f,signal:p}=s,m=!1,h=Date.now(),g=!1,_=0,v=0,y=``;f&&(c=this._enhanceQueryWithSchema(c,f));try{(u&&!this._initialized||!this._initialized&&this.autoInitialize)&&(await this.initialize(),m=!0);let e=this._agentExecutor;if(!e)throw Error(`MCP agent failed to initialize`);this.maxSteps=l??this.maxSteps;let n=typeof c==`string`&&c.length>50?`${c.slice(0,50).replace(/\n/g,` `)}...`:typeof c==`string`?c.replace(/\n/g,` `):String(c);t.info(`\u{1F4AC} Received query for streamEvents: '${n}'`),this.memoryEnabled&&(t.info(`\u{1F504} Adding user message to history: ${n}`),this.addToHistory(new j({content:c})));let r=d??this.conversationHistory,i=[];for(let e of r)this._isHumanMessageLike(e)||this._isAIMessageLike(e)||this._isToolMessageLike(e)?i.push(e):t.info(`\u26A0\uFE0F Skipped message of type: ${e.constructor?.name||typeof e}`);let a=[...i,new j(c)];t.info(`callbacks`,this.callbacks);let o=e.streamEvents({messages:a},{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},...p&&{signal:p}});for await(let e of o){if(p?.aborted)break;if(_++,!(!e||typeof e!=`object`)){if(e.event===`on_chat_model_stream`&&e.data?.chunk?.content&&(v+=e.data.chunk.content.length),e.event===`on_chat_model_stream`&&e.data?.chunk){let n=e.data.chunk;if(n.content){y||=``;let e=this._normalizeOutput(n.content);y+=e,t.debug(`\u{1F4DD} Accumulated response length: ${y.length}`)}}if(yield e,e.event===`on_chain_end`&&e.data?.output&&!y){let t=e.data.output;Array.isArray(t)&&t.length>0&&t[0]?.text?y=t[0].text:typeof t==`string`?y=t:t&&typeof t==`object`&&`output`in t&&(y=t.output)}}}if(f&&y){t.info(`🔧 Attempting structured output conversion...`);try{let e=!1,n=null,r=null;this._attemptStructuredOutput(y,this.llm,f).then(t=>(e=!0,n=t,t)).catch(t=>{throw e=!0,r=t,t});let i=0;for(;!e;)await new Promise(e=>setTimeout(e,2e3)),e||(i++,yield{event:`on_structured_output_progress`,data:{message:`Converting to structured output... (${i*2}s)`,elapsed:i*2}});if(r)throw r;n&&(yield{event:`on_structured_output`,data:{output:n}},this.memoryEnabled&&this.addToHistory(new A(`Structured result: ${JSON.stringify(n)}`)),t.info(`✅ Structured output successful`))}catch(e){t.warn(`\u26A0\uFE0F Structured output failed: ${e}`),yield{event:`on_structured_output_error`,data:{error:e instanceof Error?e.message:String(e)}}}}else this.memoryEnabled&&y&&this.addToHistory(new A(y));console.log(`
|
|
344
344
|
|
|
345
345
|
`),t.info(`\u{1F389} StreamEvents complete - ${_} events emitted`),g=!0}catch(e){throw t.error(`\u274C Error during streamEvents: ${e}`),m&&u&&(t.info(`🧹 Cleaning up resources after initialization error in streamEvents`),await this.close()),e}finally{let e=Date.now()-h,n=0;this.client?n=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(n=this.connectors.length);let r=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:`streamEvents`,query:c,success:g,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:n,serverIdentifiers:this.connectors.map(e=>e.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(e=>e.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:l??null,manageConnector:u??!0,externalHistoryUsed:d!==void 0,response:`[STREAMED RESPONSE - ${v} chars]`,executionTimeMs:e,errorType:g?null:`streaming_error`,conversationHistoryLength:r}),u&&!this.client&&m&&(t.info(`🧹 Closing agent after streamEvents completion`),await this.close())}}async _attemptStructuredOutput(e,n,i){t.info(`\u{1F504} Attempting structured output with schema: ${JSON.stringify(i,null,2)}`),t.info(`\u{1F504} Raw result: ${JSON.stringify(e,null,2)}`);let a=null,o=``;if(t.debug(`\u{1F504} Structured output requested, schema: ${JSON.stringify(r(i),null,2)}`),n&&`withStructuredOutput`in n&&typeof n.withStructuredOutput==`function`)a=n.withStructuredOutput(i);else if(n)a=n;else throw Error(`LLM is required for structured output`);let{$schema:s,additionalProperties:c,...l}=r(i);o=JSON.stringify(l,null,2),t.info(`\u{1F504} Schema description: ${o}`);let u=``;typeof e==`string`?u=e:e&&typeof e==`object`&&(u=JSON.stringify(e)),t.info(`rawResult`,e),u||=JSON.stringify(e);let d=``;for(let e=1;e<=3;e++){t.info(`\u{1F504} Structured output attempt ${e}/3`);let n=`
|
|
346
346
|
Please format the following information according to the EXACT schema specified below.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./chunk-3GQAWCBQ-C-9Cm0Np.js";import{n as t}from"./chunk-QWQYAQCK-CyFuZlX8.js";import{I as n,_r as r}from"./json-schema-processors-DSIsU0go.js";import{F as i,N as a,P as o,_ as s,c,g as l,i as u,n as d,r as f,t as p}from"./client-DEFMLVFC.js";import{S as m,a as ee,d as te,f as h,m as g,o as _,p as ne,s as v,t as re,v as y}from"./schemas-79owEkeD.js";var ie={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`},ae;(function(e){})(ae||={});function oe(e){return n(re,e)}function b(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function se(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...b(t.headers),...b(r.headers)}:t.headers}):e}var ce=globalThis.crypto;async function le(e){return(await ce).getRandomValues(new Uint8Array(e))}async function ue(e){let t=``;for(;t.length<e;){let n=await le(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function de(e){return await ue(e)}async function fe(e){let t=await(await ce).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function pe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await de(e);return{code_verifier:t,code_challenge:await fe(t)}}var x=m().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ie.custom,message:`URL must be parseable`,fatal:!0}),r}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),me=h({resource:y().url(),authorization_servers:_(x).optional(),jwks_uri:y().url().optional(),scopes_supported:_(y()).optional(),bearer_methods_supported:_(y()).optional(),resource_signing_alg_values_supported:_(y()).optional(),resource_name:y().optional(),resource_documentation:y().optional(),resource_policy_uri:y().url().optional(),resource_tos_uri:y().url().optional(),tls_client_certificate_bound_access_tokens:v().optional(),authorization_details_types_supported:_(y()).optional(),dpop_signing_alg_values_supported:_(y()).optional(),dpop_bound_access_tokens_required:v().optional()}),he=h({issuer:y(),authorization_endpoint:x,token_endpoint:x,registration_endpoint:x.optional(),scopes_supported:_(y()).optional(),response_types_supported:_(y()),response_modes_supported:_(y()).optional(),grant_types_supported:_(y()).optional(),token_endpoint_auth_methods_supported:_(y()).optional(),token_endpoint_auth_signing_alg_values_supported:_(y()).optional(),service_documentation:x.optional(),revocation_endpoint:x.optional(),revocation_endpoint_auth_methods_supported:_(y()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(y()).optional(),introspection_endpoint:y().optional(),introspection_endpoint_auth_methods_supported:_(y()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(y()).optional(),code_challenge_methods_supported:_(y()).optional(),client_id_metadata_document_supported:v().optional()}),ge=g({...h({issuer:y(),authorization_endpoint:x,token_endpoint:x,userinfo_endpoint:x.optional(),jwks_uri:x,registration_endpoint:x.optional(),scopes_supported:_(y()).optional(),response_types_supported:_(y()),response_modes_supported:_(y()).optional(),grant_types_supported:_(y()).optional(),acr_values_supported:_(y()).optional(),subject_types_supported:_(y()),id_token_signing_alg_values_supported:_(y()),id_token_encryption_alg_values_supported:_(y()).optional(),id_token_encryption_enc_values_supported:_(y()).optional(),userinfo_signing_alg_values_supported:_(y()).optional(),userinfo_encryption_alg_values_supported:_(y()).optional(),userinfo_encryption_enc_values_supported:_(y()).optional(),request_object_signing_alg_values_supported:_(y()).optional(),request_object_encryption_alg_values_supported:_(y()).optional(),request_object_encryption_enc_values_supported:_(y()).optional(),token_endpoint_auth_methods_supported:_(y()).optional(),token_endpoint_auth_signing_alg_values_supported:_(y()).optional(),display_values_supported:_(y()).optional(),claim_types_supported:_(y()).optional(),claims_supported:_(y()).optional(),service_documentation:y().optional(),claims_locales_supported:_(y()).optional(),ui_locales_supported:_(y()).optional(),claims_parameter_supported:v().optional(),request_parameter_supported:v().optional(),request_uri_parameter_supported:v().optional(),require_request_uri_registration:v().optional(),op_policy_uri:x.optional(),op_tos_uri:x.optional(),client_id_metadata_document_supported:v().optional()}).shape,...he.pick({code_challenge_methods_supported:!0}).shape}),_e=g({access_token:y(),id_token:y().optional(),token_type:y(),expires_in:oe().optional(),scope:y().optional(),refresh_token:y().optional()}).strip(),ve=g({error:y(),error_description:y().optional(),error_uri:y().optional()}),ye=x.optional().or(te(``).transform(()=>void 0)),be=g({redirect_uris:_(x),token_endpoint_auth_method:y().optional(),grant_types:_(y()).optional(),response_types:_(y()).optional(),client_name:y().optional(),client_uri:x.optional(),logo_uri:ye,scope:y().optional(),contacts:_(y()).optional(),tos_uri:ye,policy_uri:y().optional(),jwks_uri:x.optional(),jwks:ee().optional(),software_id:y().optional(),software_version:y().optional(),software_statement:y().optional()}).strip(),xe=g({client_id:y(),client_secret:y().optional(),client_id_issued_at:ne().optional(),client_secret_expires_at:ne().optional()}).strip(),Se=be.merge(xe);g({error:y(),error_description:y().optional()}).strip(),g({token:y(),token_type_hint:y().optional()}).strip();function Ce(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function we({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var S=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Te=class extends S{};Te.errorCode=`invalid_request`;var C=class extends S{};C.errorCode=`invalid_client`;var w=class extends S{};w.errorCode=`invalid_grant`;var T=class extends S{};T.errorCode=`unauthorized_client`;var Ee=class extends S{};Ee.errorCode=`unsupported_grant_type`;var De=class extends S{};De.errorCode=`invalid_scope`;var E=class extends S{};E.errorCode=`access_denied`;var D=class extends S{};D.errorCode=`server_error`;var Oe=class extends S{};Oe.errorCode=`temporarily_unavailable`;var ke=class extends S{};ke.errorCode=`unsupported_response_type`;var Ae=class extends S{};Ae.errorCode=`unsupported_token_type`;var je=class extends S{};je.errorCode=`invalid_token`;var Me=class extends S{};Me.errorCode=`method_not_allowed`;var Ne=class extends S{};Ne.errorCode=`too_many_requests`;var O=class extends S{};O.errorCode=`invalid_client_metadata`;var Pe=class extends S{};Pe.errorCode=`insufficient_scope`;var Fe=class extends S{};Fe.errorCode=`invalid_target`;var Ie={[Te.errorCode]:Te,[C.errorCode]:C,[w.errorCode]:w,[T.errorCode]:T,[Ee.errorCode]:Ee,[De.errorCode]:De,[E.errorCode]:E,[D.errorCode]:D,[Oe.errorCode]:Oe,[ke.errorCode]:ke,[Ae.errorCode]:Ae,[je.errorCode]:je,[Me.errorCode]:Me,[Ne.errorCode]:Ne,[O.errorCode]:O,[Pe.errorCode]:Pe,[Fe.errorCode]:Fe},k=class extends Error{constructor(e){super(e??`Unauthorized`)}};function Le(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var Re=`code`,ze=`S256`;function Be(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&Le(e.token_endpoint_auth_method)&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Ve(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:He(i,a,n);return;case`client_secret_post`:Ue(i,a,r);return;case`none`:We(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function He(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Ue(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function We(e,t){t.set(`client_id`,e)}async function Ge(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=ve.parse(JSON.parse(n));return new(Ie[e]||D)(t||``,r)}catch(e){return new D(`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function A(e,t){try{return await Ke(e,t)}catch(n){if(n instanceof C||n instanceof T)return await e.invalidateCredentials?.(`all`),await Ke(e,t);if(n instanceof w)return await e.invalidateCredentials?.(`tokens`),await Ke(e,t);throw n}}async function Ke(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await rt(c,{fetchFn:a}),!s)try{s=await Xe(t,{resourceMetadataUrl:u},a)}catch{}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await it(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await Je(t,e,s),f=await Promise.resolve(e.clientInformation());if(!f){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!qe(r))throw new O(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)f={client_id:r},await e.saveClientInformation?.(f);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await ut(c,{metadata:l,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(t),f=t}}let p=!e.redirectUrl;if(n!==void 0||p){let t=await lt(e,c,{metadata:l,resource:d,authorizationCode:n,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}let m=await e.tokens();if(m?.refresh_token)try{let t=await ct(c,{metadata:l,clientInformation:f,refreshToken:m.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof S)||e instanceof D))throw e}let ee=e.state?await e.state():void 0,{authorizationUrl:te,codeVerifier:h}=await at(c,{metadata:l,clientInformation:f,state:ee,redirectUrl:e.redirectUrl,scope:r||s?.scopes_supported?.join(` `)||e.clientMetadata.scope,resource:d});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(te),`REDIRECT`}function qe(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function Je(e,t,n){let r=Ce(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!we({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function j(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=Ye(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=Ye(e,`scope`)||void 0,s=Ye(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function Ye(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=n.match(r);return i?i[1]||i[2]:null}async function Xe(e,t,n=fetch){let r=await tt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.body?.cancel(),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.body?.cancel(),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return me.parse(await r.json())}async function Ze(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Ze(e,void 0,n):void 0;throw r}}function Qe(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function $e(e,t,n=fetch){return await Ze(e,{"MCP-Protocol-Version":t},n)}function et(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function tt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Qe(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await $e(o,a,n);return!r?.metadataUrl&&et(s,i.pathname)&&(s=await $e(new URL(`/.well-known/${t}`,i),a,n)),s}function nt(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function rt(e,{fetchFn:t=fetch,protocolVersion:n=s}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=nt(e);for(let{url:e,type:n}of i){let i=await Ze(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?he.parse(await i.json()):ge.parse(await i.json())}}}async function it(e,t){let n,r;try{n=await Xe(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch{}r||=String(new URL(`/`,e));let i=await rt(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function at(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Re))throw Error(`Incompatible auth server: does not support response type ${Re}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(ze))throw Error(`Incompatible auth server: does not support code challenge method ${ze}`)}else s=new URL(`/authorize`,e);let c=await pe(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Re),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,ze),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function ot(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function st(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&Ve(Be(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await Ge(l);return _e.parse(await l.json())}async function ct(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await st(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function lt(e,t,{metadata:n,resource:r,authorizationCode:i,fetchFn:a}={}){let o=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);s=ot(i,await e.codeVerifier(),e.redirectUrl)}let c=await e.clientInformation();return st(t,{metadata:n,tokenRequestParams:s,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:a})}async function ut(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Ge(a);return Se.parse(await a.json())}var dt=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function ft(e){}function pt(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=ft,onError:n=ft,onRetry:r=ft,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=mt(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1;f(n,e.slice(t+r),e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
1
|
+
import{t as e}from"./chunk-3GQAWCBQ-C-9Cm0Np.js";import{n as t}from"./chunk-QWQYAQCK-CyFuZlX8.js";import{I as n,_r as r}from"./json-schema-processors-DSIsU0go.js";import{F as i,N as a,P as o,_ as s,c,g as l,i as u,n as d,r as f,t as p}from"./client-6SIHYz8o.js";import{S as m,a as ee,d as te,f as h,m as g,o as _,p as ne,s as v,t as re,v as y}from"./schemas-79owEkeD.js";var ie={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`},ae;(function(e){})(ae||={});function oe(e){return n(re,e)}function b(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function se(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...b(t.headers),...b(r.headers)}:t.headers}):e}var ce=globalThis.crypto;async function le(e){return(await ce).getRandomValues(new Uint8Array(e))}async function ue(e){let t=``;for(;t.length<e;){let n=await le(e-t.length);for(let e of n)e<198&&(t+=`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~`[e%66])}return t}async function de(e){return await ue(e)}async function fe(e){let t=await(await ce).subtle.digest(`SHA-256`,new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,`_`).replace(/\+/g,`-`).replace(/=/g,``)}async function pe(e){if(e||=43,e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await de(e);return{code_verifier:t,code_challenge:await fe(t)}}var x=m().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:ie.custom,message:`URL must be parseable`,fatal:!0}),r}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),me=h({resource:y().url(),authorization_servers:_(x).optional(),jwks_uri:y().url().optional(),scopes_supported:_(y()).optional(),bearer_methods_supported:_(y()).optional(),resource_signing_alg_values_supported:_(y()).optional(),resource_name:y().optional(),resource_documentation:y().optional(),resource_policy_uri:y().url().optional(),resource_tos_uri:y().url().optional(),tls_client_certificate_bound_access_tokens:v().optional(),authorization_details_types_supported:_(y()).optional(),dpop_signing_alg_values_supported:_(y()).optional(),dpop_bound_access_tokens_required:v().optional()}),he=h({issuer:y(),authorization_endpoint:x,token_endpoint:x,registration_endpoint:x.optional(),scopes_supported:_(y()).optional(),response_types_supported:_(y()),response_modes_supported:_(y()).optional(),grant_types_supported:_(y()).optional(),token_endpoint_auth_methods_supported:_(y()).optional(),token_endpoint_auth_signing_alg_values_supported:_(y()).optional(),service_documentation:x.optional(),revocation_endpoint:x.optional(),revocation_endpoint_auth_methods_supported:_(y()).optional(),revocation_endpoint_auth_signing_alg_values_supported:_(y()).optional(),introspection_endpoint:y().optional(),introspection_endpoint_auth_methods_supported:_(y()).optional(),introspection_endpoint_auth_signing_alg_values_supported:_(y()).optional(),code_challenge_methods_supported:_(y()).optional(),client_id_metadata_document_supported:v().optional()}),ge=g({...h({issuer:y(),authorization_endpoint:x,token_endpoint:x,userinfo_endpoint:x.optional(),jwks_uri:x,registration_endpoint:x.optional(),scopes_supported:_(y()).optional(),response_types_supported:_(y()),response_modes_supported:_(y()).optional(),grant_types_supported:_(y()).optional(),acr_values_supported:_(y()).optional(),subject_types_supported:_(y()),id_token_signing_alg_values_supported:_(y()),id_token_encryption_alg_values_supported:_(y()).optional(),id_token_encryption_enc_values_supported:_(y()).optional(),userinfo_signing_alg_values_supported:_(y()).optional(),userinfo_encryption_alg_values_supported:_(y()).optional(),userinfo_encryption_enc_values_supported:_(y()).optional(),request_object_signing_alg_values_supported:_(y()).optional(),request_object_encryption_alg_values_supported:_(y()).optional(),request_object_encryption_enc_values_supported:_(y()).optional(),token_endpoint_auth_methods_supported:_(y()).optional(),token_endpoint_auth_signing_alg_values_supported:_(y()).optional(),display_values_supported:_(y()).optional(),claim_types_supported:_(y()).optional(),claims_supported:_(y()).optional(),service_documentation:y().optional(),claims_locales_supported:_(y()).optional(),ui_locales_supported:_(y()).optional(),claims_parameter_supported:v().optional(),request_parameter_supported:v().optional(),request_uri_parameter_supported:v().optional(),require_request_uri_registration:v().optional(),op_policy_uri:x.optional(),op_tos_uri:x.optional(),client_id_metadata_document_supported:v().optional()}).shape,...he.pick({code_challenge_methods_supported:!0}).shape}),_e=g({access_token:y(),id_token:y().optional(),token_type:y(),expires_in:oe().optional(),scope:y().optional(),refresh_token:y().optional()}).strip(),ve=g({error:y(),error_description:y().optional(),error_uri:y().optional()}),ye=x.optional().or(te(``).transform(()=>void 0)),be=g({redirect_uris:_(x),token_endpoint_auth_method:y().optional(),grant_types:_(y()).optional(),response_types:_(y()).optional(),client_name:y().optional(),client_uri:x.optional(),logo_uri:ye,scope:y().optional(),contacts:_(y()).optional(),tos_uri:ye,policy_uri:y().optional(),jwks_uri:x.optional(),jwks:ee().optional(),software_id:y().optional(),software_version:y().optional(),software_statement:y().optional()}).strip(),xe=g({client_id:y(),client_secret:y().optional(),client_id_issued_at:ne().optional(),client_secret_expires_at:ne().optional()}).strip(),Se=be.merge(xe);g({error:y(),error_description:y().optional()}).strip(),g({token:y(),token_type_hint:y().optional()}).strip();function Ce(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function we({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}var S=class extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){let e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}},Te=class extends S{};Te.errorCode=`invalid_request`;var C=class extends S{};C.errorCode=`invalid_client`;var w=class extends S{};w.errorCode=`invalid_grant`;var T=class extends S{};T.errorCode=`unauthorized_client`;var Ee=class extends S{};Ee.errorCode=`unsupported_grant_type`;var De=class extends S{};De.errorCode=`invalid_scope`;var E=class extends S{};E.errorCode=`access_denied`;var D=class extends S{};D.errorCode=`server_error`;var Oe=class extends S{};Oe.errorCode=`temporarily_unavailable`;var ke=class extends S{};ke.errorCode=`unsupported_response_type`;var Ae=class extends S{};Ae.errorCode=`unsupported_token_type`;var je=class extends S{};je.errorCode=`invalid_token`;var Me=class extends S{};Me.errorCode=`method_not_allowed`;var Ne=class extends S{};Ne.errorCode=`too_many_requests`;var O=class extends S{};O.errorCode=`invalid_client_metadata`;var Pe=class extends S{};Pe.errorCode=`insufficient_scope`;var Fe=class extends S{};Fe.errorCode=`invalid_target`;var Ie={[Te.errorCode]:Te,[C.errorCode]:C,[w.errorCode]:w,[T.errorCode]:T,[Ee.errorCode]:Ee,[De.errorCode]:De,[E.errorCode]:E,[D.errorCode]:D,[Oe.errorCode]:Oe,[ke.errorCode]:ke,[Ae.errorCode]:Ae,[je.errorCode]:je,[Me.errorCode]:Me,[Ne.errorCode]:Ne,[O.errorCode]:O,[Pe.errorCode]:Pe,[Fe.errorCode]:Fe},k=class extends Error{constructor(e){super(e??`Unauthorized`)}};function Le(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var Re=`code`,ze=`S256`;function Be(e,t){let n=e.client_secret!==void 0;return t.length===0?n?`client_secret_post`:`none`:`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&Le(e.token_endpoint_auth_method)&&t.includes(e.token_endpoint_auth_method)?e.token_endpoint_auth_method:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Ve(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:He(i,a,n);return;case`client_secret_post`:Ue(i,a,r);return;case`none`:We(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function He(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Ue(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function We(e,t){t.set(`client_id`,e)}async function Ge(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=ve.parse(JSON.parse(n));return new(Ie[e]||D)(t||``,r)}catch(e){return new D(`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`)}}async function A(e,t){try{return await Ke(e,t)}catch(n){if(n instanceof C||n instanceof T)return await e.invalidateCredentials?.(`all`),await Ke(e,t);if(n instanceof w)return await e.invalidateCredentials?.(`tokens`),await Ke(e,t);throw n}}async function Ke(e,{serverUrl:t,authorizationCode:n,scope:r,resourceMetadataUrl:i,fetchFn:a}){let o=await e.discoveryState?.(),s,c,l,u=i;if(!u&&o?.resourceMetadataUrl&&(u=new URL(o.resourceMetadataUrl)),o?.authorizationServerUrl){if(c=o.authorizationServerUrl,s=o.resourceMetadata,l=o.authorizationServerMetadata??await rt(c,{fetchFn:a}),!s)try{s=await Xe(t,{resourceMetadataUrl:u},a)}catch{}(l!==o.authorizationServerMetadata||s!==o.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}else{let n=await it(t,{resourceMetadataUrl:u,fetchFn:a});c=n.authorizationServerUrl,l=n.authorizationServerMetadata,s=n.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:u?.toString(),resourceMetadata:s,authorizationServerMetadata:l})}let d=await Je(t,e,s),f=await Promise.resolve(e.clientInformation());if(!f){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=l?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!qe(r))throw new O(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)f={client_id:r},await e.saveClientInformation?.(f);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);let t=await ut(c,{metadata:l,clientMetadata:e.clientMetadata,fetchFn:a});await e.saveClientInformation(t),f=t}}let p=!e.redirectUrl;if(n!==void 0||p){let t=await lt(e,c,{metadata:l,resource:d,authorizationCode:n,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}let m=await e.tokens();if(m?.refresh_token)try{let t=await ct(c,{metadata:l,clientInformation:f,refreshToken:m.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:a});return await e.saveTokens(t),`AUTHORIZED`}catch(e){if(!(!(e instanceof S)||e instanceof D))throw e}let ee=e.state?await e.state():void 0,{authorizationUrl:te,codeVerifier:h}=await at(c,{metadata:l,clientInformation:f,state:ee,redirectUrl:e.redirectUrl,scope:r||s?.scopes_supported?.join(` `)||e.clientMetadata.scope,resource:d});return await e.saveCodeVerifier(h),await e.redirectToAuthorization(te),`REDIRECT`}function qe(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function Je(e,t,n){let r=Ce(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!we({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}function j(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(n.toLowerCase()!==`bearer`||!r)return{};let i=Ye(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=Ye(e,`scope`)||void 0,s=Ye(e,`error`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s}}function Ye(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=n.match(r);return i?i[1]||i[2]:null}async function Xe(e,t,n=fetch){let r=await tt(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.body?.cancel(),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.body?.cancel(),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return me.parse(await r.json())}async function Ze(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?Ze(e,void 0,n):void 0;throw r}}function Qe(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function $e(e,t,n=fetch){return await Ze(e,{"MCP-Protocol-Version":t},n)}function et(e,t){return!e||e.status>=400&&e.status<500&&t!==`/`}async function tt(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=Qe(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await $e(o,a,n);return!r?.metadataUrl&&et(s,i.pathname)&&(s=await $e(new URL(`/.well-known/${t}`,i),a,n)),s}function nt(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function rt(e,{fetchFn:t=fetch,protocolVersion:n=s}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=nt(e);for(let{url:e,type:n}of i){let i=await Ze(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?he.parse(await i.json()):ge.parse(await i.json())}}}async function it(e,t){let n,r;try{n=await Xe(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch{}r||=String(new URL(`/`,e));let i=await rt(r,{fetchFn:t?.fetchFn});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}async function at(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Re))throw Error(`Incompatible auth server: does not support response type ${Re}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(ze))throw Error(`Incompatible auth server: does not support code challenge method ${ze}`)}else s=new URL(`/authorize`,e);let c=await pe(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Re),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,ze),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function ot(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function st(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&Ve(Be(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let l=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!l.ok)throw await Ge(l);return _e.parse(await l.json())}async function ct(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await st(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}async function lt(e,t,{metadata:n,resource:r,authorizationCode:i,fetchFn:a}={}){let o=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(o)),!s){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);s=ot(i,await e.codeVerifier(),e.redirectUrl)}let c=await e.clientInformation();return st(t,{metadata:n,tokenRequestParams:s,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:r,fetchFn:a})}async function ut(e,{metadata:t,clientMetadata:n,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);i=new URL(t.registration_endpoint)}else i=new URL(`/register`,e);let a=await(r??fetch)(i,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n)});if(!a.ok)throw await Ge(a);return Se.parse(await a.json())}var dt=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function ft(e){}function pt(e){if(typeof e==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=ft,onError:n=ft,onRetry:r=ft,onComment:i}=e,a=``,o=!0,s,c=``,l=``;function u(e){let t=o?e.replace(/^\xEF\xBB\xBF/,``):e,[n,r]=mt(`${a}${t}`);for(let e of n)d(e);a=r,o=!1}function d(e){if(e===``){p();return}if(e.startsWith(`:`)){i&&i(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1;f(n,e.slice(t+r),e);return}f(e,``,e)}function f(e,t,i){switch(e){case`event`:l=t;break;case`data`:c=`${c}${t}
|
|
2
2
|
`;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new dt(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new dt(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
|
|
3
3
|
`)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function mt(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
|
|
4
4
|
`,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./chunk-3GQAWCBQ-C-9Cm0Np.js";import{_ as t,a as n,b as r,i,m as a,o,p as s,s as c,v as l}from"./schemas-79owEkeD.js";import{f as u}from"./chunk-
|
|
1
|
+
import{t as e}from"./chunk-3GQAWCBQ-C-9Cm0Np.js";import{_ as t,a as n,b as r,i,m as a,o,p as s,s as c,v as l}from"./schemas-79owEkeD.js";import{f as u}from"./chunk-PQMRWHFE-CV30_nBm.js";var d=class{static{e(this,`JSONSchemaToZod`)}static convert(e){return this.parseSchema(e)}static matchesCondition(e,t){if(!t.properties)return!0;if(typeof e!=`object`||!e||Array.isArray(e))return!1;let n=e;for(let[e,r]of Object.entries(t.properties)){if(!(e in n)){if(`const`in r)return!1;continue}let t=n[e];if(`const`in r&&t!==r.const||`minimum`in r&&typeof t==`number`&&t<r.minimum||`maximum`in r&&typeof t==`number`&&t>r.maximum)return!1}return!0}static validateConditionalSchema(e,t,n){this.validateRequiredProperties(e,t,n),this.validatePropertyPatterns(e,t,n),this.validateNestedConditions(e,t,n)}static validateRequiredProperties(e,t,n){if(t.required){if(typeof e!=`object`||!e){for(let e of t.required)n.addIssue({code:u.custom,message:`Required property '${e}' is missing`,path:[e]});return}for(let r of t.required)r in e||n.addIssue({code:u.custom,message:`Required property '${r}' is missing`,path:[r]})}}static validatePropertyPatterns(e,t,n){if(!t.properties||typeof e!=`object`||!e||Array.isArray(e))return;let r=e;for(let[e,i]of Object.entries(t.properties)){if(!(e in r))continue;let t=r[e];i.pattern&&typeof t==`string`&&(new RegExp(i.pattern).test(t)||n.addIssue({code:u.custom,message:`String '${t}' does not match pattern '${i.pattern}'`,path:[e]}))}}static validateNestedConditions(e,t,n){!t.if||!t.then||(this.matchesCondition(e,t.if)?this.validateConditionalSchema(e,t.then,n):t.else&&this.validateConditionalSchema(e,t.else,n))}static parseSchema(e){let t;return t=Array.isArray(e.type)?this.handleTypeArray(e):e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.if&&e.then||e.properties&&(!e.type||e.type===`object`)?this.parseObject(e):this.handleSingleType(e),e.description&&typeof t.describe==`function`&&(t=t.describe(e.description)),t}static handleTypeArray(e){if(!Array.isArray(e.type))throw Error(`Expected schema.type to be an array`);return e.type.includes(`null`)?this.handleNullableType(e):this.createUnionFromTypes(e.type,e)}static handleNullableType(e){if(!Array.isArray(e.type))throw Error(`Expected schema.type to be an array`);let t={...e};return t.type=e.type.filter(e=>e!==`null`),t.type.length===1?this.handleSingleType({...e,type:t.type[0]}).nullable():this.parseSchema(t).nullable()}static createUnionFromTypes(e,t){return r(e.map(e=>{let n={...t,type:e};return this.parseSchema(n)}))}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):n();switch(e.type){case`string`:return this.parseString(e);case`number`:case`integer`:return this.parseNumberSchema(e);case`boolean`:return c();case`array`:return this.parseArray(e);case`object`:return this.parseObject(e);default:throw Error(`Unsupported schema type`)}}static parseNumberSchema(e){let t=s(),n=t;return n=this.applyNumberBounds(t,e),n=this.applyNumberMultipleOf(t,e),n=this.applyNumberEnum(t,e),n=this.applyIntegerConstraint(t,e),n}static applyNumberBounds(e,t){let n=e;return t.minimum!==void 0&&(n=t.exclusiveMinimum?n.gt(t.minimum):n.gte(t.minimum)),t.maximum!==void 0&&(n=t.exclusiveMaximum?n.lt(t.maximum):n.lte(t.maximum)),n}static applyNumberMultipleOf(e,t){return t.multipleOf===void 0?e:e.refine(e=>e%t.multipleOf===0,{message:`Number must be a multiple of ${t.multipleOf}`})}static applyNumberEnum(e,t){if(!t.enum)return e;let n=t.enum.filter(e=>typeof e==`number`);return n.length===0?e:e.refine(e=>n.includes(e),{message:`Number must be one of: ${n.join(`, `)}`})}static applyIntegerConstraint(e,t){return t.type===`integer`?e.refine(e=>Number.isInteger(e),{message:`Number must be an integer`}):e}static parseString(e){let t=l(),n=t;return e.format?this.applyStringFormat(t,e):(n=this.applyStringPattern(t,e),n=this.applyStringLength(t,e),n=this.applyStringEnum(t,e),n)}static applyStringFormat(e,t){if(!t.format)return e;switch(t.format){case`email`:return e.email();case`date-time`:return e.datetime();case`uri`:return e.url();case`uuid`:return e.uuid();case`date`:return e.date();default:return e}}static applyStringPattern(e,t){if(!t.pattern)return e;let n=new RegExp(t.pattern);return e.regex(n,{message:`String must match pattern: ${t.pattern}`})}static applyStringLength(e,t){let n=e;return t.minLength!==void 0&&(e=e.min(t.minLength)),t.maxLength!==void 0&&(e=e.max(t.maxLength)),n}static applyStringEnum(e,t){return t.enum?e.refine(e=>t.enum?.includes(e),{message:`Value must be one of: ${t.enum?.join(`, `)}`}):e}static parseArray(e){if(Array.isArray(e.items))return r(e.items.map(e=>this.parseSchema(e)));let t=o(e.items?this.parseSchema(e.items):n()),i=t;return i=this.applyArrayConstraints(t,e),i}static applyArrayConstraints(e,t){return t.minItems!==void 0&&(e=e.min(t.minItems)),t.maxItems!==void 0&&(e=e.max(t.maxItems)),t.uniqueItems?e.refine(e=>new Set(e).size===e.length,{message:`Array items must be unique`}):e}static parseObject(e){if(e.if&&e.then)return this.parseConditional(e);if(!e.properties&&e.additionalProperties&&typeof e.additionalProperties==`object`){let n=this.parseSchema(e.additionalProperties);return t(l(),n)}let n={};return this.processObjectProperties(e,n),this.processAdditionalProperties(e,a(n))}static processObjectProperties(e,t){let n=new Set(e.required||[]);if(e.properties)for(let[r,i]of Object.entries(e.properties)){let e=this.parseSchema(i);t[r]=n.has(r)?e:e.optional()}}static processAdditionalProperties(e,t){if(e.additionalProperties===!0)return t.passthrough();if(e.additionalProperties&&typeof e.additionalProperties==`object`){let n=this.parseSchema(e.additionalProperties);return t.catchall(n)}else return t.strict()}static parseConditional(e){let t=this.createBaseObjectSchema(e),n=e.if,r=e.then,i=e.else;return t.superRefine((t,a)=>{let o=this.applyDefaultValues(t,e);this.matchesCondition(o,n)?this.validateConditionalSchema(o,r,a):i&&this.validateConditionalSchema(o,i,a)})}static createBaseObjectSchema(e){let t={},n=new Set(e.required||[]);for(let[r,i]of Object.entries(e.properties||{})){let e=this.parseSchema(i);t[r]=n.has(r)?e:e.optional()}let r=a(t);return this.processAdditionalProperties(e,r)}static applyDefaultValues(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n={...e};if(!t.properties)return n;for(let[e,r]of Object.entries(t.properties))!(e in n)&&`default`in r&&(n[e]=r.default);return n}static parseCombinator(e){if(e.oneOf)return this.parseOneOf(e.oneOf);if(e.anyOf)return this.parseAnyOf(e.anyOf);if(e.allOf)return this.parseAllOf(e.allOf);throw Error(`Unsupported schema type`)}static parseOneOf(e){return this.createUnionFromSchemas(e)}static parseAnyOf(e){return this.createUnionFromSchemas(e)}static createUnionFromSchemas(e){if(e.length===0)return n();if(e.length===1)return this.parseSchema(e[0]);let t=[];for(let n of e)n.type===`null`?t.push(i()):t.push(this.parseSchema(n));return t.length>=2?r(t):t.length===1?t[0]:n()}static parseAllOf(e){if(e.length===0)return n();if(e.length===1)return this.parseSchema(e[0]);let t=e.reduce((e,t)=>this.mergeSchemas(e,t));return this.parseSchema(t)}static mergeSchemas(e,t){let n={...e,...t};return e.properties&&t.properties&&(n.properties={...e.properties,...t.properties}),e.required&&t.required&&(n.required=[...new Set([...e.required,...t.required])]),n}};export{d as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{it as e,mr as t}from"./index-
|
|
1
|
+
import{it as e,mr as t}from"./index-B2Y-NYsA.js";var n={};t(n,{Embeddings:()=>r});var r=class{caller;constructor(t){this.caller=new e(t??{})}},i={};t(i,{chunkArray:()=>a});var a=(e,t)=>e.reduce((e,n,r)=>{let i=Math.floor(r/t);return e[i]=(e[i]||[]).concat([n]),e},[]);export{r as n,n as r,i as t};
|