@mcp-use/inspector 0.25.1-canary.4 → 0.25.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cdn/inspector.js +5 -5
- package/dist/client/index.js +31 -31
- package/dist/web/assets/{browser-2gXtFd7A.js → browser-C8flDcFw.js} +3 -3
- package/dist/web/assets/{chunk-RPN2XO5I-BblF2OVy.js → chunk-RPN2XO5I-BXH06g3J.js} +1 -1
- package/dist/web/assets/{chunk-OTKWAUHW-DXsHKp47.js → chunk-UY6K7YNZ-CwjjzrEf.js} +1 -1
- package/dist/web/assets/{chunk_array-BGgj_Zit.js → chunk_array-D_zGgmvz.js} +1 -1
- package/dist/web/assets/{client-SQLW334Q-uYsMCMIE.js → client-5EGX4URK-uXOuum47.js} +3 -3
- package/dist/web/assets/{client-Nw5FmHWR.js → client-Di9rP6XG.js} +1 -1
- package/dist/web/assets/{dist-BlM2WHNO.js → dist-3Jr7Nsoj.js} +1 -1
- package/dist/web/assets/{dist-CAIJ2M-0.js → dist-BgVgAH7L.js} +1 -1
- package/dist/web/assets/{dist-Er8DHusL.js → dist-CWw0H-wA.js} +1 -1
- package/dist/web/assets/{function_calling-DcbYtrxA.js → function_calling-NA-IYsn6.js} +1 -1
- package/dist/web/assets/{index-XQv3xJiK.js → index-BP7yLFfO.js} +9 -9
- package/dist/web/assets/{llms-C2hEVIhM.js → llms-CHoe81gP.js} +1 -1
- package/dist/web/assets/messages-BaGiV01-.js +1 -0
- package/dist/web/assets/react-Dm0bV-f-.js +1 -0
- package/dist/web/assets/{rpc-logger-TPNV75J4-COOjMZG1.js → rpc-logger-TPNV75J4-B-ljtEDx.js} +1 -1
- package/dist/web/assets/{stdio-2KZFTJJ3-CsEXClCo.js → stdio-BMUBXC7G-CpOO4KvA.js} +1 -1
- package/dist/web/assets/{tools-CBQVS7fv.js → tools-BslK6xtH.js} +1 -1
- package/dist/web/index.html +4 -4
- package/package.json +2 -2
- package/dist/web/assets/messages-Dgu5huAh.js +0 -1
- package/dist/web/assets/react-DH-w6jjB.js +0 -1
package/dist/cdn/inspector.js
CHANGED
|
@@ -23071,7 +23071,7 @@ var ET, DT, die, fie, pie, OT, kT, AT, jT, MT, mie, NT, PT, FT, hie, gie, _ie, I
|
|
|
23071
23071
|
}(), Pse);
|
|
23072
23072
|
}));
|
|
23073
23073
|
//#endregion
|
|
23074
|
-
//#region ../mcp-use/dist/chunk-
|
|
23074
|
+
//#region ../mcp-use/dist/chunk-XDVQTYI5.js
|
|
23075
23075
|
function UO() {
|
|
23076
23076
|
return Jse;
|
|
23077
23077
|
}
|
|
@@ -23196,7 +23196,7 @@ function qse(e) {
|
|
|
23196
23196
|
XO.getInstance().setSource(e);
|
|
23197
23197
|
}
|
|
23198
23198
|
var Jse, qO, Yse, Xse, Zse, Qse, $se, ece, tce, nce, rce, ice, ace, oce, JO, YO, XO, ZO, sce, QO = o((() => {
|
|
23199
|
-
C(), g(), fre(), $f(), Jse = "1.22.1
|
|
23199
|
+
C(), g(), fre(), $f(), Jse = "1.22.1", m(UO, "getPackageVersion"), qO = class {
|
|
23200
23200
|
static {
|
|
23201
23201
|
m(this, "BaseTelemetryEvent");
|
|
23202
23202
|
}
|
|
@@ -30093,7 +30093,7 @@ var Zue, Que, Bk, Vk, Hk, Uk, Wk, Gk, Kk, qk, Jk, Yk, Xk, Zk, Qk, $k, eA, tA, nA
|
|
|
30093
30093
|
};
|
|
30094
30094
|
}));
|
|
30095
30095
|
//#endregion
|
|
30096
|
-
//#region ../mcp-use/dist/chunk-
|
|
30096
|
+
//#region ../mcp-use/dist/chunk-UY6K7YNZ.js
|
|
30097
30097
|
function dde(e, t) {
|
|
30098
30098
|
return {
|
|
30099
30099
|
onSampling: e?.onSampling ?? e?.samplingCallback ?? t?.onSampling ?? t?.samplingCallback,
|
|
@@ -30522,7 +30522,7 @@ var mde, cA, lA, hde, uA = o((() => {
|
|
|
30522
30522
|
};
|
|
30523
30523
|
}));
|
|
30524
30524
|
//#endregion
|
|
30525
|
-
//#region ../mcp-use/dist/chunk-
|
|
30525
|
+
//#region ../mcp-use/dist/chunk-SHTVP5MY.js
|
|
30526
30526
|
function dA(e) {
|
|
30527
30527
|
let t = /* @__PURE__ */ m(() => {
|
|
30528
30528
|
throw Error(`Invalid url to pass to open(): ${e}`);
|
|
@@ -59908,7 +59908,7 @@ var eSe = class {
|
|
|
59908
59908
|
//#region src/client/telemetry/utils.ts
|
|
59909
59909
|
function cSe() {
|
|
59910
59910
|
try {
|
|
59911
|
-
return "0.25.1
|
|
59911
|
+
return "0.25.1";
|
|
59912
59912
|
} catch {
|
|
59913
59913
|
return "0.0.0";
|
|
59914
59914
|
}
|
package/dist/client/index.js
CHANGED
|
@@ -5169,7 +5169,7 @@ var init_module = __esm({
|
|
|
5169
5169
|
}
|
|
5170
5170
|
});
|
|
5171
5171
|
|
|
5172
|
-
// ../mcp-use/dist/chunk-
|
|
5172
|
+
// ../mcp-use/dist/chunk-XDVQTYI5.js
|
|
5173
5173
|
import { RESOURCE_MIME_TYPE } from "@modelcontextprotocol/ext-apps";
|
|
5174
5174
|
import {
|
|
5175
5175
|
CreateMessageRequestSchema,
|
|
@@ -5337,12 +5337,12 @@ function setTelemetrySource(source) {
|
|
|
5337
5337
|
Tel.getInstance().setSource(source);
|
|
5338
5338
|
}
|
|
5339
5339
|
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;
|
|
5340
|
-
var
|
|
5341
|
-
"../mcp-use/dist/chunk-
|
|
5340
|
+
var init_chunk_XDVQTYI5 = __esm({
|
|
5341
|
+
"../mcp-use/dist/chunk-XDVQTYI5.js"() {
|
|
5342
5342
|
"use strict";
|
|
5343
5343
|
init_chunk_QWQYAQCK();
|
|
5344
5344
|
init_chunk_3GQAWCBQ();
|
|
5345
|
-
VERSION = "1.22.1
|
|
5345
|
+
VERSION = "1.22.1";
|
|
5346
5346
|
__name(getPackageVersion2, "getPackageVersion");
|
|
5347
5347
|
BaseTelemetryEvent = (_a3 = class {
|
|
5348
5348
|
}, __name(_a3, "BaseTelemetryEvent"), _a3);
|
|
@@ -6612,7 +6612,7 @@ var init_chunk_NXMD4YPL = __esm({
|
|
|
6612
6612
|
}
|
|
6613
6613
|
});
|
|
6614
6614
|
|
|
6615
|
-
// ../mcp-use/dist/chunk-
|
|
6615
|
+
// ../mcp-use/dist/chunk-UY6K7YNZ.js
|
|
6616
6616
|
import {
|
|
6617
6617
|
Client
|
|
6618
6618
|
} from "@modelcontextprotocol/sdk/client/index.js";
|
|
@@ -6677,10 +6677,10 @@ function createConnectorFromConfig(serverConfig, connectorOptions) {
|
|
|
6677
6677
|
throw new Error("Cannot determine connector type from config");
|
|
6678
6678
|
}
|
|
6679
6679
|
var _a18, SseConnectionManager, _a19, HttpConnector, _a20, MCPSession, _a21, BaseMCPClient;
|
|
6680
|
-
var
|
|
6681
|
-
"../mcp-use/dist/chunk-
|
|
6680
|
+
var init_chunk_UY6K7YNZ = __esm({
|
|
6681
|
+
"../mcp-use/dist/chunk-UY6K7YNZ.js"() {
|
|
6682
6682
|
"use strict";
|
|
6683
|
-
|
|
6683
|
+
init_chunk_XDVQTYI5();
|
|
6684
6684
|
init_chunk_QWQYAQCK();
|
|
6685
6685
|
init_chunk_3GQAWCBQ();
|
|
6686
6686
|
SseConnectionManager = (_a18 = class extends ConnectionManager {
|
|
@@ -7937,7 +7937,7 @@ var init_chunk_OTKWAUHW = __esm({
|
|
|
7937
7937
|
}
|
|
7938
7938
|
});
|
|
7939
7939
|
|
|
7940
|
-
// ../mcp-use/dist/chunk-
|
|
7940
|
+
// ../mcp-use/dist/chunk-SHTVP5MY.js
|
|
7941
7941
|
import {
|
|
7942
7942
|
discoverOAuthProtectedResourceMetadata,
|
|
7943
7943
|
discoverAuthorizationServerMetadata,
|
|
@@ -8235,11 +8235,11 @@ async function onMcpAuthorization() {
|
|
|
8235
8235
|
}
|
|
8236
8236
|
}
|
|
8237
8237
|
var _a22, BrowserMCPClient, _a23, BrowserOAuthClientProvider;
|
|
8238
|
-
var
|
|
8239
|
-
"../mcp-use/dist/chunk-
|
|
8238
|
+
var init_chunk_SHTVP5MY = __esm({
|
|
8239
|
+
"../mcp-use/dist/chunk-SHTVP5MY.js"() {
|
|
8240
8240
|
"use strict";
|
|
8241
|
-
|
|
8242
|
-
|
|
8241
|
+
init_chunk_UY6K7YNZ();
|
|
8242
|
+
init_chunk_XDVQTYI5();
|
|
8243
8243
|
init_chunk_QWQYAQCK();
|
|
8244
8244
|
init_chunk_3GQAWCBQ();
|
|
8245
8245
|
BrowserMCPClient = (_a22 = class extends BaseMCPClient {
|
|
@@ -15092,18 +15092,18 @@ var init_stdio_transport = __esm({
|
|
|
15092
15092
|
}
|
|
15093
15093
|
});
|
|
15094
15094
|
|
|
15095
|
-
// ../mcp-use/dist/stdio-
|
|
15096
|
-
var
|
|
15097
|
-
__export(
|
|
15095
|
+
// ../mcp-use/dist/stdio-BMUBXC7G.js
|
|
15096
|
+
var stdio_BMUBXC7G_exports = {};
|
|
15097
|
+
__export(stdio_BMUBXC7G_exports, {
|
|
15098
15098
|
StdioConnector: () => StdioConnector
|
|
15099
15099
|
});
|
|
15100
15100
|
import { Client as Client2 } from "@modelcontextprotocol/sdk/client/index.js";
|
|
15101
15101
|
import process2 from "process";
|
|
15102
15102
|
var _a25, StdioConnectionManager, _a26, StdioConnector;
|
|
15103
|
-
var
|
|
15104
|
-
"../mcp-use/dist/stdio-
|
|
15103
|
+
var init_stdio_BMUBXC7G = __esm({
|
|
15104
|
+
"../mcp-use/dist/stdio-BMUBXC7G.js"() {
|
|
15105
15105
|
"use strict";
|
|
15106
|
-
|
|
15106
|
+
init_chunk_XDVQTYI5();
|
|
15107
15107
|
init_chunk_QWQYAQCK();
|
|
15108
15108
|
init_chunk_3GQAWCBQ();
|
|
15109
15109
|
init_stdio_transport();
|
|
@@ -15247,9 +15247,9 @@ var init_stdio_2KZFTJJ3 = __esm({
|
|
|
15247
15247
|
}
|
|
15248
15248
|
});
|
|
15249
15249
|
|
|
15250
|
-
// ../mcp-use/dist/client-
|
|
15251
|
-
var
|
|
15252
|
-
__export(
|
|
15250
|
+
// ../mcp-use/dist/client-5EGX4URK.js
|
|
15251
|
+
var client_5EGX4URK_exports = {};
|
|
15252
|
+
__export(client_5EGX4URK_exports, {
|
|
15253
15253
|
BaseCodeExecutor: () => BaseCodeExecutor,
|
|
15254
15254
|
E2BCodeExecutor: () => E2BCodeExecutor,
|
|
15255
15255
|
MCPClient: () => MCPClient,
|
|
@@ -15375,12 +15375,12 @@ function validate(params, content) {
|
|
|
15375
15375
|
}
|
|
15376
15376
|
}
|
|
15377
15377
|
var _a27, BaseCodeExecutor, _a28, E2BCodeExecutor, vm, vmCheckAttempted, _a29, VMCodeExecutor, _a30, CodeModeConnector, _a31, MCPClient;
|
|
15378
|
-
var
|
|
15379
|
-
"../mcp-use/dist/client-
|
|
15378
|
+
var init_client_5EGX4URK = __esm({
|
|
15379
|
+
"../mcp-use/dist/client-5EGX4URK.js"() {
|
|
15380
15380
|
"use strict";
|
|
15381
15381
|
init_chunk_RPN2XO5I();
|
|
15382
|
-
|
|
15383
|
-
|
|
15382
|
+
init_chunk_UY6K7YNZ();
|
|
15383
|
+
init_chunk_XDVQTYI5();
|
|
15384
15384
|
init_chunk_QWQYAQCK();
|
|
15385
15385
|
init_chunk_3GQAWCBQ();
|
|
15386
15386
|
init_fs();
|
|
@@ -16333,7 +16333,7 @@ ${shim}
|
|
|
16333
16333
|
clientInfo: serverConfig.clientInfo ?? this.config.clientInfo
|
|
16334
16334
|
};
|
|
16335
16335
|
if ("command" in merged && "args" in merged) {
|
|
16336
|
-
const { StdioConnector: StdioConnector2 } = await Promise.resolve().then(() => (
|
|
16336
|
+
const { StdioConnector: StdioConnector2 } = await Promise.resolve().then(() => (init_stdio_BMUBXC7G(), stdio_BMUBXC7G_exports));
|
|
16337
16337
|
const stdioConfig = merged;
|
|
16338
16338
|
return new StdioConnector2({
|
|
16339
16339
|
command: stdioConfig.command,
|
|
@@ -62021,11 +62021,11 @@ var _a32, BaseAdapter, _a33, LangChainAdapter, _a34, MCPServerTool, PresentActiv
|
|
|
62021
62021
|
var init_browser = __esm({
|
|
62022
62022
|
"../mcp-use/dist/src/browser.js"() {
|
|
62023
62023
|
"use strict";
|
|
62024
|
-
|
|
62024
|
+
init_chunk_SHTVP5MY();
|
|
62025
62025
|
init_chunk_UJPHRNQP();
|
|
62026
62026
|
init_chunk_RPN2XO5I();
|
|
62027
|
-
|
|
62028
|
-
|
|
62027
|
+
init_chunk_UY6K7YNZ();
|
|
62028
|
+
init_chunk_XDVQTYI5();
|
|
62029
62029
|
init_chunk_QWQYAQCK();
|
|
62030
62030
|
init_chunk_3GQAWCBQ();
|
|
62031
62031
|
BaseAdapter = (_a32 = class {
|
|
@@ -63370,7 +63370,7 @@ Raw error: ${result}`
|
|
|
63370
63370
|
logger.info(
|
|
63371
63371
|
`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`
|
|
63372
63372
|
);
|
|
63373
|
-
const { MCPClient: MCPClient2 } = await Promise.resolve().then(() => (
|
|
63373
|
+
const { MCPClient: MCPClient2 } = await Promise.resolve().then(() => (init_client_5EGX4URK(), client_5EGX4URK_exports));
|
|
63374
63374
|
this.client = new MCPClient2({ mcpServers: this.mcpServersConfig });
|
|
63375
63375
|
logger.info("\u2705 MCPClient created successfully");
|
|
63376
63376
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/langfuse-U2OEF7K7-UPVEn4-O.js","assets/chunk-QWQYAQCK-CyFuZlX8.js","assets/chunk-3GQAWCBQ-C-9Cm0Np.js","assets/chunk-zsgVPwQN.js","assets/chunk-UJPHRNQP-C81GjauI.js","assets/preload-helper-XLr9-hSf.js","assets/client-
|
|
2
|
-
import{t as e}from"./chunk-3GQAWCBQ-C-9Cm0Np.js";import{n as t}from"./chunk-QWQYAQCK-CyFuZlX8.js";import{It as n,S as r,er as i}from"./json-schema-processors-DSIsU0go.js";import{a,c as o,s}from"./client-Nw5FmHWR.js";import{a as c,c as l,m as u,n as d,v as f}from"./schemas-79owEkeD.js";import"./chunk-OTKWAUHW-DXsHKp47.js";import{t as p}from"./preload-helper-XLr9-hSf.js";import{$n as m,A as h,An as g,Ar as _,At as v,Bn as y,Bt as b,C as ee,Ct as x,Dr as S,Dt as te,E as ne,En as re,Er as ie,Et as ae,F as oe,Fr as C,Ft as se,G as ce,Ht as le,I as ue,In as de,Ir as fe,It as pe,Jn as me,Kt as he,L as ge,Lr as _e,M as ve,Mr as ye,Mt as be,N as xe,Nr as Se,Nt as Ce,Or as we,Ot as Te,Pn as Ee,Pr as w,Pt as De,Qn as Oe,R as ke,Rr as T,Rt as Ae,S as je,St as Me,Tr as Ne,Tt as Pe,Ut as Fe,Vt as Ie,W as E,Wt as Le,Xt as Re,Zn as ze,_n as Be,at as Ve,b as He,bt as Ue,d as We,dn as Ge,dt as Ke,er as qe,fn as Je,g as Ye,gt as Xe,i as Ze,j as Qe,jn as $e,jr as et,jt as tt,k as nt,kr as rt,kt as it,l as at,lt as ot,mn as st,mr as D,mt as ct,nn as lt,nr as ut,nt as dt,o as ft,on as pt,ot as mt,pn as O,pt as ht,qn as gt,qt as _t,rr as vt,rt as yt,s as k,sn as bt,t as xt,tn as A,tr as St,ut as Ct,vn as j,vt as wt,w as Tt,wt as Et,x as Dt,xt as Ot,yn as kt,yt as At,zn as jt,zr as Mt,zt as Nt}from"./index-XQv3xJiK.js";import{C as Pt,D as Ft,M as It,O as Lt,S as Rt,T as zt,_ as Bt,b as Vt,c as Ht,d as Ut,f as Wt,g as Gt,h as Kt,j as qt,k as Jt,m as Yt,n as Xt,s as Zt,u as Qt,v as $t,x as en,y as tn}from"./function_calling-DcbYtrxA.js";import{a as nn,i as rn,n as an,o as on,r as sn,t as cn}from"./tools-CBQVS7fv.js";import{n as ln,r as un,t as dn}from"./chunk_array-BGgj_Zit.js";import{n as fn,r as pn,t as mn}from"./llms-C2hEVIhM.js";import{t as hn}from"./chunk-RPN2XO5I-BblF2OVy.js";import"./chunk-UJPHRNQP-C81GjauI.js";var gn,_n,vn=0,yn=0;function bn(e,t,n){var r=t&&n||0,i=t||Array(16);e||={};var a=e.node,o=e.clockseq;if(e._v6||(a||=gn,o??=_n),a==null||o==null){var s=e.random||(e.rng||b)();a??(a=[s[0],s[1],s[2],s[3],s[4],s[5]],!gn&&!e._v6&&(a[0]|=1,gn=a)),o??(o=(s[6]<<8|s[7])&16383,_n===void 0&&!e._v6&&(_n=o))}var c=e.msecs===void 0?Date.now():e.msecs,l=e.nsecs===void 0?yn+1:e.nsecs,u=c-vn+(l-yn)/1e4;if(u<0&&e.clockseq===void 0&&(o=o+1&16383),(u<0||c>vn)&&e.nsecs===void 0&&(l=0),l>=1e4)throw Error(`uuid.v1(): Can't create more than 10M uuids/sec`);vn=c,yn=l,_n=o,c+=0xb1d069b5400;var d=((c&268435455)*1e4+l)%4294967296;i[r++]=d>>>24&255,i[r++]=d>>>16&255,i[r++]=d>>>8&255,i[r++]=d&255;var f=c/4294967296*1e4&268435455;i[r++]=f>>>8&255,i[r++]=f&255,i[r++]=f>>>24&15|16,i[r++]=f>>>16&255,i[r++]=o>>>8|128,i[r++]=o&255;for(var p=0;p<6;++p)i[r+p]=a[p];return t||Ie(i)}function xn(e){var t=Sn(typeof e==`string`?le(e):e);return typeof e==`string`?Ie(t):t}function Sn(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function Cn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Cn(Object(n),!0).forEach(function(t){Tn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Cn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Tn(e,t,n){return(t=En(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function En(e){var t=Dn(e,`string`);return typeof t==`symbol`?t:t+``}function Dn(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function On(e={},t,n=0){var r=bn(wn(wn({},e),{},{_v6:!0}),new Uint8Array(16));if(r=xn(r),t){for(var i=0;i<16;i++)t[n+i]=r[i];return t}return Ie(r)}var kn=Object.defineProperty,An=(e,t)=>{for(var n in t)kn(e,n,{get:t[n],enumerable:!0})};An({},{ConfigurableModel:()=>In,MODEL_PROVIDER_CONFIG:()=>jn,_inferModelProvider:()=>Fn,getChatModelByClassName:()=>Nn,initChatModel:()=>Ln});var jn={openai:{package:`@langchain/openai`,className:`ChatOpenAI`},anthropic:{package:`@langchain/anthropic`,className:`ChatAnthropic`},azure_openai:{package:`@langchain/openai`,className:`AzureChatOpenAI`},cohere:{package:`@langchain/cohere`,className:`ChatCohere`},"google-vertexai":{package:`@langchain/google-vertexai`,className:`ChatVertexAI`},"google-vertexai-web":{package:`@langchain/google-vertexai-web`,className:`ChatVertexAI`},"google-genai":{package:`@langchain/google-genai`,className:`ChatGoogleGenerativeAI`},ollama:{package:`@langchain/ollama`,className:`ChatOllama`},mistralai:{package:`@langchain/mistralai`,className:`ChatMistralAI`},mistral:{package:`@langchain/mistralai`,className:`ChatMistralAI`},groq:{package:`@langchain/groq`,className:`ChatGroq`},cerebras:{package:`@langchain/cerebras`,className:`ChatCerebras`},bedrock:{package:`@langchain/aws`,className:`ChatBedrockConverse`},deepseek:{package:`@langchain/deepseek`,className:`ChatDeepSeek`},xai:{package:`@langchain/xai`,className:`ChatXAI`},fireworks:{package:`@langchain/community/chat_models/fireworks`,className:`ChatFireworks`,hasCircularDependency:!0},together:{package:`@langchain/community/chat_models/togetherai`,className:`ChatTogetherAI`,hasCircularDependency:!0},perplexity:{package:`@langchain/community/chat_models/perplexity`,className:`ChatPerplexity`,hasCircularDependency:!0}},Mn=Object.keys(jn);async function Nn(e){let t=Object.entries(jn).find(([,t])=>t.className===e);if(!t)return;let[,n]=t;try{return(await p(()=>import(n.package),[]))[n.className]}catch(e){let t=e;if(`code`in t&&t.code?.toString().includes(`ERR_MODULE_NOT_FOUND`)&&`message`in t&&typeof t.message==`string`){let e=(t.message.startsWith(`Error: `)?t.message.slice(7):t.message).split(`Cannot find package '`)[1].split(`'`)[0];throw Error(`Unable to import ${e}. Please install with \`npm install ${e}\` or \`pnpm install ${e}\``)}throw e}}async function Pn(e,t,n={}){let r=t||Fn(e);if(!r)throw Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let i=jn[r];if(!i){let e=Mn.join(`, `);throw Error(`Unsupported { modelProvider: ${r} }.\n\nSupported model providers are: ${e}`)}let{modelProvider:a,...o}=n;return new(await(Nn(i.className)))({model:e,...o})}function Fn(e){if(e.startsWith(`gpt-3`)||e.startsWith(`gpt-4`)||e.startsWith(`gpt-5`)||e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`))return`openai`;if(e.startsWith(`claude`))return`anthropic`;if(e.startsWith(`command`))return`cohere`;if(e.startsWith(`accounts/fireworks`))return`fireworks`;if(e.startsWith(`gemini`))return`google-vertexai`;if(e.startsWith(`amazon.`))return`bedrock`;if(e.startsWith(`mistral`))return`mistralai`;if(e.startsWith(`sonar`)||e.startsWith(`pplx`))return`perplexity`}var In=class e extends Zt{_llmType(){return`chat_model`}lc_namespace=[`langchain`,`chat_models`];_defaultConfig={};_configurableFields=`any`;_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields===`any`?this._configurableFields=`any`:this._configurableFields=e.configurableFields??[`model`,`modelProvider`],e.configPrefix?this._configPrefix=e.configPrefix.endsWith(`_`)?e.configPrefix:`${e.configPrefix}_`:this._configPrefix=``,this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations,this._profile=e.profile??void 0}async _getModelInstance(e){let t=this._getCacheKey(e),n=this._modelInstanceCache.get(t);if(n)return n;let r={...this._defaultConfig,...this._modelParams(e)},i=await Pn(r.model,r.modelProvider,r);for(let[e,t]of Object.entries(this._queuedMethodOperations))e in i&&typeof i[e]==`function`&&(i=await i[e](...t));return this._modelInstanceCache.set(t,i),i}async _generate(e,t,n){return(await this._getModelInstance(t))._generate(e,t??{},n)}bindTools(t,n){let r={...this._queuedMethodOperations};return r.bindTools=[t,n],new e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(t,...n)=>{let r={...this._queuedMethodOperations};return r.withStructuredOutput=[t,...n],new e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})};_modelParams(e){let t=e?.configurable??{},n={};for(let[e,r]of Object.entries(t))if(e.startsWith(this._configPrefix)){let t=this._removePrefix(e,this._configPrefix);n[t]=r}return this._configurableFields!==`any`&&(n=Object.fromEntries(Object.entries(n).filter(([e])=>this._configurableFields.includes(e)))),n}_removePrefix(e,t){return e.startsWith(t)?e.slice(t.length):e}withConfig(t){let n={...t||{}},r=this._modelParams(n),i=Object.fromEntries(Object.entries(n).filter(([e])=>e!==`configurable`));return i.configurable=Object.fromEntries(Object.entries(n.configurable||{}).filter(([e])=>this._configPrefix&&!Object.keys(r).includes(this._removePrefix(e,this._configPrefix)))),new at({config:n,bound:new e({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(e,t){let n=await this._getModelInstance(t),r=At(t);return n.invoke(e,r)}async stream(e,t){let n=new ht({generator:await(await this._getModelInstance(t)).stream(e,t),config:t});return await n.setup,ct.fromAsyncGenerator(n)}async batch(e,t,n){return super.batch(e,t,n)}async*transform(e,t){let n=await this._getModelInstance(t),r=At(t);yield*n.transform(e,r)}async*streamLog(e,t,n){let r=await this._getModelInstance(t),i=At(t);yield*r.streamLog(e,i,{...n,_schemaFormat:`original`,includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(e,t,n){let r=this;async function*i(){let i=await r._getModelInstance(t),a=At(t),o=i.streamEvents(e,a,n);for await(let e of o)yield e}return ct.fromAsyncGenerator(i())}get profile(){if(this._profile)return this._profile;let e=this._getCacheKey({});return this._modelInstanceCache.get(e)?.profile??{}}_getCacheKey(e){let t=e??{};if(t.configurable){let{configurable:e}=t,n={};for(let[t,r]of Object.entries(e))t.startsWith(`__pregel_`)||(n[t]=r);t={...t,configurable:n}}return JSON.stringify(t)}};async function Ln(e,t){let{configurableFields:n,configPrefix:r,modelProvider:i,profile:a,...o}={configPrefix:``,...t??{}};if(i===void 0&&e?.includes(`:`)){let[t,...n]=e.split(`:`),r=n.length===0?[t]:[t,n.join(`:`)];Mn.includes(r[0])&&([i,e]=r)}let s=Array.isArray(n)?[...n]:n;!e&&s===void 0&&(s=[`model`,`modelProvider`]),r&&s===void 0&&console.warn(`{ configPrefix: ${r} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let c={...o},l;return s===void 0?l=new In({defaultConfig:{...c,model:e,modelProvider:i},configPrefix:r,profile:a}):(e&&(c.model=e),i&&(c.modelProvider=i),l=new In({defaultConfig:c,configPrefix:r,configurableFields:s,profile:a})),await l._getModelInstance(),l}var Rn=class{constructor(){this.store=void 0}getStore(){return this.store}run(e,t,...n){this.store=e;try{return t(...n)}finally{this.store=void 0}}exit(e,...t){let n=this.store;this.store=void 0;try{return e(...t)}finally{this.store=n}}enterWith(e){this.store=e}disable(){this.store=void 0}};function zn(){Pe.initializeGlobalInstance(new Rn)}var Bn=class extends Error{lc_error_code;constructor(e,t){let n=e??``;t?.lc_error_code&&(n=`${n}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/\n`),super(n),this.lc_error_code=t?.lc_error_code}},Vn=class extends Bn{get is_bubble_up(){return!0}},Hn=class extends Bn{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},Un=class extends Bn{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},Wn=class extends Vn{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},Gn=class extends Wn{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},Kn=class extends Vn{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function qn(e){return e!==void 0&&e.name===Kn.unminifiable_name}function Jn(e){return e!==void 0&&e.is_bubble_up===!0}function Yn(e){return e!==void 0&&[Wn.unminifiable_name,Gn.unminifiable_name].includes(e.name)}var Xn=class extends Bn{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},M=class extends Bn{constructor(e,t){super(e,t),this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},N=class extends Bn{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},Zn=class extends Bn{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},Qn=class extends Bn{constructor(e,t){super(e,t),this.name=`StateGraphInputError`,this.message=`Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema.`}static get unminifiable_name(){return`StateGraphInputError`}};function $n(e){return On({clockseq:e})}function er(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return Ae(e,new Uint8Array(n))}var tr=`__error__`,nr=`__scheduled__`,rr=`__interrupt__`,ir=`__resume__`,ar=`[...]`,or=`[Circular]`,sr=[],cr=[];function lr(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function ur(e,t,n,r){r===void 0&&(r=lr()),fr(e,``,0,[],void 0,0,r);var i;try{i=cr.length===0?JSON.stringify(e,t,n):JSON.stringify(e,pr(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;sr.length!==0;){var a=sr.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function dr(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,sr.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),sr.push([r,n,t,i])):cr.push([t,n,e])}function fr(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){dr(or,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){dr(ar,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){dr(ar,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)fr(e[s],s,s,r,e,a,o);else{var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];fr(e[l],l,s,r,e,a,o)}}r.pop()}}function pr(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(cr.length>0)for(var r=0;r<cr.length;r++){var i=cr[r];if(i[1]===t&&i[0]===n){n=i[2],cr.splice(r,1);break}}return e.call(this,t,n)}}var mr=[],hr={},gr={};D(gr,{BaseChatMessageHistory:()=>_r,BaseListChatMessageHistory:()=>vr,InMemoryChatMessageHistory:()=>yr});var _r=class extends ze{async addMessages(e){for(let t of e)await this.addMessage(t)}},vr=class extends ze{addUserMessage(e){return this.addMessage(new j(e))}addAIMessage(e){return this.addMessage(new A(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},yr=class extends vr{lc_namespace=[`langchain`,`stores`,`message`,`in_memory`];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},br={},xr={};D(xr,{BaseMemory:()=>Sr,getInputValue:()=>wr,getOutputValue:()=>Tr,getPromptInputKey:()=>Er});var Sr=class{},Cr=(e,t)=>{if(t!==void 0)return e[t];let n=Object.keys(e);if(n.length===1)return e[n[0]]},wr=(e,t)=>{let n=Cr(e,t);if(!n){let t=Object.keys(e);throw Error(`input values have ${t.length} keys, you must specify an input key or pass only 1 key as input`)}return n},Tr=(e,t)=>{let n=Cr(e,t);if(!n&&n!==``){let t=Object.keys(e);throw Error(`output values have ${t.length} keys, you must specify an output key or pass only 1 key as output`)}return n};function Er(e,t){let n=Object.keys(e).filter(e=>!t.includes(e)&&e!==`stop`);if(n.length!==1)throw Error(`One input key expected, but got ${n.length}`);return n[0]}var Dr={};D(Dr,{BaseStore:()=>Or,InMemoryStore:()=>kr});var Or=class extends ze{},kr=class extends Or{lc_namespace=[`langchain`,`storage`];store={};async mget(e){return e.map(e=>this.store[e])}async mset(e){for(let[t,n]of e)this.store[t]=n}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let n of t)(e===void 0||n.startsWith(e))&&(yield n)}},Ar={};D(Ar,{BaseRetriever:()=>jr});var jr=class extends k{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw Error(`Not implemented!`)}async invoke(e,t){let n=At(Te(t)),r=await(await ae.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let t=await this._getRelevantDocuments(e,r);return await r?.handleRetrieverEnd(t),t}catch(e){throw await r?.handleRetrieverError(e),e}}},Mr={};D(Mr,{SaveableVectorStore:()=>Fr,VectorStore:()=>Pr,VectorStoreRetriever:()=>Nr});var Nr=class extends jr{static lc_name(){return`VectorStoreRetriever`}get lc_namespace(){return[`langchain_core`,`vectorstores`]}vectorStore;k=4;searchType=`similarity`;searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType===`mmr`&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType===`mmr`){if(typeof this.vectorStore.maxMarginalRelevanceSearch!=`function`)throw Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild(`vectorstore`))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild(`vectorstore`))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},Pr=class extends ze{lc_namespace=[`langchain`,`vectorstores`,this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw Error(`Not implemented.`)}async similaritySearch(e,t=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)).map(e=>e[0])}async similaritySearchWithScore(e,t=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)}static fromTexts(e,t,n,r){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}static fromDocuments(e,t,n){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}asRetriever(e,t,n,r,i,a){if(typeof e==`number`)return new Nr({vectorStore:this,k:e,filter:t,tags:[...r??[],this._vectorstoreType()],metadata:i,verbose:a,callbacks:n});{let t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType===`mmr`?new Nr({...t,searchKwargs:e.searchKwargs}):new Nr({...t})}}},Fr=class extends Pr{static load(e,t){throw Error(`Not implemented`)}},Ir={};D(Ir,{BaseDocumentLoader:()=>Lr});var Lr=class{},Rr={};D(Rr,{LangSmithLoader:()=>zr});var zr=class extends Lr{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw Error(`client and clientConfig cannot both be provided.`);this.client=e.client??new De(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??Br,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){let e=[];for await(let t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=t.inputs;for(let e of this.contentKey)n=n[e];let r=this.formatContent(n),i=t;[`created_at`,`modified_at`].forEach(e=>{e in i&&typeof i[e]==`object`&&(i[e]=i[e].toString())}),e.push({pageContent:r,metadata:i})}return e}};function Br(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var Vr=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},Hr=class extends k{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},Ur=class extends Hr{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},Wr={};D(Wr,{BaseDocumentTransformer:()=>Hr,Document:()=>Vr,MappingDocumentTransformer:()=>Ur});var Gr=class extends ze{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},Kr=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},qr=class extends Kr{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,n]of this.conditionals)if(t(e))return n;return this.defaultPrompt}};function Jr(e){return e._modelType()===`base_llm`}function Yr(e){return e._modelType()===`base_chat_model`}function Xr(e){return e.split(/\n| /).length}var Zr=class e extends Gr{examples=[];examplePrompt;getTextLength=Xr;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Xr}async addExample(e){this.examples.push(e);let t=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(t))}async calculateExampleTextLengths(e,t){if(e.length>0)return e;let{examples:n,examplePrompt:r}=t;return(await Promise.all(n.map(e=>r.format(e)))).map(e=>this.getTextLength(e))}async selectExamples(e){let t=Object.values(e).join(` `),n=this.maxLength-this.getTextLength(t),r=0,i=[];for(;n>0&&r<this.examples.length;){let e=n-this.exampleTextLengths[r];if(e<0)break;i.push(this.examples[r]),n=e,r+=1}return i}static async fromExamples(t,n){let r=new e(n);return await Promise.all(t.map(e=>r.addExample(e))),r}};function Qr(e){return Object.keys(e).sort().map(t=>e[t])}var $r=class e extends Gr{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`)}async addExample(e){let t=Qr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new Vr({pageContent:t,metadata:e})])}async selectExamples(e){let t=Qr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `),n=(await this.vectorStoreRetriever.invoke(t)).map(e=>e.metadata);return this.exampleKeys?n.map(e=>this.exampleKeys.reduce((t,n)=>({...t,[n]:e[n]}),{})):n}static async fromExamples(t,n,r,i={}){let a=i.inputKeys??null,o=t.map(e=>Qr(a?a.reduce((t,n)=>({...t,[n]:e[n]}),{}):e).join(` `));return new e({vectorStore:await r.fromTexts(o,t,n,i),k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}},ei={};D(ei,{BaseExampleSelector:()=>Gr,BasePromptSelector:()=>Kr,ConditionalPromptSelector:()=>qr,LengthBasedExampleSelector:()=>Zr,SemanticSimilarityExampleSelector:()=>$r,isChatModel:()=>Yr,isLLM:()=>Jr});var ti=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,ni=class extends ze{lc_namespace=[`langchain`,`recordmanagers`]},ri=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Bt;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=[`hash_`,`content_hash`,`metadata_hash`];for(let t of e)if(t in this.metadata)throw Error(`Metadata cannot contain key ${t} as it is reserved for internal use. Restricted keys: [${e.join(`, `)}]`);let t=this._hashStringToUUID(this.pageContent);try{let e=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=e}catch(e){throw Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||=this.hash_}toDocument(){return new Vr({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let n=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return n.calculateHashes(),n}_hashStringToUUID(e){return Ae(this.keyEncoder(e),ti)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return Ae(this.keyEncoder(t),ti)}};function ii(e,t){let n=[],r=[];return t.forEach(t=>{r.push(t),r.length>=e&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function ai(e){let t=new Set,n=[];for(let r of e){if(!r.hash_)throw Error(`Hashed document does not have a hash`);t.has(r.hash_)||(t.add(r.hash_),n.push(r))}return n}function oi(e){if(e===null)return e=>null;if(typeof e==`string`)return t=>t.metadata[e];if(typeof e==`function`)return e;throw Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var si=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function ci(e){let{docsSource:t,recordManager:n,vectorStore:r,options:i}=e,{batchSize:a=100,cleanup:o,sourceIdKey:s,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=i??{};if(o===`incremental`&&!s)throw Error(`sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.`);let u=si(t)?await t.load():t,d=oi(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=ii(a??100,u);for(let e of _){let t=ai(e.map(e=>ri.fromDocument(e))),i=t.map(e=>d(e));o===`incremental`&&t.forEach((e,t)=>{if(i[t]===null)throw Error(`sourceIdKey must be provided when cleanup is incremental`)});let a=await n.exists(t.map(e=>e.uid)),s=[],c=[],u=[],_=new Set;if(t.forEach((e,t)=>{if(a[t])if(l)_.add(e.uid);else{u.push(e.uid);return}s.push(e.uid),c.push(e.toDocument())}),u.length>0&&(await n.update(u,{timeAtLeast:f}),g+=u.length),c.length>0&&(await r.addDocuments(c,{ids:s}),p+=c.length-_.size,h+=_.size),await n.update(t.map(e=>e.uid),{timeAtLeast:f,groupIds:i}),o===`incremental`){i.forEach(e=>{if(!e)throw Error(`Source id cannot be null`)});let e=await n.listKeys({before:f,groupIds:i});e.length>0&&(await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length)}}if(o===`full`){let e=await n.listKeys({before:f,limit:c});for(;e.length>0;)await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length,e=await n.listKeys({before:f,limit:c})}return{numAdded:p,numDeleted:m,numUpdated:h,numSkipped:g}}var li={};D(li,{RecordManager:()=>ni,UUIDV5_NAMESPACE:()=>ti,_HashedDocument:()=>ri,_batch:()=>ii,_deduplicateInOrder:()=>ai,_getSourceIdAssigner:()=>oi,_isBaseDocumentLoader:()=>si,index:()=>ci});var ui={},di=class extends Lt{static lc_name(){return`OutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if(`message`in e[0]){let t=e[0].message.additional_kwargs.function_call;if(!t)throw Error(`No function_call in message ${JSON.stringify(e)}`);if(!t.arguments)throw Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?t.arguments:JSON.stringify(t)}else throw Error(`No message in generations ${JSON.stringify(e)}`)}},fi=class extends Ft{static lc_name(){return`JsonOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new di(e)}_diff(e,t){if(t)return Ke(e??{},t)}async parsePartialResult(e){let t=e[0];if(!t.message)return;let{message:n}=t,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?pt(r.arguments):{...r,arguments:pt(r.arguments)}}async parseResult(e){let t=await this.outputParser.parseResult(e);if(!t)throw Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){let t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return``}},pi=class extends Lt{static lc_name(){return`JsonKeyOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser=new fi;attrName;get lc_aliases(){return{attrName:`key_name`}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},mi={};D(mi,{JsonKeyOutputFunctionsParser:()=>pi,JsonOutputFunctionsParser:()=>fi,OutputFunctionsParser:()=>di});var hi=class extends k{lc_serializable=!0;lc_namespace=[`langchain_core`,`prompts`,this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);let{inputVariables:t}=e;if(t.includes(`stop`))throw Error(`Cannot have an input variable named 'stop', as it is used internally, please rename.`);Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},n={};for(let[e,r]of Object.entries(t))typeof r==`string`?n[e]=r:n[e]=await r();return{...n,...e}}async invoke(e,t){let n={...this.metadata,...t?.metadata},r=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(e=>this.formatPromptValue(e),e,{...t,tags:r,metadata:n,runType:`prompt`})}},gi=class extends hi{async formatPromptValue(e){return new Vt(await this.format(e))}},_i=Object.prototype.toString,vi=Array.isArray||function(e){return _i.call(e)===`[object Array]`};function yi(e){return typeof e==`function`}function bi(e){return vi(e)?`array`:typeof e}function xi(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function Si(e,t){return typeof e==`object`&&!!e&&t in e}function Ci(e,t){return e!=null&&typeof e!=`object`&&e.hasOwnProperty&&e.hasOwnProperty(t)}var wi=RegExp.prototype.test;function Ti(e,t){return wi.call(e,t)}var Ei=/\S/;function Di(e){return!Ti(Ei,e)}var Oi={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`,"/":`/`,"`":```,"=":`=`};function ki(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return Oi[e]})}var Ai=/\s*/,ji=/\s+/,Mi=/\s*=/,Ni=/\s*\}/,Pi=/#|\^|\/|>|\{|&|=|!/;function Fi(e,t){if(!e)return[];var n=!1,r=[],i=[],a=[],o=!1,s=!1,c=``,l=0;function u(){if(o&&!s)for(;a.length;)delete i[a.pop()];else a=[];o=!1,s=!1}var d,f,p;function m(e){if(typeof e==`string`&&(e=e.split(ji,2)),!vi(e)||e.length!==2)throw Error(`Invalid tags: `+e);d=RegExp(xi(e[0])+`\\s*`),f=RegExp(`\\s*`+xi(e[1])),p=RegExp(`\\s*`+xi(`}`+e[1]))}m(t||F.tags);for(var h=new Ri(e),g,_,v,y,b,ee;!h.eos();){if(g=h.pos,v=h.scanUntil(d),v)for(var x=0,S=v.length;x<S;++x)y=v.charAt(x),Di(y)?(a.push(i.length),c+=y):(s=!0,n=!0,c+=` `),i.push([`text`,y,g,g+1]),g+=1,y===`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/langfuse-U2OEF7K7-UPVEn4-O.js","assets/chunk-QWQYAQCK-CyFuZlX8.js","assets/chunk-3GQAWCBQ-C-9Cm0Np.js","assets/chunk-zsgVPwQN.js","assets/chunk-UJPHRNQP-C81GjauI.js","assets/preload-helper-XLr9-hSf.js","assets/client-5EGX4URK-uXOuum47.js","assets/client-Di9rP6XG.js","assets/schemas-79owEkeD.js","assets/json-schema-processors-DSIsU0go.js","assets/chunk-UY6K7YNZ-CwjjzrEf.js","assets/path-BzTN_bR6.js","assets/chunk-RPN2XO5I-BXH06g3J.js","assets/display-A5IEINAP-BFwsYEHq.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./chunk-3GQAWCBQ-C-9Cm0Np.js";import{n as t}from"./chunk-QWQYAQCK-CyFuZlX8.js";import{It as n,S as r,er as i}from"./json-schema-processors-DSIsU0go.js";import{a,c as o,s}from"./client-Di9rP6XG.js";import{a as c,c as l,m as u,n as d,v as f}from"./schemas-79owEkeD.js";import"./chunk-UY6K7YNZ-CwjjzrEf.js";import{t as p}from"./preload-helper-XLr9-hSf.js";import{$n as m,A as h,An as g,Ar as _,At as v,Bn as y,Bt as b,C as ee,Ct as x,Dr as S,Dt as te,E as ne,En as re,Er as ie,Et as ae,F as oe,Fr as C,Ft as se,G as ce,Ht as le,I as ue,In as de,Ir as fe,It as pe,Jn as me,Kt as he,L as ge,Lr as _e,M as ve,Mr as ye,Mt as be,N as xe,Nr as Se,Nt as Ce,Or as we,Ot as Te,Pn as Ee,Pr as w,Pt as De,Qn as Oe,R as ke,Rr as T,Rt as Ae,S as je,St as Me,Tr as Ne,Tt as Pe,Ut as Fe,Vt as Ie,W as E,Wt as Le,Xt as Re,Zn as ze,_n as Be,at as Ve,b as He,bt as Ue,d as We,dn as Ge,dt as Ke,er as qe,fn as Je,g as Ye,gt as Xe,i as Ze,j as Qe,jn as $e,jr as et,jt as tt,k as nt,kr as rt,kt as it,l as at,lt as ot,mn as st,mr as D,mt as ct,nn as lt,nr as ut,nt as dt,o as ft,on as pt,ot as mt,pn as O,pt as ht,qn as gt,qt as _t,rr as vt,rt as yt,s as k,sn as bt,t as xt,tn as A,tr as St,ut as Ct,vn as j,vt as wt,w as Tt,wt as Et,x as Dt,xt as Ot,yn as kt,yt as At,zn as jt,zr as Mt,zt as Nt}from"./index-BP7yLFfO.js";import{C as Pt,D as Ft,M as It,O as Lt,S as Rt,T as zt,_ as Bt,b as Vt,c as Ht,d as Ut,f as Wt,g as Gt,h as Kt,j as qt,k as Jt,m as Yt,n as Xt,s as Zt,u as Qt,v as $t,x as en,y as tn}from"./function_calling-NA-IYsn6.js";import{a as nn,i as rn,n as an,o as on,r as sn,t as cn}from"./tools-BslK6xtH.js";import{n as ln,r as un,t as dn}from"./chunk_array-D_zGgmvz.js";import{n as fn,r as pn,t as mn}from"./llms-CHoe81gP.js";import{t as hn}from"./chunk-RPN2XO5I-BXH06g3J.js";import"./chunk-UJPHRNQP-C81GjauI.js";var gn,_n,vn=0,yn=0;function bn(e,t,n){var r=t&&n||0,i=t||Array(16);e||={};var a=e.node,o=e.clockseq;if(e._v6||(a||=gn,o??=_n),a==null||o==null){var s=e.random||(e.rng||b)();a??(a=[s[0],s[1],s[2],s[3],s[4],s[5]],!gn&&!e._v6&&(a[0]|=1,gn=a)),o??(o=(s[6]<<8|s[7])&16383,_n===void 0&&!e._v6&&(_n=o))}var c=e.msecs===void 0?Date.now():e.msecs,l=e.nsecs===void 0?yn+1:e.nsecs,u=c-vn+(l-yn)/1e4;if(u<0&&e.clockseq===void 0&&(o=o+1&16383),(u<0||c>vn)&&e.nsecs===void 0&&(l=0),l>=1e4)throw Error(`uuid.v1(): Can't create more than 10M uuids/sec`);vn=c,yn=l,_n=o,c+=0xb1d069b5400;var d=((c&268435455)*1e4+l)%4294967296;i[r++]=d>>>24&255,i[r++]=d>>>16&255,i[r++]=d>>>8&255,i[r++]=d&255;var f=c/4294967296*1e4&268435455;i[r++]=f>>>8&255,i[r++]=f&255,i[r++]=f>>>24&15|16,i[r++]=f>>>16&255,i[r++]=o>>>8|128,i[r++]=o&255;for(var p=0;p<6;++p)i[r+p]=a[p];return t||Ie(i)}function xn(e){var t=Sn(typeof e==`string`?le(e):e);return typeof e==`string`?Ie(t):t}function Sn(e,t=!1){return Uint8Array.of((e[6]&15)<<4|e[7]>>4&15,(e[7]&15)<<4|(e[4]&240)>>4,(e[4]&15)<<4|(e[5]&240)>>4,(e[5]&15)<<4|(e[0]&240)>>4,(e[0]&15)<<4|(e[1]&240)>>4,(e[1]&15)<<4|(e[2]&240)>>4,96|e[2]&15,e[3],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15])}function Cn(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wn(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Cn(Object(n),!0).forEach(function(t){Tn(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Cn(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Tn(e,t,n){return(t=En(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function En(e){var t=Dn(e,`string`);return typeof t==`symbol`?t:t+``}function Dn(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function On(e={},t,n=0){var r=bn(wn(wn({},e),{},{_v6:!0}),new Uint8Array(16));if(r=xn(r),t){for(var i=0;i<16;i++)t[n+i]=r[i];return t}return Ie(r)}var kn=Object.defineProperty,An=(e,t)=>{for(var n in t)kn(e,n,{get:t[n],enumerable:!0})};An({},{ConfigurableModel:()=>In,MODEL_PROVIDER_CONFIG:()=>jn,_inferModelProvider:()=>Fn,getChatModelByClassName:()=>Nn,initChatModel:()=>Ln});var jn={openai:{package:`@langchain/openai`,className:`ChatOpenAI`},anthropic:{package:`@langchain/anthropic`,className:`ChatAnthropic`},azure_openai:{package:`@langchain/openai`,className:`AzureChatOpenAI`},cohere:{package:`@langchain/cohere`,className:`ChatCohere`},"google-vertexai":{package:`@langchain/google-vertexai`,className:`ChatVertexAI`},"google-vertexai-web":{package:`@langchain/google-vertexai-web`,className:`ChatVertexAI`},"google-genai":{package:`@langchain/google-genai`,className:`ChatGoogleGenerativeAI`},ollama:{package:`@langchain/ollama`,className:`ChatOllama`},mistralai:{package:`@langchain/mistralai`,className:`ChatMistralAI`},mistral:{package:`@langchain/mistralai`,className:`ChatMistralAI`},groq:{package:`@langchain/groq`,className:`ChatGroq`},cerebras:{package:`@langchain/cerebras`,className:`ChatCerebras`},bedrock:{package:`@langchain/aws`,className:`ChatBedrockConverse`},deepseek:{package:`@langchain/deepseek`,className:`ChatDeepSeek`},xai:{package:`@langchain/xai`,className:`ChatXAI`},fireworks:{package:`@langchain/community/chat_models/fireworks`,className:`ChatFireworks`,hasCircularDependency:!0},together:{package:`@langchain/community/chat_models/togetherai`,className:`ChatTogetherAI`,hasCircularDependency:!0},perplexity:{package:`@langchain/community/chat_models/perplexity`,className:`ChatPerplexity`,hasCircularDependency:!0}},Mn=Object.keys(jn);async function Nn(e){let t=Object.entries(jn).find(([,t])=>t.className===e);if(!t)return;let[,n]=t;try{return(await p(()=>import(n.package),[]))[n.className]}catch(e){let t=e;if(`code`in t&&t.code?.toString().includes(`ERR_MODULE_NOT_FOUND`)&&`message`in t&&typeof t.message==`string`){let e=(t.message.startsWith(`Error: `)?t.message.slice(7):t.message).split(`Cannot find package '`)[1].split(`'`)[0];throw Error(`Unable to import ${e}. Please install with \`npm install ${e}\` or \`pnpm install ${e}\``)}throw e}}async function Pn(e,t,n={}){let r=t||Fn(e);if(!r)throw Error(`Unable to infer model provider for { model: ${e} }, please specify modelProvider directly.`);let i=jn[r];if(!i){let e=Mn.join(`, `);throw Error(`Unsupported { modelProvider: ${r} }.\n\nSupported model providers are: ${e}`)}let{modelProvider:a,...o}=n;return new(await(Nn(i.className)))({model:e,...o})}function Fn(e){if(e.startsWith(`gpt-3`)||e.startsWith(`gpt-4`)||e.startsWith(`gpt-5`)||e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`))return`openai`;if(e.startsWith(`claude`))return`anthropic`;if(e.startsWith(`command`))return`cohere`;if(e.startsWith(`accounts/fireworks`))return`fireworks`;if(e.startsWith(`gemini`))return`google-vertexai`;if(e.startsWith(`amazon.`))return`bedrock`;if(e.startsWith(`mistral`))return`mistralai`;if(e.startsWith(`sonar`)||e.startsWith(`pplx`))return`perplexity`}var In=class e extends Zt{_llmType(){return`chat_model`}lc_namespace=[`langchain`,`chat_models`];_defaultConfig={};_configurableFields=`any`;_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(e){super(e),this._defaultConfig=e.defaultConfig??{},e.configurableFields===`any`?this._configurableFields=`any`:this._configurableFields=e.configurableFields??[`model`,`modelProvider`],e.configPrefix?this._configPrefix=e.configPrefix.endsWith(`_`)?e.configPrefix:`${e.configPrefix}_`:this._configPrefix=``,this._queuedMethodOperations=e.queuedMethodOperations??this._queuedMethodOperations,this._profile=e.profile??void 0}async _getModelInstance(e){let t=this._getCacheKey(e),n=this._modelInstanceCache.get(t);if(n)return n;let r={...this._defaultConfig,...this._modelParams(e)},i=await Pn(r.model,r.modelProvider,r);for(let[e,t]of Object.entries(this._queuedMethodOperations))e in i&&typeof i[e]==`function`&&(i=await i[e](...t));return this._modelInstanceCache.set(t,i),i}async _generate(e,t,n){return(await this._getModelInstance(t))._generate(e,t??{},n)}bindTools(t,n){let r={...this._queuedMethodOperations};return r.bindTools=[t,n],new e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})}withStructuredOutput=(t,...n)=>{let r={...this._queuedMethodOperations};return r.withStructuredOutput=[t,...n],new e({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:r})};_modelParams(e){let t=e?.configurable??{},n={};for(let[e,r]of Object.entries(t))if(e.startsWith(this._configPrefix)){let t=this._removePrefix(e,this._configPrefix);n[t]=r}return this._configurableFields!==`any`&&(n=Object.fromEntries(Object.entries(n).filter(([e])=>this._configurableFields.includes(e)))),n}_removePrefix(e,t){return e.startsWith(t)?e.slice(t.length):e}withConfig(t){let n={...t||{}},r=this._modelParams(n),i=Object.fromEntries(Object.entries(n).filter(([e])=>e!==`configurable`));return i.configurable=Object.fromEntries(Object.entries(n.configurable||{}).filter(([e])=>this._configPrefix&&!Object.keys(r).includes(this._removePrefix(e,this._configPrefix)))),new at({config:n,bound:new e({defaultConfig:{...this._defaultConfig,...r},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(e,t){let n=await this._getModelInstance(t),r=At(t);return n.invoke(e,r)}async stream(e,t){let n=new ht({generator:await(await this._getModelInstance(t)).stream(e,t),config:t});return await n.setup,ct.fromAsyncGenerator(n)}async batch(e,t,n){return super.batch(e,t,n)}async*transform(e,t){let n=await this._getModelInstance(t),r=At(t);yield*n.transform(e,r)}async*streamLog(e,t,n){let r=await this._getModelInstance(t),i=At(t);yield*r.streamLog(e,i,{...n,_schemaFormat:`original`,includeNames:n?.includeNames,includeTypes:n?.includeTypes,includeTags:n?.includeTags,excludeNames:n?.excludeNames,excludeTypes:n?.excludeTypes,excludeTags:n?.excludeTags})}streamEvents(e,t,n){let r=this;async function*i(){let i=await r._getModelInstance(t),a=At(t),o=i.streamEvents(e,a,n);for await(let e of o)yield e}return ct.fromAsyncGenerator(i())}get profile(){if(this._profile)return this._profile;let e=this._getCacheKey({});return this._modelInstanceCache.get(e)?.profile??{}}_getCacheKey(e){let t=e??{};if(t.configurable){let{configurable:e}=t,n={};for(let[t,r]of Object.entries(e))t.startsWith(`__pregel_`)||(n[t]=r);t={...t,configurable:n}}return JSON.stringify(t)}};async function Ln(e,t){let{configurableFields:n,configPrefix:r,modelProvider:i,profile:a,...o}={configPrefix:``,...t??{}};if(i===void 0&&e?.includes(`:`)){let[t,...n]=e.split(`:`),r=n.length===0?[t]:[t,n.join(`:`)];Mn.includes(r[0])&&([i,e]=r)}let s=Array.isArray(n)?[...n]:n;!e&&s===void 0&&(s=[`model`,`modelProvider`]),r&&s===void 0&&console.warn(`{ configPrefix: ${r} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let c={...o},l;return s===void 0?l=new In({defaultConfig:{...c,model:e,modelProvider:i},configPrefix:r,profile:a}):(e&&(c.model=e),i&&(c.modelProvider=i),l=new In({defaultConfig:c,configPrefix:r,configurableFields:s,profile:a})),await l._getModelInstance(),l}var Rn=class{constructor(){this.store=void 0}getStore(){return this.store}run(e,t,...n){this.store=e;try{return t(...n)}finally{this.store=void 0}}exit(e,...t){let n=this.store;this.store=void 0;try{return e(...t)}finally{this.store=n}}enterWith(e){this.store=e}disable(){this.store=void 0}};function zn(){Pe.initializeGlobalInstance(new Rn)}var Bn=class extends Error{lc_error_code;constructor(e,t){let n=e??``;t?.lc_error_code&&(n=`${n}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${t.lc_error_code}/\n`),super(n),this.lc_error_code=t?.lc_error_code}},Vn=class extends Bn{get is_bubble_up(){return!0}},Hn=class extends Bn{constructor(e,t){super(e,t),this.name=`GraphRecursionError`}static get unminifiable_name(){return`GraphRecursionError`}},Un=class extends Bn{constructor(e,t){super(e,t),this.name=`GraphValueError`}static get unminifiable_name(){return`GraphValueError`}},Wn=class extends Vn{interrupts;constructor(e,t){super(JSON.stringify(e,null,2),t),this.name=`GraphInterrupt`,this.interrupts=e??[]}static get unminifiable_name(){return`GraphInterrupt`}},Gn=class extends Wn{constructor(e,t){super([{value:e}],t),this.name=`NodeInterrupt`}static get unminifiable_name(){return`NodeInterrupt`}},Kn=class extends Vn{command;constructor(e){super(),this.name=`ParentCommand`,this.command=e}static get unminifiable_name(){return`ParentCommand`}};function qn(e){return e!==void 0&&e.name===Kn.unminifiable_name}function Jn(e){return e!==void 0&&e.is_bubble_up===!0}function Yn(e){return e!==void 0&&[Wn.unminifiable_name,Gn.unminifiable_name].includes(e.name)}var Xn=class extends Bn{constructor(e,t){super(e,t),this.name=`EmptyInputError`}static get unminifiable_name(){return`EmptyInputError`}},M=class extends Bn{constructor(e,t){super(e,t),this.name=`EmptyChannelError`}static get unminifiable_name(){return`EmptyChannelError`}},N=class extends Bn{constructor(e,t){super(e,t),this.name=`InvalidUpdateError`}static get unminifiable_name(){return`InvalidUpdateError`}},Zn=class extends Bn{constructor(e,t){super(e,t),this.name=`UnreachableNodeError`}static get unminifiable_name(){return`UnreachableNodeError`}},Qn=class extends Bn{constructor(e,t){super(e,t),this.name=`StateGraphInputError`,this.message=`Invalid StateGraph input. Make sure to pass a valid StateDefinition, Annotation.Root, or Zod schema.`}static get unminifiable_name(){return`StateGraphInputError`}};function $n(e){return On({clockseq:e})}function er(e,t){let n=t.replace(/-/g,``).match(/.{2}/g).map(e=>parseInt(e,16));return Ae(e,new Uint8Array(n))}var tr=`__error__`,nr=`__scheduled__`,rr=`__interrupt__`,ir=`__resume__`,ar=`[...]`,or=`[Circular]`,sr=[],cr=[];function lr(){return{depthLimit:2**53-1,edgesLimit:2**53-1}}function ur(e,t,n,r){r===void 0&&(r=lr()),fr(e,``,0,[],void 0,0,r);var i;try{i=cr.length===0?JSON.stringify(e,t,n):JSON.stringify(e,pr(t),n)}catch{return JSON.stringify(`[unable to serialize, circular reference is too complex to analyze]`)}finally{for(;sr.length!==0;){var a=sr.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return i}function dr(e,t,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get===void 0?(r[n]=e,sr.push([r,n,t])):i.configurable?(Object.defineProperty(r,n,{value:e}),sr.push([r,n,t,i])):cr.push([t,n,e])}function fr(e,t,n,r,i,a,o){a+=1;var s;if(typeof e==`object`&&e){for(s=0;s<r.length;s++)if(r[s]===e){dr(or,e,t,i);return}if(o.depthLimit!==void 0&&a>o.depthLimit){dr(ar,e,t,i);return}if(o.edgesLimit!==void 0&&n+1>o.edgesLimit){dr(ar,e,t,i);return}if(r.push(e),Array.isArray(e))for(s=0;s<e.length;s++)fr(e[s],s,s,r,e,a,o);else{var c=Object.keys(e);for(s=0;s<c.length;s++){var l=c[s];fr(e[l],l,s,r,e,a,o)}}r.pop()}}function pr(e){return e=e===void 0?function(e,t){return t}:e,function(t,n){if(cr.length>0)for(var r=0;r<cr.length;r++){var i=cr[r];if(i[1]===t&&i[0]===n){n=i[2],cr.splice(r,1);break}}return e.call(this,t,n)}}var mr=[],hr={},gr={};D(gr,{BaseChatMessageHistory:()=>_r,BaseListChatMessageHistory:()=>vr,InMemoryChatMessageHistory:()=>yr});var _r=class extends ze{async addMessages(e){for(let t of e)await this.addMessage(t)}},vr=class extends ze{addUserMessage(e){return this.addMessage(new j(e))}addAIMessage(e){return this.addMessage(new A(e))}async addMessages(e){for(let t of e)await this.addMessage(t)}clear(){throw Error(`Not implemented.`)}},yr=class extends vr{lc_namespace=[`langchain`,`stores`,`message`,`in_memory`];messages=[];constructor(e){super(...arguments),this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}},br={},xr={};D(xr,{BaseMemory:()=>Sr,getInputValue:()=>wr,getOutputValue:()=>Tr,getPromptInputKey:()=>Er});var Sr=class{},Cr=(e,t)=>{if(t!==void 0)return e[t];let n=Object.keys(e);if(n.length===1)return e[n[0]]},wr=(e,t)=>{let n=Cr(e,t);if(!n){let t=Object.keys(e);throw Error(`input values have ${t.length} keys, you must specify an input key or pass only 1 key as input`)}return n},Tr=(e,t)=>{let n=Cr(e,t);if(!n&&n!==``){let t=Object.keys(e);throw Error(`output values have ${t.length} keys, you must specify an output key or pass only 1 key as output`)}return n};function Er(e,t){let n=Object.keys(e).filter(e=>!t.includes(e)&&e!==`stop`);if(n.length!==1)throw Error(`One input key expected, but got ${n.length}`);return n[0]}var Dr={};D(Dr,{BaseStore:()=>Or,InMemoryStore:()=>kr});var Or=class extends ze{},kr=class extends Or{lc_namespace=[`langchain`,`storage`];store={};async mget(e){return e.map(e=>this.store[e])}async mset(e){for(let[t,n]of e)this.store[t]=n}async mdelete(e){for(let t of e)delete this.store[t]}async*yieldKeys(e){let t=Object.keys(this.store);for(let n of t)(e===void 0||n.startsWith(e))&&(yield n)}},Ar={};D(Ar,{BaseRetriever:()=>jr});var jr=class extends k{callbacks;tags;metadata;verbose;constructor(e){super(e),this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,t){throw Error(`Not implemented!`)}async invoke(e,t){let n=At(Te(t)),r=await(await ae.configure(n.callbacks,this.callbacks,n.tags,this.tags,n.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,n.runId,void 0,void 0,void 0,n.runName);try{let t=await this._getRelevantDocuments(e,r);return await r?.handleRetrieverEnd(t),t}catch(e){throw await r?.handleRetrieverError(e),e}}},Mr={};D(Mr,{SaveableVectorStore:()=>Fr,VectorStore:()=>Pr,VectorStoreRetriever:()=>Nr});var Nr=class extends jr{static lc_name(){return`VectorStoreRetriever`}get lc_namespace(){return[`langchain_core`,`vectorstores`]}vectorStore;k=4;searchType=`similarity`;searchKwargs;filter;_vectorstoreType(){return this.vectorStore._vectorstoreType()}constructor(e){super(e),this.vectorStore=e.vectorStore,this.k=e.k??this.k,this.searchType=e.searchType??this.searchType,this.filter=e.filter,e.searchType===`mmr`&&(this.searchKwargs=e.searchKwargs)}async _getRelevantDocuments(e,t){if(this.searchType===`mmr`){if(typeof this.vectorStore.maxMarginalRelevanceSearch!=`function`)throw Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`);return this.vectorStore.maxMarginalRelevanceSearch(e,{k:this.k,filter:this.filter,...this.searchKwargs},t?.getChild(`vectorstore`))}return this.vectorStore.similaritySearch(e,this.k,this.filter,t?.getChild(`vectorstore`))}async addDocuments(e,t){return this.vectorStore.addDocuments(e,t)}},Pr=class extends ze{lc_namespace=[`langchain`,`vectorstores`,this._vectorstoreType()];embeddings;constructor(e,t){super(t),this.embeddings=e}async delete(e){throw Error(`Not implemented.`)}async similaritySearch(e,t=4,n=void 0,r=void 0){return(await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)).map(e=>e[0])}async similaritySearchWithScore(e,t=4,n=void 0,r=void 0){return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(e),t,n)}static fromTexts(e,t,n,r){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}static fromDocuments(e,t,n){throw Error(`the Langchain vectorstore implementation you are using forgot to override this, please report a bug`)}asRetriever(e,t,n,r,i,a){if(typeof e==`number`)return new Nr({vectorStore:this,k:e,filter:t,tags:[...r??[],this._vectorstoreType()],metadata:i,verbose:a,callbacks:n});{let t={vectorStore:this,k:e?.k,filter:e?.filter,tags:[...e?.tags??[],this._vectorstoreType()],metadata:e?.metadata,verbose:e?.verbose,callbacks:e?.callbacks,searchType:e?.searchType};return e?.searchType===`mmr`?new Nr({...t,searchKwargs:e.searchKwargs}):new Nr({...t})}}},Fr=class extends Pr{static load(e,t){throw Error(`Not implemented`)}},Ir={};D(Ir,{BaseDocumentLoader:()=>Lr});var Lr=class{},Rr={};D(Rr,{LangSmithLoader:()=>zr});var zr=class extends Lr{datasetId;datasetName;exampleIds;asOf;splits;inlineS3Urls;offset;limit;metadata;filter;contentKey;formatContent;client;constructor(e){if(super(),e.client&&e.clientConfig)throw Error(`client and clientConfig cannot both be provided.`);this.client=e.client??new De(e?.clientConfig),this.contentKey=e.contentKey?e.contentKey.split(`.`):[],this.formatContent=e.formatContent??Br,this.datasetId=e.datasetId,this.datasetName=e.datasetName,this.exampleIds=e.exampleIds,this.asOf=e.asOf,this.splits=e.splits,this.inlineS3Urls=e.inlineS3Urls,this.offset=e.offset,this.limit=e.limit,this.metadata=e.metadata,this.filter=e.filter}async load(){let e=[];for await(let t of this.client.listExamples({datasetId:this.datasetId,datasetName:this.datasetName,exampleIds:this.exampleIds,asOf:this.asOf,splits:this.splits,inlineS3Urls:this.inlineS3Urls,offset:this.offset,limit:this.limit,metadata:this.metadata,filter:this.filter})){let n=t.inputs;for(let e of this.contentKey)n=n[e];let r=this.formatContent(n),i=t;[`created_at`,`modified_at`].forEach(e=>{e in i&&typeof i[e]==`object`&&(i[e]=i[e].toString())}),e.push({pageContent:r,metadata:i})}return e}};function Br(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}}var Vr=class{pageContent;metadata;id;constructor(e){this.pageContent=e.pageContent===void 0?``:e.pageContent.toString(),this.metadata=e.metadata??{},this.id=e.id}},Hr=class extends k{lc_namespace=[`langchain_core`,`documents`,`transformers`];invoke(e,t){return this.transformDocuments(e)}},Ur=class extends Hr{async transformDocuments(e){let t=[];for(let n of e){let e=await this._transformDocument(n);t.push(e)}return t}},Wr={};D(Wr,{BaseDocumentTransformer:()=>Hr,Document:()=>Vr,MappingDocumentTransformer:()=>Ur});var Gr=class extends ze{lc_namespace=[`langchain_core`,`example_selectors`,`base`]},Kr=class{async getPromptAsync(e,t){return this.getPrompt(e).partial(t?.partialVariables??{})}},qr=class extends Kr{defaultPrompt;conditionals;constructor(e,t=[]){super(),this.defaultPrompt=e,this.conditionals=t}getPrompt(e){for(let[t,n]of this.conditionals)if(t(e))return n;return this.defaultPrompt}};function Jr(e){return e._modelType()===`base_llm`}function Yr(e){return e._modelType()===`base_chat_model`}function Xr(e){return e.split(/\n| /).length}var Zr=class e extends Gr{examples=[];examplePrompt;getTextLength=Xr;maxLength=2048;exampleTextLengths=[];constructor(e){super(e),this.examplePrompt=e.examplePrompt,this.maxLength=e.maxLength??2048,this.getTextLength=e.getTextLength??Xr}async addExample(e){this.examples.push(e);let t=await this.examplePrompt.format(e);this.exampleTextLengths.push(this.getTextLength(t))}async calculateExampleTextLengths(e,t){if(e.length>0)return e;let{examples:n,examplePrompt:r}=t;return(await Promise.all(n.map(e=>r.format(e)))).map(e=>this.getTextLength(e))}async selectExamples(e){let t=Object.values(e).join(` `),n=this.maxLength-this.getTextLength(t),r=0,i=[];for(;n>0&&r<this.examples.length;){let e=n-this.exampleTextLengths[r];if(e<0)break;i.push(this.examples[r]),n=e,r+=1}return i}static async fromExamples(t,n){let r=new e(n);return await Promise.all(t.map(e=>r.addExample(e))),r}};function Qr(e){return Object.keys(e).sort().map(t=>e[t])}var $r=class e extends Gr{vectorStoreRetriever;exampleKeys;inputKeys;constructor(e){if(super(e),this.exampleKeys=e.exampleKeys,this.inputKeys=e.inputKeys,e.vectorStore!==void 0)this.vectorStoreRetriever=e.vectorStore.asRetriever({k:e.k??4,filter:e.filter});else if(e.vectorStoreRetriever)this.vectorStoreRetriever=e.vectorStoreRetriever;else throw Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`)}async addExample(e){let t=Qr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `);await this.vectorStoreRetriever.addDocuments([new Vr({pageContent:t,metadata:e})])}async selectExamples(e){let t=Qr((this.inputKeys??Object.keys(e)).reduce((t,n)=>({...t,[n]:e[n]}),{})).join(` `),n=(await this.vectorStoreRetriever.invoke(t)).map(e=>e.metadata);return this.exampleKeys?n.map(e=>this.exampleKeys.reduce((t,n)=>({...t,[n]:e[n]}),{})):n}static async fromExamples(t,n,r,i={}){let a=i.inputKeys??null,o=t.map(e=>Qr(a?a.reduce((t,n)=>({...t,[n]:e[n]}),{}):e).join(` `));return new e({vectorStore:await r.fromTexts(o,t,n,i),k:i.k??4,exampleKeys:i.exampleKeys,inputKeys:i.inputKeys})}},ei={};D(ei,{BaseExampleSelector:()=>Gr,BasePromptSelector:()=>Kr,ConditionalPromptSelector:()=>qr,LengthBasedExampleSelector:()=>Zr,SemanticSimilarityExampleSelector:()=>$r,isChatModel:()=>Yr,isLLM:()=>Jr});var ti=`10f90ea3-90a4-4962-bf75-83a0f3c1c62a`,ni=class extends ze{lc_namespace=[`langchain`,`recordmanagers`]},ri=class{uid;hash_;contentHash;metadataHash;pageContent;metadata;keyEncoder=Bt;constructor(e){this.uid=e.uid,this.pageContent=e.pageContent,this.metadata=e.metadata}makeDefaultKeyEncoder(e){this.keyEncoder=e}calculateHashes(){let e=[`hash_`,`content_hash`,`metadata_hash`];for(let t of e)if(t in this.metadata)throw Error(`Metadata cannot contain key ${t} as it is reserved for internal use. Restricted keys: [${e.join(`, `)}]`);let t=this._hashStringToUUID(this.pageContent);try{let e=this._hashNestedDictToUUID(this.metadata);this.contentHash=t,this.metadataHash=e}catch(e){throw Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`)}this.hash_=this._hashStringToUUID(this.contentHash+this.metadataHash),this.uid||=this.hash_}toDocument(){return new Vr({pageContent:this.pageContent,metadata:this.metadata})}static fromDocument(e,t){let n=new this({pageContent:e.pageContent,metadata:e.metadata,uid:t||e.uid});return n.calculateHashes(),n}_hashStringToUUID(e){return Ae(this.keyEncoder(e),ti)}_hashNestedDictToUUID(e){let t=JSON.stringify(e,Object.keys(e).sort());return Ae(this.keyEncoder(t),ti)}};function ii(e,t){let n=[],r=[];return t.forEach(t=>{r.push(t),r.length>=e&&(n.push(r),r=[])}),r.length>0&&n.push(r),n}function ai(e){let t=new Set,n=[];for(let r of e){if(!r.hash_)throw Error(`Hashed document does not have a hash`);t.has(r.hash_)||(t.add(r.hash_),n.push(r))}return n}function oi(e){if(e===null)return e=>null;if(typeof e==`string`)return t=>t.metadata[e];if(typeof e==`function`)return e;throw Error(`sourceIdKey should be null, a string or a function, got ${typeof e}`)}var si=e=>`load`in e&&typeof e.load==`function`&&`loadAndSplit`in e&&typeof e.loadAndSplit==`function`;async function ci(e){let{docsSource:t,recordManager:n,vectorStore:r,options:i}=e,{batchSize:a=100,cleanup:o,sourceIdKey:s,cleanupBatchSize:c=1e3,forceUpdate:l=!1}=i??{};if(o===`incremental`&&!s)throw Error(`sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'.`);let u=si(t)?await t.load():t,d=oi(s??null),f=await n.getTime(),p=0,m=0,h=0,g=0,_=ii(a??100,u);for(let e of _){let t=ai(e.map(e=>ri.fromDocument(e))),i=t.map(e=>d(e));o===`incremental`&&t.forEach((e,t)=>{if(i[t]===null)throw Error(`sourceIdKey must be provided when cleanup is incremental`)});let a=await n.exists(t.map(e=>e.uid)),s=[],c=[],u=[],_=new Set;if(t.forEach((e,t)=>{if(a[t])if(l)_.add(e.uid);else{u.push(e.uid);return}s.push(e.uid),c.push(e.toDocument())}),u.length>0&&(await n.update(u,{timeAtLeast:f}),g+=u.length),c.length>0&&(await r.addDocuments(c,{ids:s}),p+=c.length-_.size,h+=_.size),await n.update(t.map(e=>e.uid),{timeAtLeast:f,groupIds:i}),o===`incremental`){i.forEach(e=>{if(!e)throw Error(`Source id cannot be null`)});let e=await n.listKeys({before:f,groupIds:i});e.length>0&&(await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length)}}if(o===`full`){let e=await n.listKeys({before:f,limit:c});for(;e.length>0;)await r.delete({ids:e}),await n.deleteKeys(e),m+=e.length,e=await n.listKeys({before:f,limit:c})}return{numAdded:p,numDeleted:m,numUpdated:h,numSkipped:g}}var li={};D(li,{RecordManager:()=>ni,UUIDV5_NAMESPACE:()=>ti,_HashedDocument:()=>ri,_batch:()=>ii,_deduplicateInOrder:()=>ai,_getSourceIdAssigner:()=>oi,_isBaseDocumentLoader:()=>si,index:()=>ci});var ui={},di=class extends Lt{static lc_name(){return`OutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;argsOnly=!0;constructor(e){super(),this.argsOnly=e?.argsOnly??this.argsOnly}async parseResult(e){if(`message`in e[0]){let t=e[0].message.additional_kwargs.function_call;if(!t)throw Error(`No function_call in message ${JSON.stringify(e)}`);if(!t.arguments)throw Error(`No arguments in function_call ${JSON.stringify(e)}`);return this.argsOnly?t.arguments:JSON.stringify(t)}else throw Error(`No message in generations ${JSON.stringify(e)}`)}},fi=class extends Ft{static lc_name(){return`JsonOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser;argsOnly=!0;constructor(e){super(e),this.argsOnly=e?.argsOnly??this.argsOnly,this.outputParser=new di(e)}_diff(e,t){if(t)return Ke(e??{},t)}async parsePartialResult(e){let t=e[0];if(!t.message)return;let{message:n}=t,r=n.additional_kwargs.function_call;if(r)return this.argsOnly?pt(r.arguments):{...r,arguments:pt(r.arguments)}}async parseResult(e){let t=await this.outputParser.parseResult(e);if(!t)throw Error(`No result from "OutputFunctionsParser" ${JSON.stringify(e)}`);return this.parse(t)}async parse(e){let t=JSON.parse(e);return this.argsOnly||(t.arguments=JSON.parse(t.arguments)),t}getFormatInstructions(){return``}},pi=class extends Lt{static lc_name(){return`JsonKeyOutputFunctionsParser`}lc_namespace=[`langchain`,`output_parsers`,`openai_functions`];lc_serializable=!0;outputParser=new fi;attrName;get lc_aliases(){return{attrName:`key_name`}}constructor(e){super(e),this.attrName=e.attrName}async parseResult(e){return(await this.outputParser.parseResult(e))[this.attrName]}},mi={};D(mi,{JsonKeyOutputFunctionsParser:()=>pi,JsonOutputFunctionsParser:()=>fi,OutputFunctionsParser:()=>di});var hi=class extends k{lc_serializable=!0;lc_namespace=[`langchain_core`,`prompts`,this._getPromptType()];get lc_attributes(){return{partialVariables:void 0}}inputVariables;outputParser;partialVariables;metadata;tags;constructor(e){super(e);let{inputVariables:t}=e;if(t.includes(`stop`))throw Error(`Cannot have an input variable named 'stop', as it is used internally, please rename.`);Object.assign(this,e)}async mergePartialAndUserVariables(e){let t=this.partialVariables??{},n={};for(let[e,r]of Object.entries(t))typeof r==`string`?n[e]=r:n[e]=await r();return{...n,...e}}async invoke(e,t){let n={...this.metadata,...t?.metadata},r=[...this.tags??[],...t?.tags??[]];return this._callWithConfig(e=>this.formatPromptValue(e),e,{...t,tags:r,metadata:n,runType:`prompt`})}},gi=class extends hi{async formatPromptValue(e){return new Vt(await this.format(e))}},_i=Object.prototype.toString,vi=Array.isArray||function(e){return _i.call(e)===`[object Array]`};function yi(e){return typeof e==`function`}function bi(e){return vi(e)?`array`:typeof e}function xi(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,`\\$&`)}function Si(e,t){return typeof e==`object`&&!!e&&t in e}function Ci(e,t){return e!=null&&typeof e!=`object`&&e.hasOwnProperty&&e.hasOwnProperty(t)}var wi=RegExp.prototype.test;function Ti(e,t){return wi.call(e,t)}var Ei=/\S/;function Di(e){return!Ti(Ei,e)}var Oi={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`,"/":`/`,"`":```,"=":`=`};function ki(e){return String(e).replace(/[&<>"'`=\/]/g,function(e){return Oi[e]})}var Ai=/\s*/,ji=/\s+/,Mi=/\s*=/,Ni=/\s*\}/,Pi=/#|\^|\/|>|\{|&|=|!/;function Fi(e,t){if(!e)return[];var n=!1,r=[],i=[],a=[],o=!1,s=!1,c=``,l=0;function u(){if(o&&!s)for(;a.length;)delete i[a.pop()];else a=[];o=!1,s=!1}var d,f,p;function m(e){if(typeof e==`string`&&(e=e.split(ji,2)),!vi(e)||e.length!==2)throw Error(`Invalid tags: `+e);d=RegExp(xi(e[0])+`\\s*`),f=RegExp(`\\s*`+xi(e[1])),p=RegExp(`\\s*`+xi(`}`+e[1]))}m(t||F.tags);for(var h=new Ri(e),g,_,v,y,b,ee;!h.eos();){if(g=h.pos,v=h.scanUntil(d),v)for(var x=0,S=v.length;x<S;++x)y=v.charAt(x),Di(y)?(a.push(i.length),c+=y):(s=!0,n=!0,c+=` `),i.push([`text`,y,g,g+1]),g+=1,y===`
|
|
3
3
|
`&&(u(),c=``,l=0,n=!1);if(!h.scan(d))break;if(o=!0,_=h.scan(Pi)||`name`,h.scan(Ai),_===`=`?(v=h.scanUntil(Mi),h.scan(Mi),h.scanUntil(f)):_===`{`?(v=h.scanUntil(p),h.scan(Ni),h.scanUntil(f),_=`&`):v=h.scanUntil(f),!h.scan(f))throw Error(`Unclosed tag at `+h.pos);if(b=_==`>`?[_,v,g,h.pos,c,l,n]:[_,v,g,h.pos],l++,i.push(b),_===`#`||_===`^`)r.push(b);else if(_===`/`){if(ee=r.pop(),!ee)throw Error(`Unopened section "`+v+`" at `+g);if(ee[1]!==v)throw Error(`Unclosed section "`+ee[1]+`" at `+g)}else _===`name`||_===`{`||_===`&`?s=!0:_===`=`&&m(v)}if(u(),ee=r.pop(),ee)throw Error(`Unclosed section "`+ee[1]+`" at `+h.pos);return Li(Ii(i))}function Ii(e){for(var t=[],n,r,i=0,a=e.length;i<a;++i)n=e[i],n&&(n[0]===`text`&&r&&r[0]===`text`?(r[1]+=n[1],r[3]=n[3]):(t.push(n),r=n));return t}function Li(e){for(var t=[],n=t,r=[],i,a,o=0,s=e.length;o<s;++o)switch(i=e[o],i[0]){case`#`:case`^`:n.push(i),r.push(i),n=i[4]=[];break;case`/`:a=r.pop(),a[5]=i[2],n=r.length>0?r[r.length-1][4]:t;break;default:n.push(i)}return t}function Ri(e){this.string=e,this.tail=e,this.pos=0}Ri.prototype.eos=function(){return this.tail===``},Ri.prototype.scan=function(e){var t=this.tail.match(e);if(!t||t.index!==0)return``;var n=t[0];return this.tail=this.tail.substring(n.length),this.pos+=n.length,n},Ri.prototype.scanUntil=function(e){var t=this.tail.search(e),n;switch(t){case-1:n=this.tail,this.tail=``;break;case 0:n=``;break;default:n=this.tail.substring(0,t),this.tail=this.tail.substring(t)}return this.pos+=n.length,n};function zi(e,t){this.view=e,this.cache={".":this.view},this.parent=t}zi.prototype.push=function(e){return new zi(e,this)},zi.prototype.lookup=function(e){var t=this.cache,n;if(t.hasOwnProperty(e))n=t[e];else{for(var r=this,i,a,o,s=!1;r;){if(e.indexOf(`.`)>0)for(i=r.view,a=e.split(`.`),o=0;i!=null&&o<a.length;)o===a.length-1&&(s=Si(i,a[o])||Ci(i,a[o])),i=i[a[o++]];else i=r.view[e],s=Si(r.view,e);if(s){n=i;break}r=r.parent}t[e]=n}return yi(n)&&(n=n.call(this.view)),n};function P(){this.templateCache={_cache:{},set:function(e,t){this._cache[e]=t},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}P.prototype.clearCache=function(){this.templateCache!==void 0&&this.templateCache.clear()},P.prototype.parse=function(e,t){var n=this.templateCache,r=e+`:`+(t||F.tags).join(`:`),i=n!==void 0,a=i?n.get(r):void 0;return a??(a=Fi(e,t),i&&n.set(r,a)),a},P.prototype.render=function(e,t,n,r){var i=this.getConfigTags(r),a=this.parse(e,i),o=t instanceof zi?t:new zi(t,void 0);return this.renderTokens(a,o,n,e,r)},P.prototype.renderTokens=function(e,t,n,r,i){for(var a=``,o,s,c,l=0,u=e.length;l<u;++l)c=void 0,o=e[l],s=o[0],s===`#`?c=this.renderSection(o,t,n,r,i):s===`^`?c=this.renderInverted(o,t,n,r,i):s===`>`?c=this.renderPartial(o,t,n,i):s===`&`?c=this.unescapedValue(o,t):s===`name`?c=this.escapedValue(o,t,i):s===`text`&&(c=this.rawValue(o)),c!==void 0&&(a+=c);return a},P.prototype.renderSection=function(e,t,n,r,i){var a=this,o=``,s=t.lookup(e[1]);function c(e){return a.render(e,t,n,i)}if(s){if(vi(s))for(var l=0,u=s.length;l<u;++l)o+=this.renderTokens(e[4],t.push(s[l]),n,r,i);else if(typeof s==`object`||typeof s==`string`||typeof s==`number`)o+=this.renderTokens(e[4],t.push(s),n,r,i);else if(yi(s)){if(typeof r!=`string`)throw Error(`Cannot use higher-order sections without the original template`);s=s.call(t.view,r.slice(e[3],e[5]),c),s!=null&&(o+=s)}else o+=this.renderTokens(e[4],t,n,r,i);return o}},P.prototype.renderInverted=function(e,t,n,r,i){var a=t.lookup(e[1]);if(!a||vi(a)&&a.length===0)return this.renderTokens(e[4],t,n,r,i)},P.prototype.indentPartial=function(e,t,n){for(var r=t.replace(/[^ \t]/g,``),i=e.split(`
|
|
4
4
|
`),a=0;a<i.length;a++)i[a].length&&(a>0||!n)&&(i[a]=r+i[a]);return i.join(`
|
|
5
5
|
`)},P.prototype.renderPartial=function(e,t,n,r){if(n){var i=this.getConfigTags(r),a=yi(n)?n(e[1]):n[e[1]];if(a!=null){var o=e[6],s=e[5],c=e[4],l=a;s==0&&c&&(l=this.indentPartial(a,c,o));var u=this.parse(l,i);return this.renderTokens(u,t,n,l,r)}}},P.prototype.unescapedValue=function(e,t){var n=t.lookup(e[1]);if(n!=null)return n},P.prototype.escapedValue=function(e,t,n){var r=this.getConfigEscape(n)||F.escape,i=t.lookup(e[1]);if(i!=null)return typeof i==`number`&&r===F.escape?String(i):r(i)},P.prototype.rawValue=function(e){return e[1]},P.prototype.getConfigTags=function(e){if(vi(e))return e;if(e&&typeof e==`object`)return e.tags},P.prototype.getConfigEscape=function(e){if(e&&typeof e==`object`&&!vi(e))return e.escape};var F={name:`mustache.js`,version:`4.2.0`,tags:[`{{`,`}}`],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(e){Bi.templateCache=e},get templateCache(){return Bi.templateCache}},Bi=new P;F.clearCache=function(){return Bi.clearCache()},F.parse=function(e,t){return Bi.parse(e,t)},F.render=function(e,t,n,r){if(typeof e!=`string`)throw TypeError(`Invalid template! Template should be a "string" but "`+bi(e)+`" was given as the first argument for mustache#render(template, view, partials)`);return Bi.render(e,t,n,r)},F.escape=ki,F.Scanner=Ri,F.Context=zi,F.Writer=P;function Vi(){F.escape=e=>e}var Hi=e=>{let t=e.split(``),n=[],r=(e,n)=>{for(let r=n;r<t.length;r+=1)if(e.includes(t[r]))return r;return-1},i=0;for(;i<t.length;)if(t[i]===`{`&&i+1<t.length&&t[i+1]===`{`)n.push({type:`literal`,text:`{`}),i+=2;else if(t[i]===`}`&&i+1<t.length&&t[i+1]===`}`)n.push({type:`literal`,text:`}`}),i+=2;else if(t[i]===`{`){let e=r(`}`,i);if(e<0)throw Error(`Unclosed '{' in template.`);n.push({type:`variable`,name:t.slice(i+1,e).join(``)}),i=e+1}else if(t[i]===`}`)throw Error(`Single '}' in template.`);else{let e=r(`{}`,i),a=(e<0?t.slice(i):t.slice(i,e)).join(``);n.push({type:`literal`,text:a}),i=e<0?t.length:e}return n},Ui=(e,t=[])=>{let n=[];for(let r of e)if(r[0]===`name`){let e=r[1].includes(`.`)?r[1].split(`.`)[0]:r[1];n.push({type:`variable`,name:e})}else if([`#`,`&`,`^`,`>`].includes(r[0])){if(n.push({type:`variable`,name:r[1]}),r[0]===`#`&&r.length>4&&Array.isArray(r[4])){let e=[...t,r[1]],i=Ui(r[4],e);n.push(...i)}}else n.push({type:`literal`,text:r[1]});return n},Wi=e=>(Vi(),Ui(F.parse(e))),Gi=(e,t)=>Hi(e).reduce((e,n)=>{if(n.type===`variable`){if(n.name in t)return e+(typeof t[n.name]==`string`?t[n.name]:JSON.stringify(t[n.name]));throw Error(`(f-string) Missing value for input ${n.name}`)}return e+n.text},``),Ki=(e,t)=>(Vi(),F.render(e,t)),qi={"f-string":Gi,mustache:Ki},Ji={"f-string":Hi,mustache:Wi},Yi=(e,t,n)=>{try{return qi[t](e,n)}catch(e){throw Ge(e,`INVALID_PROMPT_INPUT`)}},Xi=(e,t)=>Ji[t](e),Zi=(e,t,n)=>{if(!(t in qi)){let e=Object.keys(qi);throw Error(`Invalid template format. Got \`${t}\`;
|
|
@@ -340,7 +340,7 @@ Here are the tools *currently* available to you (this list includes server manag
|
|
|
340
340
|
\u2022 Missing or invalid MCP server configurations
|
|
341
341
|
\u2022 Network connectivity issues with MCP servers
|
|
342
342
|
\u2022 Missing environment variables or credentials
|
|
343
|
-
Raw error: ${c}`)}return l?this.parseStructuredResponse(c,l):typeof c==`object`&&c&&`result`in c?c.result:typeof c==`string`?c:String(c)}catch(e){throw e instanceof Error?e.name===`AbortError`?(t.error(`\u274C Remote execution timed out: ${e}`),Error(`Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.`)):(t.error(`\u274C Remote execution error: ${e}`),Error(`Remote agent execution failed: ${e.message}`)):(t.error(`\u274C Remote execution error: ${e}`),Error(`Remote agent execution failed: ${String(e)}`))}}async*stream(e,t,n,r,i){return await this.run(e,t,n,r,i)}async close(){t.info(`🔌 Remote agent client closed`)}},fh={openai:{package:`@langchain/openai`,className:`ChatOpenAI`,envVars:[`OPENAI_API_KEY`],defaultModel:`gpt-4o`},anthropic:{package:`@langchain/anthropic`,className:`ChatAnthropic`,envVars:[`ANTHROPIC_API_KEY`],defaultModel:`claude-3-5-sonnet-20241022`},google:{package:`@langchain/google-genai`,className:`ChatGoogleGenerativeAI`,envVars:[`GOOGLE_API_KEY`,`GOOGLE_GENERATIVE_AI_API_KEY`],defaultModel:`gemini-pro`},groq:{package:`@langchain/groq`,className:`ChatGroq`,envVars:[`GROQ_API_KEY`],defaultModel:`llama-3.1-70b-versatile`}};function ph(e){let t=e.split(`/`);if(t.length!==2)throw Error(`Invalid LLM string format. Expected 'provider/model', got '${e}'. Examples: 'openai/gpt-4', 'anthropic/claude-3-5-sonnet-20241022', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`);let[n,r]=t;if(!n||!r)throw Error(`Invalid LLM string format. Both provider and model must be non-empty. Got '${e}'`);let i=n.toLowerCase();if(!(i in fh)){let e=Object.keys(fh).join(`, `);throw Error(`Unsupported LLM provider '${n}'. Supported providers: ${e}`)}return{provider:i,model:r}}e(ph,`parseLLMString`);function mh(e,n){if(n?.apiKey)return n.apiKey;let r=fh[e];if(typeof process<`u`)for(let n of r.envVars){let r={}[n];if(r)return t.debug(`Using API key from environment variable ${n} for provider ${e}`),r}let i=r.envVars.join(` or `);throw Error(`API key not found for provider '${e}'. Set ${i} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${e}/model', llmConfig: { apiKey: 'your-key' } })`)}e(mh,`getAPIKey`);async function hh(e,n){t.info(`Creating LLM from string: ${e}`);let{provider:r,model:i}=ph(e),a=fh[r],o=mh(r,n),s;try{t.debug(`Importing package ${a.package}...`),s=await p(()=>import(a.package),[])}catch(e){throw e?.code===`MODULE_NOT_FOUND`||e?.message?.includes(`Cannot find module`)||e?.message?.includes(`Cannot find package`)?Error(`Package '${a.package}' is not installed. Install it with: npm install ${a.package} or yarn add ${a.package}`):Error(`Failed to import ${a.package}: ${e?.message||e}`)}let c=s[a.className];if(!c)throw Error(`Could not find ${a.className} in package ${a.package}. This might be a version compatibility issue.`);let l={model:i,apiKey:o,...n};n?.apiKey&&(delete l.apiKey,l.apiKey=o),(r===`anthropic`||r===`google`||r===`openai`||r===`groq`)&&(l.model=i);try{let e=new c(l);return t.info(`Successfully created ${r} LLM with model ${i}`),e}catch(e){throw Error(`Failed to instantiate ${a.className} with model '${i}': ${e?.message||e}`)}}e(hh,`createLLMFromString`);function gh(e){try{return ph(e),!0}catch{return!1}}e(gh,`isValidLLMString`);function _h(){return Object.keys(fh)}e(_h,`getSupportedProviders`);function vh(e,t,n,r,i,a){if(typeof e==`object`&&e){let t=e;return{query:t.prompt,maxSteps:t.maxSteps,manageConnector:t.manageConnector,externalHistory:t.externalHistory,outputSchema:t.schema,signal:t.signal}}return{query:e,maxSteps:t,manageConnector:n,externalHistory:r,outputSchema:i,signal:a}}e(vh,`normalizeRunOptions`);var yh=class{static{e(this,`MCPAgent`)}static getPackageVersion(){return o()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];exposeResourcesAsTools=!0;exposePromptsAsTools=!0;useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(n){if(n.agentId){this.isRemote=!0,this.remoteAgent=new dh({agentId:n.agentId,apiKey:n.apiKey,baseUrl:n.baseUrl}),this.maxSteps=n.maxSteps??5,this.memoryEnabled=n.memoryEnabled??!0,this.autoInitialize=n.autoInitialize??!1,this.verbose=n.verbose??!1,this.observe=n.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new Um,this.telemetry=a.getInstance(),this.modelProvider=`remote`,this.modelName=`remote-agent`,this.observabilityManager=new nh({customCallbacks:n.callbacks,agentId:n.agentId}),this.callbacks=[];return}if(!n.llm)throw Error(`llm is required for local execution. For remote execution, provide agentId instead.`);if(typeof n.llm==`string`){if(this.isSimplifiedMode=!0,this.llmString=n.llm,this.llmConfig=n.llmConfig,this.mcpServersConfig=n.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw Error(`Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }`);this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],t.info(`\u{1F3AF} Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=n.llm,this.client=n.client,this.connectors=n.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw Error(`Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.`);if(this.maxSteps=n.maxSteps??5,this.autoInitialize=n.autoInitialize??!1,this.memoryEnabled=n.memoryEnabled??!0,this.systemPrompt=n.systemPrompt??null,this.systemPromptTemplateOverride=n.systemPromptTemplate??null,this.additionalInstructions=n.additionalInstructions??null,this.disallowedTools=n.disallowedTools??[],this.additionalTools=n.additionalTools??[],this.toolsUsedNames=n.toolsUsedNames??[],this.exposeResourcesAsTools=n.exposeResourcesAsTools??!0,this.exposePromptsAsTools=n.exposePromptsAsTools??!0,this.useServerManager=n.useServerManager??!1,this.verbose=n.verbose??!1,this.observe=n.observe??!0,this.isSimplifiedMode)this.adapter=n.adapter??new Um(this.disallowedTools),this.telemetry=a.getInstance(),this.modelProvider=`unknown`,this.modelName=`unknown`;else{if(this.useServerManager){if(!this.client)throw Error(`'client' must be provided when 'useServerManager' is true.`);this.adapter=n.adapter??new Um(this.disallowedTools),this.serverManager=n.serverManagerFactory?.(this.client)??new th(this.client,this.adapter)}else this.adapter=n.adapter??new Um(this.disallowedTools);if(this.telemetry=a.getInstance(),this.llm){let[e,t]=s(this.llm);this.modelProvider=e,this.modelName=t}else this.modelProvider=`unknown`,this.modelName=`unknown`}this.observabilityManager=new nh({customCallbacks:n.callbacks,verbose:this.verbose,observe:this.observe,agentId:n.agentId,metadataProvider:e(()=>this.getMetadata(),`metadataProvider`),tagsProvider:e(()=>this.getTags(),`tagsProvider`)}),Object.defineProperty(this,`agentExecutor`,{get:e(()=>this._agentExecutor,`get`),configurable:!0}),Object.defineProperty(this,`tools`,{get:e(()=>this._tools,`get`),configurable:!0}),Object.defineProperty(this,`initialized`,{get:e(()=>this._initialized,`get`),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(t.info(`🚀 Initializing MCP agent and connecting to services...`),this.isSimplifiedMode){if(t.info(`🎯 Simplified mode: Creating client and LLM from configuration...`),this.mcpServersConfig){t.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);let{MCPClient:e}=await p(async()=>{let{MCPClient:e}=await import(`./client-SQLW334Q-uYsMCMIE.js`);return{MCPClient:e}},__vite__mapDeps([6,5,7,3,8,9,2,1,10,11,12]));this.client=new e({mcpServers:this.mcpServersConfig}),t.info(`✅ MCPClient created successfully`)}if(this.llmString){t.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await hh(this.llmString,this.llmConfig),t.info(`✅ LLM created successfully`);let[e,n]=s(this.llm);this.modelProvider=e,this.modelName=n}catch(e){throw Error(`Failed to create LLM from string '${this.llmString}': ${e?.message||e}`)}}if(this.useServerManager){if(!this.client)throw Error(`'client' must be available when 'useServerManager' is true.`);this.serverManager=new th(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();let e=await this.observabilityManager.getHandlerNames();if(e.length>0&&t.info(`\u{1F4CA} Observability enabled with: ${e.join(`, `)}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();let e=this.serverManager.tools;this._tools=e,this._tools.push(...this.additionalTools),t.info(`\u{1F527} Server manager mode active with ${e.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),t.info(`\u{1F50C} Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(e=>e!==`code_mode`).length===0&&(t.info(`🔄 No active sessions found, creating new ones...`),this.sessions=await this.client.createAllSessions(),t.info(`\u2705 Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){let e=this.sessions.code_mode;if(e)this._tools=await this.adapter.createToolsFromConnectors([e.connector]),t.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} code mode tools`);else throw Error(`Code mode enabled but code_mode session not found`)}else{let e=Object.values(this.sessions).map(e=>e.connector),n=await this.adapter.createToolsFromConnectors(e),r=this.exposeResourcesAsTools?await this.adapter.createResourcesFromConnectors(e):[],i=this.exposePromptsAsTools?await this.adapter.createPromptsFromConnectors(e):[];this._tools=[...n,...r,...i],t.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from client: ${n.length} tools, ${r.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{t.info(`\u{1F517} Connecting to ${this.connectors.length} direct connectors...`);for(let e of this.connectors)e.isClientConnected||await e.connect();let e=await this.adapter.createToolsFromConnectors(this.connectors),n=await this.adapter.createResourcesFromConnectors(this.connectors),r=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...e,...n,...r],this._tools.push(...this.additionalTools),t.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from connectors: ${e.length} tools, ${n.length} resources, ${r.length} prompts`)}t.info(`\u{1F9F0} Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;let n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),t.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),t.info(`✨ Agent initialization complete`)}async createSystemMessageFromTools(e){this.systemMessage=ah(e,this.systemPromptTemplateOverride??oh,sh,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(e=>!(e instanceof O))])}createAgent(){if(!this.llm)throw Error(`LLM is required to create agent`);let e=this.systemMessage?.content??`You are a helpful assistant.`,n=this._tools.map(e=>e.name);t.info(`\u{1F9E0} Agent ready with tools: ${n.join(`, `)}`);let r=[bm({runLimit:this.maxSteps})],i=Lf({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return t.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),i}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new O(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(e=>!(e instanceof O)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),t.debug(`Agent recreated with new system message`))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new Um(this.disallowedTools),this._initialized&&t.debug(`Agent already initialized. Changes will take effect on next initialization.`)}getDisallowedTools(){return this.disallowedTools}setMetadata(e){let n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},t.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){let n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],t.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){let n={};for(let[r,i]of Object.entries(e)){if(typeof r!=`string`||r.length===0){t.warn(`Invalid metadata key: ${r}. Skipping.`);continue}let e=r.replace(/[^\w-]/g,`_`);if(i==null)n[e]=i;else if(typeof i==`string`||typeof i==`number`||typeof i==`boolean`)n[e]=i;else if(Array.isArray(i)){let t=i.filter(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`);t.length>0&&(n[e]=t)}else if(typeof i==`object`)try{let r=JSON.stringify(i);r.length>1e3?(t.warn(`Metadata value for key '${e}' is too large. Truncating.`),n[e]=`${r.substring(0,1e3)}...`):n[e]=i}catch(n){t.warn(`Failed to serialize metadata value for key '${e}': ${n}. Skipping.`)}else t.warn(`Unsupported metadata value type for key '${e}': ${typeof i}. Skipping.`)}return n}sanitizeTags(e){return e.filter(e=>typeof e==`string`&&e.length>0).map(e=>e.replace(/[^\w:-]/g,`_`)).filter(e=>e.length<=50)}getMCPServerInfo(){let e={};try{if(this.client){let n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;let r={};for(let e of n)try{let t=this.client.getServerConfig(e);if(t){let n=`unknown`;t.command?n=`command`:t.url?n=`http`:t.ws_url&&(n=`websocket`),r[e]={type:n,has_args:!!t.args,has_env:!!t.env,has_headers:!!t.headers,url:t.url||null,command:t.command||null}}}catch(n){t.warn(`Failed to get config for server '${e}': ${n}`),r[e]={type:`error`,error:`config_unavailable`}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(e=>e.publicIdentifier),e.mcp_server_types=this.connectors.map(e=>e.constructor.name))}catch(n){t.warn(`Failed to collect MCP server info: ${n}`),e.error=`collection_failed`}return e}_normalizeOutput(e){try{if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`content`in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){let t=[];for(let n of e)if(typeof n==`object`&&n)`text`in n&&typeof n.text==`string`?t.push(n.text):`content`in n?t.push(this._normalizeOutput(n.content)):t.push(String(n));else{let e=n&&typeof n==`object`&&`text`in n?n.text:null;if(typeof e==`string`)t.push(e);else{let e=n&&typeof n==`object`&&`content`in n?n.content:n;t.push(this._normalizeOutput(e))}}return t.join(``)}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof A)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{let e=t.getType();if(e===`ai`||e===`assistant`)return!0}catch{}if(typeof t._getType==`function`)try{let e=t._getType();if(e===`ai`||e===`assistant`)return!0}catch{}return`type`in t?t.type===`ai`||t.type===`assistant`:`role`in t?t.role===`ai`||t.role===`assistant`:!1}_messageHasToolCalls(e){return typeof e==`object`&&e&&`tool_calls`in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof j)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{let e=t.getType();if(e===`human`||e===`user`)return!0}catch{}return`type`in t&&(t.type===`human`||t.type===`user`)||`role`in t&&(t.role===`human`||t.role===`user`)}_isToolMessageLike(e){if(e instanceof g)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{if(t.getType()===`tool`)return!0}catch{}return`type`in t&&t.type===`tool`}_getMessageContent(e){if(e instanceof A||e&&typeof e==`object`&&`content`in e)return e.content}async _consumeAndReturn(e){for(;;){let{done:t,value:n}=await e.next();if(t)return n}}async run(e,t,n,r,i,a){let{query:o,maxSteps:s,manageConnector:c,externalHistory:l,outputSchema:u,signal:d}=vh(e,t,n,r,i,a);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(o,s,c,l,u);let f=this.stream(o,s,c,l,u,d);return this._consumeAndReturn(f)}async*stream(e,n,r=!0,i,a,o){let{query:s,maxSteps:c,manageConnector:l,externalHistory:u,outputSchema:d,signal:f}=vh(e,n,r,i,a,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(s,c,l,u,d);let p=!1,m=Date.now(),h=!1,g=null,_=0;try{if((l&&!this._initialized||!this._initialized&&this.autoInitialize)&&(await this.initialize(),p=!0),!this._agentExecutor)throw Error(`MCP agent failed to initialize`);if(this.useServerManager&&this.serverManager){let e=this.serverManager.tools,n=new Set(e.map(e=>e.name)),r=new Set(this._tools.map(e=>e.name));(n.size!==r.size||[...n].some(e=>!r.has(e)))&&(t.info(`\u{1F504} Tools changed before execution, updating agent. New tools: ${[...n].join(`, `)}`),this._tools=e,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}let e=u??this.conversationHistory,n=[];for(let t of e)(this._isHumanMessageLike(t)||this._isAIMessageLike(t)||this._isToolMessageLike(t))&&n.push(t);let r=s.length>50?`${s.slice(0,50).replace(/\n/g,` `)}...`:s.replace(/\n/g,` `);t.info(`\u{1F4AC} Received query: '${r}'`),t.info(`🏁 Starting agent execution`);let i=0,a=[...n,new j(s)];for(;i<=3;){let e={messages:a},n=!1,r=await this._agentExecutor.stream(e,{streamMode:`updates`,callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||`mcp-use-agent`,recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id},...f&&{signal:f}});for await(let e of r){if(f?.aborted)break;for(let[r,o]of Object.entries(e))if(t.debug(`\u{1F4E6} Node '${r}' output: ${JSON.stringify(o)}`),o&&typeof o==`object`&&`messages`in o){let e=o.messages;Array.isArray(e)||(e=[e]);for(let t of e)a.includes(t)||a.push(t);for(let r of e){if(`tool_calls`in r&&Array.isArray(r.tool_calls)&&r.tool_calls.length>0)for(let e of r.tool_calls){let n=e.name||`unknown`,r=e.args||{};this.toolsUsedNames.push(n),_++;let i=JSON.stringify(r);i.length>100&&(i=`${i.slice(0,97)}...`),t.info(`\u{1F527} Tool call: ${n} with input: ${i}`),yield{action:{tool:n,toolInput:r,log:`Calling tool ${n}`},observation:``}}if(this._isToolMessageLike(r)){let e=r.content,a=String(e);if(a.length>100&&(a=`${a.slice(0,97)}...`),a=a.replace(/\n/g,` `),t.info(`\u{1F4C4} Tool result: ${a}`),this.useServerManager&&this.serverManager){let e=this.serverManager.tools,r=new Set(e.map(e=>e.name)),a=new Set(this._tools.map(e=>e.name));if(r.size!==a.size||[...r].some(e=>!a.has(e))){t.info(`\u{1F504} Tools changed during execution. New tools: ${[...r].join(`, `)}`),this._tools=e,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),n=!0,i++,t.info(`\u{1F503} Restarting execution with updated tools (restart ${i}/3)`);break}}}this._isAIMessageLike(r)&&!this._messageHasToolCalls(r)&&(g=this._normalizeOutput(this._getMessageContent(r)),t.info(`✅ Agent finished with output`))}if(n)break}if(n)break}if(!n)break;if(i>3){t.warn(`⚠️ Max restarts (3) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){let e=a.slice(n.length);for(let t of e)this.addToHistory(t)}if(d&&g)try{t.info(`🔧 Attempting structured output...`);let e=await this._attemptStructuredOutput(g,this.llm,d);return this.memoryEnabled&&this.addToHistory(new A(`Structured result: ${JSON.stringify(e)}`)),t.info(`✅ Structured output successful`),h=!0,e}catch(e){throw t.error(`\u274C Structured output failed: ${e}`),Error(`Failed to generate structured output: ${e instanceof Error?e.message:String(e)}`)}return t.info(`\u{1F389} Agent execution complete in ${((Date.now()-m)/1e3).toFixed(2)} seconds`),h=!0,g||`No output generated`}catch(e){throw t.error(`\u274C Error running query: ${e}`),p&&l&&(t.info(`🧹 Cleaning up resources after error`),await this.close()),e}finally{let e=Date.now()-m,n=0;this.client?n=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(n=this.connectors.length);let r=this.memoryEnabled?this.conversationHistory.length:0,i=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:`stream`,query:s,success:h,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:n,serverIdentifiers:this.connectors.map(e=>e.publicIdentifier),totalToolsAvailable:i.length,toolsAvailableNames:i.map(e=>e.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:c??null,manageConnector:l??!0,externalHistoryUsed:u!==void 0,stepsTaken:_,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||``,executionTimeMs:e,errorType:h?null:`execution_error`,conversationHistoryLength:r}),l&&!this.client&&p&&(t.info(`🧹 Closing agent after stream completion`),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(t.debug(`Flushing observability traces...`),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}t.info(`🔌 Closing MCPAgent resources…`),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(t.info(`🔄 Closing internally-created client (simplified mode) and cleaning up resources`),await this.client.close(),this.sessions={},this.client=void 0):(t.info(`🔄 Closing client and cleaning up resources`),await this.client.close(),this.sessions={});else for(let e of this.connectors)t.info(`🔄 Disconnecting connector`),await e.disconnect();this.isSimplifiedMode&&this.llm&&(t.debug(`🔄 Clearing LLM reference (simplified mode)`),this.llm=void 0),`connectorToolMap`in this.adapter&&(this.adapter=new Um)}finally{this._initialized=!1,t.info(`👋 Agent closed successfully`)}}async*prettyStreamEvents(e,t,n=!0,r,i){let{prettyStreamEvents:a}=await p(async()=>{let{prettyStreamEvents:e}=await import(`./display-A5IEINAP-BFwsYEHq.js`);return{prettyStreamEvents:e}},__vite__mapDeps([13,3,5,2]));for await(let o of a(this.streamEvents(e,t,n,r,i)))yield;return``}async*streamEvents(e,n,r=!0,i,a,o){let s=vh(e,n,r,i,a,o),{query:c}=s,{maxSteps:l,manageConnector:u,externalHistory:d,outputSchema:f,signal:p}=s,m=!1,h=Date.now(),g=!1,_=0,v=0,y=``;f&&(c=this._enhanceQueryWithSchema(c,f));try{(u&&!this._initialized||!this._initialized&&this.autoInitialize)&&(await this.initialize(),m=!0);let e=this._agentExecutor;if(!e)throw Error(`MCP agent failed to initialize`);this.maxSteps=l??this.maxSteps;let n=typeof c==`string`&&c.length>50?`${c.slice(0,50).replace(/\n/g,` `)}...`:typeof c==`string`?c.replace(/\n/g,` `):String(c);t.info(`\u{1F4AC} Received query for streamEvents: '${n}'`),this.memoryEnabled&&(t.info(`\u{1F504} Adding user message to history: ${n}`),this.addToHistory(new j({content:c})));let r=d??this.conversationHistory,i=[];for(let e of r)this._isHumanMessageLike(e)||this._isAIMessageLike(e)||this._isToolMessageLike(e)?i.push(e):t.info(`\u26A0\uFE0F Skipped message of type: ${e.constructor?.name||typeof e}`);let a=[...i,new j(c)];t.info(`callbacks`,this.callbacks);let o=e.streamEvents({messages:a},{streamMode:`messages`,version:`v2`,callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||`mcp-use-agent`,recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id},...p&&{signal:p}});for await(let e of o){if(p?.aborted)break;if(_++,!(!e||typeof e!=`object`)){if(e.event===`on_chat_model_stream`&&e.data?.chunk?.content&&(v+=e.data.chunk.content.length),e.event===`on_chat_model_stream`&&e.data?.chunk){let n=e.data.chunk;if(n.content){y||=``;let e=this._normalizeOutput(n.content);y+=e,t.debug(`\u{1F4DD} Accumulated response length: ${y.length}`)}}if(yield e,e.event===`on_chain_end`&&e.data?.output&&!y){let t=e.data.output;Array.isArray(t)&&t.length>0&&t[0]?.text?y=t[0].text:typeof t==`string`?y=t:t&&typeof t==`object`&&`output`in t&&(y=t.output)}}}if(f&&y){t.info(`🔧 Attempting structured output conversion...`);try{let e=!1,n=null,r=null;this._attemptStructuredOutput(y,this.llm,f).then(t=>(e=!0,n=t,t)).catch(t=>{throw e=!0,r=t,t});let i=0;for(;!e;)await new Promise(e=>setTimeout(e,2e3)),e||(i++,yield{event:`on_structured_output_progress`,data:{message:`Converting to structured output... (${i*2}s)`,elapsed:i*2}});if(r)throw r;n&&(yield{event:`on_structured_output`,data:{output:n}},this.memoryEnabled&&this.addToHistory(new A(`Structured result: ${JSON.stringify(n)}`)),t.info(`✅ Structured output successful`))}catch(e){t.warn(`\u26A0\uFE0F Structured output failed: ${e}`),yield{event:`on_structured_output_error`,data:{error:e instanceof Error?e.message:String(e)}}}}else this.memoryEnabled&&y&&this.addToHistory(new A(y));console.log(`
|
|
343
|
+
Raw error: ${c}`)}return l?this.parseStructuredResponse(c,l):typeof c==`object`&&c&&`result`in c?c.result:typeof c==`string`?c:String(c)}catch(e){throw e instanceof Error?e.name===`AbortError`?(t.error(`\u274C Remote execution timed out: ${e}`),Error(`Remote agent execution timed out. The server may be overloaded or the query is taking too long to process. Try again or use a simpler query.`)):(t.error(`\u274C Remote execution error: ${e}`),Error(`Remote agent execution failed: ${e.message}`)):(t.error(`\u274C Remote execution error: ${e}`),Error(`Remote agent execution failed: ${String(e)}`))}}async*stream(e,t,n,r,i){return await this.run(e,t,n,r,i)}async close(){t.info(`🔌 Remote agent client closed`)}},fh={openai:{package:`@langchain/openai`,className:`ChatOpenAI`,envVars:[`OPENAI_API_KEY`],defaultModel:`gpt-4o`},anthropic:{package:`@langchain/anthropic`,className:`ChatAnthropic`,envVars:[`ANTHROPIC_API_KEY`],defaultModel:`claude-3-5-sonnet-20241022`},google:{package:`@langchain/google-genai`,className:`ChatGoogleGenerativeAI`,envVars:[`GOOGLE_API_KEY`,`GOOGLE_GENERATIVE_AI_API_KEY`],defaultModel:`gemini-pro`},groq:{package:`@langchain/groq`,className:`ChatGroq`,envVars:[`GROQ_API_KEY`],defaultModel:`llama-3.1-70b-versatile`}};function ph(e){let t=e.split(`/`);if(t.length!==2)throw Error(`Invalid LLM string format. Expected 'provider/model', got '${e}'. Examples: 'openai/gpt-4', 'anthropic/claude-3-5-sonnet-20241022', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`);let[n,r]=t;if(!n||!r)throw Error(`Invalid LLM string format. Both provider and model must be non-empty. Got '${e}'`);let i=n.toLowerCase();if(!(i in fh)){let e=Object.keys(fh).join(`, `);throw Error(`Unsupported LLM provider '${n}'. Supported providers: ${e}`)}return{provider:i,model:r}}e(ph,`parseLLMString`);function mh(e,n){if(n?.apiKey)return n.apiKey;let r=fh[e];if(typeof process<`u`)for(let n of r.envVars){let r={}[n];if(r)return t.debug(`Using API key from environment variable ${n} for provider ${e}`),r}let i=r.envVars.join(` or `);throw Error(`API key not found for provider '${e}'. Set ${i} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${e}/model', llmConfig: { apiKey: 'your-key' } })`)}e(mh,`getAPIKey`);async function hh(e,n){t.info(`Creating LLM from string: ${e}`);let{provider:r,model:i}=ph(e),a=fh[r],o=mh(r,n),s;try{t.debug(`Importing package ${a.package}...`),s=await p(()=>import(a.package),[])}catch(e){throw e?.code===`MODULE_NOT_FOUND`||e?.message?.includes(`Cannot find module`)||e?.message?.includes(`Cannot find package`)?Error(`Package '${a.package}' is not installed. Install it with: npm install ${a.package} or yarn add ${a.package}`):Error(`Failed to import ${a.package}: ${e?.message||e}`)}let c=s[a.className];if(!c)throw Error(`Could not find ${a.className} in package ${a.package}. This might be a version compatibility issue.`);let l={model:i,apiKey:o,...n};n?.apiKey&&(delete l.apiKey,l.apiKey=o),(r===`anthropic`||r===`google`||r===`openai`||r===`groq`)&&(l.model=i);try{let e=new c(l);return t.info(`Successfully created ${r} LLM with model ${i}`),e}catch(e){throw Error(`Failed to instantiate ${a.className} with model '${i}': ${e?.message||e}`)}}e(hh,`createLLMFromString`);function gh(e){try{return ph(e),!0}catch{return!1}}e(gh,`isValidLLMString`);function _h(){return Object.keys(fh)}e(_h,`getSupportedProviders`);function vh(e,t,n,r,i,a){if(typeof e==`object`&&e){let t=e;return{query:t.prompt,maxSteps:t.maxSteps,manageConnector:t.manageConnector,externalHistory:t.externalHistory,outputSchema:t.schema,signal:t.signal}}return{query:e,maxSteps:t,manageConnector:n,externalHistory:r,outputSchema:i,signal:a}}e(vh,`normalizeRunOptions`);var yh=class{static{e(this,`MCPAgent`)}static getPackageVersion(){return o()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];exposeResourcesAsTools=!0;exposePromptsAsTools=!0;useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(n){if(n.agentId){this.isRemote=!0,this.remoteAgent=new dh({agentId:n.agentId,apiKey:n.apiKey,baseUrl:n.baseUrl}),this.maxSteps=n.maxSteps??5,this.memoryEnabled=n.memoryEnabled??!0,this.autoInitialize=n.autoInitialize??!1,this.verbose=n.verbose??!1,this.observe=n.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new Um,this.telemetry=a.getInstance(),this.modelProvider=`remote`,this.modelName=`remote-agent`,this.observabilityManager=new nh({customCallbacks:n.callbacks,agentId:n.agentId}),this.callbacks=[];return}if(!n.llm)throw Error(`llm is required for local execution. For remote execution, provide agentId instead.`);if(typeof n.llm==`string`){if(this.isSimplifiedMode=!0,this.llmString=n.llm,this.llmConfig=n.llmConfig,this.mcpServersConfig=n.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw Error(`Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }`);this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],t.info(`\u{1F3AF} Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=n.llm,this.client=n.client,this.connectors=n.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw Error(`Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.`);if(this.maxSteps=n.maxSteps??5,this.autoInitialize=n.autoInitialize??!1,this.memoryEnabled=n.memoryEnabled??!0,this.systemPrompt=n.systemPrompt??null,this.systemPromptTemplateOverride=n.systemPromptTemplate??null,this.additionalInstructions=n.additionalInstructions??null,this.disallowedTools=n.disallowedTools??[],this.additionalTools=n.additionalTools??[],this.toolsUsedNames=n.toolsUsedNames??[],this.exposeResourcesAsTools=n.exposeResourcesAsTools??!0,this.exposePromptsAsTools=n.exposePromptsAsTools??!0,this.useServerManager=n.useServerManager??!1,this.verbose=n.verbose??!1,this.observe=n.observe??!0,this.isSimplifiedMode)this.adapter=n.adapter??new Um(this.disallowedTools),this.telemetry=a.getInstance(),this.modelProvider=`unknown`,this.modelName=`unknown`;else{if(this.useServerManager){if(!this.client)throw Error(`'client' must be provided when 'useServerManager' is true.`);this.adapter=n.adapter??new Um(this.disallowedTools),this.serverManager=n.serverManagerFactory?.(this.client)??new th(this.client,this.adapter)}else this.adapter=n.adapter??new Um(this.disallowedTools);if(this.telemetry=a.getInstance(),this.llm){let[e,t]=s(this.llm);this.modelProvider=e,this.modelName=t}else this.modelProvider=`unknown`,this.modelName=`unknown`}this.observabilityManager=new nh({customCallbacks:n.callbacks,verbose:this.verbose,observe:this.observe,agentId:n.agentId,metadataProvider:e(()=>this.getMetadata(),`metadataProvider`),tagsProvider:e(()=>this.getTags(),`tagsProvider`)}),Object.defineProperty(this,`agentExecutor`,{get:e(()=>this._agentExecutor,`get`),configurable:!0}),Object.defineProperty(this,`tools`,{get:e(()=>this._tools,`get`),configurable:!0}),Object.defineProperty(this,`initialized`,{get:e(()=>this._initialized,`get`),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(t.info(`🚀 Initializing MCP agent and connecting to services...`),this.isSimplifiedMode){if(t.info(`🎯 Simplified mode: Creating client and LLM from configuration...`),this.mcpServersConfig){t.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);let{MCPClient:e}=await p(async()=>{let{MCPClient:e}=await import(`./client-5EGX4URK-uXOuum47.js`);return{MCPClient:e}},__vite__mapDeps([6,5,7,3,8,9,2,1,10,11,12]));this.client=new e({mcpServers:this.mcpServersConfig}),t.info(`✅ MCPClient created successfully`)}if(this.llmString){t.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await hh(this.llmString,this.llmConfig),t.info(`✅ LLM created successfully`);let[e,n]=s(this.llm);this.modelProvider=e,this.modelName=n}catch(e){throw Error(`Failed to create LLM from string '${this.llmString}': ${e?.message||e}`)}}if(this.useServerManager){if(!this.client)throw Error(`'client' must be available when 'useServerManager' is true.`);this.serverManager=new th(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();let e=await this.observabilityManager.getHandlerNames();if(e.length>0&&t.info(`\u{1F4CA} Observability enabled with: ${e.join(`, `)}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();let e=this.serverManager.tools;this._tools=e,this._tools.push(...this.additionalTools),t.info(`\u{1F527} Server manager mode active with ${e.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),t.info(`\u{1F50C} Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(e=>e!==`code_mode`).length===0&&(t.info(`🔄 No active sessions found, creating new ones...`),this.sessions=await this.client.createAllSessions(),t.info(`\u2705 Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){let e=this.sessions.code_mode;if(e)this._tools=await this.adapter.createToolsFromConnectors([e.connector]),t.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} code mode tools`);else throw Error(`Code mode enabled but code_mode session not found`)}else{let e=Object.values(this.sessions).map(e=>e.connector),n=await this.adapter.createToolsFromConnectors(e),r=this.exposeResourcesAsTools?await this.adapter.createResourcesFromConnectors(e):[],i=this.exposePromptsAsTools?await this.adapter.createPromptsFromConnectors(e):[];this._tools=[...n,...r,...i],t.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from client: ${n.length} tools, ${r.length} resources, ${i.length} prompts`)}this._tools.push(...this.additionalTools)}else{t.info(`\u{1F517} Connecting to ${this.connectors.length} direct connectors...`);for(let e of this.connectors)e.isClientConnected||await e.connect();let e=await this.adapter.createToolsFromConnectors(this.connectors),n=await this.adapter.createResourcesFromConnectors(this.connectors),r=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...e,...n,...r],this._tools.push(...this.additionalTools),t.info(`\u{1F6E0}\uFE0F Created ${this._tools.length} LangChain items from connectors: ${e.length} tools, ${n.length} resources, ${r.length} prompts`)}t.info(`\u{1F9F0} Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;let n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),t.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),t.info(`✨ Agent initialization complete`)}async createSystemMessageFromTools(e){this.systemMessage=ah(e,this.systemPromptTemplateOverride??oh,sh,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(e=>!(e instanceof O))])}createAgent(){if(!this.llm)throw Error(`LLM is required to create agent`);let e=this.systemMessage?.content??`You are a helpful assistant.`,n=this._tools.map(e=>e.name);t.info(`\u{1F9E0} Agent ready with tools: ${n.join(`, `)}`);let r=[bm({runLimit:this.maxSteps})],i=Lf({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return t.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),i}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new O(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(e=>!(e instanceof O)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),t.debug(`Agent recreated with new system message`))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new Um(this.disallowedTools),this._initialized&&t.debug(`Agent already initialized. Changes will take effect on next initialization.`)}getDisallowedTools(){return this.disallowedTools}setMetadata(e){let n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},t.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){let n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],t.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){let n={};for(let[r,i]of Object.entries(e)){if(typeof r!=`string`||r.length===0){t.warn(`Invalid metadata key: ${r}. Skipping.`);continue}let e=r.replace(/[^\w-]/g,`_`);if(i==null)n[e]=i;else if(typeof i==`string`||typeof i==`number`||typeof i==`boolean`)n[e]=i;else if(Array.isArray(i)){let t=i.filter(e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`);t.length>0&&(n[e]=t)}else if(typeof i==`object`)try{let r=JSON.stringify(i);r.length>1e3?(t.warn(`Metadata value for key '${e}' is too large. Truncating.`),n[e]=`${r.substring(0,1e3)}...`):n[e]=i}catch(n){t.warn(`Failed to serialize metadata value for key '${e}': ${n}. Skipping.`)}else t.warn(`Unsupported metadata value type for key '${e}': ${typeof i}. Skipping.`)}return n}sanitizeTags(e){return e.filter(e=>typeof e==`string`&&e.length>0).map(e=>e.replace(/[^\w:-]/g,`_`)).filter(e=>e.length<=50)}getMCPServerInfo(){let e={};try{if(this.client){let n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;let r={};for(let e of n)try{let t=this.client.getServerConfig(e);if(t){let n=`unknown`;t.command?n=`command`:t.url?n=`http`:t.ws_url&&(n=`websocket`),r[e]={type:n,has_args:!!t.args,has_env:!!t.env,has_headers:!!t.headers,url:t.url||null,command:t.command||null}}}catch(n){t.warn(`Failed to get config for server '${e}': ${n}`),r[e]={type:`error`,error:`config_unavailable`}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(e=>e.publicIdentifier),e.mcp_server_types=this.connectors.map(e=>e.constructor.name))}catch(n){t.warn(`Failed to collect MCP server info: ${n}`),e.error=`collection_failed`}return e}_normalizeOutput(e){try{if(typeof e==`string`)return e;if(e&&typeof e==`object`&&`content`in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){let t=[];for(let n of e)if(typeof n==`object`&&n)`text`in n&&typeof n.text==`string`?t.push(n.text):`content`in n?t.push(this._normalizeOutput(n.content)):t.push(String(n));else{let e=n&&typeof n==`object`&&`text`in n?n.text:null;if(typeof e==`string`)t.push(e);else{let e=n&&typeof n==`object`&&`content`in n?n.content:n;t.push(this._normalizeOutput(e))}}return t.join(``)}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof A)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{let e=t.getType();if(e===`ai`||e===`assistant`)return!0}catch{}if(typeof t._getType==`function`)try{let e=t._getType();if(e===`ai`||e===`assistant`)return!0}catch{}return`type`in t?t.type===`ai`||t.type===`assistant`:`role`in t?t.role===`ai`||t.role===`assistant`:!1}_messageHasToolCalls(e){return typeof e==`object`&&e&&`tool_calls`in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof j)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{let e=t.getType();if(e===`human`||e===`user`)return!0}catch{}return`type`in t&&(t.type===`human`||t.type===`user`)||`role`in t&&(t.role===`human`||t.role===`user`)}_isToolMessageLike(e){if(e instanceof g)return!0;if(typeof e!=`object`||!e)return!1;let t=e;if(typeof t.getType==`function`)try{if(t.getType()===`tool`)return!0}catch{}return`type`in t&&t.type===`tool`}_getMessageContent(e){if(e instanceof A||e&&typeof e==`object`&&`content`in e)return e.content}async _consumeAndReturn(e){for(;;){let{done:t,value:n}=await e.next();if(t)return n}}async run(e,t,n,r,i,a){let{query:o,maxSteps:s,manageConnector:c,externalHistory:l,outputSchema:u,signal:d}=vh(e,t,n,r,i,a);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(o,s,c,l,u);let f=this.stream(o,s,c,l,u,d);return this._consumeAndReturn(f)}async*stream(e,n,r=!0,i,a,o){let{query:s,maxSteps:c,manageConnector:l,externalHistory:u,outputSchema:d,signal:f}=vh(e,n,r,i,a,o);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(s,c,l,u,d);let p=!1,m=Date.now(),h=!1,g=null,_=0;try{if((l&&!this._initialized||!this._initialized&&this.autoInitialize)&&(await this.initialize(),p=!0),!this._agentExecutor)throw Error(`MCP agent failed to initialize`);if(this.useServerManager&&this.serverManager){let e=this.serverManager.tools,n=new Set(e.map(e=>e.name)),r=new Set(this._tools.map(e=>e.name));(n.size!==r.size||[...n].some(e=>!r.has(e)))&&(t.info(`\u{1F504} Tools changed before execution, updating agent. New tools: ${[...n].join(`, `)}`),this._tools=e,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}let e=u??this.conversationHistory,n=[];for(let t of e)(this._isHumanMessageLike(t)||this._isAIMessageLike(t)||this._isToolMessageLike(t))&&n.push(t);let r=s.length>50?`${s.slice(0,50).replace(/\n/g,` `)}...`:s.replace(/\n/g,` `);t.info(`\u{1F4AC} Received query: '${r}'`),t.info(`🏁 Starting agent execution`);let i=0,a=[...n,new j(s)];for(;i<=3;){let e={messages:a},n=!1,r=await this._agentExecutor.stream(e,{streamMode:`updates`,callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||`mcp-use-agent`,recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id},...f&&{signal:f}});for await(let e of r){if(f?.aborted)break;for(let[r,o]of Object.entries(e))if(t.debug(`\u{1F4E6} Node '${r}' output: ${JSON.stringify(o)}`),o&&typeof o==`object`&&`messages`in o){let e=o.messages;Array.isArray(e)||(e=[e]);for(let t of e)a.includes(t)||a.push(t);for(let r of e){if(`tool_calls`in r&&Array.isArray(r.tool_calls)&&r.tool_calls.length>0)for(let e of r.tool_calls){let n=e.name||`unknown`,r=e.args||{};this.toolsUsedNames.push(n),_++;let i=JSON.stringify(r);i.length>100&&(i=`${i.slice(0,97)}...`),t.info(`\u{1F527} Tool call: ${n} with input: ${i}`),yield{action:{tool:n,toolInput:r,log:`Calling tool ${n}`},observation:``}}if(this._isToolMessageLike(r)){let e=r.content,a=String(e);if(a.length>100&&(a=`${a.slice(0,97)}...`),a=a.replace(/\n/g,` `),t.info(`\u{1F4C4} Tool result: ${a}`),this.useServerManager&&this.serverManager){let e=this.serverManager.tools,r=new Set(e.map(e=>e.name)),a=new Set(this._tools.map(e=>e.name));if(r.size!==a.size||[...r].some(e=>!a.has(e))){t.info(`\u{1F504} Tools changed during execution. New tools: ${[...r].join(`, `)}`),this._tools=e,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),n=!0,i++,t.info(`\u{1F503} Restarting execution with updated tools (restart ${i}/3)`);break}}}this._isAIMessageLike(r)&&!this._messageHasToolCalls(r)&&(g=this._normalizeOutput(this._getMessageContent(r)),t.info(`✅ Agent finished with output`))}if(n)break}if(n)break}if(!n)break;if(i>3){t.warn(`⚠️ Max restarts (3) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){let e=a.slice(n.length);for(let t of e)this.addToHistory(t)}if(d&&g)try{t.info(`🔧 Attempting structured output...`);let e=await this._attemptStructuredOutput(g,this.llm,d);return this.memoryEnabled&&this.addToHistory(new A(`Structured result: ${JSON.stringify(e)}`)),t.info(`✅ Structured output successful`),h=!0,e}catch(e){throw t.error(`\u274C Structured output failed: ${e}`),Error(`Failed to generate structured output: ${e instanceof Error?e.message:String(e)}`)}return t.info(`\u{1F389} Agent execution complete in ${((Date.now()-m)/1e3).toFixed(2)} seconds`),h=!0,g||`No output generated`}catch(e){throw t.error(`\u274C Error running query: ${e}`),p&&l&&(t.info(`🧹 Cleaning up resources after error`),await this.close()),e}finally{let e=Date.now()-m,n=0;this.client?n=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(n=this.connectors.length);let r=this.memoryEnabled?this.conversationHistory.length:0,i=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:`stream`,query:s,success:h,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:n,serverIdentifiers:this.connectors.map(e=>e.publicIdentifier),totalToolsAvailable:i.length,toolsAvailableNames:i.map(e=>e.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:c??null,manageConnector:l??!0,externalHistoryUsed:u!==void 0,stepsTaken:_,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:g||``,executionTimeMs:e,errorType:h?null:`execution_error`,conversationHistoryLength:r}),l&&!this.client&&p&&(t.info(`🧹 Closing agent after stream completion`),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(t.debug(`Flushing observability traces...`),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}t.info(`🔌 Closing MCPAgent resources…`),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(t.info(`🔄 Closing internally-created client (simplified mode) and cleaning up resources`),await this.client.close(),this.sessions={},this.client=void 0):(t.info(`🔄 Closing client and cleaning up resources`),await this.client.close(),this.sessions={});else for(let e of this.connectors)t.info(`🔄 Disconnecting connector`),await e.disconnect();this.isSimplifiedMode&&this.llm&&(t.debug(`🔄 Clearing LLM reference (simplified mode)`),this.llm=void 0),`connectorToolMap`in this.adapter&&(this.adapter=new Um)}finally{this._initialized=!1,t.info(`👋 Agent closed successfully`)}}async*prettyStreamEvents(e,t,n=!0,r,i){let{prettyStreamEvents:a}=await p(async()=>{let{prettyStreamEvents:e}=await import(`./display-A5IEINAP-BFwsYEHq.js`);return{prettyStreamEvents:e}},__vite__mapDeps([13,3,5,2]));for await(let o of a(this.streamEvents(e,t,n,r,i)))yield;return``}async*streamEvents(e,n,r=!0,i,a,o){let s=vh(e,n,r,i,a,o),{query:c}=s,{maxSteps:l,manageConnector:u,externalHistory:d,outputSchema:f,signal:p}=s,m=!1,h=Date.now(),g=!1,_=0,v=0,y=``;f&&(c=this._enhanceQueryWithSchema(c,f));try{(u&&!this._initialized||!this._initialized&&this.autoInitialize)&&(await this.initialize(),m=!0);let e=this._agentExecutor;if(!e)throw Error(`MCP agent failed to initialize`);this.maxSteps=l??this.maxSteps;let n=typeof c==`string`&&c.length>50?`${c.slice(0,50).replace(/\n/g,` `)}...`:typeof c==`string`?c.replace(/\n/g,` `):String(c);t.info(`\u{1F4AC} Received query for streamEvents: '${n}'`),this.memoryEnabled&&(t.info(`\u{1F504} Adding user message to history: ${n}`),this.addToHistory(new j({content:c})));let r=d??this.conversationHistory,i=[];for(let e of r)this._isHumanMessageLike(e)||this._isAIMessageLike(e)||this._isToolMessageLike(e)?i.push(e):t.info(`\u26A0\uFE0F Skipped message of type: ${e.constructor?.name||typeof e}`);let a=[...i,new j(c)];t.info(`callbacks`,this.callbacks);let o=e.streamEvents({messages:a},{streamMode:`messages`,version:`v2`,callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||`mcp-use-agent`,recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id},...p&&{signal:p}});for await(let e of o){if(p?.aborted)break;if(_++,!(!e||typeof e!=`object`)){if(e.event===`on_chat_model_stream`&&e.data?.chunk?.content&&(v+=e.data.chunk.content.length),e.event===`on_chat_model_stream`&&e.data?.chunk){let n=e.data.chunk;if(n.content){y||=``;let e=this._normalizeOutput(n.content);y+=e,t.debug(`\u{1F4DD} Accumulated response length: ${y.length}`)}}if(yield e,e.event===`on_chain_end`&&e.data?.output&&!y){let t=e.data.output;Array.isArray(t)&&t.length>0&&t[0]?.text?y=t[0].text:typeof t==`string`?y=t:t&&typeof t==`object`&&`output`in t&&(y=t.output)}}}if(f&&y){t.info(`🔧 Attempting structured output conversion...`);try{let e=!1,n=null,r=null;this._attemptStructuredOutput(y,this.llm,f).then(t=>(e=!0,n=t,t)).catch(t=>{throw e=!0,r=t,t});let i=0;for(;!e;)await new Promise(e=>setTimeout(e,2e3)),e||(i++,yield{event:`on_structured_output_progress`,data:{message:`Converting to structured output... (${i*2}s)`,elapsed:i*2}});if(r)throw r;n&&(yield{event:`on_structured_output`,data:{output:n}},this.memoryEnabled&&this.addToHistory(new A(`Structured result: ${JSON.stringify(n)}`)),t.info(`✅ Structured output successful`))}catch(e){t.warn(`\u26A0\uFE0F Structured output failed: ${e}`),yield{event:`on_structured_output_error`,data:{error:e instanceof Error?e.message:String(e)}}}}else this.memoryEnabled&&y&&this.addToHistory(new A(y));console.log(`
|
|
344
344
|
|
|
345
345
|
`),t.info(`\u{1F389} StreamEvents complete - ${_} events emitted`),g=!0}catch(e){throw t.error(`\u274C Error during streamEvents: ${e}`),m&&u&&(t.info(`🧹 Cleaning up resources after initialization error in streamEvents`),await this.close()),e}finally{let e=Date.now()-h,n=0;this.client?n=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(n=this.connectors.length);let r=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:`streamEvents`,query:c,success:g,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:n,serverIdentifiers:this.connectors.map(e=>e.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(e=>e.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:l??null,manageConnector:u??!0,externalHistoryUsed:d!==void 0,response:`[STREAMED RESPONSE - ${v} chars]`,executionTimeMs:e,errorType:g?null:`streaming_error`,conversationHistoryLength:r}),u&&!this.client&&m&&(t.info(`🧹 Closing agent after streamEvents completion`),await this.close())}}async _attemptStructuredOutput(e,n,i){t.info(`\u{1F504} Attempting structured output with schema: ${JSON.stringify(i,null,2)}`),t.info(`\u{1F504} Raw result: ${JSON.stringify(e,null,2)}`);let a=null,o=``;if(t.debug(`\u{1F504} Structured output requested, schema: ${JSON.stringify(r(i),null,2)}`),n&&`withStructuredOutput`in n&&typeof n.withStructuredOutput==`function`)a=n.withStructuredOutput(i);else if(n)a=n;else throw Error(`LLM is required for structured output`);let{$schema:s,additionalProperties:c,...l}=r(i);o=JSON.stringify(l,null,2),t.info(`\u{1F504} Schema description: ${o}`);let u=``;typeof e==`string`?u=e:e&&typeof e==`object`&&(u=JSON.stringify(e)),t.info(`rawResult`,e),u||=JSON.stringify(e);let d=``;for(let e=1;e<=3;e++){t.info(`\u{1F504} Structured output attempt ${e}/3`);let n=`
|
|
346
346
|
Please format the following information according to the EXACT schema specified below.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./chunk-3GQAWCBQ-C-9Cm0Np.js";import{_ as t,a as n,b as r,i,m as a,o,p as s,s as c,v as l}from"./schemas-79owEkeD.js";import{f as u}from"./chunk-
|
|
1
|
+
import{t as e}from"./chunk-3GQAWCBQ-C-9Cm0Np.js";import{_ as t,a as n,b as r,i,m as a,o,p as s,s as c,v as l}from"./schemas-79owEkeD.js";import{f as u}from"./chunk-UY6K7YNZ-CwjjzrEf.js";var d=class{static{e(this,`JSONSchemaToZod`)}static convert(e){return this.parseSchema(e)}static matchesCondition(e,t){if(!t.properties)return!0;if(typeof e!=`object`||!e||Array.isArray(e))return!1;let n=e;for(let[e,r]of Object.entries(t.properties)){if(!(e in n)){if(`const`in r)return!1;continue}let t=n[e];if(`const`in r&&t!==r.const||`minimum`in r&&typeof t==`number`&&t<r.minimum||`maximum`in r&&typeof t==`number`&&t>r.maximum)return!1}return!0}static validateConditionalSchema(e,t,n){this.validateRequiredProperties(e,t,n),this.validatePropertyPatterns(e,t,n),this.validateNestedConditions(e,t,n)}static validateRequiredProperties(e,t,n){if(t.required){if(typeof e!=`object`||!e){for(let e of t.required)n.addIssue({code:u.custom,message:`Required property '${e}' is missing`,path:[e]});return}for(let r of t.required)r in e||n.addIssue({code:u.custom,message:`Required property '${r}' is missing`,path:[r]})}}static validatePropertyPatterns(e,t,n){if(!t.properties||typeof e!=`object`||!e||Array.isArray(e))return;let r=e;for(let[e,i]of Object.entries(t.properties)){if(!(e in r))continue;let t=r[e];i.pattern&&typeof t==`string`&&(new RegExp(i.pattern).test(t)||n.addIssue({code:u.custom,message:`String '${t}' does not match pattern '${i.pattern}'`,path:[e]}))}}static validateNestedConditions(e,t,n){!t.if||!t.then||(this.matchesCondition(e,t.if)?this.validateConditionalSchema(e,t.then,n):t.else&&this.validateConditionalSchema(e,t.else,n))}static parseSchema(e){let t;return t=Array.isArray(e.type)?this.handleTypeArray(e):e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.if&&e.then||e.properties&&(!e.type||e.type===`object`)?this.parseObject(e):this.handleSingleType(e),e.description&&typeof t.describe==`function`&&(t=t.describe(e.description)),t}static handleTypeArray(e){if(!Array.isArray(e.type))throw Error(`Expected schema.type to be an array`);return e.type.includes(`null`)?this.handleNullableType(e):this.createUnionFromTypes(e.type,e)}static handleNullableType(e){if(!Array.isArray(e.type))throw Error(`Expected schema.type to be an array`);let t={...e};return t.type=e.type.filter(e=>e!==`null`),t.type.length===1?this.handleSingleType({...e,type:t.type[0]}).nullable():this.parseSchema(t).nullable()}static createUnionFromTypes(e,t){return r(e.map(e=>{let n={...t,type:e};return this.parseSchema(n)}))}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):n();switch(e.type){case`string`:return this.parseString(e);case`number`:case`integer`:return this.parseNumberSchema(e);case`boolean`:return c();case`array`:return this.parseArray(e);case`object`:return this.parseObject(e);default:throw Error(`Unsupported schema type`)}}static parseNumberSchema(e){let t=s(),n=t;return n=this.applyNumberBounds(t,e),n=this.applyNumberMultipleOf(t,e),n=this.applyNumberEnum(t,e),n=this.applyIntegerConstraint(t,e),n}static applyNumberBounds(e,t){let n=e;return t.minimum!==void 0&&(n=t.exclusiveMinimum?n.gt(t.minimum):n.gte(t.minimum)),t.maximum!==void 0&&(n=t.exclusiveMaximum?n.lt(t.maximum):n.lte(t.maximum)),n}static applyNumberMultipleOf(e,t){return t.multipleOf===void 0?e:e.refine(e=>e%t.multipleOf===0,{message:`Number must be a multiple of ${t.multipleOf}`})}static applyNumberEnum(e,t){if(!t.enum)return e;let n=t.enum.filter(e=>typeof e==`number`);return n.length===0?e:e.refine(e=>n.includes(e),{message:`Number must be one of: ${n.join(`, `)}`})}static applyIntegerConstraint(e,t){return t.type===`integer`?e.refine(e=>Number.isInteger(e),{message:`Number must be an integer`}):e}static parseString(e){let t=l(),n=t;return e.format?this.applyStringFormat(t,e):(n=this.applyStringPattern(t,e),n=this.applyStringLength(t,e),n=this.applyStringEnum(t,e),n)}static applyStringFormat(e,t){if(!t.format)return e;switch(t.format){case`email`:return e.email();case`date-time`:return e.datetime();case`uri`:return e.url();case`uuid`:return e.uuid();case`date`:return e.date();default:return e}}static applyStringPattern(e,t){if(!t.pattern)return e;let n=new RegExp(t.pattern);return e.regex(n,{message:`String must match pattern: ${t.pattern}`})}static applyStringLength(e,t){let n=e;return t.minLength!==void 0&&(e=e.min(t.minLength)),t.maxLength!==void 0&&(e=e.max(t.maxLength)),n}static applyStringEnum(e,t){return t.enum?e.refine(e=>t.enum?.includes(e),{message:`Value must be one of: ${t.enum?.join(`, `)}`}):e}static parseArray(e){if(Array.isArray(e.items))return r(e.items.map(e=>this.parseSchema(e)));let t=o(e.items?this.parseSchema(e.items):n()),i=t;return i=this.applyArrayConstraints(t,e),i}static applyArrayConstraints(e,t){return t.minItems!==void 0&&(e=e.min(t.minItems)),t.maxItems!==void 0&&(e=e.max(t.maxItems)),t.uniqueItems?e.refine(e=>new Set(e).size===e.length,{message:`Array items must be unique`}):e}static parseObject(e){if(e.if&&e.then)return this.parseConditional(e);if(!e.properties&&e.additionalProperties&&typeof e.additionalProperties==`object`){let n=this.parseSchema(e.additionalProperties);return t(l(),n)}let n={};return this.processObjectProperties(e,n),this.processAdditionalProperties(e,a(n))}static processObjectProperties(e,t){let n=new Set(e.required||[]);if(e.properties)for(let[r,i]of Object.entries(e.properties)){let e=this.parseSchema(i);t[r]=n.has(r)?e:e.optional()}}static processAdditionalProperties(e,t){if(e.additionalProperties===!0)return t.passthrough();if(e.additionalProperties&&typeof e.additionalProperties==`object`){let n=this.parseSchema(e.additionalProperties);return t.catchall(n)}else return t.strict()}static parseConditional(e){let t=this.createBaseObjectSchema(e),n=e.if,r=e.then,i=e.else;return t.superRefine((t,a)=>{let o=this.applyDefaultValues(t,e);this.matchesCondition(o,n)?this.validateConditionalSchema(o,r,a):i&&this.validateConditionalSchema(o,i,a)})}static createBaseObjectSchema(e){let t={},n=new Set(e.required||[]);for(let[r,i]of Object.entries(e.properties||{})){let e=this.parseSchema(i);t[r]=n.has(r)?e:e.optional()}let r=a(t);return this.processAdditionalProperties(e,r)}static applyDefaultValues(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return e;let n={...e};if(!t.properties)return n;for(let[e,r]of Object.entries(t.properties))!(e in n)&&`default`in r&&(n[e]=r.default);return n}static parseCombinator(e){if(e.oneOf)return this.parseOneOf(e.oneOf);if(e.anyOf)return this.parseAnyOf(e.anyOf);if(e.allOf)return this.parseAllOf(e.allOf);throw Error(`Unsupported schema type`)}static parseOneOf(e){return this.createUnionFromSchemas(e)}static parseAnyOf(e){return this.createUnionFromSchemas(e)}static createUnionFromSchemas(e){if(e.length===0)return n();if(e.length===1)return this.parseSchema(e[0]);let t=[];for(let n of e)n.type===`null`?t.push(i()):t.push(this.parseSchema(n));return t.length>=2?r(t):t.length===1?t[0]:n()}static parseAllOf(e){if(e.length===0)return n();if(e.length===1)return this.parseSchema(e[0]);let t=e.reduce((e,t)=>this.mergeSchemas(e,t));return this.parseSchema(t)}static mergeSchemas(e,t){let n={...e,...t};return e.properties&&t.properties&&(n.properties={...e.properties,...t.properties}),e.required&&t.required&&(n.required=[...new Set([...e.required,...t.required])]),n}};export{d as t};
|