@mcp-use/inspector 2.1.0 → 2.1.1-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.
@@ -26923,7 +26923,7 @@ var Ud = class {
26923
26923
  //#region src/client/telemetry/utils.ts
26924
26924
  function af() {
26925
26925
  try {
26926
- return "2.1.0";
26926
+ return "2.1.1-canary.1";
26927
26927
  } catch {
26928
26928
  return "0.0.0";
26929
26929
  }
@@ -51227,7 +51227,7 @@ var Ck, wk, Nme, Pme, Fme, Tk, Ek, Dk, Ok, kk, Ime, Ak, jk, Mk, Lme, Rme, zme, N
51227
51227
  }(), gve);
51228
51228
  }));
51229
51229
  //#endregion
51230
- //#region ../mcp-use/dist/chunk-MOAF7545.js
51230
+ //#region ../mcp-use/dist/chunk-L4C2FOCG.js
51231
51231
  function DM() {
51232
51232
  return Ove;
51233
51233
  }
@@ -51352,7 +51352,7 @@ function Dve(e) {
51352
51352
  FM.getInstance().setSource(e);
51353
51353
  }
51354
51354
  var Ove, MM, kve, Ave, jve, Mve, Nve, Pve, Fve, Ive, Lve, Rve, zve, Bve, NM, PM, FM, IM, Vve, LM = o((() => {
51355
- Yp(), Wp(), Ppe(), xw(), Ove = "1.24.1", W(DM, "getPackageVersion"), MM = class {
51355
+ Yp(), Wp(), Ppe(), xw(), Ove = "1.24.2-canary.1", W(DM, "getPackageVersion"), MM = class {
51356
51356
  static {
51357
51357
  W(this, "BaseTelemetryEvent");
51358
51358
  }
@@ -58249,7 +58249,7 @@ var DN, ON, kN, AN, jN, MN, NN, PN, FN, IN, LN, RN, zN, BN, VN, HN, UN, WN, GN,
58249
58249
  };
58250
58250
  }));
58251
58251
  //#endregion
58252
- //#region ../mcp-use/dist/chunk-WRL45O5E.js
58252
+ //#region ../mcp-use/dist/chunk-QCEN6KYM.js
58253
58253
  function rP(e, t) {
58254
58254
  return {
58255
58255
  onSampling: e?.onSampling ?? e?.samplingCallback ?? t?.onSampling ?? t?.samplingCallback,
@@ -58678,7 +58678,7 @@ var Ixe, aP, oP, Lxe, sP = o((() => {
58678
58678
  };
58679
58679
  }));
58680
58680
  //#endregion
58681
- //#region ../mcp-use/dist/chunk-FDNVT4RA.js
58681
+ //#region ../mcp-use/dist/chunk-QEZGRYK2.js
58682
58682
  function Rxe(e) {
58683
58683
  let t = Object.keys(e.mcpServers ?? {});
58684
58684
  FM.getInstance().trackMCPClientInit({
@@ -5177,7 +5177,7 @@ var init_module = __esm({
5177
5177
  }
5178
5178
  });
5179
5179
 
5180
- // ../mcp-use/dist/chunk-MOAF7545.js
5180
+ // ../mcp-use/dist/chunk-L4C2FOCG.js
5181
5181
  import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps";
5182
5182
  import {
5183
5183
  CreateMessageRequestSchema,
@@ -5345,12 +5345,12 @@ function setTelemetrySource(source) {
5345
5345
  Tel.getInstance().setSource(source);
5346
5346
  }
5347
5347
  var VERSION, _a3, BaseTelemetryEvent, _a4, MCPAgentExecutionEvent, _a5, ServerRunEvent, _a6, ServerInitializeEvent, _a7, ServerToolCallEvent, _a8, ServerResourceCallEvent, _a9, ServerPromptCallEvent, _a10, ServerContextEvent, _a11, MCPClientInitEvent, _a12, ConnectorInitEvent, _a13, ClientAddServerEvent, _a14, ClientRemoveServerEvent, USER_ID_STORAGE_KEY, cachedEnvironment, _a15, Telemetry2, Tel, _a16, BaseConnector, _a17, ConnectionManager;
5348
- var init_chunk_MOAF7545 = __esm({
5349
- "../mcp-use/dist/chunk-MOAF7545.js"() {
5348
+ var init_chunk_L4C2FOCG = __esm({
5349
+ "../mcp-use/dist/chunk-L4C2FOCG.js"() {
5350
5350
  "use strict";
5351
5351
  init_chunk_QWQYAQCK();
5352
5352
  init_chunk_3GQAWCBQ();
5353
- VERSION = "1.24.1";
5353
+ VERSION = "1.24.2-canary.1";
5354
5354
  __name(getPackageVersion2, "getPackageVersion");
5355
5355
  BaseTelemetryEvent = (_a3 = class {
5356
5356
  }, __name(_a3, "BaseTelemetryEvent"), _a3);
@@ -6620,7 +6620,7 @@ var init_chunk_MOAF7545 = __esm({
6620
6620
  }
6621
6621
  });
6622
6622
 
6623
- // ../mcp-use/dist/chunk-WRL45O5E.js
6623
+ // ../mcp-use/dist/chunk-QCEN6KYM.js
6624
6624
  import {
6625
6625
  Client
6626
6626
  } from "@modelcontextprotocol/sdk/client/index.js";
@@ -6685,10 +6685,10 @@ function createConnectorFromConfig(serverConfig, connectorOptions) {
6685
6685
  throw new Error("Cannot determine connector type from config");
6686
6686
  }
6687
6687
  var _a18, SseConnectionManager, _a19, HttpConnector, _a20, MCPSession, _a21, BaseMCPClient;
6688
- var init_chunk_WRL45O5E = __esm({
6689
- "../mcp-use/dist/chunk-WRL45O5E.js"() {
6688
+ var init_chunk_QCEN6KYM = __esm({
6689
+ "../mcp-use/dist/chunk-QCEN6KYM.js"() {
6690
6690
  "use strict";
6691
- init_chunk_MOAF7545();
6691
+ init_chunk_L4C2FOCG();
6692
6692
  init_chunk_QWQYAQCK();
6693
6693
  init_chunk_3GQAWCBQ();
6694
6694
  SseConnectionManager = (_a18 = class extends ConnectionManager {
@@ -7947,7 +7947,7 @@ var init_chunk_WRL45O5E = __esm({
7947
7947
  }
7948
7948
  });
7949
7949
 
7950
- // ../mcp-use/dist/chunk-FDNVT4RA.js
7950
+ // ../mcp-use/dist/chunk-QEZGRYK2.js
7951
7951
  import {
7952
7952
  discoverOAuthProtectedResourceMetadata,
7953
7953
  discoverAuthorizationServerMetadata,
@@ -8257,11 +8257,11 @@ async function onMcpAuthorization() {
8257
8257
  }
8258
8258
  }
8259
8259
  var _a22, BrowserMCPClient, _a23, BrowserOAuthClientProvider;
8260
- var init_chunk_FDNVT4RA = __esm({
8261
- "../mcp-use/dist/chunk-FDNVT4RA.js"() {
8260
+ var init_chunk_QEZGRYK2 = __esm({
8261
+ "../mcp-use/dist/chunk-QEZGRYK2.js"() {
8262
8262
  "use strict";
8263
- init_chunk_WRL45O5E();
8264
- init_chunk_MOAF7545();
8263
+ init_chunk_QCEN6KYM();
8264
+ init_chunk_L4C2FOCG();
8265
8265
  init_chunk_QWQYAQCK();
8266
8266
  init_chunk_3GQAWCBQ();
8267
8267
  __name(trackBrowserClientInit, "trackBrowserClientInit");
@@ -27978,18 +27978,18 @@ var init_stdio_transport = __esm({
27978
27978
  }
27979
27979
  });
27980
27980
 
27981
- // ../mcp-use/dist/stdio-MZVPQHDD.js
27982
- var stdio_MZVPQHDD_exports = {};
27983
- __export(stdio_MZVPQHDD_exports, {
27981
+ // ../mcp-use/dist/stdio-UHA7WM4Z.js
27982
+ var stdio_UHA7WM4Z_exports = {};
27983
+ __export(stdio_UHA7WM4Z_exports, {
27984
27984
  StdioConnector: () => StdioConnector
27985
27985
  });
27986
27986
  import { Client as Client2 } from "@modelcontextprotocol/sdk/client/index.js";
27987
27987
  import process2 from "process";
27988
27988
  var _a38, StdioConnectionManager, _a39, StdioConnector;
27989
- var init_stdio_MZVPQHDD = __esm({
27990
- "../mcp-use/dist/stdio-MZVPQHDD.js"() {
27989
+ var init_stdio_UHA7WM4Z = __esm({
27990
+ "../mcp-use/dist/stdio-UHA7WM4Z.js"() {
27991
27991
  "use strict";
27992
- init_chunk_MOAF7545();
27992
+ init_chunk_L4C2FOCG();
27993
27993
  init_chunk_QWQYAQCK();
27994
27994
  init_chunk_3GQAWCBQ();
27995
27995
  init_stdio_transport();
@@ -28133,9 +28133,9 @@ var init_stdio_MZVPQHDD = __esm({
28133
28133
  }
28134
28134
  });
28135
28135
 
28136
- // ../mcp-use/dist/client-W7K33MEL.js
28137
- var client_W7K33MEL_exports = {};
28138
- __export(client_W7K33MEL_exports, {
28136
+ // ../mcp-use/dist/client-5I7ERN3I.js
28137
+ var client_5I7ERN3I_exports = {};
28138
+ __export(client_5I7ERN3I_exports, {
28139
28139
  BaseCodeExecutor: () => BaseCodeExecutor,
28140
28140
  E2BCodeExecutor: () => E2BCodeExecutor,
28141
28141
  MCPClient: () => MCPClient,
@@ -28275,12 +28275,12 @@ function trackNodeClientInit(config, codeMode, callbacks) {
28275
28275
  }).catch((e2) => logger.debug(`Failed to track MCPClient init: ${e2}`));
28276
28276
  }
28277
28277
  var _a40, BaseCodeExecutor, _a41, E2BCodeExecutor, vm, vmCheckAttempted, _a42, VMCodeExecutor, _a43, CodeModeConnector, _a44, MCPClient;
28278
- var init_client_W7K33MEL = __esm({
28279
- "../mcp-use/dist/client-W7K33MEL.js"() {
28278
+ var init_client_5I7ERN3I = __esm({
28279
+ "../mcp-use/dist/client-5I7ERN3I.js"() {
28280
28280
  "use strict";
28281
28281
  init_chunk_LG5NSHEL();
28282
- init_chunk_WRL45O5E();
28283
- init_chunk_MOAF7545();
28282
+ init_chunk_QCEN6KYM();
28283
+ init_chunk_L4C2FOCG();
28284
28284
  init_chunk_QWQYAQCK();
28285
28285
  init_chunk_3GQAWCBQ();
28286
28286
  init_fs();
@@ -29217,7 +29217,7 @@ ${shim}
29217
29217
  clientInfo: serverConfig.clientInfo ?? this.config.clientInfo
29218
29218
  };
29219
29219
  if ("command" in merged && "args" in merged) {
29220
- const { StdioConnector: StdioConnector2 } = await Promise.resolve().then(() => (init_stdio_MZVPQHDD(), stdio_MZVPQHDD_exports));
29220
+ const { StdioConnector: StdioConnector2 } = await Promise.resolve().then(() => (init_stdio_UHA7WM4Z(), stdio_UHA7WM4Z_exports));
29221
29221
  const stdioConfig = merged;
29222
29222
  return new StdioConnector2({
29223
29223
  command: stdioConfig.command,
@@ -74896,11 +74896,11 @@ var _a45, BaseAdapter, _a46, LangChainAdapter, _a47, MCPServerTool, PresentActiv
74896
74896
  var init_browser = __esm({
74897
74897
  "../mcp-use/dist/src/browser.js"() {
74898
74898
  "use strict";
74899
- init_chunk_FDNVT4RA();
74899
+ init_chunk_QEZGRYK2();
74900
74900
  init_chunk_UJPHRNQP();
74901
74901
  init_chunk_LG5NSHEL();
74902
- init_chunk_WRL45O5E();
74903
- init_chunk_MOAF7545();
74902
+ init_chunk_QCEN6KYM();
74903
+ init_chunk_L4C2FOCG();
74904
74904
  init_chunk_QWQYAQCK();
74905
74905
  init_chunk_3GQAWCBQ();
74906
74906
  init_dist3();
@@ -76247,7 +76247,7 @@ Raw error: ${result}`
76247
76247
  logger.debug(
76248
76248
  `Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`
76249
76249
  );
76250
- const { MCPClient: MCPClient2 } = await Promise.resolve().then(() => (init_client_W7K33MEL(), client_W7K33MEL_exports));
76250
+ const { MCPClient: MCPClient2 } = await Promise.resolve().then(() => (init_client_5I7ERN3I(), client_5I7ERN3I_exports));
76251
76251
  this.client = new MCPClient2({ mcpServers: this.mcpServersConfig });
76252
76252
  logger.debug("\u2705 MCPClient created successfully");
76253
76253
  }
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/langfuse-U2OEF7K7-BF5JV8uu.js","assets/chunk-QWQYAQCK-BR4V0xsV.js","assets/chunk-3GQAWCBQ-ntjTDD_C.js","assets/chunk-zsgVPwQN.js","assets/chunk-UJPHRNQP-B14ZPq5a.js","assets/preload-helper-ckxxtgMM.js","assets/client-W7K33MEL-CSZOULYm.js","assets/client-BeIkq9vO.js","assets/schemas-BrqAD_Qo.js","assets/json-schema-processors-DNSjFPrk.js","assets/chunk-WRL45O5E-C7sNvNRg.js","assets/path-CG3438uq.js","assets/chunk-LG5NSHEL-nPdzzOXc.js","assets/display-A5IEINAP-B8BJrcag.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./chunk-3GQAWCBQ-ntjTDD_C.js";import{n as t}from"./chunk-QWQYAQCK-BR4V0xsV.js";import{$n as n,A as r,An as i,At as a,Bt as o,Cn as s,Ct as c,D as l,Dn as u,Dt as d,En as f,Et as p,F as m,Gn as h,Gt as g,H as _,Hn as v,Ht as y,I as b,It as x,Jn as S,Kn as ee,Lt as te,Mt as ne,N as re,Nt as ie,O as ae,On as oe,Ot as se,P as ce,Pt as le,Qn as ue,Rt as de,S as fe,Sn as pe,St as me,Tn as he,Tt as ge,U as _e,Un as ve,Vn as ye,Vt as be,Wn as xe,Wt as Se,Xn as C,Xt as w,Yn as Ce,Zn as T,Zt as we,_n as Te,_t as Ee,a as E,b as De,bn as Oe,bt as ke,cn as D,ct as Ae,dn as O,dt as je,er as k,et as Me,fn as Ne,ft as Pe,gn as A,gt as Fe,i as Ie,it as Le,j as Re,jn as ze,jt as Be,k as Ve,kn as He,kt as Ue,l as We,ln as Ge,lt as Ke,m as qe,mn as Je,mt as Ye,nn as Xe,on as Ze,qn as Qe,qt as $e,r as et,rt as tt,s as nt,sn as rt,st as it,t as at,tn as ot,tr as st,tt as ct,un as lt,v as ut,vt as dt,w as ft,wn as pt,wt as mt,x as ht,xn as gt,xt as _t,y as vt,yn as yt,yt as bt,zn as j,zt as xt}from"./messages-D4_mH1tk.js";import{It as St,S as Ct,er as wt}from"./json-schema-processors-DNSjFPrk.js";import{a as Tt,c as Et,s as Dt}from"./client-BeIkq9vO.js";import{a as Ot,c as kt,m as M,n as At,v as jt}from"./schemas-BrqAD_Qo.js";import"./chunk-WRL45O5E-C7sNvNRg.js";import{t as Mt}from"./preload-helper-ckxxtgMM.js";import"./chunk-FDNVT4RA-C4amwMhu.js";import{C as Nt,D as Pt,M as Ft,O as It,S as Lt,T as Rt,_ as zt,b as Bt,c as Vt,d as Ht,f as Ut,g as Wt,h as Gt,j as Kt,k as qt,m as Jt,n as Yt,s as Xt,u as Zt,v as Qt,x as $t,y as en}from"./function_calling-kK7um7Ye.js";import{a as tn,i as nn,n as rn,o as an,r as on,t as sn}from"./tools-kLe9X8V8.js";import{n as cn,r as ln,t as un}from"./chunk_array-Bw1lTtex.js";import{n as dn,r as fn,t as pn}from"./llms-ByyTYk2T.js";import{t as mn}from"./chunk-LG5NSHEL-nPdzzOXc.js";import"./chunk-UJPHRNQP-B14ZPq5a.js";var hn,gn,_n=0,vn=0;function yn(e,t,n){var r=t&&n||0,i=t||Array(16);e||={};var a=e.node,o=e.clockseq;if(e._v6||(a||=hn,o??=gn),a==null||o==null){var s=e.random||(e.rng||de)();a??(a=[s[0],s[1],s[2],s[3],s[4],s[5]],!hn&&!e._v6&&(a[0]|=1,hn=a)),o??(o=(s[6]<<8|s[7])&16383,gn===void 0&&!e._v6&&(gn=o))}var c=e.msecs===void 0?Date.now():e.msecs,l=e.nsecs===void 0?vn+1:e.nsecs,u=c-_n+(l-vn)/1e4;if(u<0&&e.clockseq===void 0&&(o=o+1&16383),(u<0||c>_n)&&e.nsecs===void 0&&(l=0),l>=1e4)throw Error(`uuid.v1(): Can't create more than 10M uuids/sec`);_n=c,vn=l,gn=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||xt(i)}function bn(e){var t=xn(typeof e==`string`?o(e):e);return typeof e==`string`?xt(t):t}function xn(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 Sn(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 Cn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Sn(Object(n),!0).forEach(function(t){wn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Sn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function wn(e,t,n){return(t=Tn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Tn(e){var t=En(e,`string`);return typeof t==`symbol`?t:t+``}function En(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 Dn(e={},t,n=0){var r=yn(Cn(Cn({},e),{},{_v6:!0}),new Uint8Array(16));if(r=bn(r),t){for(var i=0;i<16;i++)t[n+i]=r[i];return t}return xt(r)}var On=Object.defineProperty,kn=(e,t)=>{for(var n in t)On(e,n,{get:t[n],enumerable:!0})};kn({},{ConfigurableModel:()=>Fn,MODEL_PROVIDER_CONFIG:()=>An,_inferModelProvider:()=>Pn,getChatModelByClassName:()=>Mn,initChatModel:()=>In});var An={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}},jn=Object.keys(An);async function Mn(e){let t=Object.entries(An).find(([,t])=>t.className===e);if(!t)return;let[,n]=t;try{return(await Mt(()=>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 Nn(e,t,n={}){let r=t||Pn(e);if(!r)throw Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let i=An[r];if(!i){let e=jn.join(`, `);throw Error(`Unsupported { modelProvider: ${r} }.\n\nSupported model providers are: ${e}`)}let{modelProvider:a,...o}=n;return new(await(Mn(i.className)))({model:e,...o})}function Pn(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 Fn=class e extends Xt{_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 Nn(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 nt({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=Ee(t);return n.invoke(e,r)}async stream(e,t){let n=new je({generator:await(await this._getModelInstance(t)).stream(e,t),config:t});return await n.setup,Pe.fromAsyncGenerator(n)}async batch(e,t,n){return super.batch(e,t,n)}async*transform(e,t){let n=await this._getModelInstance(t),r=Ee(t);yield*n.transform(e,r)}async*streamLog(e,t,n){let r=await this._getModelInstance(t),i=Ee(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=Ee(t),o=i.streamEvents(e,a,n);for await(let e of o)yield e}return Pe.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 In(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(`:`)];jn.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 Fn({defaultConfig:{...c,model:e,modelProvider:i},configPrefix:r,profile:a}):(e&&(c.model=e),i&&(c.modelProvider=i),l=new Fn({defaultConfig:c,configPrefix:r,configurableFields:s,profile:a})),await l._getModelInstance(),l}var Ln=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 Rn(){c.initializeGlobalInstance(new Ln)}var zn=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}},Bn=class extends zn{get is_bubble_up(){return!0}},Vn=class extends zn{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},Hn=class extends zn{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},Un=class extends Bn{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},Wn=class extends Un{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},Gn=class extends Bn{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function Kn(e){return e!==void 0&&e.name===Gn.unminifiable_name}function qn(e){return e!==void 0&&e.is_bubble_up===!0}function Jn(e){return e!==void 0&&[Un.unminifiable_name,Wn.unminifiable_name].includes(e.name)}var Yn=class extends zn{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},N=class extends zn{constructor(e,t){super(e,t),this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},P=class extends zn{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},Xn=class extends zn{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},Zn=class extends zn{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 Qn(e){return Dn({clockseq:e})}function $n(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return x(e,new Uint8Array(n))}var er=`__error__`,tr=`__scheduled__`,nr=`__interrupt__`,rr=`__resume__`,ir=`[...]`,ar=`[Circular]`,or=[],sr=[];function cr(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function lr(e,t,n,r){r===void 0&&(r=cr()),dr(e,``,0,[],void 0,0,r);var i;try{i=sr.length===0?JSON.stringify(e,t,n):JSON.stringify(e,fr(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;or.length!==0;){var a=or.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function ur(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,or.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),or.push([r,n,t,i])):sr.push([t,n,e])}function dr(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){ur(ar,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){ur(ir,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){ur(ir,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)dr(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];dr(e[l],l,s,r,e,a,o)}}r.pop()}}function fr(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(sr.length>0)for(var r=0;r<sr.length;r++){var i=sr[r];if(i[1]===t&&i[0]===n){n=i[2],sr.splice(r,1);break}}return e.call(this,t,n)}}var pr=[],mr={},hr={};j(hr,{BaseChatMessageHistory:()=>gr,BaseListChatMessageHistory:()=>_r,InMemoryChatMessageHistory:()=>vr});var gr=class extends he{async addMessages(e){for(let t of e)await this.addMessage(t)}},_r=class extends he{addUserMessage(e){return this.addMessage(new O(e))}addAIMessage(e){return this.addMessage(new w(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},vr=class extends _r{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=[]}},yr={},br={};j(br,{BaseMemory:()=>xr,getInputValue:()=>Cr,getOutputValue:()=>wr,getPromptInputKey:()=>Tr});var xr=class{},Sr=(e,t)=>{if(t!==void 0)return e[t];let n=Object.keys(e);if(n.length===1)return e[n[0]]},Cr=(e,t)=>{let n=Sr(e,t);if(!n)throw Error(`input values have ${Object.keys(e).length} keys, you must specify an input key or pass only 1 key as input`);return n},wr=(e,t)=>{let n=Sr(e,t);if(!n&&n!==``)throw Error(`output values have ${Object.keys(e).length} keys, you must specify an output key or pass only 1 key as output`);return n};function Tr(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 Er={};j(Er,{BaseStore:()=>Dr,InMemoryStore:()=>Or});var Dr=class extends he{},Or=class extends Dr{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)}},kr={};j(kr,{BaseRetriever:()=>Ar});var Ar=class extends E{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=Ee(p(t)),r=await(await mt.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}}},jr={};j(jr,{SaveableVectorStore:()=>Pr,VectorStore:()=>Nr,VectorStoreRetriever:()=>Mr});var Mr=class extends Ar{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)}},Nr=class extends he{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 Mr({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 Mr({...t,searchKwargs:e.searchKwargs}):new Mr({...t})}}},Pr=class extends Nr{static load(e,t){throw Error(`Not implemented`)}},Fr={};j(Fr,{BaseDocumentLoader:()=>Ir});var Ir=class{},Lr={};j(Lr,{LangSmithLoader:()=>Rr});var Rr=class extends Ir{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 ne(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??zr,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 zr(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var Br=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},Vr=class extends E{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},Hr=class extends Vr{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},Ur={};j(Ur,{BaseDocumentTransformer:()=>Vr,Document:()=>Br,MappingDocumentTransformer:()=>Hr});var Wr=class extends he{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},Gr=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},Kr=class extends Gr{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 qr(e){return e._modelType()===`base_llm`}function Jr(e){return e._modelType()===`base_chat_model`}function Yr(e){return e.split(/\n| /).length}var Xr=class e extends Wr{examples=[];examplePrompt;getTextLength=Yr;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Yr}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 Zr(e){return Object.keys(e).sort().map(t=>e[t])}var Qr=class e extends Wr{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=Zr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new Br({pageContent:t,metadata:e})])}async selectExamples(e){let t=Zr((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=>Zr(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})}},$r={};j($r,{BaseExampleSelector:()=>Wr,BasePromptSelector:()=>Gr,ConditionalPromptSelector:()=>Kr,LengthBasedExampleSelector:()=>Xr,SemanticSimilarityExampleSelector:()=>Qr,isChatModel:()=>Jr,isLLM:()=>qr});var ei=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,ti=class extends he{lc_namespace=[`langchain`,`recordmanagers`]},ni=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=zt;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 Br({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 x(this.keyEncoder(e),ei)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return x(this.keyEncoder(t),ei)}};function ri(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 ii(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 ai(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 oi=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function si(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=oi(t)?await t.load():t,d=ai(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=ri(a??100,u);for(let e of _){let t=ii(e.map(e=>ni.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 ci={};j(ci,{RecordManager:()=>ti,UUIDV5_NAMESPACE:()=>ei,_HashedDocument:()=>ni,_batch:()=>ri,_deduplicateInOrder:()=>ii,_getSourceIdAssigner:()=>ai,_isBaseDocumentLoader:()=>oi,index:()=>si});var li={},ui=class extends It{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)}`)}},di=class extends Pt{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 ui(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?ot(r.arguments):{...r,arguments:ot(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``}},fi=class extends It{static lc_name(){return`JsonKeyOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser=new di;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]}},pi={};j(pi,{JsonKeyOutputFunctionsParser:()=>fi,JsonOutputFunctionsParser:()=>di,OutputFunctionsParser:()=>ui});var mi=class extends E{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`})}},hi=class extends mi{async formatPromptValue(e){return new Bt(await this.format(e))}},gi=Object.prototype.toString,_i=Array.isArray||function(e){return gi.call(e)===`[object Array]`};function vi(e){return typeof e==`function`}function yi(e){return _i(e)?`array`:typeof e}function bi(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function xi(e,t){return typeof e==`object`&&!!e&&t in e}function Si(e,t){return e!=null&&typeof e!=`object`&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Ci=RegExp.prototype.test;function wi(e,t){return Ci.call(e,t)}var Ti=/\S/;function Ei(e){return!wi(Ti,e)}var Di={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`,"/":`&#x2F;`,"`":`&#x60;`,"=":`&#x3D;`};function Oi(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return Di[e]})}var ki=/\s*/,Ai=/\s+/,ji=/\s*=/,Mi=/\s*\}/,Ni=/#|\^|\/|>|\{|&|=|!/;function Pi(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(Ai,2)),!_i(e)||e.length!==2)throw Error(`Invalid tags: `+e);d=RegExp(bi(e[0])+`\\s*`),f=RegExp(`\\s*`+bi(e[1])),p=RegExp(`\\s*`+bi(`}`+e[1]))}m(t||I.tags);for(var h=new Li(e),g,_,v,y,b,x;!h.eos();){if(g=h.pos,v=h.scanUntil(d),v)for(var S=0,ee=v.length;S<ee;++S)y=v.charAt(S),Ei(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-BF5JV8uu.js","assets/chunk-QWQYAQCK-BR4V0xsV.js","assets/chunk-3GQAWCBQ-ntjTDD_C.js","assets/chunk-zsgVPwQN.js","assets/chunk-UJPHRNQP-B14ZPq5a.js","assets/preload-helper-ckxxtgMM.js","assets/client-5I7ERN3I-BUccbVOh.js","assets/client-ryhqkqEA.js","assets/schemas-BrqAD_Qo.js","assets/json-schema-processors-DNSjFPrk.js","assets/chunk-QCEN6KYM-B3ENy-ef.js","assets/path-CG3438uq.js","assets/chunk-LG5NSHEL-CJN7B0O_.js","assets/display-A5IEINAP-B8BJrcag.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./chunk-3GQAWCBQ-ntjTDD_C.js";import{n as t}from"./chunk-QWQYAQCK-BR4V0xsV.js";import{$n as n,A as r,An as i,At as a,Bt as o,Cn as s,Ct as c,D as l,Dn as u,Dt as d,En as f,Et as p,F as m,Gn as h,Gt as g,H as _,Hn as v,Ht as y,I as b,It as x,Jn as S,Kn as ee,Lt as te,Mt as ne,N as re,Nt as ie,O as ae,On as oe,Ot as se,P as ce,Pt as le,Qn as ue,Rt as de,S as fe,Sn as pe,St as me,Tn as he,Tt as ge,U as _e,Un as ve,Vn as ye,Vt as be,Wn as xe,Wt as Se,Xn as C,Xt as w,Yn as Ce,Zn as T,Zt as we,_n as Te,_t as Ee,a as E,b as De,bn as Oe,bt as ke,cn as D,ct as Ae,dn as O,dt as je,er as k,et as Me,fn as Ne,ft as Pe,gn as A,gt as Fe,i as Ie,it as Le,j as Re,jn as ze,jt as Be,k as Ve,kn as He,kt as Ue,l as We,ln as Ge,lt as Ke,m as qe,mn as Je,mt as Ye,nn as Xe,on as Ze,qn as Qe,qt as $e,r as et,rt as tt,s as nt,sn as rt,st as it,t as at,tn as ot,tr as st,tt as ct,un as lt,v as ut,vt as dt,w as ft,wn as pt,wt as mt,x as ht,xn as gt,xt as _t,y as vt,yn as yt,yt as bt,zn as j,zt as xt}from"./messages-D4_mH1tk.js";import{It as St,S as Ct,er as wt}from"./json-schema-processors-DNSjFPrk.js";import{a as Tt,c as Et,s as Dt}from"./client-ryhqkqEA.js";import{a as Ot,c as kt,m as M,n as At,v as jt}from"./schemas-BrqAD_Qo.js";import"./chunk-QCEN6KYM-B3ENy-ef.js";import{t as Mt}from"./preload-helper-ckxxtgMM.js";import"./chunk-QEZGRYK2-bYjJPaOK.js";import{C as Nt,D as Pt,M as Ft,O as It,S as Lt,T as Rt,_ as zt,b as Bt,c as Vt,d as Ht,f as Ut,g as Wt,h as Gt,j as Kt,k as qt,m as Jt,n as Yt,s as Xt,u as Zt,v as Qt,x as $t,y as en}from"./function_calling-kK7um7Ye.js";import{a as tn,i as nn,n as rn,o as an,r as on,t as sn}from"./tools-kLe9X8V8.js";import{n as cn,r as ln,t as un}from"./chunk_array-Bw1lTtex.js";import{n as dn,r as fn,t as pn}from"./llms-ByyTYk2T.js";import{t as mn}from"./chunk-LG5NSHEL-CJN7B0O_.js";import"./chunk-UJPHRNQP-B14ZPq5a.js";var hn,gn,_n=0,vn=0;function yn(e,t,n){var r=t&&n||0,i=t||Array(16);e||={};var a=e.node,o=e.clockseq;if(e._v6||(a||=hn,o??=gn),a==null||o==null){var s=e.random||(e.rng||de)();a??(a=[s[0],s[1],s[2],s[3],s[4],s[5]],!hn&&!e._v6&&(a[0]|=1,hn=a)),o??(o=(s[6]<<8|s[7])&16383,gn===void 0&&!e._v6&&(gn=o))}var c=e.msecs===void 0?Date.now():e.msecs,l=e.nsecs===void 0?vn+1:e.nsecs,u=c-_n+(l-vn)/1e4;if(u<0&&e.clockseq===void 0&&(o=o+1&16383),(u<0||c>_n)&&e.nsecs===void 0&&(l=0),l>=1e4)throw Error(`uuid.v1(): Can't create more than 10M uuids/sec`);_n=c,vn=l,gn=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||xt(i)}function bn(e){var t=xn(typeof e==`string`?o(e):e);return typeof e==`string`?xt(t):t}function xn(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 Sn(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 Cn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Sn(Object(n),!0).forEach(function(t){wn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Sn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function wn(e,t,n){return(t=Tn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Tn(e){var t=En(e,`string`);return typeof t==`symbol`?t:t+``}function En(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 Dn(e={},t,n=0){var r=yn(Cn(Cn({},e),{},{_v6:!0}),new Uint8Array(16));if(r=bn(r),t){for(var i=0;i<16;i++)t[n+i]=r[i];return t}return xt(r)}var On=Object.defineProperty,kn=(e,t)=>{for(var n in t)On(e,n,{get:t[n],enumerable:!0})};kn({},{ConfigurableModel:()=>Fn,MODEL_PROVIDER_CONFIG:()=>An,_inferModelProvider:()=>Pn,getChatModelByClassName:()=>Mn,initChatModel:()=>In});var An={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}},jn=Object.keys(An);async function Mn(e){let t=Object.entries(An).find(([,t])=>t.className===e);if(!t)return;let[,n]=t;try{return(await Mt(()=>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 Nn(e,t,n={}){let r=t||Pn(e);if(!r)throw Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let i=An[r];if(!i){let e=jn.join(`, `);throw Error(`Unsupported { modelProvider: ${r} }.\n\nSupported model providers are: ${e}`)}let{modelProvider:a,...o}=n;return new(await(Mn(i.className)))({model:e,...o})}function Pn(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 Fn=class e extends Xt{_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 Nn(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 nt({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=Ee(t);return n.invoke(e,r)}async stream(e,t){let n=new je({generator:await(await this._getModelInstance(t)).stream(e,t),config:t});return await n.setup,Pe.fromAsyncGenerator(n)}async batch(e,t,n){return super.batch(e,t,n)}async*transform(e,t){let n=await this._getModelInstance(t),r=Ee(t);yield*n.transform(e,r)}async*streamLog(e,t,n){let r=await this._getModelInstance(t),i=Ee(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=Ee(t),o=i.streamEvents(e,a,n);for await(let e of o)yield e}return Pe.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 In(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(`:`)];jn.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 Fn({defaultConfig:{...c,model:e,modelProvider:i},configPrefix:r,profile:a}):(e&&(c.model=e),i&&(c.modelProvider=i),l=new Fn({defaultConfig:c,configPrefix:r,configurableFields:s,profile:a})),await l._getModelInstance(),l}var Ln=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 Rn(){c.initializeGlobalInstance(new Ln)}var zn=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}},Bn=class extends zn{get is_bubble_up(){return!0}},Vn=class extends zn{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},Hn=class extends zn{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},Un=class extends Bn{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},Wn=class extends Un{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},Gn=class extends Bn{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function Kn(e){return e!==void 0&&e.name===Gn.unminifiable_name}function qn(e){return e!==void 0&&e.is_bubble_up===!0}function Jn(e){return e!==void 0&&[Un.unminifiable_name,Wn.unminifiable_name].includes(e.name)}var Yn=class extends zn{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},N=class extends zn{constructor(e,t){super(e,t),this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},P=class extends zn{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},Xn=class extends zn{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},Zn=class extends zn{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 Qn(e){return Dn({clockseq:e})}function $n(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return x(e,new Uint8Array(n))}var er=`__error__`,tr=`__scheduled__`,nr=`__interrupt__`,rr=`__resume__`,ir=`[...]`,ar=`[Circular]`,or=[],sr=[];function cr(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function lr(e,t,n,r){r===void 0&&(r=cr()),dr(e,``,0,[],void 0,0,r);var i;try{i=sr.length===0?JSON.stringify(e,t,n):JSON.stringify(e,fr(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;or.length!==0;){var a=or.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function ur(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,or.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),or.push([r,n,t,i])):sr.push([t,n,e])}function dr(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){ur(ar,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){ur(ir,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){ur(ir,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)dr(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];dr(e[l],l,s,r,e,a,o)}}r.pop()}}function fr(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(sr.length>0)for(var r=0;r<sr.length;r++){var i=sr[r];if(i[1]===t&&i[0]===n){n=i[2],sr.splice(r,1);break}}return e.call(this,t,n)}}var pr=[],mr={},hr={};j(hr,{BaseChatMessageHistory:()=>gr,BaseListChatMessageHistory:()=>_r,InMemoryChatMessageHistory:()=>vr});var gr=class extends he{async addMessages(e){for(let t of e)await this.addMessage(t)}},_r=class extends he{addUserMessage(e){return this.addMessage(new O(e))}addAIMessage(e){return this.addMessage(new w(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},vr=class extends _r{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=[]}},yr={},br={};j(br,{BaseMemory:()=>xr,getInputValue:()=>Cr,getOutputValue:()=>wr,getPromptInputKey:()=>Tr});var xr=class{},Sr=(e,t)=>{if(t!==void 0)return e[t];let n=Object.keys(e);if(n.length===1)return e[n[0]]},Cr=(e,t)=>{let n=Sr(e,t);if(!n)throw Error(`input values have ${Object.keys(e).length} keys, you must specify an input key or pass only 1 key as input`);return n},wr=(e,t)=>{let n=Sr(e,t);if(!n&&n!==``)throw Error(`output values have ${Object.keys(e).length} keys, you must specify an output key or pass only 1 key as output`);return n};function Tr(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 Er={};j(Er,{BaseStore:()=>Dr,InMemoryStore:()=>Or});var Dr=class extends he{},Or=class extends Dr{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)}},kr={};j(kr,{BaseRetriever:()=>Ar});var Ar=class extends E{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=Ee(p(t)),r=await(await mt.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}}},jr={};j(jr,{SaveableVectorStore:()=>Pr,VectorStore:()=>Nr,VectorStoreRetriever:()=>Mr});var Mr=class extends Ar{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)}},Nr=class extends he{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 Mr({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 Mr({...t,searchKwargs:e.searchKwargs}):new Mr({...t})}}},Pr=class extends Nr{static load(e,t){throw Error(`Not implemented`)}},Fr={};j(Fr,{BaseDocumentLoader:()=>Ir});var Ir=class{},Lr={};j(Lr,{LangSmithLoader:()=>Rr});var Rr=class extends Ir{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 ne(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??zr,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 zr(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var Br=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},Vr=class extends E{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},Hr=class extends Vr{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},Ur={};j(Ur,{BaseDocumentTransformer:()=>Vr,Document:()=>Br,MappingDocumentTransformer:()=>Hr});var Wr=class extends he{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},Gr=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},Kr=class extends Gr{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 qr(e){return e._modelType()===`base_llm`}function Jr(e){return e._modelType()===`base_chat_model`}function Yr(e){return e.split(/\n| /).length}var Xr=class e extends Wr{examples=[];examplePrompt;getTextLength=Yr;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Yr}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 Zr(e){return Object.keys(e).sort().map(t=>e[t])}var Qr=class e extends Wr{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=Zr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new Br({pageContent:t,metadata:e})])}async selectExamples(e){let t=Zr((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=>Zr(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})}},$r={};j($r,{BaseExampleSelector:()=>Wr,BasePromptSelector:()=>Gr,ConditionalPromptSelector:()=>Kr,LengthBasedExampleSelector:()=>Xr,SemanticSimilarityExampleSelector:()=>Qr,isChatModel:()=>Jr,isLLM:()=>qr});var ei=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,ti=class extends he{lc_namespace=[`langchain`,`recordmanagers`]},ni=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=zt;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 Br({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 x(this.keyEncoder(e),ei)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return x(this.keyEncoder(t),ei)}};function ri(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 ii(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 ai(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 oi=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function si(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=oi(t)?await t.load():t,d=ai(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=ri(a??100,u);for(let e of _){let t=ii(e.map(e=>ni.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 ci={};j(ci,{RecordManager:()=>ti,UUIDV5_NAMESPACE:()=>ei,_HashedDocument:()=>ni,_batch:()=>ri,_deduplicateInOrder:()=>ii,_getSourceIdAssigner:()=>ai,_isBaseDocumentLoader:()=>oi,index:()=>si});var li={},ui=class extends It{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)}`)}},di=class extends Pt{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 ui(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?ot(r.arguments):{...r,arguments:ot(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``}},fi=class extends It{static lc_name(){return`JsonKeyOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser=new di;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]}},pi={};j(pi,{JsonKeyOutputFunctionsParser:()=>fi,JsonOutputFunctionsParser:()=>di,OutputFunctionsParser:()=>ui});var mi=class extends E{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`})}},hi=class extends mi{async formatPromptValue(e){return new Bt(await this.format(e))}},gi=Object.prototype.toString,_i=Array.isArray||function(e){return gi.call(e)===`[object Array]`};function vi(e){return typeof e==`function`}function yi(e){return _i(e)?`array`:typeof e}function bi(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function xi(e,t){return typeof e==`object`&&!!e&&t in e}function Si(e,t){return e!=null&&typeof e!=`object`&&e.hasOwnProperty&&e.hasOwnProperty(t)}var Ci=RegExp.prototype.test;function wi(e,t){return Ci.call(e,t)}var Ti=/\S/;function Ei(e){return!wi(Ti,e)}var Di={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`,"/":`&#x2F;`,"`":`&#x60;`,"=":`&#x3D;`};function Oi(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return Di[e]})}var ki=/\s*/,Ai=/\s+/,ji=/\s*=/,Mi=/\s*\}/,Ni=/#|\^|\/|>|\{|&|=|!/;function Pi(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(Ai,2)),!_i(e)||e.length!==2)throw Error(`Invalid tags: `+e);d=RegExp(bi(e[0])+`\\s*`),f=RegExp(`\\s*`+bi(e[1])),p=RegExp(`\\s*`+bi(`}`+e[1]))}m(t||I.tags);for(var h=new Li(e),g,_,v,y,b,x;!h.eos();){if(g=h.pos,v=h.scanUntil(d),v)for(var S=0,ee=v.length;S<ee;++S)y=v.charAt(S),Ei(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(Ni)||`name`,h.scan(ki),_===`=`?(v=h.scanUntil(ji),h.scan(ji),h.scanUntil(f)):_===`{`?(v=h.scanUntil(p),h.scan(Mi),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(x=r.pop(),!x)throw Error(`Unopened section "`+v+`" at `+g);if(x[1]!==v)throw Error(`Unclosed section "`+x[1]+`" at `+g)}else _===`name`||_===`{`||_===`&`?s=!0:_===`=`&&m(v)}if(u(),x=r.pop(),x)throw Error(`Unclosed section "`+x[1]+`" at `+h.pos);return Ii(Fi(i))}function Fi(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 Ii(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 Li(e){this.string=e,this.tail=e,this.pos=0}Li.prototype.eos=function(){return this.tail===``},Li.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},Li.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 Ri(e,t){this.view=e,this.cache={".":this.view},this.parent=t}Ri.prototype.push=function(e){return new Ri(e,this)},Ri.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=xi(i,a[o])||Si(i,a[o])),i=i[a[o++]];else i=r.view[e],s=xi(r.view,e);if(s){n=i;break}r=r.parent}t[e]=n}return vi(n)&&(n=n.call(this.view)),n};function F(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}F.prototype.clearCache=function(){this.templateCache!==void 0&&this.templateCache.clear()},F.prototype.parse=function(e,t){var n=this.templateCache,r=e+`:`+(t||I.tags).join(`:`),i=n!==void 0,a=i?n.get(r):void 0;return a??(a=Pi(e,t),i&&n.set(r,a)),a},F.prototype.render=function(e,t,n,r){var i=this.getConfigTags(r),a=this.parse(e,i),o=t instanceof Ri?t:new Ri(t,void 0);return this.renderTokens(a,o,n,e,r)},F.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},F.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(_i(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(vi(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}},F.prototype.renderInverted=function(e,t,n,r,i){var a=t.lookup(e[1]);if(!a||_i(a)&&a.length===0)return this.renderTokens(e[4],t,n,r,i)},F.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
  `)},F.prototype.renderPartial=function(e,t,n,r){if(n){var i=this.getConfigTags(r),a=vi(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)}}},F.prototype.unescapedValue=function(e,t){var n=t.lookup(e[1]);if(n!=null)return n},F.prototype.escapedValue=function(e,t,n){var r=this.getConfigEscape(n)||I.escape,i=t.lookup(e[1]);if(i!=null)return typeof i==`number`&&r===I.escape?String(i):r(i)},F.prototype.rawValue=function(e){return e[1]},F.prototype.getConfigTags=function(e){if(_i(e))return e;if(e&&typeof e==`object`)return e.tags},F.prototype.getConfigEscape=function(e){if(e&&typeof e==`object`&&!_i(e))return e.escape};var I={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){zi.templateCache=e},get templateCache(){return zi.templateCache}},zi=new F;I.clearCache=function(){return zi.clearCache()},I.parse=function(e,t){return zi.parse(e,t)},I.render=function(e,t,n,r){if(typeof e!=`string`)throw TypeError(`Invalid template! Template should be a "string" but "`+yi(e)+`" was given as the first argument for mustache#render(template, view, partials)`);return zi.render(e,t,n,r)},I.escape=Oi,I.Scanner=Li,I.Context=Ri,I.Writer=F;function Bi(){I.escape=e=>e}var Vi=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},Hi=(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=Hi(r[4],e);n.push(...i)}}else n.push({type:`literal`,text:r[1]});return n},Ui=e=>(Bi(),Hi(I.parse(e))),Wi=(e,t)=>Vi(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},``),Gi=(e,t)=>(Bi(),I.render(e,t)),Ki={"f-string":Wi,mustache:Gi},qi={"f-string":Vi,mustache:Ui},Ji=(e,t,n)=>{try{return Ki[t](e,n)}catch(e){throw Ze(e,`INVALID_PROMPT_INPUT`)}},Yi=(e,t)=>qi[t](e),Xi=(e,t,n)=>{if(!(t in Ki))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.debug(`🔌 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-sonnet-4-6`},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-sonnet-4-6', '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.debug(`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 Mt(()=>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.debug(`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 Et()}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=Tt.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.debug(`\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=Tt.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=Tt.getInstance(),this.llm){let[e,t]=Dt(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.debug(`🚀 Initializing MCP agent and connecting to services...`),this.isSimplifiedMode){if(t.debug(`🎯 Simplified mode: Creating client and LLM from configuration...`),this.mcpServersConfig){t.debug(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);let{MCPClient:e}=await Mt(async()=>{let{MCPClient:e}=await import(`./client-W7K33MEL-CSZOULYm.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.debug(`✅ MCPClient created successfully`)}if(this.llmString){t.debug(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await hh(this.llmString,this.llmConfig),t.debug(`✅ LLM created successfully`);let[e,n]=Dt(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.debug(`\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.debug(`\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.debug(`\u{1F50C} Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(e=>e!==`code_mode`).length===0&&(t.debug(`🔄 No active sessions found, creating new ones...`),this.sessions=await this.client.createAllSessions(),t.debug(`\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.debug(`\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.debug(`\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.debug(`\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.debug(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from connectors: ${e.length} tools, ${n.length} resources, ${r.length} prompts`)}t.debug(`\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.debug(`✨ 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 D))])}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.debug(`\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 D(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(e=>!(e instanceof D)),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 w)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 O)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 A)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 w||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.debug(`\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.debug(`\u{1F4AC} Received query: '${r}'`),t.debug(`🏁 Starting agent execution`);let i=0,a=[...n,new O(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.debug(`\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.debug(`\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.debug(`\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.debug(`\u{1F503} Restarting execution with updated tools (restart ${i}/3)`);break}}}this._isAIMessageLike(r)&&!this._messageHasToolCalls(r)&&(g=this._normalizeOutput(this._getMessageContent(r)),t.debug(`✅ 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.debug(`🔧 Attempting structured output...`);let e=await this._attemptStructuredOutput(g,this.llm,d);return this.memoryEnabled&&this.addToHistory(new w(`Structured result: ${JSON.stringify(e)}`)),t.debug(`✅ 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.debug(`\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.debug(`🧹 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.debug(`🧹 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.debug(`🔌 Closing MCPAgent resources…`),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(t.debug(`🔄 Closing internally-created client (simplified mode) and cleaning up resources`),await this.client.close(),this.sessions={},this.client=void 0):(t.debug(`🔄 Closing client and cleaning up resources`),await this.client.close(),this.sessions={});else for(let e of this.connectors)t.debug(`🔄 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.debug(`👋 Agent closed successfully`)}}async*prettyStreamEvents(e,t,n=!0,r,i){let{prettyStreamEvents:a}=await Mt(async()=>{let{prettyStreamEvents:e}=await import(`./display-A5IEINAP-B8BJrcag.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.debug(`\u{1F4AC} Received query for streamEvents: '${n}'`),this.memoryEnabled&&(t.debug(`\u{1F504} Adding user message to history: ${n}`),this.addToHistory(new O({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.debug(`\u26A0\uFE0F Skipped message of type: ${e.constructor?.name||typeof e}`);let a=[...i,new O(c)];t.debug(`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.debug(`🔧 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 w(`Structured result: ${JSON.stringify(n)}`)),t.debug(`✅ 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 w(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.debug(`🔌 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-sonnet-4-6`},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-sonnet-4-6', '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.debug(`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 Mt(()=>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.debug(`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 Et()}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=Tt.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.debug(`\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=Tt.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=Tt.getInstance(),this.llm){let[e,t]=Dt(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.debug(`🚀 Initializing MCP agent and connecting to services...`),this.isSimplifiedMode){if(t.debug(`🎯 Simplified mode: Creating client and LLM from configuration...`),this.mcpServersConfig){t.debug(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);let{MCPClient:e}=await Mt(async()=>{let{MCPClient:e}=await import(`./client-5I7ERN3I-BUccbVOh.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.debug(`✅ MCPClient created successfully`)}if(this.llmString){t.debug(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await hh(this.llmString,this.llmConfig),t.debug(`✅ LLM created successfully`);let[e,n]=Dt(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.debug(`\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.debug(`\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.debug(`\u{1F50C} Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(e=>e!==`code_mode`).length===0&&(t.debug(`🔄 No active sessions found, creating new ones...`),this.sessions=await this.client.createAllSessions(),t.debug(`\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.debug(`\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.debug(`\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.debug(`\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.debug(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from connectors: ${e.length} tools, ${n.length} resources, ${r.length} prompts`)}t.debug(`\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.debug(`✨ 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 D))])}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.debug(`\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 D(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(e=>!(e instanceof D)),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 w)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 O)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 A)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 w||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.debug(`\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.debug(`\u{1F4AC} Received query: '${r}'`),t.debug(`🏁 Starting agent execution`);let i=0,a=[...n,new O(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.debug(`\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.debug(`\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.debug(`\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.debug(`\u{1F503} Restarting execution with updated tools (restart ${i}/3)`);break}}}this._isAIMessageLike(r)&&!this._messageHasToolCalls(r)&&(g=this._normalizeOutput(this._getMessageContent(r)),t.debug(`✅ 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.debug(`🔧 Attempting structured output...`);let e=await this._attemptStructuredOutput(g,this.llm,d);return this.memoryEnabled&&this.addToHistory(new w(`Structured result: ${JSON.stringify(e)}`)),t.debug(`✅ 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.debug(`\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.debug(`🧹 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.debug(`🧹 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.debug(`🔌 Closing MCPAgent resources…`),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(t.debug(`🔄 Closing internally-created client (simplified mode) and cleaning up resources`),await this.client.close(),this.sessions={},this.client=void 0):(t.debug(`🔄 Closing client and cleaning up resources`),await this.client.close(),this.sessions={});else for(let e of this.connectors)t.debug(`🔄 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.debug(`👋 Agent closed successfully`)}}async*prettyStreamEvents(e,t,n=!0,r,i){let{prettyStreamEvents:a}=await Mt(async()=>{let{prettyStreamEvents:e}=await import(`./display-A5IEINAP-B8BJrcag.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.debug(`\u{1F4AC} Received query for streamEvents: '${n}'`),this.memoryEnabled&&(t.debug(`\u{1F504} Adding user message to history: ${n}`),this.addToHistory(new O({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.debug(`\u26A0\uFE0F Skipped message of type: ${e.constructor?.name||typeof e}`);let a=[...i,new O(c)];t.debug(`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.debug(`🔧 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 w(`Structured result: ${JSON.stringify(n)}`)),t.debug(`✅ 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 w(y));console.log(`
344
344
 
345
345
  `),t.debug(`\u{1F389} StreamEvents complete - ${_} events emitted`),g=!0}catch(e){throw t.error(`\u274C Error during streamEvents: ${e}`),m&&u&&(t.debug(`🧹 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.debug(`🧹 Closing agent after streamEvents completion`),await this.close())}}async _attemptStructuredOutput(e,n,r){t.debug(`\u{1F504} Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),t.debug(`\u{1F504} Raw result: ${JSON.stringify(e,null,2)}`);let i=null,a=``;if(t.debug(`\u{1F504} Structured output requested, schema: ${JSON.stringify(Ct(r),null,2)}`),n&&`withStructuredOutput`in n&&typeof n.withStructuredOutput==`function`)i=n.withStructuredOutput(r);else if(n)i=n;else throw Error(`LLM is required for structured output`);let{$schema:o,additionalProperties:s,...c}=Ct(r);a=JSON.stringify(c,null,2),t.debug(`\u{1F504} Schema description: ${a}`);let l=``;typeof e==`string`?l=e:e&&typeof e==`object`&&(l=JSON.stringify(e)),t.debug(`rawResult`,e),l||=JSON.stringify(e);let u=``;for(let e=1;e<=3;e++){t.debug(`\u{1F504} Structured output attempt ${e}/3`);let n=`
346
346
  Please format the following information according to the EXACT schema specified below.
@@ -1 +1 @@
1
- import{t as e}from"./chunk-3GQAWCBQ-ntjTDD_C.js";import{a as t,b as n,i as r,m as i,o as a,p as o,s,v as c}from"./schemas-BrqAD_Qo.js";import{f as l}from"./chunk-WRL45O5E-C7sNvNRg.js";var u=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:l.custom,message:`Required property '${e}' is missing`,path:[e]});return}for(let r of t.required)r in e||n.addIssue({code:l.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:l.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 n(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):t();switch(e.type){case`string`:return this.parseString(e);case`number`:case`integer`:return this.parseNumberSchema(e);case`boolean`:return s();case`array`:return this.parseArray(e);case`object`:return this.parseObject(e);default:throw Error(`Unsupported schema type`)}}static parseNumberSchema(e){let t=o(),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=c(),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 n(e.items.map(e=>this.parseSchema(e)));let r=a(e.items?this.parseSchema(e.items):t()),i=r;return i=this.applyArrayConstraints(r,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 t=this.parseSchema(e.additionalProperties);return i({}).catchall(t)}let t={};return this.processObjectProperties(e,t),this.processAdditionalProperties(e,i(t))}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=i(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 t();if(e.length===1)return this.parseSchema(e[0]);let i=[];for(let t of e)t.type===`null`?i.push(r()):i.push(this.parseSchema(t));return i.length>=2?n(i):i.length===1?i[0]:t()}static parseAllOf(e){if(e.length===0)return t();if(e.length===1)return this.parseSchema(e[0]);let n=e.reduce((e,t)=>this.mergeSchemas(e,t));return this.parseSchema(n)}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{u as t};
1
+ import{t as e}from"./chunk-3GQAWCBQ-ntjTDD_C.js";import{a as t,b as n,i as r,m as i,o as a,p as o,s,v as c}from"./schemas-BrqAD_Qo.js";import{f as l}from"./chunk-QCEN6KYM-B3ENy-ef.js";var u=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:l.custom,message:`Required property '${e}' is missing`,path:[e]});return}for(let r of t.required)r in e||n.addIssue({code:l.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:l.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 n(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):t();switch(e.type){case`string`:return this.parseString(e);case`number`:case`integer`:return this.parseNumberSchema(e);case`boolean`:return s();case`array`:return this.parseArray(e);case`object`:return this.parseObject(e);default:throw Error(`Unsupported schema type`)}}static parseNumberSchema(e){let t=o(),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=c(),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 n(e.items.map(e=>this.parseSchema(e)));let r=a(e.items?this.parseSchema(e.items):t()),i=r;return i=this.applyArrayConstraints(r,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 t=this.parseSchema(e.additionalProperties);return i({}).catchall(t)}let t={};return this.processObjectProperties(e,t),this.processAdditionalProperties(e,i(t))}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=i(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 t();if(e.length===1)return this.parseSchema(e[0]);let i=[];for(let t of e)t.type===`null`?i.push(r()):i.push(this.parseSchema(t));return i.length>=2?n(i):i.length===1?i[0]:t()}static parseAllOf(e){if(e.length===0)return t();if(e.length===1)return this.parseSchema(e[0]);let n=e.reduce((e,t)=>this.mergeSchemas(e,t));return this.parseSchema(n)}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{u as t};