@mcp-use/inspector 0.6.0 → 0.6.1-canary.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{chunk-VL2OQCWN-Bic-rB6T.js → chunk-VL2OQCWN-CcA-MyVH.js} +1 -1
- package/dist/client/assets/{display-LIYVTGEU-BHRqqKvX.js → display-LIYVTGEU-CQo10dsV.js} +1 -1
- package/dist/client/assets/{embeddings-lLuDNyJW.js → embeddings-Bd2i0Sjk.js} +1 -1
- package/dist/client/assets/{index-D6du61WF.js → index-BX0m6ynw.js} +1 -1
- package/dist/client/assets/{index-D3r30E5x.js → index-BudeTtaa.js} +1 -1
- package/dist/client/assets/{index-BR6cKw0d.js → index-D6Wv_tf-.js} +4 -4
- package/dist/client/assets/{index-xRISKm6b.js → index-DKWgaOQU.js} +1 -1
- package/dist/client/assets/{index-BwqAJmU6.js → index-Db4_L4WW.js} +1 -1
- package/dist/client/assets/{index-CTMpeTG-.js → index-q78x3Wop.js} +1 -1
- package/dist/client/assets/{index-UA3z-V5S.js → index-sc8ha_Bb.js} +1 -1
- package/dist/client/assets/{langfuse-C4HKZ3NL-Dbzphj3a.js → langfuse-C4HKZ3NL-DNJN4Gjo.js} +4 -4
- package/dist/client/assets/{winston-Cw4A3I6l.js → winston-DBwXBxBb.js} +1 -1
- package/dist/client/index.html +2 -2
- package/package.json +2 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{i as ne,t as fe,a as he,b as pe,C as ge,c as me,d as Ce,e as ye,f as oe,g as se,h as ie,j as _e,k as Ee,p as A,B as ve,l as we,O as Te,m as Ie,n as Oe,J as Re,R as D,o as Se}from"./index-BwqAJmU6.js";import{v as ae}from"./index-BR6cKw0d.js";import"./embeddings-lLuDNyJW.js";import"./chunk-VL2OQCWN-Bic-rB6T.js";import"./index-DRz5BQNA.js";function _(e){if(typeof e=="object"&&e!==null){const n={...e};"additionalProperties"in n&&delete n.additionalProperties,"$schema"in n&&delete n.$schema,"strict"in n&&delete n.strict;for(const t in n)t in n&&(Array.isArray(n[t])?n[t]=n[t].map(_):typeof n[t]=="object"&&n[t]!==null&&(n[t]=_(n[t])));return n}return e}function N(e){const n=_(ne(e)?fe(e):e),{$schema:t,...o}=n;return o}function Ae(e){const n=_(e),{$schema:t,...o}=n;return o}function Ne(e){const n=e._getType();return Ce.isInstance(e)?e.role:n==="tool"?n:e.name??n}function be(e){switch(e){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${e}`)}}function Me(e){if("mimeType"in e&&"data"in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if("mimeType"in e&&"fileUri"in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw new Error("Invalid media content")}function xe(e,n){return n.map(t=>oe(t)?t.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function De(e){return{providerName:"Google Gemini",fromStandardTextBlock(t){return{text:t.text}},fromStandardImageBlock(t){if(!e)throw new Error("This model does not support images");if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw new Error("This model does not support audio");if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw new Error("This model does not support files");if(t.source_type==="text")return{text:t.text};if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)}}}function G(e,n){if(_e(e))return Ee(e,De(n));if(e.type==="text")return{text:e.text};if(e.type==="executableCode")return{executableCode:e.executableCode};if(e.type==="codeExecutionResult")return{codeExecutionResult:e.codeExecutionResult};if(e.type==="image_url"){if(!n)throw new Error("This model does not support images");let t;if(typeof e.image_url=="string")t=e.image_url;else if(typeof e.image_url=="object"&&"url"in e.image_url)t=e.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[o,s]=t.split(",");if(!o.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[i,a]=o.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:s,mimeType:i}}}else{if(e.type==="media")return Me(e);if(e.type==="tool_use")return{functionCall:{name:e.name,args:e.input}};if(e.type?.includes("/")&&e.type.split("/").length===2&&"data"in e&&typeof e.data=="string")return{inlineData:{mimeType:e.type,data:e.data}};if("functionCall"in e)return;throw"type"in e?new Error(`Unknown content type ${e.type}`):new Error(`Unknown content ${JSON.stringify(e)}`)}}function Ge(e,n,t){if(ye(e)){const i=e.name??xe(e,t);if(i===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const a=Array.isArray(e.content)?e.content.map(c=>G(c,n)).filter(c=>c!==void 0):e.content;return e.status==="error"?[{functionResponse:{name:i,response:{error:{details:a}}}}]:[{functionResponse:{name:i,response:{result:a}}}]}let o=[];const s=[];return typeof e.content=="string"&&e.content&&s.push({text:e.content}),Array.isArray(e.content)&&s.push(...e.content.map(i=>G(i,n)).filter(i=>i!==void 0)),oe(e)&&e.tool_calls?.length&&(o=e.tool_calls.map(i=>({functionCall:{name:i.name,args:i.args}}))),[...s,...o]}function k(e,n,t=!1){return e.reduce((o,s,i)=>{if(!he(s))throw new Error("Unsupported message input");const a=Ne(s);if(a==="system"&&i!==0)throw new Error("System message should be the first one");const c=be(a),u=o.content[o.content.length];if(!o.mergeWithPreviousContent&&u&&u.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Ge(s,n,e.slice(0,i));if(o.mergeWithPreviousContent){const d=o.content[o.content.length-1];if(!d)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return d.parts.push(...r),{mergeWithPreviousContent:!1,content:o.content}}let p=c;(p==="function"||p==="system"&&!t)&&(p="user");const f={role:p,parts:r};return{mergeWithPreviousContent:a==="system"&&!t,content:[...o.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function ke(e,n){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.length===1&&s.parts[0].text?a=s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(p=>"text"in p)?.text??c),{generations:[{text:c,message:new pe({content:a??"",tool_calls:t?.map(r=>({...r,type:"tool_call",id:"id"in r&&typeof r.id=="string"?r.id:ae()})),additional_kwargs:{...i},usage_metadata:n?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:n?.usageMetadata?.input_tokens,completionTokens:n?.usageMetadata?.output_tokens,totalTokens:n?.usageMetadata?.total_tokens}}}}function Ue(e,n){if(!e.candidates||e.candidates.length===0)return null;const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.every(r=>"text"in r)?a=s.parts.map(r=>r.text).join(""):Array.isArray(s?.parts)?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";a&&typeof a=="string"?c=a:Array.isArray(a)&&(c=a.find(p=>"text"in p)?.text??"");const u=[];return t&&u.push(...t.map(r=>({...r,args:JSON.stringify(r.args),index:n.index,type:"tool_call_chunk",id:"id"in r&&typeof r.id=="string"?r.id:ae()}))),new ge({text:c,message:new me({content:a||"",name:s?s.role:void 0,tool_call_chunks:u,additional_kwargs:{},response_metadata:{model_provider:"google-genai"},usage_metadata:n.usageMetadata}),generationInfo:i})}function Le(e){return e.every(n=>"functionDeclarations"in n&&Array.isArray(n.functionDeclarations))?e:[{functionDeclarations:e.map(n=>{if(se(n)){const t=N(n.schema);return t.type==="object"&&"properties"in t&&Object.keys(t.properties).length===0?{name:n.name,description:n.description}:{name:n.name,description:n.description,parameters:t}}return ie(n)?{name:n.function.name,description:n.function.description??"A function available to call.",parameters:Ae(n.function.parameters)}:n})}]}var U=class extends ve{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;const n=await we(this.zodSchema,e);if(n.success)return n.data;throw new Te(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const n=e.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(n[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[t]=n;return await this._validateResult(t.args)}},L;(function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"})(L||(L={}));var P;(function(e){e.LANGUAGE_UNSPECIFIED="language_unspecified",e.PYTHON="python"})(P||(P={}));var j;(function(e){e.OUTCOME_UNSPECIFIED="outcome_unspecified",e.OUTCOME_OK="outcome_ok",e.OUTCOME_FAILED="outcome_failed",e.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(j||(j={}));const F=["user","model","function","system"];var K;(function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(K||(K={}));var $;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"})($||($={}));var H;(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(H||(H={}));var B;(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER"})(B||(B={}));var T;(function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.OTHER="OTHER"})(T||(T={}));var Y;(function(e){e.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",e.RETRIEVAL_QUERY="RETRIEVAL_QUERY",e.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",e.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",e.CLASSIFICATION="CLASSIFICATION",e.CLUSTERING="CLUSTERING"})(Y||(Y={}));var w;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"})(w||(w={}));var q;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(q||(q={}));class g extends Error{constructor(n){super(`[GoogleGenerativeAI Error]: ${n}`)}}class v extends g{constructor(n,t){super(n),this.response=t}}class re extends g{constructor(n,t,o,s){super(n),this.status=t,this.statusText=o,this.errorDetails=s}}class y extends g{}class ce extends g{}const Pe="https://generativelanguage.googleapis.com",je="v1beta",Fe="0.24.1",Ke="genai-js";var E;(function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.EMBED_CONTENT="embedContent",e.BATCH_EMBED_CONTENTS="batchEmbedContents"})(E||(E={}));class $e{constructor(n,t,o,s,i){this.model=n,this.task=t,this.apiKey=o,this.stream=s,this.requestOptions=i}toString(){var n,t;const o=((n=this.requestOptions)===null||n===void 0?void 0:n.apiVersion)||je;let i=`${((t=this.requestOptions)===null||t===void 0?void 0:t.baseUrl)||Pe}/${o}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}}function He(e){const n=[];return e?.apiClient&&n.push(e.apiClient),n.push(`${Ke}/${Fe}`),n.join(" ")}async function Be(e){var n;const t=new Headers;t.append("Content-Type","application/json"),t.append("x-goog-api-client",He(e.requestOptions)),t.append("x-goog-api-key",e.apiKey);let o=(n=e.requestOptions)===null||n===void 0?void 0:n.customHeaders;if(o){if(!(o instanceof Headers))try{o=new Headers(o)}catch(s){throw new y(`unable to convert customHeaders value ${JSON.stringify(o)} to Headers: ${s.message}`)}for(const[s,i]of o.entries()){if(s==="x-goog-api-key")throw new y(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new y(`Header name ${s} can only be set using the apiClient field`);t.append(s,i)}}return t}async function Ye(e,n,t,o,s,i){const a=new $e(e,n,t,o,i);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},Je(i)),{method:"POST",headers:await Be(a),body:s})}}async function R(e,n,t,o,s,i={},a=fetch){const{url:c,fetchOptions:u}=await Ye(e,n,t,o,s,i);return qe(c,u,a)}async function qe(e,n,t=fetch){let o;try{o=await t(e,n)}catch(s){We(s,e)}return o.ok||await Ve(o,e),o}function We(e,n){let t=e;throw t.name==="AbortError"?(t=new ce(`Request aborted when fetching ${n.toString()}: ${e.message}`),t.stack=e.stack):e instanceof re||e instanceof y||(t=new g(`Error fetching from ${n.toString()}: ${e.message}`),t.stack=e.stack),t}async function Ve(e,n){let t="",o;try{const s=await e.json();t=s.error.message,s.error.details&&(t+=` ${JSON.stringify(s.error.details)}`,o=s.error.details)}catch{}throw new re(`Error fetching from ${n.toString()}: [${e.status} ${e.statusText}] ${t}`,e.status,e.statusText,o)}function Je(e){const n={};if(e?.signal!==void 0||e?.timeout>=0){const t=new AbortController;e?.timeout>=0&&setTimeout(()=>t.abort(),e.timeout),e?.signal&&e.signal.addEventListener("abort",()=>{t.abort()}),n.signal=t.signal}return n}function b(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return ze(e)}else if(e.promptFeedback)throw new v(`Text not available. ${C(e)}`,e);return""},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),W(e)[0]}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return W(e)}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e}function ze(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.text&&i.push(a.text),a.executableCode&&i.push("\n```"+a.executableCode.language+`
|
|
1
|
+
import{i as ne,t as fe,a as he,b as pe,C as ge,c as me,d as Ce,e as ye,f as oe,g as se,h as ie,j as _e,k as Ee,p as A,B as ve,l as we,O as Te,m as Ie,n as Oe,J as Re,R as D,o as Se}from"./index-Db4_L4WW.js";import{v as ae}from"./index-D6Wv_tf-.js";import"./embeddings-Bd2i0Sjk.js";import"./chunk-VL2OQCWN-CcA-MyVH.js";import"./index-DRz5BQNA.js";function _(e){if(typeof e=="object"&&e!==null){const n={...e};"additionalProperties"in n&&delete n.additionalProperties,"$schema"in n&&delete n.$schema,"strict"in n&&delete n.strict;for(const t in n)t in n&&(Array.isArray(n[t])?n[t]=n[t].map(_):typeof n[t]=="object"&&n[t]!==null&&(n[t]=_(n[t])));return n}return e}function N(e){const n=_(ne(e)?fe(e):e),{$schema:t,...o}=n;return o}function Ae(e){const n=_(e),{$schema:t,...o}=n;return o}function Ne(e){const n=e._getType();return Ce.isInstance(e)?e.role:n==="tool"?n:e.name??n}function be(e){switch(e){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${e}`)}}function Me(e){if("mimeType"in e&&"data"in e)return{inlineData:{mimeType:e.mimeType,data:e.data}};if("mimeType"in e&&"fileUri"in e)return{fileData:{mimeType:e.mimeType,fileUri:e.fileUri}};throw new Error("Invalid media content")}function xe(e,n){return n.map(t=>oe(t)?t.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function De(e){return{providerName:"Google Gemini",fromStandardTextBlock(t){return{text:t.text}},fromStandardImageBlock(t){if(!e)throw new Error("This model does not support images");if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw new Error("This model does not support audio");if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw new Error("This model does not support files");if(t.source_type==="text")return{text:t.text};if(t.source_type==="url"){const o=A({dataUrl:t.url});return o?{inlineData:{mimeType:o.mime_type,data:o.data}}:{fileData:{mimeType:t.mime_type??"",fileUri:t.url}}}if(t.source_type==="base64")return{inlineData:{mimeType:t.mime_type??"",data:t.data}};throw new Error(`Unsupported source type: ${t.source_type}`)}}}function G(e,n){if(_e(e))return Ee(e,De(n));if(e.type==="text")return{text:e.text};if(e.type==="executableCode")return{executableCode:e.executableCode};if(e.type==="codeExecutionResult")return{codeExecutionResult:e.codeExecutionResult};if(e.type==="image_url"){if(!n)throw new Error("This model does not support images");let t;if(typeof e.image_url=="string")t=e.image_url;else if(typeof e.image_url=="object"&&"url"in e.image_url)t=e.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[o,s]=t.split(",");if(!o.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[i,a]=o.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:s,mimeType:i}}}else{if(e.type==="media")return Me(e);if(e.type==="tool_use")return{functionCall:{name:e.name,args:e.input}};if(e.type?.includes("/")&&e.type.split("/").length===2&&"data"in e&&typeof e.data=="string")return{inlineData:{mimeType:e.type,data:e.data}};if("functionCall"in e)return;throw"type"in e?new Error(`Unknown content type ${e.type}`):new Error(`Unknown content ${JSON.stringify(e)}`)}}function Ge(e,n,t){if(ye(e)){const i=e.name??xe(e,t);if(i===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${e.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const a=Array.isArray(e.content)?e.content.map(c=>G(c,n)).filter(c=>c!==void 0):e.content;return e.status==="error"?[{functionResponse:{name:i,response:{error:{details:a}}}}]:[{functionResponse:{name:i,response:{result:a}}}]}let o=[];const s=[];return typeof e.content=="string"&&e.content&&s.push({text:e.content}),Array.isArray(e.content)&&s.push(...e.content.map(i=>G(i,n)).filter(i=>i!==void 0)),oe(e)&&e.tool_calls?.length&&(o=e.tool_calls.map(i=>({functionCall:{name:i.name,args:i.args}}))),[...s,...o]}function k(e,n,t=!1){return e.reduce((o,s,i)=>{if(!he(s))throw new Error("Unsupported message input");const a=Ne(s);if(a==="system"&&i!==0)throw new Error("System message should be the first one");const c=be(a),u=o.content[o.content.length];if(!o.mergeWithPreviousContent&&u&&u.role===c)throw new Error("Google Generative AI requires alternate messages between authors");const r=Ge(s,n,e.slice(0,i));if(o.mergeWithPreviousContent){const d=o.content[o.content.length-1];if(!d)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return d.parts.push(...r),{mergeWithPreviousContent:!1,content:o.content}}let p=c;(p==="function"||p==="system"&&!t)&&(p="user");const f={role:p,parts:r};return{mergeWithPreviousContent:a==="system"&&!t,content:[...o.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function ke(e,n){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.length===1&&s.parts[0].text?a=s.parts[0].text:Array.isArray(s?.parts)&&s.parts.length>0?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";return typeof a=="string"?c=a:Array.isArray(a)&&a.length>0&&(c=a.find(p=>"text"in p)?.text??c),{generations:[{text:c,message:new pe({content:a??"",tool_calls:t?.map(r=>({...r,type:"tool_call",id:"id"in r&&typeof r.id=="string"?r.id:ae()})),additional_kwargs:{...i},usage_metadata:n?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:n?.usageMetadata?.input_tokens,completionTokens:n?.usageMetadata?.output_tokens,totalTokens:n?.usageMetadata?.total_tokens}}}}function Ue(e,n){if(!e.candidates||e.candidates.length===0)return null;const t=e.functionCalls(),[o]=e.candidates,{content:s,...i}=o;let a;Array.isArray(s?.parts)&&s.parts.every(r=>"text"in r)?a=s.parts.map(r=>r.text).join(""):Array.isArray(s?.parts)?a=s.parts.map(r=>"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let c="";a&&typeof a=="string"?c=a:Array.isArray(a)&&(c=a.find(p=>"text"in p)?.text??"");const u=[];return t&&u.push(...t.map(r=>({...r,args:JSON.stringify(r.args),index:n.index,type:"tool_call_chunk",id:"id"in r&&typeof r.id=="string"?r.id:ae()}))),new ge({text:c,message:new me({content:a||"",name:s?s.role:void 0,tool_call_chunks:u,additional_kwargs:{},response_metadata:{model_provider:"google-genai"},usage_metadata:n.usageMetadata}),generationInfo:i})}function Le(e){return e.every(n=>"functionDeclarations"in n&&Array.isArray(n.functionDeclarations))?e:[{functionDeclarations:e.map(n=>{if(se(n)){const t=N(n.schema);return t.type==="object"&&"properties"in t&&Object.keys(t.properties).length===0?{name:n.name,description:n.description}:{name:n.name,description:n.description,parameters:t}}return ie(n)?{name:n.function.name,description:n.function.description??"A function available to call.",parameters:Ae(n.function.parameters)}:n})}]}var U=class extends ve{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(e){super(e),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;const n=await we(this.zodSchema,e);if(n.success)return n.data;throw new Te(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){const n=e.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(n[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[t]=n;return await this._validateResult(t.args)}},L;(function(e){e.STRING="string",e.NUMBER="number",e.INTEGER="integer",e.BOOLEAN="boolean",e.ARRAY="array",e.OBJECT="object"})(L||(L={}));var P;(function(e){e.LANGUAGE_UNSPECIFIED="language_unspecified",e.PYTHON="python"})(P||(P={}));var j;(function(e){e.OUTCOME_UNSPECIFIED="outcome_unspecified",e.OUTCOME_OK="outcome_ok",e.OUTCOME_FAILED="outcome_failed",e.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(j||(j={}));const F=["user","model","function","system"];var K;(function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(K||(K={}));var $;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"})($||($={}));var H;(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(H||(H={}));var B;(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER"})(B||(B={}));var T;(function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.OTHER="OTHER"})(T||(T={}));var Y;(function(e){e.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",e.RETRIEVAL_QUERY="RETRIEVAL_QUERY",e.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",e.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",e.CLASSIFICATION="CLASSIFICATION",e.CLUSTERING="CLUSTERING"})(Y||(Y={}));var w;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE"})(w||(w={}));var q;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(q||(q={}));class g extends Error{constructor(n){super(`[GoogleGenerativeAI Error]: ${n}`)}}class v extends g{constructor(n,t){super(n),this.response=t}}class re extends g{constructor(n,t,o,s){super(n),this.status=t,this.statusText=o,this.errorDetails=s}}class y extends g{}class ce extends g{}const Pe="https://generativelanguage.googleapis.com",je="v1beta",Fe="0.24.1",Ke="genai-js";var E;(function(e){e.GENERATE_CONTENT="generateContent",e.STREAM_GENERATE_CONTENT="streamGenerateContent",e.COUNT_TOKENS="countTokens",e.EMBED_CONTENT="embedContent",e.BATCH_EMBED_CONTENTS="batchEmbedContents"})(E||(E={}));class $e{constructor(n,t,o,s,i){this.model=n,this.task=t,this.apiKey=o,this.stream=s,this.requestOptions=i}toString(){var n,t;const o=((n=this.requestOptions)===null||n===void 0?void 0:n.apiVersion)||je;let i=`${((t=this.requestOptions)===null||t===void 0?void 0:t.baseUrl)||Pe}/${o}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}}function He(e){const n=[];return e?.apiClient&&n.push(e.apiClient),n.push(`${Ke}/${Fe}`),n.join(" ")}async function Be(e){var n;const t=new Headers;t.append("Content-Type","application/json"),t.append("x-goog-api-client",He(e.requestOptions)),t.append("x-goog-api-key",e.apiKey);let o=(n=e.requestOptions)===null||n===void 0?void 0:n.customHeaders;if(o){if(!(o instanceof Headers))try{o=new Headers(o)}catch(s){throw new y(`unable to convert customHeaders value ${JSON.stringify(o)} to Headers: ${s.message}`)}for(const[s,i]of o.entries()){if(s==="x-goog-api-key")throw new y(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new y(`Header name ${s} can only be set using the apiClient field`);t.append(s,i)}}return t}async function Ye(e,n,t,o,s,i){const a=new $e(e,n,t,o,i);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},Je(i)),{method:"POST",headers:await Be(a),body:s})}}async function R(e,n,t,o,s,i={},a=fetch){const{url:c,fetchOptions:u}=await Ye(e,n,t,o,s,i);return qe(c,u,a)}async function qe(e,n,t=fetch){let o;try{o=await t(e,n)}catch(s){We(s,e)}return o.ok||await Ve(o,e),o}function We(e,n){let t=e;throw t.name==="AbortError"?(t=new ce(`Request aborted when fetching ${n.toString()}: ${e.message}`),t.stack=e.stack):e instanceof re||e instanceof y||(t=new g(`Error fetching from ${n.toString()}: ${e.message}`),t.stack=e.stack),t}async function Ve(e,n){let t="",o;try{const s=await e.json();t=s.error.message,s.error.details&&(t+=` ${JSON.stringify(s.error.details)}`,o=s.error.details)}catch{}throw new re(`Error fetching from ${n.toString()}: [${e.status} ${e.statusText}] ${t}`,e.status,e.statusText,o)}function Je(e){const n={};if(e?.signal!==void 0||e?.timeout>=0){const t=new AbortController;e?.timeout>=0&&setTimeout(()=>t.abort(),e.timeout),e?.signal&&e.signal.addEventListener("abort",()=>{t.abort()}),n.signal=t.signal}return n}function b(e){return e.text=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return ze(e)}else if(e.promptFeedback)throw new v(`Text not available. ${C(e)}`,e);return""},e.functionCall=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),W(e)[0]}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e.functionCalls=()=>{if(e.candidates&&e.candidates.length>0){if(e.candidates.length>1&&console.warn(`This response had ${e.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),S(e.candidates[0]))throw new v(`${C(e)}`,e);return W(e)}else if(e.promptFeedback)throw new v(`Function call not available. ${C(e)}`,e)},e}function ze(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.text&&i.push(a.text),a.executableCode&&i.push("\n```"+a.executableCode.language+`
|
|
2
2
|
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&i.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function W(e){var n,t,o,s;const i=[];if(!((t=(n=e.candidates)===null||n===void 0?void 0:n[0].content)===null||t===void 0)&&t.parts)for(const a of(s=(o=e.candidates)===null||o===void 0?void 0:o[0].content)===null||s===void 0?void 0:s.parts)a.functionCall&&i.push(a.functionCall);if(i.length>0)return i}const Xe=[T.RECITATION,T.SAFETY,T.LANGUAGE];function S(e){return!!e.finishReason&&Xe.includes(e.finishReason)}function C(e){var n,t,o;let s="";if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)s+="Response was blocked",!((n=e.promptFeedback)===null||n===void 0)&&n.blockReason&&(s+=` due to ${e.promptFeedback.blockReason}`),!((t=e.promptFeedback)===null||t===void 0)&&t.blockReasonMessage&&(s+=`: ${e.promptFeedback.blockReasonMessage}`);else if(!((o=e.candidates)===null||o===void 0)&&o[0]){const i=e.candidates[0];S(i)&&(s+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(s+=`: ${i.finishMessage}`))}return s}function I(e){return this instanceof I?(this.v=e,this):new I(e)}function Qe(e,n,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o=t.apply(e,n||[]),s,i=[];return s={},a("next"),a("throw"),a("return"),s[Symbol.asyncIterator]=function(){return this},s;function a(d){o[d]&&(s[d]=function(l){return new Promise(function(h,m){i.push([d,l,h,m])>1||c(d,l)})})}function c(d,l){try{u(o[d](l))}catch(h){f(i[0][3],h)}}function u(d){d.value instanceof I?Promise.resolve(d.value.v).then(r,p):f(i[0][2],d)}function r(d){c("next",d)}function p(d){c("throw",d)}function f(d,l){d(l),i.shift(),i.length&&c(i[0][0],i[0][1])}}const V=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function Ze(e){const n=e.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),t=nt(n),[o,s]=t.tee();return{stream:tt(o),response:et(s)}}async function et(e){const n=[],t=e.getReader();for(;;){const{done:o,value:s}=await t.read();if(o)return b(ot(n));n.push(s)}}function tt(e){return Qe(this,arguments,function*(){const t=e.getReader();for(;;){const{value:o,done:s}=yield I(t.read());if(s)break;yield yield I(b(o))}})}function nt(e){const n=e.getReader();return new ReadableStream({start(o){let s="";return i();function i(){return n.read().then(({value:a,done:c})=>{if(c){if(s.trim()){o.error(new g("Failed to parse stream"));return}o.close();return}s+=a;let u=s.match(V),r;for(;u;){try{r=JSON.parse(u[1])}catch{o.error(new g(`Error parsing JSON response: "${u[1]}"`));return}o.enqueue(r),s=s.substring(u[0].length),u=s.match(V)}return i()}).catch(a=>{let c=a;throw c.stack=a.stack,c.name==="AbortError"?c=new ce("Request aborted when reading from the stream"):c=new g("Error reading from the stream"),c})}}})}function ot(e){const n=e[e.length-1],t={promptFeedback:n?.promptFeedback};for(const o of e){if(o.candidates){let s=0;for(const i of o.candidates)if(t.candidates||(t.candidates=[]),t.candidates[s]||(t.candidates[s]={index:s}),t.candidates[s].citationMetadata=i.citationMetadata,t.candidates[s].groundingMetadata=i.groundingMetadata,t.candidates[s].finishReason=i.finishReason,t.candidates[s].finishMessage=i.finishMessage,t.candidates[s].safetyRatings=i.safetyRatings,i.content&&i.content.parts){t.candidates[s].content||(t.candidates[s].content={role:i.content.role||"user",parts:[]});const a={};for(const c of i.content.parts)c.text&&(a.text=c.text),c.functionCall&&(a.functionCall=c.functionCall),c.executableCode&&(a.executableCode=c.executableCode),c.codeExecutionResult&&(a.codeExecutionResult=c.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),t.candidates[s].content.parts.push(a)}s++}o.usageMetadata&&(t.usageMetadata=o.usageMetadata)}return t}async function le(e,n,t,o){const s=await R(n,E.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(t),o);return Ze(s)}async function ue(e,n,t,o){const i=await(await R(n,E.GENERATE_CONTENT,e,!1,JSON.stringify(t),o)).json();return{response:b(i)}}function de(e){if(e!=null){if(typeof e=="string")return{role:"system",parts:[{text:e}]};if(e.text)return{role:"system",parts:[e]};if(e.parts)return e.role?e:{role:"system",parts:e.parts}}}function O(e){let n=[];if(typeof e=="string")n=[{text:e}];else for(const t of e)typeof t=="string"?n.push({text:t}):n.push(t);return st(n)}function st(e){const n={role:"user",parts:[]},t={role:"function",parts:[]};let o=!1,s=!1;for(const i of e)"functionResponse"in i?(t.parts.push(i),s=!0):(n.parts.push(i),o=!0);if(o&&s)throw new g("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!o&&!s)throw new g("No content is provided for sending chat message.");return o?n:t}function it(e,n){var t;let o={model:n?.model,generationConfig:n?.generationConfig,safetySettings:n?.safetySettings,tools:n?.tools,toolConfig:n?.toolConfig,systemInstruction:n?.systemInstruction,cachedContent:(t=n?.cachedContent)===null||t===void 0?void 0:t.name,contents:[]};const s=e.generateContentRequest!=null;if(e.contents){if(s)throw new y("CountTokensRequest must have one of contents or generateContentRequest, not both.");o.contents=e.contents}else if(s)o=Object.assign(Object.assign({},o),e.generateContentRequest);else{const i=O(e);o.contents=[i]}return{generateContentRequest:o}}function J(e){let n;return e.contents?n=e:n={contents:[O(e)]},e.systemInstruction&&(n.systemInstruction=de(e.systemInstruction)),n}function at(e){return typeof e=="string"||Array.isArray(e)?{content:O(e)}:e}const z=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],rt={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function ct(e){let n=!1;for(const t of e){const{role:o,parts:s}=t;if(!n&&o!=="user")throw new g(`First content should be with role 'user', got ${o}`);if(!F.includes(o))throw new g(`Each item should include role field. Got ${o} but valid roles are: ${JSON.stringify(F)}`);if(!Array.isArray(s))throw new g("Content should have 'parts' property with an array of Parts");if(s.length===0)throw new g("Each Content should have at least one part");const i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const c of s)for(const u of z)u in c&&(i[u]+=1);const a=rt[o];for(const c of z)if(!a.includes(c)&&i[c]>0)throw new g(`Content with role '${o}' can't contain '${c}' part`);n=!0}}function X(e){var n;if(e.candidates===void 0||e.candidates.length===0)return!1;const t=(n=e.candidates[0])===null||n===void 0?void 0:n.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(const o of t.parts)if(o===void 0||Object.keys(o).length===0||o.text!==void 0&&o.text==="")return!1;return!0}const Q="SILENT_ERROR";class lt{constructor(n,t,o,s={}){this.model=t,this.params=o,this._requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=n,o?.history&&(ct(o.history),this._history=o.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(n,t={}){var o,s,i,a,c,u;await this._sendPromise;const r=O(n),p={safetySettings:(o=this.params)===null||o===void 0?void 0:o.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(u=this.params)===null||u===void 0?void 0:u.cachedContent,contents:[...this._history,r]},f=Object.assign(Object.assign({},this._requestOptions),t);let d;return this._sendPromise=this._sendPromise.then(()=>ue(this._apiKey,this.model,p,f)).then(l=>{var h;if(X(l.response)){this._history.push(r);const m=Object.assign({parts:[],role:"model"},(h=l.response.candidates)===null||h===void 0?void 0:h[0].content);this._history.push(m)}else{const m=C(l.response);m&&console.warn(`sendMessage() was unsuccessful. ${m}. Inspect response object for details.`)}d=l}).catch(l=>{throw this._sendPromise=Promise.resolve(),l}),await this._sendPromise,d}async sendMessageStream(n,t={}){var o,s,i,a,c,u;await this._sendPromise;const r=O(n),p={safetySettings:(o=this.params)===null||o===void 0?void 0:o.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(u=this.params)===null||u===void 0?void 0:u.cachedContent,contents:[...this._history,r]},f=Object.assign(Object.assign({},this._requestOptions),t),d=le(this._apiKey,this.model,p,f);return this._sendPromise=this._sendPromise.then(()=>d).catch(l=>{throw new Error(Q)}).then(l=>l.response).then(l=>{if(X(l)){this._history.push(r);const h=Object.assign({},l.candidates[0].content);h.role||(h.role="model"),this._history.push(h)}else{const h=C(l);h&&console.warn(`sendMessageStream() was unsuccessful. ${h}. Inspect response object for details.`)}}).catch(l=>{l.message!==Q&&console.error(l)}),d}}async function ut(e,n,t,o){return(await R(n,E.COUNT_TOKENS,e,!1,JSON.stringify(t),o)).json()}async function dt(e,n,t,o){return(await R(n,E.EMBED_CONTENT,e,!1,JSON.stringify(t),o)).json()}async function ft(e,n,t,o){const s=t.requests.map(a=>Object.assign(Object.assign({},a),{model:n}));return(await R(n,E.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:s}),o)).json()}class Z{constructor(n,t,o={}){this.apiKey=n,this._requestOptions=o,t.model.includes("/")?this.model=t.model:this.model=`models/${t.model}`,this.generationConfig=t.generationConfig||{},this.safetySettings=t.safetySettings||[],this.tools=t.tools,this.toolConfig=t.toolConfig,this.systemInstruction=de(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(n,t={}){var o;const s=J(n),i=Object.assign(Object.assign({},this._requestOptions),t);return ue(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(o=this.cachedContent)===null||o===void 0?void 0:o.name},s),i)}async generateContentStream(n,t={}){var o;const s=J(n),i=Object.assign(Object.assign({},this._requestOptions),t);return le(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(o=this.cachedContent)===null||o===void 0?void 0:o.name},s),i)}startChat(n){var t;return new lt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(t=this.cachedContent)===null||t===void 0?void 0:t.name},n),this._requestOptions)}async countTokens(n,t={}){const o=it(n,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),s=Object.assign(Object.assign({},this._requestOptions),t);return ut(this.apiKey,this.model,o,s)}async embedContent(n,t={}){const o=at(n),s=Object.assign(Object.assign({},this._requestOptions),t);return dt(this.apiKey,this.model,o,s)}async batchEmbedContents(n,t={}){const o=Object.assign(Object.assign({},this._requestOptions),t);return ft(this.apiKey,this.model,n,o)}}class ee{constructor(n){this.apiKey=n}getGenerativeModel(n,t){if(!n.model)throw new g("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new Z(this.apiKey,n,t)}getGenerativeModelFromCachedContent(n,t,o){if(!n.name)throw new y("Cached content must contain a `name` field.");if(!n.model)throw new y("Cached content must contain a `model` field.");const s=["model","systemInstruction"];for(const a of s)if(t?.[a]&&n[a]&&t?.[a]!==n[a]){if(a==="model"){const c=t.model.startsWith("models/")?t.model.replace("models/",""):t.model,u=n.model.startsWith("models/")?n.model.replace("models/",""):n.model;if(c===u)continue}throw new y(`Different value for "${a}" specified in modelParams (${t[a]}) and cachedContent (${n[a]})`)}const i=Object.assign(Object.assign({},t),{model:n.model,tools:n.tools,toolConfig:n.toolConfig,systemInstruction:n.systemInstruction,cachedContent:n});return new Z(this.apiKey,i,o)}}function te(e,n){const t=ht(e),o=gt(t,n);return{tools:t,toolConfig:o}}function ht(e){let n=[];const t=[];return e.forEach(s=>{if(se(s)){const[i]=Le([s]);i.functionDeclarations&&n.push(...i.functionDeclarations)}else if(ie(s)){const{functionDeclarations:i}=pt(s);if(i)n.push(...i);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else t.push(s)}),t.find(s=>"functionDeclarations"in s)?t.map(s=>{if(n?.length>0&&"functionDeclarations"in s){const i={functionDeclarations:[...s.functionDeclarations||[],...n]};return n=[],i}return s}):[...t,...n.length>0?[{functionDeclarations:n}]:[]]}function pt(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:_(e.function.parameters)}]}}function gt(e,n){if(!e.length||!n)return;const{toolChoice:t,allowedFunctionNames:o}=n,s={any:w.ANY,auto:w.AUTO,none:w.NONE};if(t&&["any","auto","none"].includes(t))return{functionCallingConfig:{mode:s[t]??"MODE_UNSPECIFIED",allowedFunctionNames:o}};if(typeof t=="string"||o)return{functionCallingConfig:{mode:w.ANY,allowedFunctionNames:[...o??[],...t&&typeof t=="string"?[t]:[]]}}}var vt=class extends Ie{static lc_name(){return"ChatGoogleGenerativeAI"}lc_serializable=!0;get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}lc_namespace=["langchain","chat_models","google_genai"];get lc_aliases(){return{apiKey:"google_api_key"}}model;temperature;maxOutputTokens;topP;topK;stopSequences=[];safetySettings;apiKey;streaming=!1;json;streamUsage=!0;convertSystemMessageToHumanContent;client;get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")}constructor(e){if(super(e),this.model=e.model.replace(/^models\//,""),this.maxOutputTokens=e.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=e.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=e.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=e.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=e.stopSequences??this.stopSequences,this.apiKey=e.apiKey??Oe("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=e.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(t=>t.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=e.streaming??this.streaming,this.json=e.json,this.client=new ee(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{}}},{apiVersion:e.apiVersion,baseUrl:e.baseUrl}),this.streamUsage=e.streamUsage??this.streamUsage}useCachedContent(e,n,t){this.apiKey&&(this.client=new ee(this.apiKey).getGenerativeModelFromCachedContent(e,n,t))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent=="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model==="gemini-1.0-pro-001"||this.model.startsWith("gemini-pro-vision")||this.model.startsWith("gemini-1.0-pro-vision")?!1:this.model!=="gemini-pro"}getLsParams(e){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(e,n){return this.withConfig({tools:te(e)?.tools,...n})}invocationParams(e){const n=e?.tools?.length?te(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return e?.responseSchema?(this.client.generationConfig.responseSchema=e.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...n?.tools?{tools:n.tools}:{},...n?.toolConfig?{toolConfig:n.toolConfig}:{}}}async _generate(e,n,t){const o=k(e,this._isMultimodalModel,this.useSystemInstruction);let s=o;if(o[0].role==="system"){const[r]=o;this.client.systemInstruction=r,s=o.slice(1)}const i=this.invocationParams(n);if(this.streaming){const r={},p=this._streamResponseChunks(e,n,t),f={};for await(const l of p){const h=l.generationInfo?.completion??0;f[h]===void 0?f[h]=l:f[h]=f[h].concat(l)}return{generations:Object.entries(f).sort(([l],[h])=>parseInt(l,10)-parseInt(h,10)).map(([l,h])=>h),llmOutput:{estimatedTokenUsage:r}}}const a=await this.completionWithRetry({...i,contents:s});let c;if("usageMetadata"in a.response){const r=a.response.usageMetadata;c={input_tokens:r.promptTokenCount??0,output_tokens:r.candidatesTokenCount??0,total_tokens:r.totalTokenCount??0}}const u=ke(a.response,{usageMetadata:c});return u.generations?.length>0&&await t?.handleLLMNewToken(u.generations[0]?.text??""),u}async*_streamResponseChunks(e,n,t){const o=k(e,this._isMultimodalModel,this.useSystemInstruction);let s=o;if(o[0].role==="system"){const[l]=o;this.client.systemInstruction=l,s=o.slice(1)}const a={...this.invocationParams(n),contents:s},c=await this.caller.callWithOptions({signal:n?.signal},async()=>{const{stream:l}=await this.client.generateContentStream(a);return l});let u,r=0,p=0,f=0,d=0;for await(const l of c){if("usageMetadata"in l&&l.usageMetadata!==void 0&&this.streamUsage!==!1&&n.streamUsage!==!1){u={input_tokens:l.usageMetadata.promptTokenCount??0,output_tokens:l.usageMetadata.candidatesTokenCount??0,total_tokens:l.usageMetadata.totalTokenCount??0};const m=l.usageMetadata.promptTokenCount??0;u.input_tokens=Math.max(0,m-r),r=m;const M=l.usageMetadata.candidatesTokenCount??0;u.output_tokens=Math.max(0,M-p),p=M;const x=l.usageMetadata.totalTokenCount??0;u.total_tokens=Math.max(0,x-f),f=x}const h=Ue(l,{usageMetadata:u,index:d});d+=1,h&&(yield h,await t?.handleLLMNewToken(h.text??""))}}async completionWithRetry(e,n){return this.caller.callWithOptions({signal:n?.signal},async()=>{try{return await this.client.generateContent(e)}catch(t){throw t.message?.includes("400 Bad Request")&&(t.status=400),t}})}withStructuredOutput(e,n){const t=e,o=n?.name,s=n?.method,i=n?.includeRaw;if(s==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,c;if(s==="functionCalling"){let f=o??"extract",d;if(ne(t)){const l=N(t);d=[{functionDeclarations:[{name:f,description:l.description??"A function available to call.",parameters:l}]}],c=new U({returnSingle:!0,keyName:f,zodSchema:t})}else{let l;typeof t.name=="string"&&typeof t.parameters=="object"&&t.parameters!=null?(l=t,l.parameters=_(t.parameters),f=t.name):l={name:f,description:t.description??"",parameters:_(t)},d=[{functionDeclarations:[l]}],c=new U({returnSingle:!0,keyName:f})}a=this.bindTools(d).withConfig({allowedFunctionNames:[f]})}else{const f=N(t);a=this.withConfig({responseSchema:f}),c=new Re}if(!i)return a.pipe(c).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const u=D.assign({parsed:(f,d)=>c.invoke(f.raw,d)}),r=D.assign({parsed:()=>null}),p=u.withFallbacks({fallbacks:[r]});return Se.from([{raw:a},p]).withConfig({runName:"StructuredOutputRunnable"})}};export{vt as ChatGoogleGenerativeAI};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-LIYVTGEU-
|
|
2
|
-
var yy=Object.defineProperty;var _y=(e,t,n)=>t in e?yy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var du=(e,t,n)=>_y(e,typeof t!="symbol"?t+"":t,n);import{_ as G,c as Wi,u as gt,a as Tt,d as bs,n as le,s as pe,e as Jt,o as Y,f as wy,Z as M,h as nt,i as hu,l as vr,j as vy,k as Ua,p as sh,m as Ur,r as Ss,q as Ba,t as E,w as Ts,v as by,B as Sy,x as Ty,H as Ey,L as Cy,y as Ay,M as ky,W as Oy,z as xy}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/display-LIYVTGEU-CQo10dsV.js","assets/index-D6Wv_tf-.js","assets/index-CAnbiFOL.css","assets/index-BX0m6ynw.js","assets/index-q78x3Wop.js","assets/chunk-VL2OQCWN-CcA-MyVH.js","assets/index-DRz5BQNA.js","assets/__vite-browser-external-DFygW7-s.js","assets/path-C9FudP8b.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var yy=Object.defineProperty;var _y=(e,t,n)=>t in e?yy(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var du=(e,t,n)=>_y(e,typeof t!="symbol"?t+"":t,n);import{_ as G,c as Wi,u as gt,a as Tt,d as bs,n as le,s as pe,e as Jt,o as Y,f as wy,Z as M,h as nt,i as hu,l as vr,j as vy,k as Ua,p as sh,m as Ur,r as Ss,q as Ba,t as E,w as Ts,v as by,B as Sy,x as Ty,H as Ey,L as Cy,y as Ay,M as ky,W as Oy,z as xy}from"./index-D6Wv_tf-.js";import{u as Iy,w as Hc,x as Py,y as ze,z as Ny,A as My,B as Ry,C as $y,D as Ly,E as jy,F as Dy,G as Fy,H as Uy,I as By,d as kn,J as zy,g as $e,K as Hy,L as ah,M as Vy,N as Gy,O as za,h as Vc,Q as Wy,R as Jy,S as Ky,U as Zy,W as qy,X as Yy,Y as Xy,Z as Qy,a0 as e_,a1 as t_,a2 as n_,a3 as pu,a4 as r_,a5 as s_,a6 as a_,a7 as i_,s as o_,v as ke,P as nn,p as Ha,a as Es,b as ih,c as oh,i as Gc,j as c_,f as l_,_ as u_,$ as d_,e as h_,k as p_,t as fu,l as ch,V as Wc,m as f_,n as br,o as m_,T as g_,q as Jc,r as y_,a8 as __}from"./chunk-VL2OQCWN-CcA-MyVH.js";import{o as Fo}from"./__vite-browser-external-DFygW7-s.js";import{j as Va,d as mu,i as w_}from"./path-C9FudP8b.js";var Ji,oa,Ki=0,Zi=0;function v_(e,t,n){var r=0,s=t||new Array(16);e=e||{};var a=e.node,i=e.clockseq;if(e._v6||(a||(a=Ji),i==null&&(i=oa)),a==null||i==null){var o=e.random||(e.rng||Iy)();a==null&&(a=[o[0],o[1],o[2],o[3],o[4],o[5]],!Ji&&!e._v6&&(a[0]|=1,Ji=a)),i==null&&(i=(o[6]<<8|o[7])&16383,oa===void 0&&!e._v6&&(oa=i))}var c=e.msecs!==void 0?e.msecs:Date.now(),l=e.nsecs!==void 0?e.nsecs:Zi+1,u=c-Ki+(l-Zi)/1e4;if(u<0&&e.clockseq===void 0&&(i=i+1&16383),(u<0||c>Ki)&&e.nsecs===void 0&&(l=0),l>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Ki=c,Zi=l,oa=i,c+=122192928e5;var d=((c&268435455)*1e4+l)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=d&255;var h=c/4294967296*1e4&268435455;s[r++]=h>>>8&255,s[r++]=h&255,s[r++]=h>>>24&15|16,s[r++]=h>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var p=0;p<6;++p)s[r+p]=a[p];return t||Hc(s)}function b_(e){var t=typeof e=="string"?Py(e):e,n=S_(t);return typeof e=="string"?Hc(n):n}function S_(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 gu(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function yu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?gu(Object(n),!0).forEach(function(r){T_(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gu(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function T_(e,t,n){return(t=E_(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function E_(e){var t=C_(e,"string");return typeof t=="symbol"?t:t+""}function C_(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function A_(e={},t,n=0){var r=v_(yu(yu({},e),{},{_v6:!0}),new Uint8Array(16));return r=b_(r),Hc(r)}const k_=(e,t)=>{Ny.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>Ry(e,n)},flatten:{value:n=>My(e,n)},addIssue:{value:n=>e.issues.push(n)},addIssues:{value:n=>e.issues.push(...n)},isEmpty:{get(){return e.issues.length===0}}})},yi=ze("ZodError",k_,{Parent:Error}),O_=$y(yi),x_=jy(yi),I_=Ly(yi),P_=Dy(yi),ut=ze("ZodType",(e,t)=>(By.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),e.clone=(n,r)=>kn(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>O_(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>I_(e,n,r),e.parseAsync=async(n,r)=>x_(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>P_(e,n,r),e.spa=e.safeParseAsync,e.refine=(n,r)=>e.check(nw(n,r)),e.superRefine=n=>e.check(rw(n)),e.overwrite=n=>e.check(zy(n)),e.optional=()=>_u(e),e.nullable=()=>wu(e),e.nullish=()=>_u(wu(e)),e.nonoptional=n=>K_(e,n),e.array=()=>R_(e),e.or=n=>L_([e,n]),e.and=n=>D_(e,n),e.transform=n=>vu(e,U_(n)),e.default=n=>V_(e,n),e.prefault=n=>W_(e,n),e.catch=n=>q_(e,n),e.pipe=n=>vu(e,n),e.readonly=()=>Q_(e),e.describe=n=>{const r=e.clone();return $e.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){return $e.get(e)?.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return $e.get(e);const r=e.clone();return $e.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),N_=ze("ZodAny",(e,t)=>{Uy.init(e,t),ut.init(e,t)});function ca(){return Fy(N_)}const M_=ze("ZodArray",(e,t)=>{n_.init(e,t),ut.init(e,t),e.element=t.element,e.min=(n,r)=>e.check(pu(n,r)),e.nonempty=n=>e.check(pu(1,n)),e.max=(n,r)=>e.check(r_(n,r)),e.length=(n,r)=>e.check(s_(n,r)),e.unwrap=()=>e.element});function R_(e,t){return Vy(M_,e,t)}const $_=ze("ZodUnion",(e,t)=>{Ky.init(e,t),ut.init(e,t),e.options=t.options});function L_(e,t){return new $_({type:"union",options:e,...ah(t)})}const j_=ze("ZodIntersection",(e,t)=>{Zy.init(e,t),ut.init(e,t)});function D_(e,t){return new j_({type:"intersection",left:e,right:t})}const F_=ze("ZodTransform",(e,t)=>{Yy.init(e,t),ut.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=a=>{if(typeof a=="string")n.issues.push(za(a,n.value,t));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=e),i.continue??(i.continue=!0),n.issues.push(za(i))}};const s=t.transform(n.value,n);return s instanceof Promise?s.then(a=>(n.value=a,n)):(n.value=s,n)}});function U_(e){return new F_({type:"transform",transform:e})}const B_=ze("ZodOptional",(e,t)=>{Vc.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function _u(e){return new B_({type:"optional",innerType:e})}const z_=ze("ZodNullable",(e,t)=>{Wy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function wu(e){return new z_({type:"nullable",innerType:e})}const H_=ze("ZodDefault",(e,t)=>{Xy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function V_(e,t){return new H_({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const G_=ze("ZodPrefault",(e,t)=>{Qy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function W_(e,t){return new G_({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():t}})}const J_=ze("ZodNonOptional",(e,t)=>{Jy.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType});function K_(e,t){return new J_({type:"nonoptional",innerType:e,...ah(t)})}const Z_=ze("ZodCatch",(e,t)=>{e_.init(e,t),ut.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function q_(e,t){return new Z_({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const Y_=ze("ZodPipe",(e,t)=>{qy.init(e,t),ut.init(e,t),e.in=t.in,e.out=t.out});function vu(e,t){return new Y_({type:"pipe",in:e,out:t})}const X_=ze("ZodReadonly",(e,t)=>{t_.init(e,t),ut.init(e,t)});function Q_(e){return new X_({type:"readonly",innerType:e})}const ew=ze("ZodCustom",(e,t)=>{a_.init(e,t),ut.init(e,t)});function tw(e){const t=new Gy({check:"custom"});return t._zod.check=e,t}function nw(e,t={}){return Hy(ew,e,t)}function rw(e){const t=tw(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(za(r,n.value,t._zod.def));else{const s=r;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!t._zod.def.abort),n.issues.push(za(s))}},e(n.value,n)));return t}async function*lh(e){for await(const t of e)if(t.event==="on_chat_model_stream"&&t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}G(lh,"streamEventsToAISDK");function uh(e){return new ReadableStream({async start(t){try{for await(const n of e)t.enqueue(n);t.close()}catch(n){t.error(n)}}})}G(uh,"createReadableStreamFromGenerator");async function*dh(e){for await(const t of e)switch(t.event){case"on_chat_model_stream":if(t.data?.chunk?.text){const n=t.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
|
|
3
3
|
🔧 Using tool: ${t.name}
|
|
4
4
|
`;break;case"on_tool_end":yield`
|
|
5
5
|
✅ Tool completed: ${t.name}
|
|
@@ -528,7 +528,7 @@ You can then use these server-specific tools in subsequent steps.
|
|
|
528
528
|
Here are the tools *currently* available to you (this list includes server management tools and will
|
|
529
529
|
change when you connect to a server):
|
|
530
530
|
{tool_descriptions}
|
|
531
|
-
`,Fr,BP=(Fr=class{llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;constructor(t){if(t.agentId){this.isRemote=!0,this.remoteAgent=new dy({agentId:t.agentId,apiKey:t.apiKey,baseUrl:t.baseUrl}),this.maxSteps=t.maxSteps??5,this.memoryEnabled=t.memoryEnabled??!0,this.autoInitialize=t.autoInitialize??!1,this.verbose=t.verbose??!1,this.observe=t.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new Dn,this.telemetry=zc.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Uc({customCallbacks:t.callbacks,agentId:t.agentId}),this.callbacks=[];return}if(!t.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(this.llm=t.llm,this.client=t.client,this.connectors=t.connectors??[],this.maxSteps=t.maxSteps??5,this.autoInitialize=t.autoInitialize??!1,this.memoryEnabled=t.memoryEnabled??!0,this.systemPrompt=t.systemPrompt??null,this.systemPromptTemplateOverride=t.systemPromptTemplate??null,this.additionalInstructions=t.additionalInstructions??null,this.disallowedTools=t.disallowedTools??[],this.additionalTools=t.additionalTools??[],this.toolsUsedNames=t.toolsUsedNames??[],this.useServerManager=t.useServerManager??!1,this.verbose=t.verbose??!1,this.observe=t.observe??!0,!this.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=t.adapter??new Dn(this.disallowedTools),this.serverManager=t.serverManagerFactory?.(this.client)??new NP(this.client,this.adapter)}else this.adapter=t.adapter??new Dn(this.disallowedTools);if(this.telemetry=zc.getInstance(),this.llm){const[n,r]=uy(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Uc({customCallbacks:t.callbacks,verbose:this.verbose,observe:this.observe,agentId:t.agentId,metadataProvider:G(()=>this.getMetadata(),"metadataProvider"),tagsProvider:G(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:G(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:G(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:G(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}E.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const t=await this.observabilityManager.getHandlerNames();if(t.length>0&&E.info(`📊 Observability enabled with: ${t.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),E.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),E.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(E.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),E.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),E.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await Dn.createTools(this.client),E.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{E.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const r of this.connectors)r.isClientConnected||await r.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),E.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}E.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),E.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),E.info("✨ Agent initialization complete")}async createSystemMessageFromTools(t){const n=this.systemPromptTemplateOverride??FP;this.systemMessage=fy(t,n,UP,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof Se))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const t=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(a=>a.name);E.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[ay({runLimit:this.maxSteps})],s=Kg({model:this.llm,tools:this._tools,systemPrompt:t,middleware:r});return E.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(t){this.memoryEnabled&&this.conversationHistory.push(t)}getSystemMessage(){return this.systemMessage}setSystemMessage(t){this.systemMessage=new Se(t),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof Se)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),E.debug("Agent recreated with new system message"))}setDisallowedTools(t){this.disallowedTools=t,this.adapter=new Dn(this.disallowedTools),this._initialized&&E.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(t){const n=this.sanitizeMetadata(t);this.metadata={...this.metadata,...n},E.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(t){const n=this.sanitizeTags(t);this.tags=[...new Set([...this.tags,...n])],E.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(t){const n={};for(const[r,s]of Object.entries(t)){if(typeof r!="string"||r.length===0){E.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const a=r.replace(/[^\w-]/g,"_");if(s==null)n[a]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[a]=s;else if(Array.isArray(s)){const i=s.filter(o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean");i.length>0&&(n[a]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(E.warn(`Metadata value for key '${a}' is too large. Truncating.`),n[a]=`${i.substring(0,1e3)}...`):n[a]=s}catch(i){E.warn(`Failed to serialize metadata value for key '${a}': ${i}. Skipping.`)}else E.warn(`Unsupported metadata value type for key '${a}': ${typeof s}. Skipping.`)}return n}sanitizeTags(t){return t.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const t={};try{if(this.client){const n=this.client.getServerNames();t.mcp_servers_count=n.length,t.mcp_server_names=n;const r={};for(const s of n)try{const a=this.client.getServerConfig(s);if(a){let i="unknown";a.command?i="command":a.url?i="http":a.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!a.args,has_env:!!a.env,has_headers:!!a.headers,url:a.url||null,command:a.command||null}}}catch(a){E.warn(`Failed to get config for server '${s}': ${a}`),r[s]={type:"error",error:"config_unavailable"}}t.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(t.mcp_servers_count=this.connectors.length,t.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),t.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){E.warn(`Failed to collect MCP server info: ${n}`),t.error="collection_failed"}return t}_normalizeOutput(t){try{if(typeof t=="string")return t;if(t&&typeof t=="object"&&"content"in t)return this._normalizeOutput(t.content);if(Array.isArray(t)){const n=[];for(const r of t)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const a=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(a))}}return n.join("")}return String(t)}catch{return String(t)}}_isAIMessageLike(t){if(t instanceof D)return!0;if(typeof t!="object"||t===null)return!1;const n=t;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(t){return typeof t=="object"&&t!==null&&"tool_calls"in t&&Array.isArray(t.tool_calls)?t.tool_calls.length>0:!1}_isHumanMessageLike(t){if(t instanceof he)return!0;if(typeof t!="object"||t===null)return!1;const n=t;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(t){if(t instanceof X)return!0;if(typeof t!="object"||t===null)return!1;const n=t;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(t){if(t instanceof D||t&&typeof t=="object"&&"content"in t)return t.content}async _consumeAndReturn(t){for(;;){const{done:n,value:r}=await t.next();if(n)return r}}async run(t,n,r,s,a){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(t,n,r,s,a);const i=this.stream(t,n,r,s,a);return this._consumeAndReturn(i)}async*stream(t,n,r=!0,s,a){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(t,n,r,s,a);let i=!1;const o=Date.now();let c=!1,l=null,u=0;try{if(r&&!this._initialized?(await this.initialize(),i=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),i=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const S=this.serverManager.tools,w=new Set(S.map(T=>T.name)),v=new Set(this._tools.map(T=>T.name));(w.size!==v.size||[...w].some(T=>!v.has(T)))&&(E.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...w].join(", ")}`),this._tools=S,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const d=s??this.conversationHistory,h=[];for(const S of d)(this._isHumanMessageLike(S)||this._isAIMessageLike(S))&&h.push(S);const p=t.length>50?`${t.slice(0,50).replace(/\n/g," ")}...`:t.replace(/\n/g," ");E.info(`💬 Received query: '${p}'`),E.info("🏁 Starting agent execution");const f=3;let g=0;const b=[...h,new he(t)];for(;g<=f;){const S={messages:b};let w=!1;const v=await this._agentExecutor.stream(S,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const T of v){for(const[k,O]of Object.entries(T))if(E.debug(`📦 Node '${k}' output: ${JSON.stringify(O)}`),O&&typeof O=="object"&&"messages"in O){let C=O.messages;Array.isArray(C)||(C=[C]);for(const y of C)b.includes(y)||b.push(y);for(const y of C){if("tool_calls"in y&&Array.isArray(y.tool_calls)&&y.tool_calls.length>0)for(const N of y.tool_calls){const I=N.name||"unknown",R=N.args||{};this.toolsUsedNames.push(I),u++;let z=JSON.stringify(R);z.length>100&&(z=`${z.slice(0,97)}...`),E.info(`🔧 Tool call: ${I} with input: ${z}`),yield{action:{tool:I,toolInput:R,log:`Calling tool ${I}`},observation:""}}if(this._isToolMessageLike(y)){const N=y.content;let I=String(N);if(I.length>100&&(I=`${I.slice(0,97)}...`),I=I.replace(/\n/g," "),E.info(`📄 Tool result: ${I}`),this.useServerManager&&this.serverManager){const R=this.serverManager.tools,z=new Set(R.map(fe=>fe.name)),ce=new Set(this._tools.map(fe=>fe.name));if(z.size!==ce.size||[...z].some(fe=>!ce.has(fe))){E.info(`🔄 Tools changed during execution. New tools: ${[...z].join(", ")}`),this._tools=R,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),w=!0,g++,E.info(`🔃 Restarting execution with updated tools (restart ${g}/${f})`);break}}}this._isAIMessageLike(y)&&!this._messageHasToolCalls(y)&&(l=this._normalizeOutput(this._getMessageContent(y)),E.info("✅ Agent finished with output"))}if(w)break}if(w)break}if(!w)break;if(g>f){E.warn(`⚠️ Max restarts (${f}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled&&(this.addToHistory(new he(t)),l&&this.addToHistory(new D(l))),a&&l)try{E.info("🔧 Attempting structured output...");const S=await this._attemptStructuredOutput(l,this.llm,a);return this.memoryEnabled&&this.addToHistory(new D(`Structured result: ${JSON.stringify(S)}`)),E.info("✅ Structured output successful"),c=!0,S}catch(S){throw E.error(`❌ Structured output failed: ${S}`),new Error(`Failed to generate structured output: ${S instanceof Error?S.message:String(S)}`)}return E.info(`🎉 Agent execution complete in ${((Date.now()-o)/1e3).toFixed(2)} seconds`),c=!0,l||"No output generated"}catch(d){throw E.error(`❌ Error running query: ${d}`),i&&r&&(E.info("🧹 Cleaning up resources after error"),await this.close()),d}finally{const d=Date.now()-o;let h=0;this.client?h=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(h=this.connectors.length);const p=this.memoryEnabled?this.conversationHistory.length:0,f=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:t,success:c,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:h,serverIdentifiers:this.connectors.map(g=>g.publicIdentifier),totalToolsAvailable:f.length,toolsAvailableNames:f.map(g=>g.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:l||"",executionTimeMs:d,errorType:c?null:"execution_error",conversationHistoryLength:p}),r&&!this.client&&i&&(E.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(E.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}E.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)E.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const t of this.connectors)E.info("🔄 Disconnecting connector"),await t.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new Dn)}finally{this._initialized=!1,E.info("👋 Agent closed successfully")}}async*prettyStreamEvents(t,n,r=!0,s,a){const{prettyStreamEvents:i}=await Ts(async()=>{const{prettyStreamEvents:c}=await import("./display-LIYVTGEU-BHRqqKvX.js");return{prettyStreamEvents:c}},__vite__mapDeps([0,1,2])),o="";for await(const c of i(this.streamEvents(t,n,r,s,a)))yield;return o}async*streamEvents(t,n,r=!0,s,a){let i=!1;const o=Date.now();let c=!1,l=0,u=0,d="";a&&(t=this._enhanceQueryWithSchema(t,a));try{r&&!this._initialized?(await this.initialize(),i=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),i=!0);const h=this._agentExecutor;if(!h)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const p=typeof t=="string"&&t.length>50?`${t.slice(0,50).replace(/\n/g," ")}...`:typeof t=="string"?t.replace(/\n/g," "):String(t);E.info(`💬 Received query for streamEvents: '${p}'`),this.memoryEnabled&&(E.info(`🔄 Adding user message to history: ${p}`),this.addToHistory(new he({content:t})));const f=s??this.conversationHistory,g=[];for(const w of f)this._isHumanMessageLike(w)||this._isAIMessageLike(w)||this._isToolMessageLike(w)?g.push(w):E.info(`⚠️ Skipped message of type: ${w.constructor?.name||typeof w}`);const b=[...g,new he(t)];E.info("callbacks",this.callbacks);const S=h.streamEvents({messages:b},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const w of S)if(l++,!(!w||typeof w!="object")){if(w.event==="on_chat_model_stream"&&w.data?.chunk?.content&&(u+=w.data.chunk.content.length),w.event==="on_chat_model_stream"&&w.data?.chunk){const v=w.data.chunk;if(v.content){d||(d="");const T=this._normalizeOutput(v.content);d+=T,E.debug(`📝 Accumulated response length: ${d.length}`)}}if(yield w,w.event==="on_chain_end"&&w.data?.output&&!d){const v=w.data.output;Array.isArray(v)&&v.length>0&&v[0]?.text?d=v[0].text:typeof v=="string"?d=v:v&&typeof v=="object"&&"output"in v&&(d=v.output)}}if(a&&d){E.info("🔧 Attempting structured output conversion...");try{let w=!1,v=null,T=null;this._attemptStructuredOutput(d,this.llm,a).then(O=>(w=!0,v=O,O)).catch(O=>{throw w=!0,T=O,O});let k=0;for(;!w;)await new Promise(O=>setTimeout(O,2e3)),w||(k++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${k*2}s)`,elapsed:k*2}});if(T)throw T;v&&(yield{event:"on_structured_output",data:{output:v}},this.memoryEnabled&&this.addToHistory(new D(`Structured result: ${JSON.stringify(v)}`)),E.info("✅ Structured output successful"))}catch(w){E.warn(`⚠️ Structured output failed: ${w}`),yield{event:"on_structured_output_error",data:{error:w instanceof Error?w.message:String(w)}}}}else this.memoryEnabled&&d&&this.addToHistory(new D(d));console.log(`
|
|
531
|
+
`,Fr,BP=(Fr=class{llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;constructor(t){if(t.agentId){this.isRemote=!0,this.remoteAgent=new dy({agentId:t.agentId,apiKey:t.apiKey,baseUrl:t.baseUrl}),this.maxSteps=t.maxSteps??5,this.memoryEnabled=t.memoryEnabled??!0,this.autoInitialize=t.autoInitialize??!1,this.verbose=t.verbose??!1,this.observe=t.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new Dn,this.telemetry=zc.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Uc({customCallbacks:t.callbacks,agentId:t.agentId}),this.callbacks=[];return}if(!t.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(this.llm=t.llm,this.client=t.client,this.connectors=t.connectors??[],this.maxSteps=t.maxSteps??5,this.autoInitialize=t.autoInitialize??!1,this.memoryEnabled=t.memoryEnabled??!0,this.systemPrompt=t.systemPrompt??null,this.systemPromptTemplateOverride=t.systemPromptTemplate??null,this.additionalInstructions=t.additionalInstructions??null,this.disallowedTools=t.disallowedTools??[],this.additionalTools=t.additionalTools??[],this.toolsUsedNames=t.toolsUsedNames??[],this.useServerManager=t.useServerManager??!1,this.verbose=t.verbose??!1,this.observe=t.observe??!0,!this.client&&this.connectors.length===0)throw new Error("Either 'client' or at least one 'connector' must be provided.");if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=t.adapter??new Dn(this.disallowedTools),this.serverManager=t.serverManagerFactory?.(this.client)??new NP(this.client,this.adapter)}else this.adapter=t.adapter??new Dn(this.disallowedTools);if(this.telemetry=zc.getInstance(),this.llm){const[n,r]=uy(this.llm);this.modelProvider=n,this.modelName=r}else this.modelProvider="unknown",this.modelName="unknown";this.observabilityManager=new Uc({customCallbacks:t.callbacks,verbose:this.verbose,observe:this.observe,agentId:t.agentId,metadataProvider:G(()=>this.getMetadata(),"metadataProvider"),tagsProvider:G(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:G(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:G(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:G(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}E.info("🚀 Initializing MCP agent and connecting to services..."),this.callbacks=await this.observabilityManager.getCallbacks();const t=await this.observabilityManager.getHandlerNames();if(t.length>0&&E.info(`📊 Observability enabled with: ${t.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),E.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),E.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(E.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),E.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),E.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else this._tools=await Dn.createTools(this.client),E.info(`🛠️ Created ${this._tools.length} LangChain tools from client`);this._tools.push(...this.additionalTools)}else{E.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const r of this.connectors)r.isClientConnected||await r.connect();this._tools=await this.adapter.createToolsFromConnectors(this.connectors),this._tools.push(...this.additionalTools),E.info(`🛠️ Created ${this._tools.length} LangChain tools from connectors`)}E.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),E.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),E.info("✨ Agent initialization complete")}async createSystemMessageFromTools(t){const n=this.systemPromptTemplateOverride??FP;this.systemMessage=fy(t,n,UP,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof Se))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const t=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(a=>a.name);E.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[ay({runLimit:this.maxSteps})],s=Kg({model:this.llm,tools:this._tools,systemPrompt:t,middleware:r});return E.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(t){this.memoryEnabled&&this.conversationHistory.push(t)}getSystemMessage(){return this.systemMessage}setSystemMessage(t){this.systemMessage=new Se(t),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof Se)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),E.debug("Agent recreated with new system message"))}setDisallowedTools(t){this.disallowedTools=t,this.adapter=new Dn(this.disallowedTools),this._initialized&&E.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(t){const n=this.sanitizeMetadata(t);this.metadata={...this.metadata,...n},E.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(t){const n=this.sanitizeTags(t);this.tags=[...new Set([...this.tags,...n])],E.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(t){const n={};for(const[r,s]of Object.entries(t)){if(typeof r!="string"||r.length===0){E.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const a=r.replace(/[^\w-]/g,"_");if(s==null)n[a]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[a]=s;else if(Array.isArray(s)){const i=s.filter(o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean");i.length>0&&(n[a]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(E.warn(`Metadata value for key '${a}' is too large. Truncating.`),n[a]=`${i.substring(0,1e3)}...`):n[a]=s}catch(i){E.warn(`Failed to serialize metadata value for key '${a}': ${i}. Skipping.`)}else E.warn(`Unsupported metadata value type for key '${a}': ${typeof s}. Skipping.`)}return n}sanitizeTags(t){return t.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const t={};try{if(this.client){const n=this.client.getServerNames();t.mcp_servers_count=n.length,t.mcp_server_names=n;const r={};for(const s of n)try{const a=this.client.getServerConfig(s);if(a){let i="unknown";a.command?i="command":a.url?i="http":a.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!a.args,has_env:!!a.env,has_headers:!!a.headers,url:a.url||null,command:a.command||null}}}catch(a){E.warn(`Failed to get config for server '${s}': ${a}`),r[s]={type:"error",error:"config_unavailable"}}t.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(t.mcp_servers_count=this.connectors.length,t.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),t.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){E.warn(`Failed to collect MCP server info: ${n}`),t.error="collection_failed"}return t}_normalizeOutput(t){try{if(typeof t=="string")return t;if(t&&typeof t=="object"&&"content"in t)return this._normalizeOutput(t.content);if(Array.isArray(t)){const n=[];for(const r of t)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const a=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(a))}}return n.join("")}return String(t)}catch{return String(t)}}_isAIMessageLike(t){if(t instanceof D)return!0;if(typeof t!="object"||t===null)return!1;const n=t;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(t){return typeof t=="object"&&t!==null&&"tool_calls"in t&&Array.isArray(t.tool_calls)?t.tool_calls.length>0:!1}_isHumanMessageLike(t){if(t instanceof he)return!0;if(typeof t!="object"||t===null)return!1;const n=t;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(t){if(t instanceof X)return!0;if(typeof t!="object"||t===null)return!1;const n=t;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(t){if(t instanceof D||t&&typeof t=="object"&&"content"in t)return t.content}async _consumeAndReturn(t){for(;;){const{done:n,value:r}=await t.next();if(n)return r}}async run(t,n,r,s,a){if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(t,n,r,s,a);const i=this.stream(t,n,r,s,a);return this._consumeAndReturn(i)}async*stream(t,n,r=!0,s,a){if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(t,n,r,s,a);let i=!1;const o=Date.now();let c=!1,l=null,u=0;try{if(r&&!this._initialized?(await this.initialize(),i=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),i=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const S=this.serverManager.tools,w=new Set(S.map(T=>T.name)),v=new Set(this._tools.map(T=>T.name));(w.size!==v.size||[...w].some(T=>!v.has(T)))&&(E.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...w].join(", ")}`),this._tools=S,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const d=s??this.conversationHistory,h=[];for(const S of d)(this._isHumanMessageLike(S)||this._isAIMessageLike(S))&&h.push(S);const p=t.length>50?`${t.slice(0,50).replace(/\n/g," ")}...`:t.replace(/\n/g," ");E.info(`💬 Received query: '${p}'`),E.info("🏁 Starting agent execution");const f=3;let g=0;const b=[...h,new he(t)];for(;g<=f;){const S={messages:b};let w=!1;const v=await this._agentExecutor.stream(S,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const T of v){for(const[k,O]of Object.entries(T))if(E.debug(`📦 Node '${k}' output: ${JSON.stringify(O)}`),O&&typeof O=="object"&&"messages"in O){let C=O.messages;Array.isArray(C)||(C=[C]);for(const y of C)b.includes(y)||b.push(y);for(const y of C){if("tool_calls"in y&&Array.isArray(y.tool_calls)&&y.tool_calls.length>0)for(const N of y.tool_calls){const I=N.name||"unknown",R=N.args||{};this.toolsUsedNames.push(I),u++;let z=JSON.stringify(R);z.length>100&&(z=`${z.slice(0,97)}...`),E.info(`🔧 Tool call: ${I} with input: ${z}`),yield{action:{tool:I,toolInput:R,log:`Calling tool ${I}`},observation:""}}if(this._isToolMessageLike(y)){const N=y.content;let I=String(N);if(I.length>100&&(I=`${I.slice(0,97)}...`),I=I.replace(/\n/g," "),E.info(`📄 Tool result: ${I}`),this.useServerManager&&this.serverManager){const R=this.serverManager.tools,z=new Set(R.map(fe=>fe.name)),ce=new Set(this._tools.map(fe=>fe.name));if(z.size!==ce.size||[...z].some(fe=>!ce.has(fe))){E.info(`🔄 Tools changed during execution. New tools: ${[...z].join(", ")}`),this._tools=R,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),w=!0,g++,E.info(`🔃 Restarting execution with updated tools (restart ${g}/${f})`);break}}}this._isAIMessageLike(y)&&!this._messageHasToolCalls(y)&&(l=this._normalizeOutput(this._getMessageContent(y)),E.info("✅ Agent finished with output"))}if(w)break}if(w)break}if(!w)break;if(g>f){E.warn(`⚠️ Max restarts (${f}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled&&(this.addToHistory(new he(t)),l&&this.addToHistory(new D(l))),a&&l)try{E.info("🔧 Attempting structured output...");const S=await this._attemptStructuredOutput(l,this.llm,a);return this.memoryEnabled&&this.addToHistory(new D(`Structured result: ${JSON.stringify(S)}`)),E.info("✅ Structured output successful"),c=!0,S}catch(S){throw E.error(`❌ Structured output failed: ${S}`),new Error(`Failed to generate structured output: ${S instanceof Error?S.message:String(S)}`)}return E.info(`🎉 Agent execution complete in ${((Date.now()-o)/1e3).toFixed(2)} seconds`),c=!0,l||"No output generated"}catch(d){throw E.error(`❌ Error running query: ${d}`),i&&r&&(E.info("🧹 Cleaning up resources after error"),await this.close()),d}finally{const d=Date.now()-o;let h=0;this.client?h=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(h=this.connectors.length);const p=this.memoryEnabled?this.conversationHistory.length:0,f=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:t,success:c,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:h,serverIdentifiers:this.connectors.map(g=>g.publicIdentifier),totalToolsAvailable:f.length,toolsAvailableNames:f.map(g=>g.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,stepsTaken:u,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:l||"",executionTimeMs:d,errorType:c?null:"execution_error",conversationHistoryLength:p}),r&&!this.client&&i&&(E.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(E.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}E.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)E.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={};else for(const t of this.connectors)E.info("🔄 Disconnecting connector"),await t.disconnect();"connectorToolMap"in this.adapter&&(this.adapter=new Dn)}finally{this._initialized=!1,E.info("👋 Agent closed successfully")}}async*prettyStreamEvents(t,n,r=!0,s,a){const{prettyStreamEvents:i}=await Ts(async()=>{const{prettyStreamEvents:c}=await import("./display-LIYVTGEU-CQo10dsV.js");return{prettyStreamEvents:c}},__vite__mapDeps([0,1,2])),o="";for await(const c of i(this.streamEvents(t,n,r,s,a)))yield;return o}async*streamEvents(t,n,r=!0,s,a){let i=!1;const o=Date.now();let c=!1,l=0,u=0,d="";a&&(t=this._enhanceQueryWithSchema(t,a));try{r&&!this._initialized?(await this.initialize(),i=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),i=!0);const h=this._agentExecutor;if(!h)throw new Error("MCP agent failed to initialize");this.maxSteps=n??this.maxSteps;const p=typeof t=="string"&&t.length>50?`${t.slice(0,50).replace(/\n/g," ")}...`:typeof t=="string"?t.replace(/\n/g," "):String(t);E.info(`💬 Received query for streamEvents: '${p}'`),this.memoryEnabled&&(E.info(`🔄 Adding user message to history: ${p}`),this.addToHistory(new he({content:t})));const f=s??this.conversationHistory,g=[];for(const w of f)this._isHumanMessageLike(w)||this._isAIMessageLike(w)||this._isToolMessageLike(w)?g.push(w):E.info(`⚠️ Skipped message of type: ${w.constructor?.name||typeof w}`);const b=[...g,new he(t)];E.info("callbacks",this.callbacks);const S=h.streamEvents({messages:b},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id}});for await(const w of S)if(l++,!(!w||typeof w!="object")){if(w.event==="on_chat_model_stream"&&w.data?.chunk?.content&&(u+=w.data.chunk.content.length),w.event==="on_chat_model_stream"&&w.data?.chunk){const v=w.data.chunk;if(v.content){d||(d="");const T=this._normalizeOutput(v.content);d+=T,E.debug(`📝 Accumulated response length: ${d.length}`)}}if(yield w,w.event==="on_chain_end"&&w.data?.output&&!d){const v=w.data.output;Array.isArray(v)&&v.length>0&&v[0]?.text?d=v[0].text:typeof v=="string"?d=v:v&&typeof v=="object"&&"output"in v&&(d=v.output)}}if(a&&d){E.info("🔧 Attempting structured output conversion...");try{let w=!1,v=null,T=null;this._attemptStructuredOutput(d,this.llm,a).then(O=>(w=!0,v=O,O)).catch(O=>{throw w=!0,T=O,O});let k=0;for(;!w;)await new Promise(O=>setTimeout(O,2e3)),w||(k++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${k*2}s)`,elapsed:k*2}});if(T)throw T;v&&(yield{event:"on_structured_output",data:{output:v}},this.memoryEnabled&&this.addToHistory(new D(`Structured result: ${JSON.stringify(v)}`)),E.info("✅ Structured output successful"))}catch(w){E.warn(`⚠️ Structured output failed: ${w}`),yield{event:"on_structured_output_error",data:{error:w instanceof Error?w.message:String(w)}}}}else this.memoryEnabled&&d&&this.addToHistory(new D(d));console.log(`
|
|
532
532
|
|
|
533
533
|
`),E.info(`🎉 StreamEvents complete - ${l} events emitted`),c=!0}catch(h){throw E.error(`❌ Error during streamEvents: ${h}`),i&&r&&(E.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),h}finally{const h=Date.now()-o;let p=0;this.client?p=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(p=this.connectors.length);const f=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:t,success:c,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:p,serverIdentifiers:this.connectors.map(g=>g.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(g=>g.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:n??null,manageConnector:r,externalHistoryUsed:s!==void 0,response:`[STREAMED RESPONSE - ${u} chars]`,executionTimeMs:h,errorType:c?null:"streaming_error",conversationHistoryLength:f}),r&&!this.client&&i&&(E.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(t,n,r){E.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),E.info(`🔄 Raw result: ${JSON.stringify(t,null,2)}`);let s=null,a="";if(E.debug(`🔄 Structured output requested, schema: ${JSON.stringify(ba(r),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")s=n.withStructuredOutput(r);else if(n)s=n;else throw new Error("LLM is required for structured output");const i=ba(r),{$schema:o,additionalProperties:c,...l}=i;a=JSON.stringify(l,null,2),E.info(`🔄 Schema description: ${a}`);let u="";typeof t=="string"?u=t:t&&typeof t=="object"&&(u=JSON.stringify(t)),E.info("rawResult",t),u||(u=JSON.stringify(t));const d=3;let h="";for(let p=1;p<=d;p++){E.info(`🔄 Structured output attempt ${p}/${d}`);let f=`
|
|
534
534
|
Please format the following information according to the EXACT schema specified below.
|
|
@@ -561,4 +561,4 @@ ${f}`);const b=await s.stream(f);let S=null,w=0;for await(const T of b){if(w++,E
|
|
|
561
561
|
|
|
562
562
|
Make sure you gather ALL the required information during your task execution.
|
|
563
563
|
If any required information is missing, continue working to find it.
|
|
564
|
-
`}catch(r){return E.warn(`Could not extract schema details: ${r}`),t}}},G(Fr,"MCPAgent"),Fr),Re={},zP=Re.MCP_USE_LANGFUSE?.toLowerCase()==="false",Ws={handler:null,client:null,initPromise:null};async function au(e,t,n,r){try{const s=await Ts(()=>import("./index-
|
|
564
|
+
`}catch(r){return E.warn(`Could not extract schema details: ${r}`),t}}},G(Fr,"MCPAgent"),Fr),Re={},zP=Re.MCP_USE_LANGFUSE?.toLowerCase()==="false",Ws={handler:null,client:null,initPromise:null};async function au(e,t,n,r){try{const s=await Ts(()=>import("./index-BX0m6ynw.js"),__vite__mapDeps([3,4,1,2,5,6,7,8])).catch(()=>null);if(!s){E.debug("Langfuse package not installed - tracing disabled. Install with: npm install @langfuse/langchain");return}const{CallbackHandler:a}=s,u=class u extends a{agentId;metadata;metadataProvider;tagsProvider;verbose;constructor(h,p,f,g,b){super(h),this.agentId=p,this.metadata=f,this.metadataProvider=g,this.tagsProvider=b,this.verbose=h?.verbose??!1}async handleChainStart(h,p,f,g,b,S,w,v){E.debug("Langfuse: Chain start intercepted");const T=this.getCustomTags(),k=this.getMetadata(),O=[...b||[],...T],C={...S||{},...k};return this.verbose&&(E.debug(`Langfuse: Chain start with custom tags: ${JSON.stringify(O)}`),E.debug(`Langfuse: Chain start with metadata: ${JSON.stringify(C)}`)),super.handleChainStart(h,p,f,g,O,C,w,v)}getCustomTags(){const h=[],p=this.getEnvironmentTag();if(p&&h.push(`env:${p}`),this.agentId&&h.push(`agent_id:${this.agentId}`),this.tagsProvider){const f=this.tagsProvider();f&&f.length>0&&h.push(...f)}return h}getMetadata(){const h={},p=this.getEnvironmentTag();if(p&&(h.env=p),this.agentId&&(h.agent_id=this.agentId),this.metadata&&Object.assign(h,this.metadata),this.metadataProvider){const f=this.metadataProvider();f&&Object.assign(h,f)}return h}getEnvironmentTag(){const h=Re.MCP_USE_AGENT_ENV;if(!h)return"unknown";const p=h.toLowerCase();return p==="local"||p==="development"?"local":p==="production"||p==="prod"?"production":p==="staging"||p==="stage"?"staging":p==="hosted"||p==="cloud"?"hosted":p.replace(/[^a-z0-9_-]/g,"_")}async handleLLMStart(...h){return E.debug("Langfuse: LLM start intercepted"),this.verbose&&E.debug(`Langfuse: LLM start args: ${JSON.stringify(h)}`),super.handleLLMStart(...h)}async handleToolStart(...h){return E.debug("Langfuse: Tool start intercepted"),this.verbose&&E.debug(`Langfuse: Tool start args: ${JSON.stringify(h)}`),super.handleToolStart(...h)}async handleRetrieverStart(...h){return E.debug("Langfuse: Retriever start intercepted"),this.verbose&&E.debug(`Langfuse: Retriever start args: ${JSON.stringify(h)}`),super.handleRetrieverStart(...h)}async handleAgentAction(...h){return E.debug("Langfuse: Agent action intercepted"),this.verbose&&E.debug(`Langfuse: Agent action args: ${JSON.stringify(h)}`),super.handleAgentAction(...h)}async handleAgentEnd(...h){return E.debug("Langfuse: Agent end intercepted"),this.verbose&&E.debug(`Langfuse: Agent end args: ${JSON.stringify(h)}`),super.handleAgentEnd(...h)}};G(u,"LoggingCallbackHandler");let i=u;const o=t||(n?n():{}),c=r?r():[],l={publicKey:Re.LANGFUSE_PUBLIC_KEY,secretKey:Re.LANGFUSE_SECRET_KEY,baseUrl:Re.LANGFUSE_HOST||Re.LANGFUSE_BASEURL||"https://cloud.langfuse.com",flushAt:Number.parseInt(Re.LANGFUSE_FLUSH_AT||"15"),flushInterval:Number.parseInt(Re.LANGFUSE_FLUSH_INTERVAL||"10000"),release:Re.LANGFUSE_RELEASE,requestTimeout:Number.parseInt(Re.LANGFUSE_REQUEST_TIMEOUT||"10000"),enabled:Re.LANGFUSE_ENABLED!=="false",traceName:o.trace_name||Re.LANGFUSE_TRACE_NAME||"mcp-use-agent",sessionId:o.session_id||void 0,userId:o.user_id||void 0,tags:c.length>0?c:void 0,metadata:o||void 0};E.debug("Langfuse handler config:",JSON.stringify({traceName:l.traceName,sessionId:l.sessionId,userId:l.userId,tags:l.tags},null,2)),Ws.handler=new i(l,e,t,n,r),E.debug("Langfuse observability initialized successfully with logging enabled");try{const d=await Ts(()=>import("./index-q78x3Wop.js"),__vite__mapDeps([4,1,2,5,6,7,8])).catch(()=>null);if(d){const{Langfuse:h}=d;Ws.client=new h({publicKey:Re.LANGFUSE_PUBLIC_KEY,secretKey:Re.LANGFUSE_SECRET_KEY,baseUrl:Re.LANGFUSE_HOST||"https://cloud.langfuse.com"}),E.debug("Langfuse client initialized")}}catch(d){E.debug(`Langfuse client initialization failed: ${d}`)}}catch(s){E.debug(`Langfuse initialization error: ${s}`)}}G(au,"initializeLangfuse");zP?E.debug("Langfuse tracing disabled via MCP_USE_LANGFUSE environment variable"):!Re.LANGFUSE_PUBLIC_KEY||!Re.LANGFUSE_SECRET_KEY?E.debug("Langfuse API keys not found - tracing disabled. Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY to enable"):Ws.initPromise=au();var HP=G(()=>Ws.handler,"langfuseHandler"),VP=G(()=>Ws.initPromise,"langfuseInitPromise");const nN=Object.freeze(Object.defineProperty({__proto__:null,BaseAdapter:iy,BaseConnector:Sy,BrowserOAuthClientProvider:Ty,HttpConnector:Ey,LangChainAdapter:Dn,Logger:Cy,MCPAgent:BP,MCPClient:Ay,MCPSession:ky,ObservabilityManager:Uc,RemoteAgent:dy,WebSocketConnector:Oy,createReadableStreamFromGenerator:uh,logger:E,onMcpAuthorization:xy,streamEventsToAISDK:lh,streamEventsToAISDKWithTools:dh},Symbol.toStringTag,{value:"Module"})),rh=Object.freeze(Object.defineProperty({__proto__:null,initializeLangfuse:au,langfuseHandler:HP,langfuseInitPromise:VP},Symbol.toStringTag,{value:"Module"}));export{D as A,es as B,Xn as C,vi as F,he as H,Se as S,X as T,rt as a,yt as b,nN as c,lt as m};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as St,g as Vo}from"./index-
|
|
1
|
+
import{b as St,g as Vo}from"./index-D6Wv_tf-.js";import{o as Ko}from"./__vite-browser-external-DFygW7-s.js";import{r as Jo}from"./index-DRz5BQNA.js";import{p as Zo}from"./path-C9FudP8b.js";function Qo(r,i){for(var v=0;v<i.length;v++){const E=i[v];if(typeof E!="string"&&!Array.isArray(E)){for(const d in E)if(d!=="default"&&!(d in r)){const l=Object.getOwnPropertyDescriptor(E,d);l&&Object.defineProperty(r,d,l.get?l:{enumerable:!0,get:()=>E[d]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}var Pt={},ze={},Tt,rn;function ye(){if(rn)return Tt;rn=1;function r(m){"@babel/helpers - typeof";return r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},r(m)}function i(m,s,c){return Object.defineProperty(m,"prototype",{writable:!1}),m}function v(m,s){if(!(m instanceof s))throw new TypeError("Cannot call a class as a function")}function E(m,s,c){return s=p(s),d(m,_()?Reflect.construct(s,c||[],p(m).constructor):s.apply(m,c))}function d(m,s){if(s&&(r(s)=="object"||typeof s=="function"))return s;if(s!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return l(m)}function l(m){if(m===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return m}function h(m,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");m.prototype=Object.create(s&&s.prototype,{constructor:{value:m,writable:!0,configurable:!0}}),Object.defineProperty(m,"prototype",{writable:!1}),s&&x(m,s)}function t(m){var s=typeof Map=="function"?new Map:void 0;return t=function(a){if(a===null||!y(a))return a;if(typeof a!="function")throw new TypeError("Super expression must either be null or a function");if(s!==void 0){if(s.has(a))return s.get(a);s.set(a,o)}function o(){return u(a,arguments,p(this).constructor)}return o.prototype=Object.create(a.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),x(o,a)},t(m)}function u(m,s,c){if(_())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,s);var o=new(m.bind.apply(m,a));return c&&x(o,c.prototype),o}function _(){try{var m=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(_=function(){return!!m})()}function y(m){try{return Function.toString.call(m).indexOf("[native code]")!==-1}catch{return typeof m=="function"}}function x(m,s){return x=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(c,a){return c.__proto__=a,c},x(m,s)}function p(m){return p=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(s){return s.__proto__||Object.getPrototypeOf(s)},p(m)}var w=(function(m){function s(c){var a;return v(this,s),a=E(this,s,[`Format functions must be synchronous taking a two arguments: (info, opts)
|
|
2
2
|
Found: `.concat(c.toString().split(`
|
|
3
3
|
`)[0],`
|
|
4
4
|
`)]),Error.captureStackTrace(a,s),a}return h(s,m),i(s)})(t(Error));return Tt=function(m){if(m.length>2)throw new w(m);function s(){var a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.options=a}s.prototype.transform=m;function c(a){return new s(a)}return c.Format=s,c},Tt}var Be={exports:{}},jt={exports:{}},Lt={exports:{}};function po(){return()=>{}}function yo(r){return JSON.stringify(r)}function mo(){}function go(){}const Xo={debuglog:po,inspect:yo,inherits:mo,format:go},ea=Object.freeze(Object.defineProperty({__proto__:null,debuglog:po,default:Xo,format:go,inherits:mo,inspect:yo},Symbol.toStringTag,{value:"Module"})),_e=St(ea);var Mt={exports:{}},nn;function ta(){return nn||(nn=1,(function(r){var i={};r.exports=i;var v={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],brightRed:[91,39],brightGreen:[92,39],brightYellow:[93,39],brightBlue:[94,39],brightMagenta:[95,39],brightCyan:[96,39],brightWhite:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgGray:[100,49],bgGrey:[100,49],bgBrightRed:[101,49],bgBrightGreen:[102,49],bgBrightYellow:[103,49],bgBrightBlue:[104,49],bgBrightMagenta:[105,49],bgBrightCyan:[106,49],bgBrightWhite:[107,49],blackBG:[40,49],redBG:[41,49],greenBG:[42,49],yellowBG:[43,49],blueBG:[44,49],magentaBG:[45,49],cyanBG:[46,49],whiteBG:[47,49]};Object.keys(v).forEach(function(E){var d=v[E],l=i[E]=[];l.open="\x1B["+d[0]+"m",l.close="\x1B["+d[1]+"m"})})(Mt)),Mt.exports}const be=St(Ko);var At,on;function ra(){return on||(on=1,At=function(r,i){i=i||process.argv||[];var v=i.indexOf("--"),E=/^-{1,2}/.test(r)?"":"--",d=i.indexOf(E+r);return d!==-1&&(v===-1?!0:d<v)}),At}var Ct,an;function na(){if(an)return Ct;an=1;var r={},i=ra(),v=r,E=void 0;i("no-color")||i("no-colors")||i("color=false")?E=!1:(i("color")||i("colors")||i("color=true")||i("color=always"))&&(E=!0),"FORCE_COLOR"in v&&(E=v.FORCE_COLOR.length===0||parseInt(v.FORCE_COLOR,10)!==0);function d(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function l(t){if(E===!1)return 0;if(i("color=16m")||i("color=full")||i("color=truecolor"))return 3;if(i("color=256"))return 2;if(t&&!t.isTTY&&E!==!0)return 0;var u=E?1:0;if("CI"in v)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(function(y){return y in v})||v.CI_NAME==="codeship"?1:u;if("TEAMCITY_VERSION"in v)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(v.TEAMCITY_VERSION)?1:0;if("TERM_PROGRAM"in v){var _=parseInt((v.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(v.TERM_PROGRAM){case"iTerm.app":return _>=3?3:2;case"Hyper":return 3;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(v.TERM)?2:/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(v.TERM)||"COLORTERM"in v?1:(v.TERM==="dumb",u)}function h(t){var u=l(t);return d(u)}return Ct={supportsColor:h,stdout:h(process.stdout),stderr:h(process.stderr)},Ct}var It={exports:{}},un;function ia(){return un||(un=1,(function(r){r.exports=function(v,E){var d="";v=v||"Run the trap, drop the bass",v=v.split("");var l={a:["@","Ą","Ⱥ","Ʌ","Δ","Λ","Д"],b:["ß","Ɓ","Ƀ","ɮ","β","฿"],c:["©","Ȼ","Ͼ"],d:["Ð","Ɗ","Ԁ","ԁ","Ԃ","ԃ"],e:["Ë","ĕ","Ǝ","ɘ","Σ","ξ","Ҽ","੬"],f:["Ӻ"],g:["ɢ"],h:["Ħ","ƕ","Ң","Һ","Ӈ","Ԋ"],i:["༏"],j:["Ĵ"],k:["ĸ","Ҡ","Ӄ","Ԟ"],l:["Ĺ"],m:["ʍ","Ӎ","ӎ","Ԡ","ԡ","൩"],n:["Ñ","ŋ","Ɲ","Ͷ","Π","Ҋ"],o:["Ø","õ","ø","Ǿ","ʘ","Ѻ","ם","","๏"],p:["Ƿ","Ҏ"],q:["্"],r:["®","Ʀ","Ȑ","Ɍ","ʀ","Я"],s:["§","Ϟ","ϟ","Ϩ"],t:["Ł","Ŧ","ͳ"],u:["Ʊ","Ս"],v:["ט"],w:["Ш","Ѡ","Ѽ","൰"],x:["Ҳ","Ӿ","Ӽ","ӽ"],y:["¥","Ұ","Ӌ"],z:["Ƶ","ɀ"]};return v.forEach(function(h){h=h.toLowerCase();var t=l[h]||[" "],u=Math.floor(Math.random()*t.length);typeof l[h]<"u"?d+=l[h][u]:d+=h}),d}})(It)),It.exports}var qt={exports:{}},sn;function oa(){return sn||(sn=1,(function(r){r.exports=function(v,E){v=v||" he is here ";var d={up:["̍","̎","̄","̅","̿","̑","̆","̐","͒","͗","͑","̇","̈","̊","͂","̓","̈","͊","͋","͌","̃","̂","̌","͐","̀","́","̋","̏","̒","̓","̔","̽","̉","ͣ","ͤ","ͥ","ͦ","ͧ","ͨ","ͩ","ͪ","ͫ","ͬ","ͭ","ͮ","ͯ","̾","͛","͆","̚"],down:["̖","̗","̘","̙","̜","̝","̞","̟","̠","̤","̥","̦","̩","̪","̫","̬","̭","̮","̯","̰","̱","̲","̳","̹","̺","̻","̼","ͅ","͇","͈","͉","͍","͎","͓","͔","͕","͖","͙","͚","̣"],mid:["̕","̛","̀","́","͘","̡","̢","̧","̨","̴","̵","̶","͜","͝","͞","͟","͠","͢","̸","̷","͡"," ҉"]},l=[].concat(d.up,d.down,d.mid);function h(_){var y=Math.floor(Math.random()*_);return y}function t(_){var y=!1;return l.filter(function(x){y=x===_}),y}function u(_,y){var x="",p,w;y=y||{},y.up=typeof y.up<"u"?y.up:!0,y.mid=typeof y.mid<"u"?y.mid:!0,y.down=typeof y.down<"u"?y.down:!0,y.size=typeof y.size<"u"?y.size:"maxi",_=_.split("");for(w in _)if(!t(w)){switch(x=x+_[w],p={up:0,down:0,mid:0},y.size){case"mini":p.up=h(8),p.mid=h(2),p.down=h(8);break;case"maxi":p.up=h(16)+3,p.mid=h(4)+1,p.down=h(64)+3;break;default:p.up=h(8)+1,p.mid=h(6)/2,p.down=h(8)+1;break}var m=["up","mid","down"];for(var s in m)for(var c=m[s],a=0;a<=p[c];a++)y[c]&&(x=x+d[c][h(d[c].length)])}return x}return u(v,E)}})(qt)),qt.exports}var Bt={exports:{}},fn;function aa(){return fn||(fn=1,(function(r){r.exports=function(i){return function(v,E,d){if(v===" ")return v;switch(E%3){case 0:return i.red(v);case 1:return i.white(v);case 2:return i.blue(v)}}}})(Bt)),Bt.exports}var Nt={exports:{}},ln;function ua(){return ln||(ln=1,(function(r){r.exports=function(i){return function(v,E,d){return E%2===0?v:i.inverse(v)}}})(Nt)),Nt.exports}var Ft={exports:{}},cn;function sa(){return cn||(cn=1,(function(r){r.exports=function(i){var v=["red","yellow","green","blue","magenta"];return function(E,d,l){return E===" "?E:i[v[d++%v.length]](E)}}})(Ft)),Ft.exports}var Dt={exports:{}},hn;function fa(){return hn||(hn=1,(function(r){r.exports=function(i){var v=["underline","inverse","grey","yellow","red","green","blue","white","cyan","magenta","brightYellow","brightRed","brightGreen","brightBlue","brightWhite","brightCyan","brightMagenta"];return function(E,d,l){return E===" "?E:i[v[Math.round(Math.random()*(v.length-2))]](E)}}})(Dt)),Dt.exports}var pn;function la(){return pn||(pn=1,(function(r){var i={};r.exports=i,i.themes={};var v=_e,E=i.styles=ta(),d=Object.defineProperties,l=new RegExp(/[\r\n]+/g);i.supportsColor=na().supportsColor,typeof i.enabled>"u"&&(i.enabled=i.supportsColor()!==!1),i.enable=function(){i.enabled=!0},i.disable=function(){i.enabled=!1},i.stripColors=i.strip=function(s){return(""+s).replace(/\x1B\[\d+m/g,"")},i.stylize=function(c,a){if(!i.enabled)return c+"";var o=E[a];return!o&&a in i?i[a](c):o.open+c+o.close};var h=/[|\\{}()[\]^$+*?.]/g,t=function(s){if(typeof s!="string")throw new TypeError("Expected a string");return s.replace(h,"\\$&")};function u(s){var c=function a(){return x.apply(a,arguments)};return c._styles=s,c.__proto__=y,c}var _=(function(){var s={};return E.grey=E.gray,Object.keys(E).forEach(function(c){E[c].closeRe=new RegExp(t(E[c].close),"g"),s[c]={get:function(){return u(this._styles.concat(c))}}}),s})(),y=d(function(){},_);function x(){var s=Array.prototype.slice.call(arguments),c=s.map(function(S){return S!=null&&S.constructor===String?S:v.inspect(S)}).join(" ");if(!i.enabled||!c)return c;for(var a=c.indexOf(`
|
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-
|
|
30
|
+
<script type="module" crossorigin src="/inspector/assets/index-D6Wv_tf-.js"></script>
|
|
31
31
|
<link rel="stylesheet" crossorigin href="/inspector/assets/index-CAnbiFOL.css">
|
|
32
|
-
<script>window.__INSPECTOR_VERSION__ = "0.6.
|
|
32
|
+
<script>window.__INSPECTOR_VERSION__ = "0.6.1-canary.1";</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.6.
|
|
4
|
+
"version": "0.6.1-canary.1",
|
|
5
5
|
"description": "MCP Inspector - A tool for inspecting and debugging MCP servers",
|
|
6
6
|
"author": "",
|
|
7
7
|
"license": "MIT",
|
|
@@ -73,7 +73,7 @@
|
|
|
73
73
|
"sonner": "^2.0.7",
|
|
74
74
|
"tailwind-merge": "^3.3.1",
|
|
75
75
|
"vite-express": "^0.21.1",
|
|
76
|
-
"mcp-use": "1.4.
|
|
76
|
+
"mcp-use": "1.4.1-canary.1"
|
|
77
77
|
},
|
|
78
78
|
"publishConfig": {
|
|
79
79
|
"access": "public"
|