@mcp-use/inspector 0.14.0-canary.2 → 0.14.0-canary.4
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/client/assets/browser-uRJo_zTC.js +410 -0
- package/dist/client/assets/client-BHYVJu1d.js +92 -0
- package/dist/client/assets/display-A5IEINAP-DKUWUNBn.js +17 -0
- package/dist/client/assets/embeddings-Ca9Fjpq2.js +1 -0
- package/dist/client/assets/{base-RWAdy9P6.js → index-B1qQRxi5.js} +36 -33
- package/dist/client/assets/{index-DIa0UgbZ.js → index-BBou2aqe.js} +1 -1
- package/dist/client/assets/index-BDK3gn1J.css +1 -0
- package/dist/client/assets/{index-Apq2pBJl.js → index-BQjnvhrs.js} +2 -2
- package/dist/client/assets/index-BZHB-ddK.js +7 -0
- package/dist/client/assets/index-C5QQlaZ8.js +33 -0
- package/dist/client/assets/index-CaDJlO5J.js +71 -0
- package/dist/client/assets/index-CsZJl8OY.js +20 -0
- package/dist/client/assets/{index-DXrgZUfu.js → index-D6FUhbcc.js} +10 -10
- package/dist/client/assets/index-D6q56P_Q.js +1701 -0
- package/dist/client/assets/index-JiKw9JSs.js +5 -0
- package/dist/client/assets/llms-B_guC4Z-.js +2 -0
- package/dist/client/assets/util-QmrWvrtn.js +1 -0
- package/dist/client/index.html +3 -3
- package/package.json +2 -2
- package/dist/client/assets/base-Bnm339-a.js +0 -2
- package/dist/client/assets/browser-9kmymM9X.js +0 -12
- package/dist/client/assets/embeddings-C7cRBw1j.js +0 -1
- package/dist/client/assets/index-BsLLCsBP.js +0 -1701
- package/dist/client/assets/index-C2UfjD9L.js +0 -4
- package/dist/client/assets/index-C69r9Nt9.js +0 -34
- package/dist/client/assets/index-CtpnfKmY.js +0 -7
- package/dist/client/assets/index-DKR-Owed.js +0 -70
- package/dist/client/assets/index-cMXsdFDY.css +0 -1
- package/dist/client/assets/transport-wrapper-browser-BI4dDu3b.js +0 -1
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const v=(t=0)=>e=>`\x1B[${e+t}m`,A=(t=0)=>e=>`\x1B[${38+t};5;${e}m`,O=(t=0)=>(e,r,o)=>`\x1B[${38+t};2;${e};${r};${o}m`,l={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},G=Object.keys(l.modifier),M=Object.keys(l.color),N=Object.keys(l.bgColor),$=[...M,...N];function x(){const t=new Map;for(const[e,r]of Object.entries(l)){for(const[o,n]of Object.entries(r))l[o]={open:`\x1B[${n[0]}m`,close:`\x1B[${n[1]}m`},r[o]=l[o],t.set(n[0],n[1]);Object.defineProperty(l,e,{value:r,enumerable:!1})}return Object.defineProperty(l,"codes",{value:t,enumerable:!1}),l.color.close="\x1B[39m",l.bgColor.close="\x1B[49m",l.color.ansi=v(),l.color.ansi256=A(),l.color.ansi16m=O(),l.bgColor.ansi=v(10),l.bgColor.ansi256=A(10),l.bgColor.ansi16m=O(10),Object.defineProperties(l,{rgbToAnsi256:{value(e,r,o){return e===r&&r===o?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(o/255*5)},enumerable:!1},hexToRgb:{value(e){const r=/[a-f\d]{6}|[a-f\d]{3}/i.exec(e.toString(16));if(!r)return[0,0,0];let[o]=r;o.length===3&&(o=[...o].map(s=>s+s).join(""));const n=Number.parseInt(o,16);return[n>>16&255,n>>8&255,n&255]},enumerable:!1},hexToAnsi256:{value:e=>l.rgbToAnsi256(...l.hexToRgb(e)),enumerable:!1},ansi256ToAnsi:{value(e){if(e<8)return 30+e;if(e<16)return 90+(e-8);let r,o,n;if(e>=232)r=((e-232)*10+8)/255,o=r,n=r;else{e-=16;const y=e%36;r=Math.floor(e/36)/5,o=Math.floor(y/6)/5,n=y%6/5}const s=Math.max(r,o,n)*2;if(s===0)return 30;let a=30+(Math.round(n)<<2|Math.round(o)<<1|Math.round(r));return s===2&&(a+=60),a},enumerable:!1},rgbToAnsi:{value:(e,r,o)=>l.ansi256ToAnsi(l.rgbToAnsi256(e,r,o)),enumerable:!1},hexToAnsi:{value:e=>l.ansi256ToAnsi(l.hexToAnsi256(e)),enumerable:!1}}),l}const i=x(),f=(()=>{if(!("navigator"in globalThis))return 0;if(globalThis.navigator.userAgentData){const t=navigator.userAgentData.brands.find(({brand:e})=>e==="Chromium");if(t&&t.version>93)return 3}return/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)?1:0})(),B=f!==0&&{level:f,hasBasic:!0,has256:f>=2,has16m:f>=3},F={stdout:B,stderr:B};function R(t,e,r){let o=t.indexOf(e);if(o===-1)return t;const n=e.length;let s=0,a="";do a+=t.slice(s,o)+e+r,s=o+n,o=t.indexOf(e,s);while(o!==-1);return a+=t.slice(s),a}function k(t,e,r,o){let n=0,s="";do{const a=t[o-1]==="\r";s+=t.slice(n,a?o-1:o)+e+(a?`\r
|
|
2
|
+
`:`
|
|
3
|
+
`)+r,n=o+1,o=t.indexOf(`
|
|
4
|
+
`,n)}while(o!==-1);return s+=t.slice(n),s}const{stdout:C,stderr:T}=F,d=Symbol("GENERATOR"),c=Symbol("STYLER"),b=Symbol("IS_EMPTY"),S=["ansi","ansi","ansi256","ansi16m"],u=Object.create(null),w=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error("The `level` option should be an integer from 0 to 3");const r=C?C.level:0;t.level=e.level===void 0?r:e.level};class D{constructor(e){return j(e)}}const j=t=>{const e=(...r)=>r.join(" ");return w(e,t),Object.setPrototypeOf(e,h.prototype),e};function h(t){return j(t)}Object.setPrototypeOf(h.prototype,Function.prototype);for(const[t,e]of Object.entries(i))u[t]={get(){const r=g(this,p(e.open,e.close,this[c]),this[b]);return Object.defineProperty(this,t,{value:r}),r}};u.visible={get(){const t=g(this,this[c],!0);return Object.defineProperty(this,"visible",{value:t}),t}};const m=(t,e,r,...o)=>t==="rgb"?e==="ansi16m"?i[r].ansi16m(...o):e==="ansi256"?i[r].ansi256(i.rgbToAnsi256(...o)):i[r].ansi(i.rgbToAnsi(...o)):t==="hex"?m("rgb",e,r,...i.hexToRgb(...o)):i[r][t](...o),E=["rgb","hex","ansi256"];for(const t of E){u[t]={get(){const{level:r}=this;return function(...o){const n=p(m(t,S[r],"color",...o),i.color.close,this[c]);return g(this,n,this[b])}}};const e="bg"+t[0].toUpperCase()+t.slice(1);u[e]={get(){const{level:r}=this;return function(...o){const n=p(m(t,S[r],"bgColor",...o),i.bgColor.close,this[c]);return g(this,n,this[b])}}}}const I=Object.defineProperties(()=>{},{...u,level:{enumerable:!0,get(){return this[d].level},set(t){this[d].level=t}}}),p=(t,e,r)=>{let o,n;return r===void 0?(o=t,n=e):(o=r.openAll+t,n=e+r.closeAll),{open:t,close:e,openAll:o,closeAll:n,parent:r}},g=(t,e,r)=>{const o=(...n)=>P(o,n.length===1?""+n[0]:n.join(" "));return Object.setPrototypeOf(o,I),o[d]=t,o[c]=e,o[b]=r,o},P=(t,e)=>{if(t.level<=0||!e)return t[b]?"":e;let r=t[c];if(r===void 0)return e;const{openAll:o,closeAll:n}=r;if(e.includes("\x1B"))for(;r!==void 0;)e=R(e,r.close,r.open),r=r.parent;const s=e.indexOf(`
|
|
5
|
+
`);return s!==-1&&(e=k(e,n,o,s)),o+e+n};Object.defineProperties(h.prototype,u);const Y=h(),L=h({level:T?T.level:0});export{D as Chalk,N as backgroundColorNames,N as backgroundColors,L as chalkStderr,$ as colorNames,$ as colors,Y as default,M as foregroundColorNames,M as foregroundColors,G as modifierNames,G as modifiers,C as supportsColor,T as supportsColorStderr};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{r as O,t as M,u as R,g as b,C as L,G as N,w as x,x as J,R as P}from"./index-B1qQRxi5.js";import{O as k,d as E,e as T}from"./index-CaDJlO5J.js";function C(n,e){if(n.function===void 0)return;let t;if(e?.partial)try{t=R(n.function.arguments??"{}")}catch{return}else try{t=JSON.parse(n.function.arguments)}catch(r){throw new k([`Function "${n.function.name}" arguments:`,"",n.function.arguments,"","are not valid JSON.",`Error: ${r.message}`].join(`
|
|
2
|
+
`))}const s={name:n.function.name,args:t,type:"tool_call"};return e?.returnId&&(s.id=n.id),s}function z(n){if(n.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.args)}}}function A(n,e){return{name:n.function?.name,args:n.function?.arguments,id:n.id,error:e,type:"invalid_tool_call"}}var S=class extends E{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(n){super(n),this.returnId=n?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(n){return await this.parsePartialResult(n,!1)}async parsePartialResult(n,e=!0){const t=n[0].message;let s;if(M(t)&&t.tool_calls?.length?s=t.tool_calls.map(a=>{const{id:l,...u}=a;return this.returnId?{id:l,...u}:u}):t.additional_kwargs.tool_calls!==void 0&&(s=JSON.parse(JSON.stringify(t.additional_kwargs.tool_calls)).map(l=>C(l,{returnId:this.returnId,partial:e}))),!s)return[];const r=[];for(const a of s)if(a!==void 0){const l={type:a.name,args:a.args,id:a.id};r.push(l)}return r}},F=class extends S{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(n){super(n),this.keyName=n.keyName,this.returnSingle=n.returnSingle??this.returnSingle,this.zodSchema=n.zodSchema}async _validateResult(n){if(this.zodSchema===void 0)return n;const e=await O(this.zodSchema,n);if(e.success)return e.data;throw new k(`Failed to parse. Text: "${JSON.stringify(n,null,2)}". Error: ${JSON.stringify(e.error?.issues)}`,JSON.stringify(n,null,2))}async parsePartialResult(n){const t=(await super.parsePartialResult(n)).filter(r=>r.type===this.keyName);let s=t;if(t.length)return this.returnId||(s=t.map(r=>r.args)),this.returnSingle?s[0]:s}async parseResult(n){const t=(await super.parsePartialResult(n,!1)).filter(a=>a.type===this.keyName);let s=t;return t.length?(this.returnId||(s=t.map(a=>a.args)),this.returnSingle?this._validateResult(s[0]):await Promise.all(s.map(a=>this._validateResult(a)))):void 0}},K={};b(K,{JsonOutputKeyToolsParser:()=>F,JsonOutputToolsParser:()=>S,convertLangChainToolCallToOpenAI:()=>z,makeInvalidToolCall:()=>A,parseToolCall:()=>C});var U={};b(U,{BaseLLM:()=>I,LLM:()=>j});var I=class f extends T{lc_namespace=["langchain","llms",this._llmType()];async invoke(e,t){const s=f._convertInputToPromptValue(e);return(await this.generatePrompt([s],t,t?.callbacks)).generations[0][0].text}async*_streamResponseChunks(e,t,s){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(e){const[t,s]=super._separateRunnableConfigFromCallOptions(e);return s.signal=t.signal,[t,s]}async*_streamIterator(e,t){if(this._streamResponseChunks===f.prototype._streamResponseChunks)yield this.invoke(e,t);else{const s=f._convertInputToPromptValue(e),[r,a]=this._separateRunnableConfigFromCallOptionsCompat(t),l=await L.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),u={options:a,invocation_params:this?.invocationParams(a),batch_size:1},h=await l?.handleLLMStart(this.toJSON(),[s.toString()],r.runId,void 0,u,void 0,void 0,r.runName);let o=new N({text:""});try{for await(const i of this._streamResponseChunks(s.toString(),a,h?.[0]))o?o=o.concat(i):o=i,typeof i.text=="string"&&(yield i.text)}catch(i){throw await Promise.all((h??[]).map(d=>d?.handleLLMError(i))),i}await Promise.all((h??[]).map(i=>i?.handleLLMEnd({generations:[[o]]})))}}async generatePrompt(e,t,s){const r=e.map(a=>a.toString());return this.generate(r,t,s)}invocationParams(e){return{}}_flattenLLMResult(e){const t=[];for(let s=0;s<e.generations.length;s+=1){const r=e.generations[s];if(s===0)t.push({generations:[r],llmOutput:e.llmOutput});else{const a=e.llmOutput?{...e.llmOutput,tokenUsage:{}}:void 0;t.push({generations:[r],llmOutput:a})}}return t}async _generateUncached(e,t,s,r){let a;if(r!==void 0&&r.length===e.length)a=r;else{const o=await L.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),i={options:t,invocation_params:this?.invocationParams(t),batch_size:e.length};a=await o?.handleLLMStart(this.toJSON(),e,s.runId,void 0,i,void 0,void 0,s?.runName)}const l=!!a?.[0].handlers.find(x);let u;if(l&&e.length===1&&this._streamResponseChunks!==f.prototype._streamResponseChunks)try{const o=await this._streamResponseChunks(e[0],t,a?.[0]);let i;for await(const d of o)i===void 0?i=d:i=J(i,d);if(i===void 0)throw new Error("Received empty response from chat model call.");u={generations:[[i]],llmOutput:{}},await a?.[0].handleLLMEnd(u)}catch(o){throw await a?.[0].handleLLMError(o),o}else{try{u=await this._generate(e,t,a?.[0])}catch(i){throw await Promise.all((a??[]).map(d=>d?.handleLLMError(i))),i}const o=this._flattenLLMResult(u);await Promise.all((a??[]).map((i,d)=>i?.handleLLMEnd(o[d])))}const h=a?.map(o=>o.runId)||void 0;return Object.defineProperty(u,P,{value:h?{runIds:h}:void 0,configurable:!0}),u}async _generateCached({prompts:e,cache:t,llmStringKey:s,parsedOptions:r,handledOptions:a,runId:l}){const u=await L.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),h={options:r,invocation_params:this?.invocationParams(r),batch_size:e.length},o=await u?.handleLLMStart(this.toJSON(),e,l,void 0,h,void 0,void 0,a?.runName),i=[],v=(await Promise.allSettled(e.map(async(c,m)=>{const _=await t.lookup(c,s);return _==null&&i.push(m),_}))).map((c,m)=>({result:c,runManager:o?.[m]})).filter(({result:c})=>c.status==="fulfilled"&&c.value!=null||c.status==="rejected"),p=[];await Promise.all(v.map(async({result:c,runManager:m},_)=>{if(c.status==="fulfilled"){const y=c.value;return p[_]=y.map(w=>(w.generationInfo={...w.generationInfo,tokenUsage:{}},w)),y.length&&await m?.handleLLMNewToken(y[0].text),m?.handleLLMEnd({generations:[y]},void 0,void 0,void 0,{cached:!0})}else return await m?.handleLLMError(c.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(c.reason)}));const g={generations:p,missingPromptIndices:i,startedRunManagers:o};return Object.defineProperty(g,P,{value:o?{runIds:o?.map(c=>c.runId)}:void 0,configurable:!0}),g}async generate(e,t,s){if(!Array.isArray(e))throw new Error("Argument 'prompts' is expected to be a string[]");let r;Array.isArray(t)?r={stop:t}:r=t;const[a,l]=this._separateRunnableConfigFromCallOptionsCompat(r);if(a.callbacks=a.callbacks??s,!this.cache)return this._generateUncached(e,l,a);const{cache:u}=this,h=this._getSerializedCacheKeyParametersForCall(l),{generations:o,missingPromptIndices:i,startedRunManagers:d}=await this._generateCached({prompts:e,cache:u,llmStringKey:h,parsedOptions:l,handledOptions:a,runId:a.runId});let v={};if(i.length>0){const p=await this._generateUncached(i.map(g=>e[g]),l,a,d!==void 0?i.map(g=>d?.[g]):void 0);await Promise.all(p.generations.map(async(g,c)=>{const m=i[c];return o[m]=g,u.update(e[m],h,g)})),v=p.llmOutput??{}}return{generations:o,llmOutput:v}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},j=class extends I{async _generate(n,e,t){return{generations:await Promise.all(n.map((r,a)=>this._call(r,{...e,promptIndex:a},t).then(l=>[{text:l}])))}}};export{F as J,j as L,z as c,U as l,A as m,K as o,C as p};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function t(){return()=>{}}function i(n){return JSON.stringify(n)}function u(){}function o(){}const r={debuglog:t,inspect:i,inherits:u,format:o};export{t as debuglog,r as default,o as format,u as inherits,i as inspect};
|
package/dist/client/index.html
CHANGED
|
@@ -27,9 +27,9 @@
|
|
|
27
27
|
rel="stylesheet"
|
|
28
28
|
/>
|
|
29
29
|
<title>Inspector | mcp-use</title>
|
|
30
|
-
<script type="module" crossorigin src="/inspector/assets/index-
|
|
31
|
-
<link rel="stylesheet" crossorigin href="/inspector/assets/index-
|
|
32
|
-
<script>window.__INSPECTOR_VERSION__ = "0.14.0-canary.
|
|
30
|
+
<script type="module" crossorigin src="/inspector/assets/index-D6q56P_Q.js"></script>
|
|
31
|
+
<link rel="stylesheet" crossorigin href="/inspector/assets/index-BDK3gn1J.css">
|
|
32
|
+
<script>window.__INSPECTOR_VERSION__ = "0.14.0-canary.4";</script>
|
|
33
33
|
</head>
|
|
34
34
|
<body>
|
|
35
35
|
<script>
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mcp-use/inspector",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.14.0-canary.
|
|
4
|
+
"version": "0.14.0-canary.4",
|
|
5
5
|
"description": "MCP Inspector - A tool for inspecting and debugging MCP servers",
|
|
6
6
|
"author": "",
|
|
7
7
|
"license": "MIT",
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
"sonner": "^2.0.7",
|
|
87
87
|
"tailwind-merge": "^3.4.0",
|
|
88
88
|
"vite-express": "^0.21.1",
|
|
89
|
-
"mcp-use": "1.12.0-canary.
|
|
89
|
+
"mcp-use": "1.12.0-canary.4"
|
|
90
90
|
},
|
|
91
91
|
"publishConfig": {
|
|
92
92
|
"access": "public"
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{i as G,av as P,G as U,ad as X,aw as Y,_ as C,O as Z,q as L,ai as Q}from"./base-RWAdy9P6.js";import{g as ee}from"./index-BsLLCsBP.js";function te(e){return e!==void 0&&Array.isArray(e.lc_namespace)}function se(e){return e!==void 0&&P.isRunnable(e)&&"lc_name"in e.constructor&&typeof e.constructor.lc_name=="function"&&e.constructor.lc_name()==="RunnableToolLike"}function ae(e){return!!e&&typeof e=="object"&&"name"in e&&"schema"in e&&(G(e.schema)||e.schema!=null&&typeof e.schema=="object"&&"type"in e.schema&&typeof e.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(e.schema.type))}function Re(e){return ae(e)||se(e)||te(e)}var re={};C(re,{BasePromptValue:()=>M,ChatPromptValue:()=>V,ImagePromptValue:()=>ie,StringPromptValue:()=>O});var M=class extends Y{},O=class extends M{static lc_name(){return"StringPromptValue"}lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;value;constructor(e){super({value:e}),this.value=e}toString(){return this.value}toChatMessages(){return[new U(this.value)]}},V=class extends M{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ChatPromptValue"}messages;constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),this.messages=e.messages}toString(){return X(this.messages)}toChatMessages(){return this.messages}},ie=class extends M{lc_namespace=["langchain_core","prompt_values"];lc_serializable=!0;static lc_name(){return"ImagePromptValue"}imageUrl;value;constructor(e){"imageUrl"in e||(e={imageUrl:e}),super(e),this.imageUrl=e.imageUrl}toString(){return this.imageUrl.url}toChatMessages(){return[new U({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}},o="0123456789abcdef".split(""),ne=[-2147483648,8388608,32768,128],_=[24,16,8,0],E=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],m=[];function A(e,t){t?(m[0]=m[16]=m[1]=m[2]=m[3]=m[4]=m[5]=m[6]=m[7]=m[8]=m[9]=m[10]=m[11]=m[12]=m[13]=m[14]=m[15]=0,this.blocks=m):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],e?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=e}A.prototype.update=function(e){if(!this.finalized){var t,r=typeof e;if(r!=="string"){if(r==="object"){if(e===null)throw new Error(ERROR);if(ARRAY_BUFFER&&e.constructor===ArrayBuffer)e=new Uint8Array(e);else if(!Array.isArray(e)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(e)))throw new Error(ERROR)}else throw new Error(ERROR);t=!0}for(var s,i=0,a,h=e.length,n=this.blocks;i<h;){if(this.hashed&&(this.hashed=!1,n[0]=this.block,this.block=n[16]=n[1]=n[2]=n[3]=n[4]=n[5]=n[6]=n[7]=n[8]=n[9]=n[10]=n[11]=n[12]=n[13]=n[14]=n[15]=0),t)for(a=this.start;i<h&&a<64;++i)n[a>>>2]|=e[i]<<_[a++&3];else for(a=this.start;i<h&&a<64;++i)s=e.charCodeAt(i),s<128?n[a>>>2]|=s<<_[a++&3]:s<2048?(n[a>>>2]|=(192|s>>>6)<<_[a++&3],n[a>>>2]|=(128|s&63)<<_[a++&3]):s<55296||s>=57344?(n[a>>>2]|=(224|s>>>12)<<_[a++&3],n[a>>>2]|=(128|s>>>6&63)<<_[a++&3],n[a>>>2]|=(128|s&63)<<_[a++&3]):(s=65536+((s&1023)<<10|e.charCodeAt(++i)&1023),n[a>>>2]|=(240|s>>>18)<<_[a++&3],n[a>>>2]|=(128|s>>>12&63)<<_[a++&3],n[a>>>2]|=(128|s>>>6&63)<<_[a++&3],n[a>>>2]|=(128|s&63)<<_[a++&3]);this.lastByteIndex=a,this.bytes+=a-this.start,a>=64?(this.block=n[16],this.start=a-64,this.hash(),this.hashed=!0):this.start=a}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};A.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var e=this.blocks,t=this.lastByteIndex;e[16]=this.block,e[t>>>2]|=ne[t&3],this.block=e[16],t>=56&&(this.hashed||this.hash(),e[0]=this.block,e[16]=e[1]=e[2]=e[3]=e[4]=e[5]=e[6]=e[7]=e[8]=e[9]=e[10]=e[11]=e[12]=e[13]=e[14]=e[15]=0),e[14]=this.hBytes<<3|this.bytes>>>29,e[15]=this.bytes<<3,this.hash()}};A.prototype.hash=function(){var e=this.h0,t=this.h1,r=this.h2,s=this.h3,i=this.h4,a=this.h5,h=this.h6,n=this.h7,g=this.blocks,u,b,x,k,c,l,p,d,y,f,v;for(u=16;u<64;++u)c=g[u-15],b=(c>>>7|c<<25)^(c>>>18|c<<14)^c>>>3,c=g[u-2],x=(c>>>17|c<<15)^(c>>>19|c<<13)^c>>>10,g[u]=g[u-16]+b+g[u-7]+x<<0;for(v=t&r,u=0;u<64;u+=4)this.first?(this.is224?(d=300032,c=g[0]-1413257819,n=c-150054599<<0,s=c+24177077<<0):(d=704751109,c=g[0]-210244248,n=c-1521486534<<0,s=c+143694565<<0),this.first=!1):(b=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),x=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),d=e&t,k=d^e&r^v,p=i&a^~i&h,c=n+x+p+E[u]+g[u],l=b+k,n=s+c<<0,s=c+l<<0),b=(s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10),x=(n>>>6|n<<26)^(n>>>11|n<<21)^(n>>>25|n<<7),y=s&e,k=y^s&t^d,p=h&n^~h&i,c=a+x+p+E[u+1]+g[u+1],l=b+k,h=r+c<<0,r=c+l<<0,b=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),x=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),f=r&s,k=f^r&e^y,p=a&h^~a&n,c=i+x+p+E[u+2]+g[u+2],l=b+k,a=t+c<<0,t=c+l<<0,b=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),x=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),v=t&r,k=v^t&s^f,p=a&h^~a&n,c=i+x+p+E[u+3]+g[u+3],l=b+k,i=e+c<<0,e=c+l<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+e<<0,this.h1=this.h1+t<<0,this.h2=this.h2+r<<0,this.h3=this.h3+s<<0,this.h4=this.h4+i<<0,this.h5=this.h5+a<<0,this.h6=this.h6+h<<0,this.h7=this.h7+n<<0};A.prototype.hex=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,s=this.h3,i=this.h4,a=this.h5,h=this.h6,n=this.h7,g=o[e>>>28&15]+o[e>>>24&15]+o[e>>>20&15]+o[e>>>16&15]+o[e>>>12&15]+o[e>>>8&15]+o[e>>>4&15]+o[e&15]+o[t>>>28&15]+o[t>>>24&15]+o[t>>>20&15]+o[t>>>16&15]+o[t>>>12&15]+o[t>>>8&15]+o[t>>>4&15]+o[t&15]+o[r>>>28&15]+o[r>>>24&15]+o[r>>>20&15]+o[r>>>16&15]+o[r>>>12&15]+o[r>>>8&15]+o[r>>>4&15]+o[r&15]+o[s>>>28&15]+o[s>>>24&15]+o[s>>>20&15]+o[s>>>16&15]+o[s>>>12&15]+o[s>>>8&15]+o[s>>>4&15]+o[s&15]+o[i>>>28&15]+o[i>>>24&15]+o[i>>>20&15]+o[i>>>16&15]+o[i>>>12&15]+o[i>>>8&15]+o[i>>>4&15]+o[i&15]+o[a>>>28&15]+o[a>>>24&15]+o[a>>>20&15]+o[a>>>16&15]+o[a>>>12&15]+o[a>>>8&15]+o[a>>>4&15]+o[a&15]+o[h>>>28&15]+o[h>>>24&15]+o[h>>>20&15]+o[h>>>16&15]+o[h>>>12&15]+o[h>>>8&15]+o[h>>>4&15]+o[h&15];return this.is224||(g+=o[n>>>28&15]+o[n>>>24&15]+o[n>>>20&15]+o[n>>>16&15]+o[n>>>12&15]+o[n>>>8&15]+o[n>>>4&15]+o[n&15]),g};A.prototype.toString=A.prototype.hex;A.prototype.digest=function(){this.finalize();var e=this.h0,t=this.h1,r=this.h2,s=this.h3,i=this.h4,a=this.h5,h=this.h6,n=this.h7,g=[e>>>24&255,e>>>16&255,e>>>8&255,e&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255];return this.is224||g.push(n>>>24&255,n>>>16&255,n>>>8&255,n&255),g};A.prototype.array=A.prototype.digest;A.prototype.arrayBuffer=function(){this.finalize();var e=new ArrayBuffer(this.is224?28:32),t=new DataView(e);return t.setUint32(0,this.h0),t.setUint32(4,this.h1),t.setUint32(8,this.h2),t.setUint32(12,this.h3),t.setUint32(16,this.h4),t.setUint32(20,this.h5),t.setUint32(24,this.h6),this.is224||t.setUint32(28,this.h7),e};const I=(...e)=>new A(!1,!0).update(e.join("")).hex();var ce={};C(ce,{sha256:()=>I});var oe={};C(oe,{BaseCache:()=>$,InMemoryCache:()=>D,defaultHashKeyEncoder:()=>H,deserializeStoredGeneration:()=>he,serializeGeneration:()=>le});const H=(...e)=>I(e.join("_"));function he(e){return e.message!==void 0?{text:e.text,message:Z(e.message)}:{text:e.text}}function le(e){const t={text:e.text};return e.message!==void 0&&(t.message=e.message.toDict()),t}var $=class{keyEncoder=H;makeDefaultKeyEncoder(e){this.keyEncoder=e}};const ue=new Map;var D=class W extends ${cache;constructor(t){super(),this.cache=t??new Map}lookup(t,r){return Promise.resolve(this.cache.get(this.keyEncoder(t,r))??null)}async update(t,r,s){this.cache.set(this.keyEncoder(t,r),s)}static global(){return new W(ue)}},F={},z;function pe(){if(z)return F;z=1,F.byteLength=n,F.toByteArray=u,F.fromByteArray=k;for(var e=[],t=[],r=typeof Uint8Array<"u"?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,a=s.length;i<a;++i)e[i]=s[i],t[s.charCodeAt(i)]=i;t[45]=62,t[95]=63;function h(c){var l=c.length;if(l%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var p=c.indexOf("=");p===-1&&(p=l);var d=p===l?0:4-p%4;return[p,d]}function n(c){var l=h(c),p=l[0],d=l[1];return(p+d)*3/4-d}function g(c,l,p){return(l+p)*3/4-p}function u(c){var l,p=h(c),d=p[0],y=p[1],f=new r(g(c,d,y)),v=0,T=y>0?d-4:d,w;for(w=0;w<T;w+=4)l=t[c.charCodeAt(w)]<<18|t[c.charCodeAt(w+1)]<<12|t[c.charCodeAt(w+2)]<<6|t[c.charCodeAt(w+3)],f[v++]=l>>16&255,f[v++]=l>>8&255,f[v++]=l&255;return y===2&&(l=t[c.charCodeAt(w)]<<2|t[c.charCodeAt(w+1)]>>4,f[v++]=l&255),y===1&&(l=t[c.charCodeAt(w)]<<10|t[c.charCodeAt(w+1)]<<4|t[c.charCodeAt(w+2)]>>2,f[v++]=l>>8&255,f[v++]=l&255),f}function b(c){return e[c>>18&63]+e[c>>12&63]+e[c>>6&63]+e[c&63]}function x(c,l,p){for(var d,y=[],f=l;f<p;f+=3)d=(c[f]<<16&16711680)+(c[f+1]<<8&65280)+(c[f+2]&255),y.push(b(d));return y.join("")}function k(c){for(var l,p=c.length,d=p%3,y=[],f=16383,v=0,T=p-d;v<T;v+=f)y.push(x(c,v,v+f>T?T:v+f));return d===1?(l=c[p-1],y.push(e[l>>2]+e[l<<4&63]+"==")):d===2&&(l=(c[p-2]<<8)+c[p-1],y.push(e[l>>10]+e[l>>4&63]+e[l<<2&63]+"=")),y.join("")}return F}var ge=pe();const de=ee(ge);var fe=Object.defineProperty,be=(e,t,r)=>t in e?fe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,me=(e,t,r)=>(be(e,t+"",r),r);function ve(e,t){let r=Array.from({length:e.length},(s,i)=>({start:i,end:i+1}));for(;r.length>1;){let s=null;for(let i=0;i<r.length-1;i++){const a=e.slice(r[i].start,r[i+1].end),h=t.get(a.join(","));h!=null&&(s==null||h<s[0])&&(s=[h,i])}if(s!=null){const i=s[1];r[i]={start:r[i].start,end:r[i+1].end},r.splice(i+1,1)}else break}return r}function ye(e,t){return e.length===1?[t.get(e.join(","))]:ve(e,t).map(r=>t.get(e.slice(r.start,r.end).join(","))).filter(r=>r!=null)}function xe(e){return e.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var R=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(e,t){this.patStr=e.pat_str;const r=e.bpe_ranks.split(`
|
|
2
|
-
`).filter(Boolean).reduce((s,i)=>{const[a,h,...n]=i.split(" "),g=Number.parseInt(h,10);return n.forEach((u,b)=>s[u]=g+b),s},{});for(const[s,i]of Object.entries(r)){const a=de.toByteArray(s);this.rankMap.set(a.join(","),i),this.textMap.set(i,a)}this.specialTokens={...e.special_tokens,...t},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((s,[i,a])=>(s[a]=this.textEncoder.encode(i),s),{})}encode(e,t=[],r="all"){const s=new RegExp(this.patStr,"ug"),i=R.specialTokenRegex(Object.keys(this.specialTokens)),a=[],h=new Set(t==="all"?Object.keys(this.specialTokens):t),n=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!h.has(u)):r);if(n.size>0){const u=R.specialTokenRegex([...n]),b=e.match(u);if(b!=null)throw new Error(`The text contains a special token that is not allowed: ${b[0]}`)}let g=0;for(;;){let u=null,b=g;for(;i.lastIndex=b,u=i.exec(e),!(u==null||h.has(u[0]));)b=u.index+1;const x=u?.index??e.length;for(const c of e.substring(g,x).matchAll(s)){const l=this.textEncoder.encode(c[0]),p=this.rankMap.get(l.join(","));if(p!=null){a.push(p);continue}a.push(...ye(l,this.rankMap))}if(u==null)break;let k=this.specialTokens[u[0]];a.push(k),g=u.index+u[0].length}return a}decode(e){const t=[];let r=0;for(let a=0;a<e.length;++a){const h=e[a],n=this.textMap.get(h)??this.inverseSpecialTokens[h];n!=null&&(t.push(n),r+=n.length)}const s=new Uint8Array(r);let i=0;for(const a of t)s.set(a,i),i+=a.length;return this.textDecoder.decode(s)}},J=R;me(J,"specialTokenRegex",e=>new RegExp(e.map(t=>xe(t)).join("|"),"g"));function ke(e){switch(e){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}var we={};C(we,{encodingForModel:()=>j,getEncoding:()=>K});const S={},_e=new L({});async function K(e){return e in S||(S[e]=_e.fetch(`https://tiktoken.pages.dev/js/${e}.json`).then(t=>t.json()).then(t=>new J(t)).catch(t=>{throw delete S[e],t})),await S[e]}async function j(e){return K(ke(e))}var Ae={};C(Ae,{BaseLangChain:()=>q,BaseLanguageModel:()=>Se,calculateMaxTokens:()=>Ce,getEmbeddingContextSize:()=>Te,getModelContextSize:()=>N,getModelNameForTiktoken:()=>B,isOpenAITool:()=>Fe});const B=e=>e.startsWith("gpt-5")?"gpt-5":e.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":e.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":e.startsWith("gpt-4-32k")?"gpt-4-32k":e.startsWith("gpt-4-")?"gpt-4":e.startsWith("gpt-4o")?"gpt-4o":e,Te=e=>{switch(e){case"text-embedding-ada-002":return 8191;default:return 2046}},N=e=>{switch(B(e)){case"gpt-5":case"gpt-5-turbo":case"gpt-5-turbo-preview":return 4e5;case"gpt-4o":case"gpt-4o-mini":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":return 128e3;case"gpt-4-turbo":case"gpt-4-turbo-preview":case"gpt-4-turbo-2024-04-09":case"gpt-4-0125-preview":case"gpt-4-1106-preview":return 128e3;case"gpt-4-32k":case"gpt-4-32k-0314":case"gpt-4-32k-0613":return 32768;case"gpt-4":case"gpt-4-0314":case"gpt-4-0613":return 8192;case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-16k-0613":return 16384;case"gpt-3.5-turbo":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-1106":case"gpt-3.5-turbo-0125":return 4096;case"text-davinci-003":case"text-davinci-002":return 4097;case"text-davinci-001":return 2049;case"text-curie-001":case"text-babbage-001":case"text-ada-001":return 2048;case"code-davinci-002":case"code-davinci-001":return 8e3;case"code-cushman-001":return 2048;case"claude-3-5-sonnet-20241022":case"claude-3-5-sonnet-20240620":case"claude-3-opus-20240229":case"claude-3-sonnet-20240229":case"claude-3-haiku-20240307":case"claude-2.1":return 2e5;case"claude-2.0":case"claude-instant-1.2":return 1e5;case"gemini-1.5-pro":case"gemini-1.5-pro-latest":case"gemini-1.5-flash":case"gemini-1.5-flash-latest":return 1e6;case"gemini-pro":case"gemini-pro-vision":return 32768;default:return 4097}};function Fe(e){return typeof e!="object"||!e?!1:!!("type"in e&&e.type==="function"&&"function"in e&&typeof e.function=="object"&&e.function&&"name"in e.function&&"parameters"in e.function)}const Ce=async({prompt:e,modelName:t})=>{let r;try{r=(await j(B(t))).encode(e).length}catch{console.warn("Failed to calculate number of tokens, falling back to approximate count"),r=Math.ceil(e.length/4)}return N(t)-r},Ee=()=>!1;var q=class extends P{verbose;callbacks;tags;metadata;get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),this.verbose=e.verbose??Ee(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}},Se=class extends q{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}caller;cache;constructor({callbacks:e,callbackManager:t,...r}){const{cache:s,...i}=r;super({callbacks:e??t,...i}),typeof s=="object"?this.cache=s:s?this.cache=D.global():this.cache=void 0,this.caller=new L(r??{})}_encoding;async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join("");let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await j("modelName"in this?B(this.modelName):"gpt2")}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}if(this._encoding)try{r=this._encoding.encode(t).length}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new O(e):Array.isArray(e)?new V(e.map(Q)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([a,h])=>h!==void 0).map(([a,h])=>`${a}:${JSON.stringify(h)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}};export{q as B,te as a,se as b,Re as c,Fe as d,Se as e,ae as i};
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import{B as d,C as O,D as a,h as Y,Z as N,f as T,E,c as Z,n as W,s as z,b as Q,o as w,F as X}from"./index-BsLLCsBP.js";import{G as ve,H as Se,T as we,I as Ee,L as Ae,J as Ce,M as _e,T as Pe,K as Ie,V as Le,N as $e,O as Oe,P as Ne,P as Te}from"./index-BsLLCsBP.js";import{D as k}from"./index-CtpnfKmY.js";import"./base-RWAdy9P6.js";import"./base-Bnm339-a.js";async function*ee(c){for await(const e of c)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const t=e.data.chunk.text;typeof t=="string"&&t.length>0&&(yield t)}}d(ee,"streamEventsToAISDK");function te(c){return new ReadableStream({async start(e){try{for await(const t of c)e.enqueue(t);e.close()}catch(t){e.error(t)}}})}d(te,"createReadableStreamFromGenerator");async function*re(c){for await(const e of c)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const t=e.data.chunk.text;typeof t=="string"&&t.length>0&&(yield t)}break;case"on_tool_start":yield`
|
|
2
|
-
🔧 Using tool: ${e.name}
|
|
3
|
-
`;break;case"on_tool_end":yield`
|
|
4
|
-
✅ Tool completed: ${e.name}
|
|
5
|
-
`;break}}d(re,"streamEventsToAISDKWithTools");var M={},A;A=class{customCallbacks;availableHandlers=[];handlerNames=[];initialized=!1;verbose;observe;agentId;metadata;metadataProvider;tagsProvider;constructor(e={}){this.customCallbacks=e.customCallbacks,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.agentId=e.agentId,this.metadata=e.metadata,this.metadataProvider=e.metadataProvider,this.tagsProvider=e.tagsProvider}async collectAvailableHandlers(){if(!this.initialized){try{const{langfuseHandler:e,langfuseInitPromise:t}=await O(async()=>{const{langfuseHandler:n,langfuseInitPromise:s}=await Promise.resolve().then(()=>K);return{langfuseHandler:n,langfuseInitPromise:s}},void 0);if(this.agentId||this.metadata||this.metadataProvider||this.tagsProvider){const{initializeLangfuse:n}=await O(async()=>{const{initializeLangfuse:s}=await Promise.resolve().then(()=>K);return{initializeLangfuse:s}},void 0);await n(this.agentId,this.metadata,this.metadataProvider,this.tagsProvider),a.debug(`ObservabilityManager: Reinitialized Langfuse with agent ID: ${this.agentId}, metadata: ${JSON.stringify(this.metadata)}`)}else{const n=t();n&&await n}const r=e();r&&(this.availableHandlers.push(r),this.handlerNames.push("Langfuse"),a.debug("ObservabilityManager: Langfuse handler available"))}catch{a.debug("ObservabilityManager: Langfuse module not available")}this.initialized=!0}}async getCallbacks(){return this.observe?this.customCallbacks?(a.debug(`ObservabilityManager: Using ${this.customCallbacks.length} custom callbacks`),this.customCallbacks):(await this.collectAvailableHandlers(),this.availableHandlers.length>0?a.debug(`ObservabilityManager: Using ${this.availableHandlers.length} handlers`):a.debug("ObservabilityManager: No callbacks configured"),this.availableHandlers):(a.debug("ObservabilityManager: Observability disabled via observe=false"),[])}async getHandlerNames(){return this.observe?this.customCallbacks?this.customCallbacks.map(e=>e.constructor.name):(await this.collectAvailableHandlers(),this.handlerNames):[]}async hasCallbacks(){return this.observe?(await this.getCallbacks()).length>0:!1}async getStatus(){const e=await this.getCallbacks(),t=await this.getHandlerNames(),r=this.metadataProvider?this.metadataProvider():this.metadata||{},n=this.tagsProvider?this.tagsProvider():[];return{enabled:this.observe&&e.length>0,callbackCount:e.length,handlerNames:t,metadata:r,tags:n}}addCallback(e){this.customCallbacks||(this.customCallbacks=[]),this.customCallbacks.push(e),a.debug(`ObservabilityManager: Added custom callback: ${e.constructor.name}`)}clearCallbacks(){this.customCallbacks=[],a.debug("ObservabilityManager: Cleared all custom callbacks")}async flush(){const e=await this.getCallbacks();for(const t of e)"flushAsync"in t&&typeof t.flushAsync=="function"&&await t.flushAsync();a.debug("ObservabilityManager: All traces flushed")}async shutdown(){await this.flush();const e=await this.getCallbacks();for(const t of e)"shutdownAsync"in t&&typeof t.shutdownAsync=="function"?await t.shutdownAsync():"shutdown"in t&&typeof t.shutdown=="function"&&await t.shutdown();a.debug("ObservabilityManager: All handlers shutdown")}toString(){const e=this.handlerNames;return e.length>0?`ObservabilityManager(handlers=${e.join(", ")})`:"ObservabilityManager(no handlers)"}},d(A,"ObservabilityManager");var ne="/api/v1/chats",se="/api/v1/chats/{chat_id}/execute";function q(c,e,t,r,n){if(typeof c=="object"&&c!==null){const s=c;return{query:s.prompt,maxSteps:s.maxSteps,manageConnector:s.manageConnector,externalHistory:s.externalHistory,outputSchema:s.schema}}return{query:c,maxSteps:e,manageConnector:t,externalHistory:r,outputSchema:n}}d(q,"normalizeRemoteRunOptions");var C;C=class{agentId;apiKey;baseUrl;chatId=null;constructor(e){this.agentId=e.agentId,this.baseUrl=e.baseUrl??"https://cloud.mcp-use.com";const t=e.apiKey??(typeof process<"u"&&M?.MCP_USE_API_KEY);if(!t)throw new Error("API key is required for remote execution. Please provide it as a parameter or set the MCP_USE_API_KEY environment variable. You can get an API key from https://cloud.mcp-use.com");this.apiKey=t}pydanticToJsonSchema(e){return Y(e)}parseStructuredResponse(e,t){let r;if(typeof e=="object"&&e!==null)if("result"in e){const n=e.result;typeof n=="object"&&n!==null&&"result"in n?r=n.result:r=n}else r=e;else if(typeof e=="string")try{r=JSON.parse(e)}catch{r={content:e}}else r=e;try{return t.parse(r)}catch(n){a.warn(`Failed to parse structured output: ${n}`);const s=t._def?.shape();if(s&&"content"in s)return t.parse({content:String(r)});throw n}}async createChatSession(){const e={title:`Remote Agent Session - ${this.agentId}`,agent_id:this.agentId,type:"agent_execution"},t={"Content-Type":"application/json","x-api-key":this.apiKey},r=`${this.baseUrl}${ne}`;a.info(`📝 Creating chat session for agent ${this.agentId}`);try{const n=await fetch(r,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok){const o=await n.text(),u=n.status;throw u===404?new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`):new Error(`Failed to create chat session: ${u} - ${o}`)}const i=(await n.json()).id;return a.info(`✅ Chat session created: ${i}`),i}catch(n){throw n instanceof Error?new TypeError(`Failed to create chat session: ${n.message}`):new Error(`Failed to create chat session: ${String(n)}`)}}async run(e,t,r,n,s){const{query:i,maxSteps:o,externalHistory:u,outputSchema:p}=q(e,t,r,n,s);u!==void 0&&a.warn("External history is not yet supported for remote execution");try{a.info(`🌐 Executing query on remote agent ${this.agentId}`),this.chatId===null&&(this.chatId=await this.createChatSession());const b=this.chatId,S={query:i,max_steps:o??10};p&&(S.output_schema=this.pydanticToJsonSchema(p),a.info("🔧 Using structured output with schema"));const l={"Content-Type":"application/json","x-api-key":this.apiKey},g=`${this.baseUrl}${se.replace("{chat_id}",b)}`;a.info(`🚀 Executing agent in chat ${b}`);const m=await fetch(g,{method:"POST",headers:l,body:JSON.stringify(S),signal:AbortSignal.timeout(3e5)});if(!m.ok){const y=await m.text(),v=m.status;throw v===401?(a.error(`❌ Authentication failed: ${y}`),new Error("Authentication failed: Invalid or missing API key. Please check your API key and ensure the MCP_USE_API_KEY environment variable is set correctly.")):v===403?(a.error(`❌ Access forbidden: ${y}`),new Error(`Access denied: You don't have permission to execute agent '${this.agentId}'. Check if the agent exists and you have the necessary permissions.`)):v===404?(a.error(`❌ Agent not found: ${y}`),new Error(`Agent not found: Agent '${this.agentId}' does not exist or you don't have access to it. Please verify the agent ID and ensure it exists in your account.`)):v===422?(a.error(`❌ Validation error: ${y}`),new Error(`Request validation failed: ${y}. Please check your query parameters and output schema format.`)):v===500?(a.error(`❌ Server error: ${y}`),new Error("Internal server error occurred during agent execution. Please try again later or contact support if the issue persists.")):(a.error(`❌ Remote execution failed with status ${v}: ${y}`),new Error(`Remote agent execution failed: ${v} - ${y}`))}const f=await m.json();if(a.info(`🔧 Response: ${JSON.stringify(f)}`),a.info("✅ Remote execution completed successfully"),typeof f=="object"&&f!==null){if(f.status==="error"||f.error!==null){const y=f.error??String(f);throw a.error(`❌ Remote agent execution failed: ${y}`),new Error(`Remote agent execution failed: ${y}`)}if(String(f).includes("failed to initialize"))throw a.error(`❌ Agent initialization failed: ${f}`),new Error(`Agent initialization failed on remote server. This usually indicates:
|
|
6
|
-
• Invalid agent configuration (LLM model, system prompt)
|
|
7
|
-
• Missing or invalid MCP server configurations
|
|
8
|
-
• Network connectivity issues with MCP servers
|
|
9
|
-
• Missing environment variables or credentials
|
|
10
|
-
Raw error: ${f}`)}return p?this.parseStructuredResponse(f,p):typeof f=="object"&&f!==null&&"result"in f?f.result:typeof f=="string"?f:String(f)}catch(b){throw b instanceof Error?b.name==="AbortError"?(a.error(`❌ Remote execution timed out: ${b}`),new 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.")):(a.error(`❌ Remote execution error: ${b}`),new Error(`Remote agent execution failed: ${b.message}`)):(a.error(`❌ Remote execution error: ${b}`),new Error(`Remote agent execution failed: ${String(b)}`))}}async*stream(e,t,r,n,s){return await this.run(e,t,r,n,s)}async close(){a.info("🔌 Remote agent client closed")}},d(C,"RemoteAgent");var L={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 x(c){const e=c.split("/");if(e.length!==2)throw new Error(`Invalid LLM string format. Expected 'provider/model', got '${c}'. Examples: 'openai/gpt-4', 'anthropic/claude-3-5-sonnet-20241022', 'google/gemini-pro', 'groq/llama-3.1-70b-versatile'`);const[t,r]=e;if(!t||!r)throw new Error(`Invalid LLM string format. Both provider and model must be non-empty. Got '${c}'`);const n=t.toLowerCase();if(!(n in L)){const s=Object.keys(L).join(", ");throw new Error(`Unsupported LLM provider '${t}'. Supported providers: ${s}`)}return{provider:n,model:r}}d(x,"parseLLMString");function G(c,e){if(e?.apiKey)return e.apiKey;const t=L[c];if(typeof process<"u"&&M)for(const n of t.envVars){const s=M[n];if(s)return a.debug(`Using API key from environment variable ${n} for provider ${c}`),s}const r=t.envVars.join(" or ");throw new Error(`API key not found for provider '${c}'. Set ${r} environment variable or pass apiKey in llmConfig. Example: new MCPAgent({ llm: '${c}/model', llmConfig: { apiKey: 'your-key' } })`)}d(G,"getAPIKey");async function ae(c,e){a.info(`Creating LLM from string: ${c}`);const{provider:t,model:r}=x(c),n=L[t],s=G(t,e);let i;try{a.debug(`Importing package ${n.package}...`),i=await import(n.package)}catch(p){throw p?.code==="MODULE_NOT_FOUND"||p?.message?.includes("Cannot find module")||p?.message?.includes("Cannot find package")?new Error(`Package '${n.package}' is not installed. Install it with: npm install ${n.package} or yarn add ${n.package}`):new Error(`Failed to import ${n.package}: ${p?.message||p}`)}const o=i[n.className];if(!o)throw new Error(`Could not find ${n.className} in package ${n.package}. This might be a version compatibility issue.`);const u={model:r,apiKey:s,...e};e?.apiKey&&(delete u.apiKey,u.apiKey=s),(t==="anthropic"||t==="google"||t==="openai"||t==="groq")&&(u.model=r);try{const p=new o(u);return a.info(`Successfully created ${t} LLM with model ${r}`),p}catch(p){throw new Error(`Failed to instantiate ${n.className} with model '${r}': ${p?.message||p}`)}}d(ae,"createLLMFromString");function ie(c){try{return x(c),!0}catch{return!1}}d(ie,"isValidLLMString");function oe(){return Object.keys(L)}d(oe,"getSupportedProviders");var F={};function h(c){if(typeof process<"u"&&F)return F[c]}d(h,"getEnvVar");var le=h("MCP_USE_LANGFUSE")?.toLowerCase()==="false",$={handler:null,client:null,initPromise:null};async function R(c,e,t,r){try{const n=await O(()=>import("langfuse-langchain"),[]).catch(()=>null);if(!n){a.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:s}=n,b=class b extends s{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(l,g,m,f,y){super(l),this.agentId=g,this.metadata=m,this.metadataProvider=f,this.tagsProvider=y,this.verbose=l?.verbose??!1}async handleChainStart(l,g,m,f,y,v,V,J){a.debug("Langfuse: Chain start intercepted");const D=this.getCustomTags(),B=this.getMetadata(),U=[...y||[],...D],j={...v||{},...B};return this.verbose&&(a.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(U)}`),a.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(j)}`)),super.handleChainStart(l,g,m,f,U,j,V,J)}getCustomTags(){const l=[],g=this.getEnvironmentTag();if(g&&l.push(`env:${g}`),this.agentId&&l.push(`agent_id:${this.agentId}`),this.tagsProvider){const m=this.tagsProvider();m&&m.length>0&&l.push(...m)}return l}getMetadata(){const l={},g=this.getEnvironmentTag();if(g&&(l.env=g),this.agentId&&(l.agent_id=this.agentId),this.metadata&&Object.assign(l,this.metadata),this.metadataProvider){const m=this.metadataProvider();m&&Object.assign(l,m)}return l}getEnvironmentTag(){const l=h("MCP_USE_AGENT_ENV");if(!l)return"unknown";const g=l.toLowerCase();return g==="local"||g==="development"?"local":g==="production"||g==="prod"?"production":g==="staging"||g==="stage"?"staging":g==="hosted"||g==="cloud"?"hosted":g.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...l){return a.debug("Langfuse: LLM start intercepted"),this.verbose&&a.debug(`Langfuse: LLM start args: ${JSON.stringify(l)}`),super.handleLLMStart(...l)}async handleToolStart(...l){return a.debug("Langfuse: Tool start intercepted"),this.verbose&&a.debug(`Langfuse: Tool start args: ${JSON.stringify(l)}`),super.handleToolStart(...l)}async handleRetrieverStart(...l){return a.debug("Langfuse: Retriever start intercepted"),this.verbose&&a.debug(`Langfuse: Retriever start args: ${JSON.stringify(l)}`),super.handleRetrieverStart(...l)}async handleAgentAction(...l){return a.debug("Langfuse: Agent action intercepted"),this.verbose&&a.debug(`Langfuse: Agent action args: ${JSON.stringify(l)}`),super.handleAgentAction(...l)}async handleAgentEnd(...l){return a.debug("Langfuse: Agent end intercepted"),this.verbose&&a.debug(`Langfuse: Agent end args: ${JSON.stringify(l)}`),super.handleAgentEnd(...l)}};d(b,"LoggingCallbackHandler");let i=b;const o=e||(t?t():{}),u=r?r():[],p={publicKey:h("LANGFUSE_PUBLIC_KEY"),secretKey:h("LANGFUSE_SECRET_KEY"),baseUrl:h("LANGFUSE_HOST")||h("LANGFUSE_BASEURL")||"https://cloud.langfuse.com",flushAt:Number.parseInt(h("LANGFUSE_FLUSH_AT")||"15"),flushInterval:Number.parseInt(h("LANGFUSE_FLUSH_INTERVAL")||"10000"),release:h("LANGFUSE_RELEASE"),requestTimeout:Number.parseInt(h("LANGFUSE_REQUEST_TIMEOUT")||"10000"),enabled:h("LANGFUSE_ENABLED")!=="false",traceName:o.trace_name||h("LANGFUSE_TRACE_NAME")||"mcp-use-agent",sessionId:o.session_id||void 0,userId:o.user_id||void 0,tags:u.length>0?u:void 0,metadata:o||void 0};a.debug("Langfuse handler config:",JSON.stringify({traceName:p.traceName,sessionId:p.sessionId,userId:p.userId,tags:p.tags},null,2)),$.handler=new i(p,c,e,t,r),a.debug("Langfuse observability initialized successfully with logging enabled");try{const S=await O(()=>import("langfuse"),[]).catch(()=>null);if(S){const{Langfuse:l}=S;$.client=new l({publicKey:h("LANGFUSE_PUBLIC_KEY"),secretKey:h("LANGFUSE_SECRET_KEY"),baseUrl:h("LANGFUSE_HOST")||"https://cloud.langfuse.com"}),a.debug("Langfuse client initialized")}}catch(S){a.debug(`Langfuse client initialization failed: ${S}`)}}catch(n){a.debug(`Langfuse initialization error: ${n}`)}}d(R,"initializeLangfuse");le?a.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!h("LANGFUSE_PUBLIC_KEY")||!h("LANGFUSE_SECRET_KEY")?a.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):$.initPromise=R();var ce=d(()=>$.handler,"langfuseHandler"),ue=d(()=>$.initPromise,"langfuseInitPromise"),_,de=(_=class{disallowedTools;connectorToolMap=new Map;constructor(e){this.disallowedTools=e??[]}static async createTools(e,t){const r=new this(t);(!e.activeSessions||Object.keys(e.activeSessions).length===0)&&(a.info("No active sessions found, creating new ones..."),await e.createAllSessions());const n=e.getAllActiveSessions(),s=Object.values(n).map(i=>i.connector);return r.createToolsFromConnectors(s)}async loadToolsForConnector(e){if(this.connectorToolMap.has(e)){const n=this.connectorToolMap.get(e);return a.debug(`Returning ${n.length} existing tools for connector`),n}const t=[];if(!await this.ensureConnectorInitialized(e))return[];for(const n of e.tools){const s=this.convertTool(n,e);s&&t.push(s)}return this.connectorToolMap.set(e,t),a.debug(`Loaded ${t.length} new tools for connector: ${t.map(n=>n?.name??String(n)).join(", ")}`),t}async createToolsFromConnectors(e){const t=[];for(const r of e){const n=await this.loadToolsForConnector(r);t.push(...n)}return a.debug(`Available tools: ${t.length}`),t}async loadResourcesForConnector(e){const t=[];if(!await this.ensureConnectorInitialized(e))return[];try{const s=(await e.listAllResources())?.resources||[];if(this.convertResource)for(const i of s){const o=this.convertResource(i,e);o&&t.push(o)}a.debug(`Loaded ${t.length} new resources for connector: ${t.map(i=>i?.name??String(i)).join(", ")}`)}catch(n){a.warn(`Error loading resources for connector: ${n}`)}return t}async loadPromptsForConnector(e){const t=[];if(!await this.ensureConnectorInitialized(e))return[];try{const s=(await e.listPrompts())?.prompts||[];if(this.convertPrompt)for(const i of s){const o=this.convertPrompt(i,e);o&&t.push(o)}a.debug(`Loaded ${t.length} new prompts for connector: ${t.map(i=>i?.name??String(i)).join(", ")}`)}catch(n){a.warn(`Error loading prompts for connector: ${n}`)}return t}async createResourcesFromConnectors(e){const t=[];for(const r of e){const n=await this.loadResourcesForConnector(r);t.push(...n)}return a.debug(`Available resources: ${t.length}`),t}async createPromptsFromConnectors(e){const t=[];for(const r of e){const n=await this.loadPromptsForConnector(r);t.push(...n)}return a.debug(`Available prompts: ${t.length}`),t}checkConnectorInitialized(e){return!!(e.tools&&e.tools.length)}async ensureConnectorInitialized(e){if(!this.checkConnectorInitialized(e)){a.debug("Connector doesn't have tools, initializing it");try{return await e.initialize(),!0}catch(t){return a.error(`Error initializing connector: ${t}`),!1}}return!0}},d(_,"BaseAdapter"),_),P,fe=(P=class{static convert(e){return this.parseSchema(e)}static matchesCondition(e,t){if(!t.properties)return!0;if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;for(const[n,s]of Object.entries(t.properties)){if(!(n in r)){if("const"in s)return!1;continue}const i=r[n];if("const"in s&&i!==s.const||"minimum"in s&&typeof i=="number"&&i<s.minimum||"maximum"in s&&typeof i=="number"&&i>s.maximum)return!1}return!0}static validateConditionalSchema(e,t,r){this.validateRequiredProperties(e,t,r),this.validatePropertyPatterns(e,t,r),this.validateNestedConditions(e,t,r)}static validateRequiredProperties(e,t,r){if(t.required){if(typeof e!="object"||e===null){for(const n of t.required)r.addIssue({code:N.custom,message:`Required property '${n}' is missing`,path:[n]});return}for(const n of t.required)n in e||r.addIssue({code:N.custom,message:`Required property '${n}' is missing`,path:[n]})}}static validatePropertyPatterns(e,t,r){if(!t.properties||typeof e!="object"||e===null||Array.isArray(e))return;const n=e;for(const[s,i]of Object.entries(t.properties)){if(!(s in n))continue;const o=n[s];i.pattern&&typeof o=="string"&&(new RegExp(i.pattern).test(o)||r.addIssue({code:N.custom,message:`String '${o}' does not match pattern '${i.pattern}'`,path:[s]}))}}static validateNestedConditions(e,t,r){if(!t.if||!t.then)return;this.matchesCondition(e,t.if)?this.validateConditionalSchema(e,t.then,r):t.else&&this.validateConditionalSchema(e,t.else,r)}static parseSchema(e){return Array.isArray(e.type)?this.handleTypeArray(e):e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.if&&e.then?this.parseObject(e):e.properties&&(!e.type||e.type==="object")?this.parseObject(e):this.handleSingleType(e)}static handleTypeArray(e){if(!Array.isArray(e.type))throw new 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 new Error("Expected schema.type to be an array");const t={...e};return t.type=e.type.filter(n=>n!=="null"),t.type.length===1?this.handleSingleType({...e,type:t.type[0]}).nullable():this.parseSchema(t).nullable()}static createUnionFromTypes(e,t){const r=e.map(n=>{const s={...t,type:n};return this.parseSchema(s)});return T(r)}static handleSingleType(e){if(e.type===void 0)return e.oneOf||e.anyOf||e.allOf?this.parseCombinator(e):e.properties?this.parseObject(e):E();switch(e.type){case"string":return this.parseString(e);case"number":case"integer":return this.parseNumberSchema(e);case"boolean":return Z();case"array":return this.parseArray(e);case"object":return this.parseObject(e);default:throw new Error("Unsupported schema type")}}static parseNumberSchema(e){const t=W();let r=t;return r=this.applyNumberBounds(t,e),r=this.applyNumberMultipleOf(t,e),r=this.applyNumberEnum(t,e),r=this.applyIntegerConstraint(t,e),r}static applyNumberBounds(e,t){let r=e;return t.minimum!==void 0&&(r=t.exclusiveMinimum?r.gt(t.minimum):r.gte(t.minimum)),t.maximum!==void 0&&(r=t.exclusiveMaximum?r.lt(t.maximum):r.lte(t.maximum)),r}static applyNumberMultipleOf(e,t){return t.multipleOf===void 0?e:e.refine(r=>r%t.multipleOf===0,{message:`Number must be a multiple of ${t.multipleOf}`})}static applyNumberEnum(e,t){if(!t.enum)return e;const r=t.enum.filter(n=>typeof n=="number");return r.length===0?e:e.refine(n=>r.includes(n),{message:`Number must be one of: ${r.join(", ")}`})}static applyIntegerConstraint(e,t){return t.type!=="integer"?e:e.refine(r=>Number.isInteger(r),{message:"Number must be an integer"})}static parseString(e){const t=z();let r=t;return e.format?this.applyStringFormat(t,e):(r=this.applyStringPattern(t,e),r=this.applyStringLength(t,e),r=this.applyStringEnum(t,e),r)}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;const r=new RegExp(t.pattern);return e.regex(r,{message:`String must match pattern: ${t.pattern}`})}static applyStringLength(e,t){const r=e;return t.minLength!==void 0&&(e=e.min(t.minLength)),t.maxLength!==void 0&&(e=e.max(t.maxLength)),r}static applyStringEnum(e,t){return t.enum?e.refine(r=>t.enum?.includes(r),{message:`Value must be one of: ${t.enum?.join(", ")}`}):e}static parseArray(e){if(Array.isArray(e.items)){const s=e.items.map(i=>this.parseSchema(i));return T(s)}const t=e.items?this.parseSchema(e.items):E(),r=Q(t);let n=r;return n=this.applyArrayConstraints(r,e),n}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(r=>new Set(r).size===r.length,{message:"Array items must be unique"}):e}static parseObject(e){if(e.if&&e.then)return this.parseConditional(e);const t={};return this.processObjectProperties(e,t),this.processAdditionalProperties(e,w(t))}static processObjectProperties(e,t){const r=new Set(e.required||[]);if(e.properties)for(const[n,s]of Object.entries(e.properties)){const i=this.parseSchema(s);t[n]=r.has(n)?i:i.optional()}}static processAdditionalProperties(e,t){if(e.additionalProperties===!0)return t.passthrough();if(e.additionalProperties&&typeof e.additionalProperties=="object"){const r=this.parseSchema(e.additionalProperties);return t.catchall(r)}else return t.strict()}static parseConditional(e){const t=this.createBaseObjectSchema(e),r=e.if,n=e.then,s=e.else;return t.superRefine((i,o)=>{const u=this.applyDefaultValues(i,e);this.matchesCondition(u,r)?this.validateConditionalSchema(u,n,o):s&&this.validateConditionalSchema(u,s,o)})}static createBaseObjectSchema(e){const t={},r=new Set(e.required||[]);for(const[s,i]of Object.entries(e.properties||{})){const o=this.parseSchema(i);t[s]=r.has(s)?o:o.optional()}const n=w(t);return this.processAdditionalProperties(e,n)}static applyDefaultValues(e,t){if(typeof e!="object"||e===null||Array.isArray(e))return e;const n={...e};if(!t.properties)return n;for(const[s,i]of Object.entries(t.properties))!(s in n)&&"default"in i&&(n[s]=i.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 new 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 E();if(e.length===1)return this.parseSchema(e[0]);const t=[];for(const r of e)r.type==="null"?t.push(X()):t.push(this.parseSchema(r));return t.length>=2?T(t):t.length===1?t[0]:E()}static parseAllOf(e){if(e.length===0)return E();if(e.length===1)return this.parseSchema(e[0]);const t=e.reduce((r,n)=>this.mergeSchemas(r,n));return this.parseSchema(t)}static mergeSchemas(e,t){const r={...e,...t};if(e.properties&&t.properties){const n={...e.properties,...t.properties};r.properties=n}if(e.required&&t.required){const n=[...new Set([...e.required,...t.required])];r.required=n}return r}},d(P,"JSONSchemaToZod"),P);function H(c){try{return fe.convert(c)}catch(e){return a.warn(`Failed to convert JSON schema to Zod: ${e}`),E()}}d(H,"schemaToZod");var I;I=class extends de{constructor(e=[]){super(e)}convertTool(e,t){if(this.disallowedTools.includes(e.name))return null;const r=e.inputSchema?H(e.inputSchema):w({}).optional();return new k({name:e.name??"NO NAME",description:e.description??"",schema:r,func:d(async s=>{a.debug(`MCP tool "${e.name}" received input: ${JSON.stringify(s)}`);try{const i=await t.callTool(e.name,s);return JSON.stringify(i)}catch(i){return a.error(`Error executing MCP tool: ${i.message}`),`Error executing MCP tool: ${String(i)}`}},"func")})}convertResource(e,t){const n=d(o=>o.replace(/[^A-Za-z0-9_]+/g,"_").toLowerCase().replace(/^_+|_+$/g,""),"sanitizeName")(e.name||`resource_${e.uri}`),s=e.uri;return new k({name:n,description:e.description||`Return the content of the resource located at URI ${s}.`,schema:w({}).optional(),func:d(async()=>{a.debug(`Resource tool: "${n}" called`);try{const o=await t.readResource(s);return o.contents&&o.contents.length>0?o.contents.map(u=>typeof u=="string"?u:u.text?u.text:u.uri?u.uri:JSON.stringify(u)).join(`
|
|
11
|
-
`):"Resource is empty or unavailable"}catch(o){return a.error(`Error reading resource: ${o.message}`),`Error reading resource: ${String(o)}`}},"func")})}convertPrompt(e,t){let r=w({}).optional();if(e.arguments&&e.arguments.length>0){const s={};for(const i of e.arguments){const o=z();i.required!==!1?s[i.name]=o:s[i.name]=o.optional()}r=Object.keys(s).length>0?w(s):w({}).optional()}return new k({name:e.name,description:e.description||"",schema:r,func:d(async s=>{a.debug(`Prompt tool: "${e.name}" called with args: ${JSON.stringify(s)}`);try{const i=await t.getPrompt(e.name,s);return i.messages&&i.messages.length>0?i.messages.map(o=>typeof o=="string"?o:o.content?typeof o.content=="string"?o.content:JSON.stringify(o.content):JSON.stringify(o)).join(`
|
|
12
|
-
`):"Prompt returned no messages"}catch(i){return a.error(`Error getting prompt: ${i.message}`),`Error getting prompt: ${String(i)}`}},"func")})}},d(I,"LangChainAdapter");const K=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:R,langfuseHandler:ce,langfuseInitPromise:ue},Symbol.toStringTag,{value:"Module"}));export{de as BaseAdapter,ve as BaseConnector,Se as BrowserOAuthClientProvider,we as BrowserTelemetry,Ee as HttpConnector,Ae as Logger,Ce as MCPClient,_e as MCPSession,Pe as Tel,Ie as Telemetry,Le as VERSION,ae as createLLMFromString,te as createReadableStreamFromGenerator,$e as getPackageVersion,oe as getSupportedProviders,ie as isValidLLMString,a as logger,Oe as onMcpAuthorization,x as parseLLMString,Ne as setBrowserTelemetrySource,Te as setTelemetrySource,ee as streamEventsToAISDK,re as streamEventsToAISDKWithTools};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{_ as e,q as d}from"./base-RWAdy9P6.js";var l={};e(l,{chunkArray:()=>u});const u=(r,n)=>r.reduce((a,o,s)=>{const c=Math.floor(s/n),t=a[c]||[];return a[c]=t.concat([o]),a},[]);var _={};e(_,{Embeddings:()=>h});var h=class{caller;constructor(r){this.caller=new d(r??{})}};
|