@mcp-use/inspector 0.26.1 → 0.26.2-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. package/dist/cdn/inspector.js +64 -54
  2. package/dist/client/index.js +31 -31
  3. package/dist/web/assets/{browser-CUjguYn6.js → browser-BmLBExar.js} +3 -3
  4. package/dist/web/assets/{chunk-6E445R5C-ny1rw8Le.js → chunk-PQMRWHFE-CV30_nBm.js} +1 -1
  5. package/dist/web/assets/{chunk-RPN2XO5I-_4a18lz2.js → chunk-RPN2XO5I-BI2C4Mwo.js} +1 -1
  6. package/dist/web/assets/{chunk_array-cMM4je5w.js → chunk_array-Dt8Wg6B_.js} +1 -1
  7. package/dist/web/assets/{client-DEFMLVFC.js → client-6SIHYz8o.js} +1 -1
  8. package/dist/web/assets/{client-S6L7XHLF-Dqmt1wRx.js → client-H7MR3VAF-CO-aN8Vj.js} +3 -3
  9. package/dist/web/assets/{dist-BG8NAFfu.js → dist-E6FGji6q.js} +1 -1
  10. package/dist/web/assets/{dist-CKth7ANk.js → dist-NjrowN6N.js} +1 -1
  11. package/dist/web/assets/{dist-YxwKnKYL.js → dist-XbUgwOND.js} +1 -1
  12. package/dist/web/assets/{function_calling-XyGNNvjR.js → function_calling-BocD-RuD.js} +1 -1
  13. package/dist/web/assets/{index-zqVFP8t5.js → index-B2Y-NYsA.js} +10 -10
  14. package/dist/web/assets/{llms-DmE4p8kW.js → llms-DKXMVXWf.js} +1 -1
  15. package/dist/web/assets/messages-DQOeGdbS.js +1 -0
  16. package/dist/web/assets/react-ksVTeyRI.js +1 -0
  17. package/dist/web/assets/{rpc-logger-TPNV75J4-BPgEimJH.js → rpc-logger-TPNV75J4-BdFmawYU.js} +1 -1
  18. package/dist/web/assets/{stdio-LLTXMSZH-CQ-zxwTS.js → stdio-ZCW4I5XD-CmtXCvzt.js} +1 -1
  19. package/dist/web/assets/{tools-DWDA-ZTt.js → tools-DdqMuNxj.js} +1 -1
  20. package/dist/web/index.html +4 -4
  21. package/package.json +3 -3
  22. package/dist/web/assets/messages-DmWRSzWI.js +0 -1
  23. package/dist/web/assets/react-Cg35ZZKt.js +0 -1
@@ -58,7 +58,7 @@ Note: This type uses \`Record<K, string | undefined>\` rather than \`Partial<Rec
58
58
  for compatibility with Zod schema generation. Both are functionally equivalent for validation.`);N.object({method:N.literal(`ui/open-link`),params:N.object({url:N.string().describe(`URL to open in the host's browser`)})}),N.object({isError:N.boolean().optional().describe(`True if the host failed to open the URL (e.g., due to security policy).`)}).passthrough(),N.object({isError:N.boolean().optional().describe(`True if the host rejected or failed to deliver the message.`)}).passthrough(),N.object({method:N.literal(`ui/notifications/sandbox-proxy-ready`),params:N.object({})});var qg=N.object({connectDomains:N.array(N.string()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket).`),resourceDomains:N.array(N.string()).optional().describe(`Origins for static resources (scripts, images, styles, fonts).`),frameDomains:N.array(N.string()).optional().describe(`Origins for nested iframes (frame-src directive).`),baseUriDomains:N.array(N.string()).optional().describe(`Allowed base URIs for the document (base-uri directive).`)}),Jg=N.object({camera:N.object({}).optional().describe("Request camera access (Permission Policy `camera` feature)."),microphone:N.object({}).optional().describe("Request microphone access (Permission Policy `microphone` feature)."),geolocation:N.object({}).optional().describe("Request geolocation access (Permission Policy `geolocation` feature)."),clipboardWrite:N.object({}).optional().describe("Request clipboard write access (Permission Policy `clipboard-write` feature).")});N.object({method:N.literal(`ui/notifications/size-changed`),params:N.object({width:N.number().optional().describe(`New width in pixels.`),height:N.number().optional().describe(`New height in pixels.`)})}),N.object({method:N.literal(`ui/notifications/tool-input`),params:N.object({arguments:N.record(N.string(),N.unknown().describe(`Complete tool call arguments as key-value pairs.`)).optional().describe(`Complete tool call arguments as key-value pairs.`)})}),N.object({method:N.literal(`ui/notifications/tool-input-partial`),params:N.object({arguments:N.record(N.string(),N.unknown().describe(`Partial tool call arguments (incomplete, may change).`)).optional().describe(`Partial tool call arguments (incomplete, may change).`)})}),N.object({method:N.literal(`ui/notifications/tool-cancelled`),params:N.object({reason:N.string().optional().describe(`Optional reason for the cancellation (e.g., "user action", "timeout").`)})});var Yg=N.object({fonts:N.string().optional()}),Xg=N.object({variables:Kg.optional().describe(`CSS variables for theming the app.`),css:Yg.optional().describe(`CSS blocks that apps can inject.`)});N.object({method:N.literal(`ui/resource-teardown`),params:N.object({})}),N.record(N.string(),N.unknown());var Zg=N.object({text:N.object({}).optional().describe(`Host supports text content blocks.`),image:N.object({}).optional().describe(`Host supports image content blocks.`),audio:N.object({}).optional().describe(`Host supports audio content blocks.`),resource:N.object({}).optional().describe(`Host supports resource content blocks.`),resourceLink:N.object({}).optional().describe(`Host supports resource link content blocks.`),structuredContent:N.object({}).optional().describe(`Host supports structured content.`)}),Qg=N.object({experimental:N.object({}).optional().describe(`Experimental features (structure TBD).`),openLinks:N.object({}).optional().describe(`Host supports opening external URLs.`),serverTools:N.object({listChanged:N.boolean().optional().describe(`Host supports tools/list_changed notifications.`)}).optional().describe(`Host can proxy tool calls to the MCP server.`),serverResources:N.object({listChanged:N.boolean().optional().describe(`Host supports resources/list_changed notifications.`)}).optional().describe(`Host can proxy resource reads to the MCP server.`),logging:N.object({}).optional().describe(`Host accepts log messages.`),sandbox:N.object({permissions:Jg.optional().describe(`Permissions granted by the host (camera, microphone, geolocation).`),csp:qg.optional().describe(`CSP domains approved by the host.`)}).optional().describe(`Sandbox configuration applied by the host.`),updateModelContext:Zg.optional().describe(`Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.`),message:Zg.optional().describe(`Host supports receiving content messages (ui/message) from the view.`)}),$g=N.object({experimental:N.object({}).optional().describe(`Experimental features (structure TBD).`),tools:N.object({listChanged:N.boolean().optional().describe(`App supports tools/list_changed notifications.`)}).optional().describe(`App exposes MCP-style tools that the host can call.`),availableDisplayModes:N.array(Wg).optional().describe(`Display modes the app supports.`)});N.object({method:N.literal(`ui/notifications/initialized`),params:N.object({}).optional()}),N.object({csp:qg.optional().describe(`Content Security Policy configuration.`),permissions:Jg.optional().describe(`Sandbox permissions requested by the UI.`),domain:N.string().optional().describe(`Dedicated origin for view sandbox.`),prefersBorder:N.boolean().optional().describe(`Visual boundary preference - true if UI prefers a visible border.`)}),N.object({method:N.literal(`ui/request-display-mode`),params:N.object({mode:Wg.describe(`The display mode being requested.`)})}),N.object({mode:Wg.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough();var e_=N.union([N.literal(`model`),N.literal(`app`)]).describe(`Tool visibility scope - who can access the tool.`);N.object({resourceUri:N.string().optional(),visibility:N.array(e_).optional().describe(`Who can access this tool. Default: ["model", "app"]
59
59
  - "model": Tool visible to and callable by the agent
60
60
  - "app": Tool callable by the app from this server only`)}),N.object({mimeTypes:N.array(N.string()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),N.object({method:N.literal(`ui/message`),params:N.object({role:N.literal(`user`).describe(`Message role, currently only "user" is supported.`),content:N.array(Bt).describe(`Message content blocks (text, image, etc.).`)})}),N.object({method:N.literal(`ui/notifications/sandbox-resource-ready`),params:N.object({html:N.string().describe(`HTML content to load into the inner iframe.`),sandbox:N.string().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:qg.optional().describe(`CSP configuration from resource metadata.`),permissions:Jg.optional().describe(`Sandbox permissions from resource metadata.`)})}),N.object({method:N.literal(`ui/notifications/tool-result`),params:Yt.describe(`Standard MCP tool execution result.`)});var t_=N.object({toolInfo:N.object({id:he.optional().describe(`JSON-RPC id of the tools/call request.`),tool:Kt.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:Ug.optional().describe(`Current color theme preference.`),styles:Xg.optional().describe(`Style configuration for theming the app.`),displayMode:Wg.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:N.array(Wg).optional().describe(`Display modes the host supports.`),containerDimensions:N.union([N.object({height:N.number().describe(`Fixed container height in pixels.`)}),N.object({maxHeight:N.union([N.number(),N.undefined()]).optional().describe(`Maximum container height in pixels.`)})]).and(N.union([N.object({width:N.number().describe(`Fixed container width in pixels.`)}),N.object({maxWidth:N.union([N.number(),N.undefined()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
61
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:N.string().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:N.string().optional().describe(`User's timezone in IANA format.`),userAgent:N.string().optional().describe(`Host application identifier.`),platform:N.union([N.literal(`web`),N.literal(`desktop`),N.literal(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:N.object({touch:N.boolean().optional().describe(`Whether the device supports touch input.`),hover:N.boolean().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:N.object({top:N.number().describe(`Top safe area inset in pixels.`),right:N.number().describe(`Right safe area inset in pixels.`),bottom:N.number().describe(`Bottom safe area inset in pixels.`),left:N.number().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough();N.object({method:N.literal(`ui/notifications/host-context-changed`),params:t_.describe(`Partial context update containing only changed fields.`)}),N.object({method:N.literal(`ui/update-model-context`),params:N.object({content:N.array(Bt).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:N.record(N.string(),N.unknown().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),N.object({method:N.literal(`ui/initialize`),params:N.object({appInfo:Ae.describe(`App identification (name and version).`),appCapabilities:$g.describe(`Features and capabilities this app provides.`),protocolVersion:N.string().describe(`Protocol version this app supports.`)})}),N.object({protocolVersion:N.string().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:Ae.describe(`Host application identification and version.`),hostCapabilities:Qg.describe(`Features and capabilities provided by the host.`),hostContext:t_.describe(`Rich context about the host environment.`)}).passthrough();var n_=`text/html;profile=mcp-app`,r_=`1.22.3`;function i_(){return r_}a(i_,`getPackageVersion`);var a_=class{static{a(this,`BaseTelemetryEvent`)}},o_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`MCPAgentExecutionEvent`)}get name(){return`mcp_agent_execution`}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}};function s_(e,t){let n=Array.from(e.registrations.tools.values()),r=Array.from(e.registrations.prompts.values()),i=Array.from(e.registrations.resources.values()),a=Array.from(e.registrations.resourceTemplates.values()),o=i.map(e=>({name:e.config.name,title:e.config.title??null,description:e.config.description??null,uri:e.config.uri??null,mime_type:e.config.mimeType??null})),s=o.filter(e=>e.mime_type===`text/html+skybridge`),c=o.filter(e=>e.mime_type===`text/uri-list`||e.mime_type===`text/html`),l=o.filter(e=>e.mime_type===n_);return{transport:t,toolsNumber:e.registeredTools.length,resourcesNumber:e.registeredResources.length,promptsNumber:e.registeredPrompts.length,auth:!!e.oauthProvider,name:e.config.name,description:e.config.description??null,baseUrl:e.serverBaseUrl??null,toolNames:e.registeredTools.length>0?e.registeredTools:null,resourceNames:e.registeredResources.length>0?e.registeredResources:null,promptNames:e.registeredPrompts.length>0?e.registeredPrompts:null,tools:n.length>0?n.map(e=>({name:e.config.name,title:e.config.title??null,description:e.config.description??null,input_schema:e.config.schema?JSON.stringify(e.config.schema):null,output_schema:e.config.outputSchema?JSON.stringify(e.config.outputSchema):null})):null,resources:o.length>0?o:null,prompts:r.length>0?r.map(e=>({name:e.config.name,title:e.config.title??null,description:e.config.description??null,args:e.config.args?JSON.stringify(e.config.args):null})):null,templates:a.length>0?a.map(e=>({name:e.config.name,title:e.config.title??null,description:e.config.description??null})):null,capabilities:{logging:!0,resources:{subscribe:!0,listChanged:!0}},appsSdkResources:s.length>0?s:null,appsSdkResourcesNumber:s.length,mcpUiResources:c.length>0?c:null,mcpUiResourcesNumber:c.length,mcpAppsResources:l.length>0?l:null,mcpAppsResourcesNumber:l.length}}a(s_,`createServerRunEventData`);var c_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ServerRunEvent`)}get name(){return`server_run`}get properties(){return{transport:this.data.transport,tools_number:this.data.toolsNumber,resources_number:this.data.resourcesNumber,prompts_number:this.data.promptsNumber,auth:this.data.auth,name:this.data.name,description:this.data.description??null,base_url:this.data.baseUrl??null,tool_names:this.data.toolNames??null,resource_names:this.data.resourceNames??null,prompt_names:this.data.promptNames??null,tools:this.data.tools??null,resources:this.data.resources??null,prompts:this.data.prompts??null,templates:this.data.templates??null,capabilities:this.data.capabilities?JSON.stringify(this.data.capabilities):null,apps_sdk_resources:this.data.appsSdkResources?JSON.stringify(this.data.appsSdkResources):null,apps_sdk_resources_number:this.data.appsSdkResourcesNumber??0,mcp_ui_resources:this.data.mcpUiResources?JSON.stringify(this.data.mcpUiResources):null,mcp_ui_resources_number:this.data.mcpUiResourcesNumber??0,mcp_apps_resources:this.data.mcpAppsResources?JSON.stringify(this.data.mcpAppsResources):null,mcp_apps_resources_number:this.data.mcpAppsResourcesNumber??0}}},l_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ServerInitializeEvent`)}get name(){return`server_initialize_call`}get properties(){return{protocol_version:this.data.protocolVersion,client_info:JSON.stringify(this.data.clientInfo),client_capabilities:JSON.stringify(this.data.clientCapabilities),session_id:this.data.sessionId??null}}},u_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ServerToolCallEvent`)}get name(){return`server_tool_call`}get properties(){return{tool_name:this.data.toolName,length_input_argument:this.data.lengthInputArgument,success:this.data.success,error_type:this.data.errorType??null,execution_time_ms:this.data.executionTimeMs??null}}},d_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ServerResourceCallEvent`)}get name(){return`server_resource_call`}get properties(){return{name:this.data.name,description:this.data.description,contents:this.data.contents,success:this.data.success,error_type:this.data.errorType??null}}},f_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ServerPromptCallEvent`)}get name(){return`server_prompt_call`}get properties(){return{name:this.data.name,description:this.data.description,success:this.data.success,error_type:this.data.errorType??null}}},p_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ServerContextEvent`)}get name(){return`server_context_${this.data.contextType}`}get properties(){return{context_type:this.data.contextType,notification_type:this.data.notificationType??null}}},m_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`MCPClientInitEvent`)}get name(){return`mcpclient_init`}get properties(){return{code_mode:this.data.codeMode,sandbox:this.data.sandbox,all_callbacks:this.data.allCallbacks,verify:this.data.verify,servers:this.data.servers,num_servers:this.data.numServers,is_browser:this.data.isBrowser}}},h_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ConnectorInitEvent`)}get name(){return`connector_init`}get properties(){return{connector_type:this.data.connectorType,server_command:this.data.serverCommand??null,server_args:this.data.serverArgs??null,server_url:this.data.serverUrl??null,public_identifier:this.data.publicIdentifier??null}}},g_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ClientAddServerEvent`)}get name(){return`client_add_server`}get properties(){let{serverName:e,serverConfig:t}=this.data,n=t.url;return{server_name:e,server_url_domain:n?this._extractHostname(n):null,transport:t.transport??null,has_auth:!!(t.authToken||t.authProvider)}}_extractHostname(e){try{return new URL(e).hostname}catch{return null}}},__=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ClientRemoveServerEvent`)}get name(){return`client_remove_server`}get properties(){return{server_name:this.data.serverName}}};function v_(e){return e._llm_type||e.constructor.name.toLowerCase()}a(v_,`getModelProvider`);function y_(e){if(`_identifyingParams`in e){let t=e._identifyingParams;if(typeof t==`object`&&t){for(let e of[`model`,`modelName`,`model_name`,`modelId`,`model_id`,`deploymentName`,`deployment_name`])if(e in t)return String(t[e])}}return e.model||e.modelName||e.constructor.name}a(y_,`getModelName`);function b_(e){return[v_(e),y_(e)]}a(b_,`extractModelInfo`);function x_(){if(typeof globalThis<`u`&&globalThis.crypto&&typeof globalThis.crypto.randomUUID==`function`)return globalThis.crypto.randomUUID();if(typeof globalThis<`u`&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues==`function`){let e=new Uint8Array(16);globalThis.crypto.getRandomValues(e);let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}return`${Date.now()}-${Math.random().toString(36).substring(2,15)}-${Math.random().toString(36).substring(2,15)}`}a(x_,`generateUUID`);function S_(){if(typeof window<`u`&&window.crypto&&typeof window.crypto.getRandomValues==`function`){let e=new Uint8Array(8);return window.crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}if(typeof globalThis<`u`&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues==`function`){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}return Math.random().toString(36).substring(2,15)}a(S_,`secureRandomString`);var C_=`mcp_use_user_id`;function w_(){return typeof localStorage<`u`&&typeof localStorage.getItem==`function`&&typeof localStorage.setItem==`function`&&typeof localStorage.removeItem==`function`}a(w_,`isLocalStorageFunctional`);function T_(){try{return typeof window<`u`&&typeof document<`u`?`browser`:`unknown`}catch{return`unknown`}}a(T_,`detectRuntimeEnvironment`);function E_(e){if(e===`browser`)try{if(w_())return localStorage.setItem(`__mcp_use_test__`,`1`),localStorage.removeItem(`__mcp_use_test__`),`localStorage`}catch{}return`session-only`}a(E_,`getStorageCapability`);var D_=null;function O_(){return D_===null&&(D_=T_()),D_}a(O_,`getRuntimeEnvironment`);var k_=class e{static{a(this,`Telemetry`)}static instance=null;PROJECT_API_KEY=`phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI`;HOST=`https://eu.i.posthog.com`;UNKNOWN_USER_ID=`UNKNOWN_USER_ID`;_currUserId=null;_posthogBrowserClient=null;_posthogLoading=null;_runtimeEnvironment;_storageCapability;_source;constructor(){this._runtimeEnvironment=O_(),this._storageCapability=E_(this._runtimeEnvironment),this._source=this._getSourceFromLocalStorage()||this._runtimeEnvironment;let e=this._checkTelemetryDisabled(),t=this._runtimeEnvironment!==`unknown`;e?(this._posthogBrowserClient=null,o.debug(`Telemetry disabled via localStorage`)):t?(o.info(`Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false in localStorage to disable.`),this._posthogLoading=this._initPostHogBrowser()):(this._posthogBrowserClient=null,o.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`))}_getSourceFromLocalStorage(){try{if(w_())return localStorage.getItem(`MCP_USE_TELEMETRY_SOURCE`)}catch{}return null}_checkTelemetryDisabled(){return!!(w_()&&localStorage.getItem(`MCP_USE_ANONYMIZED_TELEMETRY`)===`false`)}async _initPostHogBrowser(){try{let e=await te(()=>import(`./module-DCsrdi7m.js`),[]),t=e.default||e.posthog;if(!t||typeof t.init!=`function`)throw Error(`posthog-js module did not export expected interface`);t.init(this.PROJECT_API_KEY,{api_host:this.HOST,persistence:`localStorage`,autocapture:!1,capture_pageview:!1,disable_session_recording:!0,loaded:a(()=>{o.debug(`PostHog browser client initialized`)},`loaded`)}),this._posthogBrowserClient=t}catch(e){o.warn(`Failed to initialize PostHog browser telemetry: ${e}`),this._posthogBrowserClient=null}}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return e.instance||=new e,e.instance}setSource(e){this._source=e;try{w_()&&localStorage.setItem(`MCP_USE_TELEMETRY_SOURCE`,e)}catch{}o.debug(`Telemetry source set to: ${e}`)}getSource(){return this._source}get isEnabled(){return this._posthogBrowserClient!==null}get userId(){if(this._currUserId)return this._currUserId;try{switch(this._storageCapability){case`localStorage`:this._currUserId=this._getUserIdFromLocalStorage();break;default:try{this._currUserId=`session-${x_()}`}catch{this._currUserId=`session-${Date.now()}-${S_()}`}break}}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}_getUserIdFromLocalStorage(){try{if(!w_())throw Error(`localStorage is not available or not functional`);localStorage.setItem(`__mcp_use_test__`,`1`),localStorage.removeItem(`__mcp_use_test__`);let e=localStorage.getItem(C_);if(!e){try{e=x_()}catch{e=`${Date.now()}-${S_()}`}localStorage.setItem(C_,e)}return e}catch(e){o.debug(`Failed to access localStorage for user ID: ${e}`);let t;try{t=`session-${x_()}`}catch{t=`session-${Date.now()}-${S_()}`}return t}}async capture(e){if(this._posthogLoading&&await this._posthogLoading,!this._posthogBrowserClient)return;let t=this.userId,n={...e.properties};if(n.mcp_use_version=i_(),n.language=`typescript`,n.source=this._source,n.runtime=this._runtimeEnvironment,this._posthogBrowserClient)try{this._posthogBrowserClient.capture(e.name,{...n,distinct_id:t})}catch(t){o.debug(`Failed to track PostHog Browser event ${e.name}: ${t}`)}}async trackAgentExecution(e){if(!this.isEnabled)return;let t=new o_(e);await this.capture(t)}async trackServerRunFromServer(e,t){if(!this.isEnabled)return;let n=new c_(s_(e,t));await this.capture(n)}async trackServerInitialize(e){if(!this.isEnabled)return;let t=new l_(e);await this.capture(t)}async trackServerToolCall(e){if(!this.isEnabled)return;let t=new u_(e);await this.capture(t)}async trackServerResourceCall(e){if(!this.isEnabled)return;let t=new d_(e);await this.capture(t)}async trackServerPromptCall(e){if(!this.isEnabled)return;let t=new f_(e);await this.capture(t)}async trackServerContext(e){if(!this.isEnabled)return;let t=new p_(e);await this.capture(t)}async trackMCPClientInit(e){if(!this.isEnabled)return;let t=new m_(e);await this.capture(t)}async trackConnectorInit(e){if(!this.isEnabled)return;let t=new h_(e);await this.capture(t)}async trackClientAddServer(e,t){if(!this.isEnabled)return;let n=new g_({serverName:e,serverConfig:t});await this.capture(n)}async trackClientRemoveServer(e){if(!this.isEnabled)return;let t=new __({serverName:e});await this.capture(t)}async trackUseMcpConnection(e){this.isEnabled&&await this.capture({name:`usemcp_connection`,properties:{url_domain:new URL(e.url).hostname,transport_type:e.transportType,success:e.success,error_type:e.errorType??null,connection_time_ms:e.connectionTimeMs??null,has_oauth:e.hasOAuth,has_sampling:e.hasSampling,has_elicitation:e.hasElicitation}})}async trackUseMcpToolCall(e){this.isEnabled&&await this.capture({name:`usemcp_tool_call`,properties:{tool_name:e.toolName,success:e.success,error_type:e.errorType??null,execution_time_ms:e.executionTimeMs??null}})}async trackUseMcpResourceRead(e){this.isEnabled&&await this.capture({name:`usemcp_resource_read`,properties:{resource_uri_scheme:e.resourceUri.split(`:`)[0],success:e.success,error_type:e.errorType??null}})}identify(e,t){if(this._posthogBrowserClient)try{this._posthogBrowserClient.identify(e,t)}catch(e){o.debug(`Failed to identify user: ${e}`)}}reset(){if(this._posthogBrowserClient)try{this._posthogBrowserClient.reset()}catch(e){o.debug(`Failed to reset user: ${e}`)}this._currUserId=null}flush(){}shutdown(){}async trackPackageDownload(e){}},A_=k_;function j_(e){A_.getInstance().setSource(e)}a(j_,`setTelemetrySource`);var M_=class{static{a(this,`BaseConnector`)}client=null;connectionManager=null;toolsCache=null;capabilitiesCache=null;serverInfoCache=null;connected=!1;opts;notificationHandlers=[];rootsCache=[];constructor(e={}){let t={...e,onSampling:e.onSampling??e.samplingCallback,onElicitation:e.onElicitation??e.elicitationCallback};e.samplingCallback&&!e.onSampling&&o.warn(`[BaseConnector] The "samplingCallback" option is deprecated. Use "onSampling" instead.`),e.elicitationCallback&&!e.onElicitation&&console.warn(`[BaseConnector] The "elicitationCallback" option is deprecated. Use "onElicitation" instead.`),this.opts=t,t.roots&&(this.rootsCache=[...t.roots]),t.onNotification&&this.notificationHandlers.push(t.onNotification)}trackConnectorInit(e){let t=this.constructor.name;k_.getInstance().trackConnectorInit({connectorType:t,...e}).catch(e=>o.debug(`Failed to track connector init: ${e}`))}onNotification(e){this.notificationHandlers.push(e),this.client&&this.setupNotificationHandler()}setupNotificationHandler(){if(!this.client)return;let e=a(async e=>{for(let t of this.notificationHandlers)try{await t(e)}catch(e){o.error(`Error in notification handler:`,e)}},`forwardToUserHandlers`);this.client.fallbackNotificationHandler=async t=>{switch(t.method){case`notifications/tools/list_changed`:await this.refreshToolsCache();break;case`notifications/resources/list_changed`:await this.onResourcesListChanged();break;case`notifications/prompts/list_changed`:await this.onPromptsListChanged();break;default:break}await e(t)};let t=this.client._notificationHandlers;for(let n of[`notifications/progress`,`notifications/cancelled`]){let r=t.get(n);r&&t.set(n,async t=>{await r(t),await e(t)})}}async refreshToolsCache(){if(this.client)try{o.debug(`[Auto] Refreshing tools cache due to list_changed notification`),this.toolsCache=(await this.client.listTools()).tools??[],o.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(e){o.warn(`[Auto] Failed to refresh tools cache:`,e)}}async onResourcesListChanged(){o.debug(`[Auto] Resources list changed - clients should re-fetch if needed`)}async onPromptsListChanged(){o.debug(`[Auto] Prompts list changed - clients should re-fetch if needed`)}async setRoots(e){this.rootsCache=[...e],this.client&&(o.debug(`Sending roots/list_changed notification with ${e.length} root(s)`),await this.client.sendRootsListChanged())}getRoots(){return[...this.rootsCache]}setupRootsHandler(){this.client&&this.client.setRequestHandler(Nn,async(e,t)=>(o.debug(`Server requested roots list, returning ${this.rootsCache.length} root(s)`),{roots:this.rootsCache}))}setupSamplingHandler(){if(!this.client){o.debug(`setupSamplingHandler: No client available`);return}let e=this.opts.onSampling??this.opts.samplingCallback;if(!e){o.debug(`setupSamplingHandler: No sampling callback provided`);return}o.debug(`setupSamplingHandler: Setting up sampling request handler`),this.client.setRequestHandler(pn,async(t,n)=>(o.debug(`Server requested sampling, forwarding to callback`),await e(t.params))),o.debug(`setupSamplingHandler: Sampling handler registered successfully`)}setupElicitationHandler(){if(!this.client){o.debug(`setupElicitationHandler: No client available`);return}let e=this.opts.onElicitation??this.opts.elicitationCallback;if(!e){o.debug(`setupElicitationHandler: No elicitation callback provided`);return}o.debug(`setupElicitationHandler: Setting up elicitation request handler`),this.client.setRequestHandler(Cn,async(t,n)=>(o.debug(`Server requested elicitation, forwarding to callback`),await e(t.params))),o.debug(`setupElicitationHandler: Elicitation handler registered successfully`)}async disconnect(){if(!this.connected){o.debug(`Not connected to MCP implementation`);return}o.debug(`Disconnecting from MCP implementation`),await this.cleanupResources(),this.connected=!1,o.debug(`Disconnected from MCP implementation`)}get isClientConnected(){return this.client!=null}async initialize(e=this.opts.defaultRequestOptions??{}){if(!this.client)throw Error(`MCP client is not connected`);o.debug(`Caching server capabilities & tools`);let t=this.client.getServerCapabilities();this.capabilitiesCache=t||null;let n=this.client.getServerVersion();this.serverInfoCache=n||null;try{this.toolsCache=(await this.client.listTools(void 0,e)).tools??[],o.debug(`Fetched ${this.toolsCache.length} tools from server`)}catch(e){let t=e;t.code===-32601?o.debug(`Server does not implement tools/list, assuming no tools`):o.debug(`Failed to list tools, assuming empty:`,t.message),this.toolsCache=[]}return o.debug(`Server capabilities:`,t),o.debug(`Server info:`,n),t}get tools(){if(!this.toolsCache)throw Error(`MCP client is not initialized; call initialize() first`);return this.toolsCache}get serverCapabilities(){return this.capabilitiesCache||{}}get serverInfo(){return this.serverInfoCache}async callTool(e,t,n){if(!this.client)throw Error(`MCP client is not connected`);let r=n?{...n}:void 0;r?.resetTimeoutOnProgress&&!r.onprogress&&(r.onprogress=()=>{},o.debug(`[BaseConnector] Added onprogress callback for tool '${e}' to enable progressToken`)),o.debug(`Calling tool '${e}' with args`,t);let i=await this.client.callTool({name:e,arguments:t},void 0,r);return o.debug(`Tool '${e}' returned`,i),i}async listTools(e){if(!this.client)throw Error(`MCP client is not connected`);o.debug(`[listTools] Fetching fresh tools from server...`);let t=await this.client.listTools(void 0,e),n=t.tools?[...t.tools]:[];return o.debug(`[listTools] Returned ${n.length} tools:`,n.map(e=>e.name)),n}async listResources(e,t){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Listing resources`,e?`with cursor: ${e}`:``),await this.client.listResources({cursor:e},t)}async listAllResources(e){if(!this.client)throw Error(`MCP client is not connected`);if(!this.capabilitiesCache?.resources)return o.debug(`Server does not advertise resources capability, skipping`),{resources:[]};try{o.debug(`Listing all resources (with auto-pagination)`);let t=[],n;do{let r=await this.client.listResources({cursor:n},e);t.push(...r.resources||[]),n=r.nextCursor}while(n);return{resources:t}}catch(e){if(e.code===-32601)return o.debug(`Server advertised resources but method not found`),{resources:[]};throw e}}async listResourceTemplates(e){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Listing resource templates`),await this.client.listResourceTemplates(void 0,e)}async complete(e,t){if(!this.client)throw Error(`MCP client is not connected`);o.debug(`[complete] Requesting completions for:`,e.ref);let n=await this.client.complete(e,t);return o.debug(`[complete] Received ${n.completion.values.length} suggestions`),n}async readResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Reading resource ${e}`),await this.client.readResource({uri:e},t)}async subscribeToResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Subscribing to resource: ${e}`),await this.client.subscribeResource({uri:e},t)}async unsubscribeFromResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Unsubscribing from resource: ${e}`),await this.client.unsubscribeResource({uri:e},t)}async listPrompts(){if(!this.client)throw Error(`MCP client is not connected`);if(!this.capabilitiesCache?.prompts)return o.debug(`Server does not advertise prompts capability, skipping`),{prompts:[]};try{return o.debug(`Listing prompts`),await this.client.listPrompts()}catch(e){if(e.code===-32601)return o.debug(`Server advertised prompts but method not found`),{prompts:[]};throw e}}async getPrompt(e,t){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Getting prompt ${e}`),await this.client.getPrompt({name:e,arguments:t})}async request(e,t=null,n){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Sending raw request '${e}' with params`,t),await this.client.request({method:e,params:t??{}},void 0,n)}async cleanupResources(){let e=[];if(this.client)try{typeof this.client.close==`function`&&await this.client.close()}catch(t){let n=`Error closing client: ${t}`;o.warn(n),e.push(n)}finally{this.client=null}if(this.connectionManager)try{await this.connectionManager.stop()}catch(t){let n=`Error stopping connection manager: ${t}`;o.warn(n),e.push(n)}finally{this.connectionManager=null}this.toolsCache=null,e.length&&o.warn(`Resource cleanup finished with ${e.length} issue(s)`)}},N_=class{static{a(this,`ConnectionManager`)}_readyPromise;_readyResolver;_donePromise;_doneResolver;_exception=null;_connection=null;_task=null;_abortController=null;constructor(){this.reset()}async start(){if(this.reset(),o.debug(`Starting ${this.constructor.name}`),this._task=this.connectionTask(),await this._readyPromise,this._exception)throw this._exception;if(this._connection===null)throw Error(`Connection was not established`);return this._connection}async stop(){if(this._task&&this._abortController){o.debug(`Cancelling ${this.constructor.name} task`),this._abortController.abort();try{await this._task}catch(e){e instanceof Error&&e.name===`AbortError`?o.debug(`${this.constructor.name} task aborted successfully`):o.warn(`Error stopping ${this.constructor.name} task: ${e}`)}}await this._donePromise,o.debug(`${this.constructor.name} task completed`)}reset(){this._readyPromise=new Promise(e=>this._readyResolver=e),this._donePromise=new Promise(e=>this._doneResolver=e),this._exception=null,this._connection=null,this._task=null,this._abortController=new AbortController}async connectionTask(){o.debug(`Running ${this.constructor.name} task`);try{this._connection=await this.establishConnection(),o.debug(`${this.constructor.name} connected successfully`),this._readyResolver(),await this.waitForAbort()}catch(e){this._exception=e,o.error(`Error in ${this.constructor.name} task: ${e}`),this._readyResolver()}finally{if(this._connection!==null){try{await this.closeConnection(this._connection)}catch(e){o.warn(`Error closing connection in ${this.constructor.name}: ${e}`)}this._connection=null}this._doneResolver()}}async waitForAbort(){return new Promise((e,t)=>{if(!this._abortController)return;let n=this._abortController.signal;if(n.aborted){e();return}let r=a(()=>{n.removeEventListener(`abort`,r),e()},`onAbort`);n.addEventListener(`abort`,r)})}},P_=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;var a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),F_=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;var t=P_(),n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;var o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),Q=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;var t=P_(),n=F_(),r=P_();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return r.Name}});var i=F_();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=ie(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ie(this.rhs,e,n),this}get names(){return re(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ie(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(ae(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>w(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(oe(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=ie(this.condition,e,t),this}get names(){let e=super.names;return re(e,this.condition),this.else&&w(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ie(this.iteration,e,t),this}get names(){return w(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return re(re(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ie(this.iterable,e,t),this}get names(){return w(super.names,this.iterable.names)}},ee=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};ee.kind=`func`;var S=class extends p{render(e){return`return `+super.render(e)}};S.kind=`return`;var C=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&w(e,this.catch.names),this.finally&&w(e,this.finally.names),e}},te=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};te.kind=`catch`;var ne=class extends m{render(e){return`finally`+super.render(e)}};ne.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
61
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:N.string().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:N.string().optional().describe(`User's timezone in IANA format.`),userAgent:N.string().optional().describe(`Host application identifier.`),platform:N.union([N.literal(`web`),N.literal(`desktop`),N.literal(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:N.object({touch:N.boolean().optional().describe(`Whether the device supports touch input.`),hover:N.boolean().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:N.object({top:N.number().describe(`Top safe area inset in pixels.`),right:N.number().describe(`Right safe area inset in pixels.`),bottom:N.number().describe(`Bottom safe area inset in pixels.`),left:N.number().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough();N.object({method:N.literal(`ui/notifications/host-context-changed`),params:t_.describe(`Partial context update containing only changed fields.`)}),N.object({method:N.literal(`ui/update-model-context`),params:N.object({content:N.array(Bt).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:N.record(N.string(),N.unknown().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),N.object({method:N.literal(`ui/initialize`),params:N.object({appInfo:Ae.describe(`App identification (name and version).`),appCapabilities:$g.describe(`Features and capabilities this app provides.`),protocolVersion:N.string().describe(`Protocol version this app supports.`)})}),N.object({protocolVersion:N.string().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:Ae.describe(`Host application identification and version.`),hostCapabilities:Qg.describe(`Features and capabilities provided by the host.`),hostContext:t_.describe(`Rich context about the host environment.`)}).passthrough();var n_=`text/html;profile=mcp-app`,r_=`1.22.4-canary.1`;function i_(){return r_}a(i_,`getPackageVersion`);var a_=class{static{a(this,`BaseTelemetryEvent`)}},o_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`MCPAgentExecutionEvent`)}get name(){return`mcp_agent_execution`}get properties(){return{execution_method:this.data.executionMethod,query:this.data.query,query_length:this.data.query.length,success:this.data.success,model_provider:this.data.modelProvider,model_name:this.data.modelName,server_count:this.data.serverCount,server_identifiers:this.data.serverIdentifiers,total_tools_available:this.data.totalToolsAvailable,tools_available_names:this.data.toolsAvailableNames,max_steps_configured:this.data.maxStepsConfigured,memory_enabled:this.data.memoryEnabled,use_server_manager:this.data.useServerManager,max_steps_used:this.data.maxStepsUsed,manage_connector:this.data.manageConnector,external_history_used:this.data.externalHistoryUsed,steps_taken:this.data.stepsTaken??null,tools_used_count:this.data.toolsUsedCount??null,tools_used_names:this.data.toolsUsedNames??null,response:this.data.response??null,response_length:this.data.response?this.data.response.length:null,execution_time_ms:this.data.executionTimeMs??null,error_type:this.data.errorType??null,conversation_history_length:this.data.conversationHistoryLength??null}}};function s_(e,t){let n=Array.from(e.registrations.tools.values()),r=Array.from(e.registrations.prompts.values()),i=Array.from(e.registrations.resources.values()),a=Array.from(e.registrations.resourceTemplates.values()),o=i.map(e=>({name:e.config.name,title:e.config.title??null,description:e.config.description??null,uri:e.config.uri??null,mime_type:e.config.mimeType??null})),s=o.filter(e=>e.mime_type===`text/html+skybridge`),c=o.filter(e=>e.mime_type===`text/uri-list`||e.mime_type===`text/html`),l=o.filter(e=>e.mime_type===n_);return{transport:t,toolsNumber:e.registeredTools.length,resourcesNumber:e.registeredResources.length,promptsNumber:e.registeredPrompts.length,auth:!!e.oauthProvider,name:e.config.name,description:e.config.description??null,baseUrl:e.serverBaseUrl??null,toolNames:e.registeredTools.length>0?e.registeredTools:null,resourceNames:e.registeredResources.length>0?e.registeredResources:null,promptNames:e.registeredPrompts.length>0?e.registeredPrompts:null,tools:n.length>0?n.map(e=>({name:e.config.name,title:e.config.title??null,description:e.config.description??null,input_schema:e.config.schema?JSON.stringify(e.config.schema):null,output_schema:e.config.outputSchema?JSON.stringify(e.config.outputSchema):null})):null,resources:o.length>0?o:null,prompts:r.length>0?r.map(e=>({name:e.config.name,title:e.config.title??null,description:e.config.description??null,args:e.config.args?JSON.stringify(e.config.args):null})):null,templates:a.length>0?a.map(e=>({name:e.config.name,title:e.config.title??null,description:e.config.description??null})):null,capabilities:{logging:!0,resources:{subscribe:!0,listChanged:!0}},appsSdkResources:s.length>0?s:null,appsSdkResourcesNumber:s.length,mcpUiResources:c.length>0?c:null,mcpUiResourcesNumber:c.length,mcpAppsResources:l.length>0?l:null,mcpAppsResourcesNumber:l.length}}a(s_,`createServerRunEventData`);var c_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ServerRunEvent`)}get name(){return`server_run`}get properties(){return{transport:this.data.transport,tools_number:this.data.toolsNumber,resources_number:this.data.resourcesNumber,prompts_number:this.data.promptsNumber,auth:this.data.auth,name:this.data.name,description:this.data.description??null,base_url:this.data.baseUrl??null,tool_names:this.data.toolNames??null,resource_names:this.data.resourceNames??null,prompt_names:this.data.promptNames??null,tools:this.data.tools??null,resources:this.data.resources??null,prompts:this.data.prompts??null,templates:this.data.templates??null,capabilities:this.data.capabilities?JSON.stringify(this.data.capabilities):null,apps_sdk_resources:this.data.appsSdkResources?JSON.stringify(this.data.appsSdkResources):null,apps_sdk_resources_number:this.data.appsSdkResourcesNumber??0,mcp_ui_resources:this.data.mcpUiResources?JSON.stringify(this.data.mcpUiResources):null,mcp_ui_resources_number:this.data.mcpUiResourcesNumber??0,mcp_apps_resources:this.data.mcpAppsResources?JSON.stringify(this.data.mcpAppsResources):null,mcp_apps_resources_number:this.data.mcpAppsResourcesNumber??0}}},l_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ServerInitializeEvent`)}get name(){return`server_initialize_call`}get properties(){return{protocol_version:this.data.protocolVersion,client_info:JSON.stringify(this.data.clientInfo),client_capabilities:JSON.stringify(this.data.clientCapabilities),session_id:this.data.sessionId??null}}},u_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ServerToolCallEvent`)}get name(){return`server_tool_call`}get properties(){return{tool_name:this.data.toolName,length_input_argument:this.data.lengthInputArgument,success:this.data.success,error_type:this.data.errorType??null,execution_time_ms:this.data.executionTimeMs??null}}},d_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ServerResourceCallEvent`)}get name(){return`server_resource_call`}get properties(){return{name:this.data.name,description:this.data.description,contents:this.data.contents,success:this.data.success,error_type:this.data.errorType??null}}},f_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ServerPromptCallEvent`)}get name(){return`server_prompt_call`}get properties(){return{name:this.data.name,description:this.data.description,success:this.data.success,error_type:this.data.errorType??null}}},p_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ServerContextEvent`)}get name(){return`server_context_${this.data.contextType}`}get properties(){return{context_type:this.data.contextType,notification_type:this.data.notificationType??null}}},m_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`MCPClientInitEvent`)}get name(){return`mcpclient_init`}get properties(){return{code_mode:this.data.codeMode,sandbox:this.data.sandbox,all_callbacks:this.data.allCallbacks,verify:this.data.verify,servers:this.data.servers,num_servers:this.data.numServers,is_browser:this.data.isBrowser}}},h_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ConnectorInitEvent`)}get name(){return`connector_init`}get properties(){return{connector_type:this.data.connectorType,server_command:this.data.serverCommand??null,server_args:this.data.serverArgs??null,server_url:this.data.serverUrl??null,public_identifier:this.data.publicIdentifier??null}}},g_=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ClientAddServerEvent`)}get name(){return`client_add_server`}get properties(){let{serverName:e,serverConfig:t}=this.data,n=t.url;return{server_name:e,server_url_domain:n?this._extractHostname(n):null,transport:t.transport??null,has_auth:!!(t.authToken||t.authProvider)}}_extractHostname(e){try{return new URL(e).hostname}catch{return null}}},__=class extends a_{constructor(e){super(),this.data=e}static{a(this,`ClientRemoveServerEvent`)}get name(){return`client_remove_server`}get properties(){return{server_name:this.data.serverName}}};function v_(e){return e._llm_type||e.constructor.name.toLowerCase()}a(v_,`getModelProvider`);function y_(e){if(`_identifyingParams`in e){let t=e._identifyingParams;if(typeof t==`object`&&t){for(let e of[`model`,`modelName`,`model_name`,`modelId`,`model_id`,`deploymentName`,`deployment_name`])if(e in t)return String(t[e])}}return e.model||e.modelName||e.constructor.name}a(y_,`getModelName`);function b_(e){return[v_(e),y_(e)]}a(b_,`extractModelInfo`);function x_(){if(typeof globalThis<`u`&&globalThis.crypto&&typeof globalThis.crypto.randomUUID==`function`)return globalThis.crypto.randomUUID();if(typeof globalThis<`u`&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues==`function`){let e=new Uint8Array(16);globalThis.crypto.getRandomValues(e);let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.substring(0,8)}-${t.substring(8,12)}-${t.substring(12,16)}-${t.substring(16,20)}-${t.substring(20)}`}return`${Date.now()}-${Math.random().toString(36).substring(2,15)}-${Math.random().toString(36).substring(2,15)}`}a(x_,`generateUUID`);function S_(){if(typeof window<`u`&&window.crypto&&typeof window.crypto.getRandomValues==`function`){let e=new Uint8Array(8);return window.crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}if(typeof globalThis<`u`&&globalThis.crypto&&typeof globalThis.crypto.getRandomValues==`function`){let e=new Uint8Array(8);return globalThis.crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}return Math.random().toString(36).substring(2,15)}a(S_,`secureRandomString`);var C_=`mcp_use_user_id`;function w_(){return typeof localStorage<`u`&&typeof localStorage.getItem==`function`&&typeof localStorage.setItem==`function`&&typeof localStorage.removeItem==`function`}a(w_,`isLocalStorageFunctional`);function T_(){try{return typeof window<`u`&&typeof document<`u`?`browser`:`unknown`}catch{return`unknown`}}a(T_,`detectRuntimeEnvironment`);function E_(e){if(e===`browser`)try{if(w_())return localStorage.setItem(`__mcp_use_test__`,`1`),localStorage.removeItem(`__mcp_use_test__`),`localStorage`}catch{}return`session-only`}a(E_,`getStorageCapability`);var D_=null;function O_(){return D_===null&&(D_=T_()),D_}a(O_,`getRuntimeEnvironment`);var k_=class e{static{a(this,`Telemetry`)}static instance=null;PROJECT_API_KEY=`phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI`;HOST=`https://eu.i.posthog.com`;UNKNOWN_USER_ID=`UNKNOWN_USER_ID`;_currUserId=null;_posthogBrowserClient=null;_posthogLoading=null;_runtimeEnvironment;_storageCapability;_source;constructor(){this._runtimeEnvironment=O_(),this._storageCapability=E_(this._runtimeEnvironment),this._source=this._getSourceFromLocalStorage()||this._runtimeEnvironment;let e=this._checkTelemetryDisabled(),t=this._runtimeEnvironment!==`unknown`;e?(this._posthogBrowserClient=null,o.debug(`Telemetry disabled via localStorage`)):t?(o.info(`Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false in localStorage to disable.`),this._posthogLoading=this._initPostHogBrowser()):(this._posthogBrowserClient=null,o.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`))}_getSourceFromLocalStorage(){try{if(w_())return localStorage.getItem(`MCP_USE_TELEMETRY_SOURCE`)}catch{}return null}_checkTelemetryDisabled(){return!!(w_()&&localStorage.getItem(`MCP_USE_ANONYMIZED_TELEMETRY`)===`false`)}async _initPostHogBrowser(){try{let e=await te(()=>import(`./module-DCsrdi7m.js`),[]),t=e.default||e.posthog;if(!t||typeof t.init!=`function`)throw Error(`posthog-js module did not export expected interface`);t.init(this.PROJECT_API_KEY,{api_host:this.HOST,persistence:`localStorage`,autocapture:!1,capture_pageview:!1,disable_session_recording:!0,loaded:a(()=>{o.debug(`PostHog browser client initialized`)},`loaded`)}),this._posthogBrowserClient=t}catch(e){o.warn(`Failed to initialize PostHog browser telemetry: ${e}`),this._posthogBrowserClient=null}}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return e.instance||=new e,e.instance}setSource(e){this._source=e;try{w_()&&localStorage.setItem(`MCP_USE_TELEMETRY_SOURCE`,e)}catch{}o.debug(`Telemetry source set to: ${e}`)}getSource(){return this._source}get isEnabled(){return this._posthogBrowserClient!==null}get userId(){if(this._currUserId)return this._currUserId;try{switch(this._storageCapability){case`localStorage`:this._currUserId=this._getUserIdFromLocalStorage();break;default:try{this._currUserId=`session-${x_()}`}catch{this._currUserId=`session-${Date.now()}-${S_()}`}break}}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}_getUserIdFromLocalStorage(){try{if(!w_())throw Error(`localStorage is not available or not functional`);localStorage.setItem(`__mcp_use_test__`,`1`),localStorage.removeItem(`__mcp_use_test__`);let e=localStorage.getItem(C_);if(!e){try{e=x_()}catch{e=`${Date.now()}-${S_()}`}localStorage.setItem(C_,e)}return e}catch(e){o.debug(`Failed to access localStorage for user ID: ${e}`);let t;try{t=`session-${x_()}`}catch{t=`session-${Date.now()}-${S_()}`}return t}}async capture(e){if(this._posthogLoading&&await this._posthogLoading,!this._posthogBrowserClient)return;let t=this.userId,n={...e.properties};if(n.mcp_use_version=i_(),n.language=`typescript`,n.source=this._source,n.runtime=this._runtimeEnvironment,this._posthogBrowserClient)try{this._posthogBrowserClient.capture(e.name,{...n,distinct_id:t})}catch(t){o.debug(`Failed to track PostHog Browser event ${e.name}: ${t}`)}}async trackAgentExecution(e){if(!this.isEnabled)return;let t=new o_(e);await this.capture(t)}async trackServerRunFromServer(e,t){if(!this.isEnabled)return;let n=new c_(s_(e,t));await this.capture(n)}async trackServerInitialize(e){if(!this.isEnabled)return;let t=new l_(e);await this.capture(t)}async trackServerToolCall(e){if(!this.isEnabled)return;let t=new u_(e);await this.capture(t)}async trackServerResourceCall(e){if(!this.isEnabled)return;let t=new d_(e);await this.capture(t)}async trackServerPromptCall(e){if(!this.isEnabled)return;let t=new f_(e);await this.capture(t)}async trackServerContext(e){if(!this.isEnabled)return;let t=new p_(e);await this.capture(t)}async trackMCPClientInit(e){if(!this.isEnabled)return;let t=new m_(e);await this.capture(t)}async trackConnectorInit(e){if(!this.isEnabled)return;let t=new h_(e);await this.capture(t)}async trackClientAddServer(e,t){if(!this.isEnabled)return;let n=new g_({serverName:e,serverConfig:t});await this.capture(n)}async trackClientRemoveServer(e){if(!this.isEnabled)return;let t=new __({serverName:e});await this.capture(t)}async trackUseMcpConnection(e){this.isEnabled&&await this.capture({name:`usemcp_connection`,properties:{url_domain:new URL(e.url).hostname,transport_type:e.transportType,success:e.success,error_type:e.errorType??null,connection_time_ms:e.connectionTimeMs??null,has_oauth:e.hasOAuth,has_sampling:e.hasSampling,has_elicitation:e.hasElicitation}})}async trackUseMcpToolCall(e){this.isEnabled&&await this.capture({name:`usemcp_tool_call`,properties:{tool_name:e.toolName,success:e.success,error_type:e.errorType??null,execution_time_ms:e.executionTimeMs??null}})}async trackUseMcpResourceRead(e){this.isEnabled&&await this.capture({name:`usemcp_resource_read`,properties:{resource_uri_scheme:e.resourceUri.split(`:`)[0],success:e.success,error_type:e.errorType??null}})}identify(e,t){if(this._posthogBrowserClient)try{this._posthogBrowserClient.identify(e,t)}catch(e){o.debug(`Failed to identify user: ${e}`)}}reset(){if(this._posthogBrowserClient)try{this._posthogBrowserClient.reset()}catch(e){o.debug(`Failed to reset user: ${e}`)}this._currUserId=null}flush(){}shutdown(){}async trackPackageDownload(e){}},A_=k_;function j_(e){A_.getInstance().setSource(e)}a(j_,`setTelemetrySource`);var M_=class{static{a(this,`BaseConnector`)}client=null;connectionManager=null;toolsCache=null;capabilitiesCache=null;serverInfoCache=null;connected=!1;opts;notificationHandlers=[];rootsCache=[];constructor(e={}){let t={...e,onSampling:e.onSampling??e.samplingCallback,onElicitation:e.onElicitation??e.elicitationCallback};e.samplingCallback&&!e.onSampling&&o.warn(`[BaseConnector] The "samplingCallback" option is deprecated. Use "onSampling" instead.`),e.elicitationCallback&&!e.onElicitation&&console.warn(`[BaseConnector] The "elicitationCallback" option is deprecated. Use "onElicitation" instead.`),this.opts=t,t.roots&&(this.rootsCache=[...t.roots]),t.onNotification&&this.notificationHandlers.push(t.onNotification)}trackConnectorInit(e){let t=this.constructor.name;k_.getInstance().trackConnectorInit({connectorType:t,...e}).catch(e=>o.debug(`Failed to track connector init: ${e}`))}onNotification(e){this.notificationHandlers.push(e),this.client&&this.setupNotificationHandler()}setupNotificationHandler(){if(!this.client)return;let e=a(async e=>{for(let t of this.notificationHandlers)try{await t(e)}catch(e){o.error(`Error in notification handler:`,e)}},`forwardToUserHandlers`);this.client.fallbackNotificationHandler=async t=>{switch(t.method){case`notifications/tools/list_changed`:await this.refreshToolsCache();break;case`notifications/resources/list_changed`:await this.onResourcesListChanged();break;case`notifications/prompts/list_changed`:await this.onPromptsListChanged();break;default:break}await e(t)};let t=this.client._notificationHandlers;for(let n of[`notifications/progress`,`notifications/cancelled`]){let r=t.get(n);r&&t.set(n,async t=>{await r(t),await e(t)})}}async refreshToolsCache(){if(this.client)try{o.debug(`[Auto] Refreshing tools cache due to list_changed notification`),this.toolsCache=(await this.client.listTools()).tools??[],o.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(e){o.warn(`[Auto] Failed to refresh tools cache:`,e)}}async onResourcesListChanged(){o.debug(`[Auto] Resources list changed - clients should re-fetch if needed`)}async onPromptsListChanged(){o.debug(`[Auto] Prompts list changed - clients should re-fetch if needed`)}async setRoots(e){this.rootsCache=[...e],this.client&&(o.debug(`Sending roots/list_changed notification with ${e.length} root(s)`),await this.client.sendRootsListChanged())}getRoots(){return[...this.rootsCache]}setupRootsHandler(){this.client&&this.client.setRequestHandler(Nn,async(e,t)=>(o.debug(`Server requested roots list, returning ${this.rootsCache.length} root(s)`),{roots:this.rootsCache}))}setupSamplingHandler(){if(!this.client){o.debug(`setupSamplingHandler: No client available`);return}let e=this.opts.onSampling??this.opts.samplingCallback;if(!e){o.debug(`setupSamplingHandler: No sampling callback provided`);return}o.debug(`setupSamplingHandler: Setting up sampling request handler`),this.client.setRequestHandler(pn,async(t,n)=>(o.debug(`Server requested sampling, forwarding to callback`),await e(t.params))),o.debug(`setupSamplingHandler: Sampling handler registered successfully`)}setupElicitationHandler(){if(!this.client){o.debug(`setupElicitationHandler: No client available`);return}let e=this.opts.onElicitation??this.opts.elicitationCallback;if(!e){o.debug(`setupElicitationHandler: No elicitation callback provided`);return}o.debug(`setupElicitationHandler: Setting up elicitation request handler`),this.client.setRequestHandler(Cn,async(t,n)=>(o.debug(`Server requested elicitation, forwarding to callback`),await e(t.params))),o.debug(`setupElicitationHandler: Elicitation handler registered successfully`)}async disconnect(){if(!this.connected){o.debug(`Not connected to MCP implementation`);return}o.debug(`Disconnecting from MCP implementation`),await this.cleanupResources(),this.connected=!1,o.debug(`Disconnected from MCP implementation`)}get isClientConnected(){return this.client!=null}async initialize(e=this.opts.defaultRequestOptions??{}){if(!this.client)throw Error(`MCP client is not connected`);o.debug(`Caching server capabilities & tools`);let t=this.client.getServerCapabilities();this.capabilitiesCache=t||null;let n=this.client.getServerVersion();this.serverInfoCache=n||null;try{this.toolsCache=(await this.client.listTools(void 0,e)).tools??[],o.debug(`Fetched ${this.toolsCache.length} tools from server`)}catch(e){let t=e;t.code===-32601?o.debug(`Server does not implement tools/list, assuming no tools`):o.debug(`Failed to list tools, assuming empty:`,t.message),this.toolsCache=[]}return o.debug(`Server capabilities:`,t),o.debug(`Server info:`,n),t}get tools(){if(!this.toolsCache)throw Error(`MCP client is not initialized; call initialize() first`);return this.toolsCache}get serverCapabilities(){return this.capabilitiesCache||{}}get serverInfo(){return this.serverInfoCache}async callTool(e,t,n){if(!this.client)throw Error(`MCP client is not connected`);let r=n?{...n}:void 0;r?.resetTimeoutOnProgress&&!r.onprogress&&(r.onprogress=()=>{},o.debug(`[BaseConnector] Added onprogress callback for tool '${e}' to enable progressToken`)),o.debug(`Calling tool '${e}' with args`,t);let i=await this.client.callTool({name:e,arguments:t},void 0,r);return o.debug(`Tool '${e}' returned`,i),i}async listTools(e){if(!this.client)throw Error(`MCP client is not connected`);o.debug(`[listTools] Fetching fresh tools from server...`);let t=await this.client.listTools(void 0,e),n=t.tools?[...t.tools]:[];return o.debug(`[listTools] Returned ${n.length} tools:`,n.map(e=>e.name)),n}async listResources(e,t){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Listing resources`,e?`with cursor: ${e}`:``),await this.client.listResources({cursor:e},t)}async listAllResources(e){if(!this.client)throw Error(`MCP client is not connected`);if(!this.capabilitiesCache?.resources)return o.debug(`Server does not advertise resources capability, skipping`),{resources:[]};try{o.debug(`Listing all resources (with auto-pagination)`);let t=[],n;do{let r=await this.client.listResources({cursor:n},e);t.push(...r.resources||[]),n=r.nextCursor}while(n);return{resources:t}}catch(e){if(e.code===-32601)return o.debug(`Server advertised resources but method not found`),{resources:[]};throw e}}async listResourceTemplates(e){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Listing resource templates`),await this.client.listResourceTemplates(void 0,e)}async complete(e,t){if(!this.client)throw Error(`MCP client is not connected`);o.debug(`[complete] Requesting completions for:`,e.ref);let n=await this.client.complete(e,t);return o.debug(`[complete] Received ${n.completion.values.length} suggestions`),n}async readResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Reading resource ${e}`),await this.client.readResource({uri:e},t)}async subscribeToResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Subscribing to resource: ${e}`),await this.client.subscribeResource({uri:e},t)}async unsubscribeFromResource(e,t){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Unsubscribing from resource: ${e}`),await this.client.unsubscribeResource({uri:e},t)}async listPrompts(){if(!this.client)throw Error(`MCP client is not connected`);if(!this.capabilitiesCache?.prompts)return o.debug(`Server does not advertise prompts capability, skipping`),{prompts:[]};try{return o.debug(`Listing prompts`),await this.client.listPrompts()}catch(e){if(e.code===-32601)return o.debug(`Server advertised prompts but method not found`),{prompts:[]};throw e}}async getPrompt(e,t){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Getting prompt ${e}`),await this.client.getPrompt({name:e,arguments:t})}async request(e,t=null,n){if(!this.client)throw Error(`MCP client is not connected`);return o.debug(`Sending raw request '${e}' with params`,t),await this.client.request({method:e,params:t??{}},void 0,n)}async cleanupResources(){let e=[];if(this.client)try{typeof this.client.close==`function`&&await this.client.close()}catch(t){let n=`Error closing client: ${t}`;o.warn(n),e.push(n)}finally{this.client=null}if(this.connectionManager)try{await this.connectionManager.stop()}catch(t){let n=`Error stopping connection manager: ${t}`;o.warn(n),e.push(n)}finally{this.connectionManager=null}this.toolsCache=null,e.length&&o.warn(`Resource cleanup finished with ${e.length} issue(s)`)}},N_=class{static{a(this,`ConnectionManager`)}_readyPromise;_readyResolver;_donePromise;_doneResolver;_exception=null;_connection=null;_task=null;_abortController=null;constructor(){this.reset()}async start(){if(this.reset(),o.debug(`Starting ${this.constructor.name}`),this._task=this.connectionTask(),await this._readyPromise,this._exception)throw this._exception;if(this._connection===null)throw Error(`Connection was not established`);return this._connection}async stop(){if(this._task&&this._abortController){o.debug(`Cancelling ${this.constructor.name} task`),this._abortController.abort();try{await this._task}catch(e){e instanceof Error&&e.name===`AbortError`?o.debug(`${this.constructor.name} task aborted successfully`):o.warn(`Error stopping ${this.constructor.name} task: ${e}`)}}await this._donePromise,o.debug(`${this.constructor.name} task completed`)}reset(){this._readyPromise=new Promise(e=>this._readyResolver=e),this._donePromise=new Promise(e=>this._doneResolver=e),this._exception=null,this._connection=null,this._task=null,this._abortController=new AbortController}async connectionTask(){o.debug(`Running ${this.constructor.name} task`);try{this._connection=await this.establishConnection(),o.debug(`${this.constructor.name} connected successfully`),this._readyResolver(),await this.waitForAbort()}catch(e){this._exception=e,o.error(`Error in ${this.constructor.name} task: ${e}`),this._readyResolver()}finally{if(this._connection!==null){try{await this.closeConnection(this._connection)}catch(e){o.warn(`Error closing connection in ${this.constructor.name}: ${e}`)}this._connection=null}this._doneResolver()}}async waitForAbort(){return new Promise((e,t)=>{if(!this._abortController)return;let n=this._abortController.signal;if(n.aborted){e();return}let r=a(()=>{n.removeEventListener(`abort`,r),e()},`onAbort`);n.addEventListener(`abort`,r)})}},P_=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;var a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),F_=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;var t=P_(),n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;var o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),Q=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;var t=P_(),n=F_(),r=P_();Object.defineProperty(e,`_`,{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,`str`,{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,`strConcat`,{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,`nil`,{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,`getProperty`,{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,`stringify`,{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,`regexpCode`,{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,`Name`,{enumerable:!0,get:function(){return r.Name}});var i=F_();Object.defineProperty(e,`Scope`,{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,`ValueScope`,{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,`ValueScopeName`,{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,`varKinds`,{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=ie(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ie(this.rhs,e,n),this}get names(){return re(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ie(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(ae(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>w(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(oe(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=ie(this.condition,e,t),this}get names(){let e=super.names;return re(e,this.condition),this.else&&w(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=ie(this.iteration,e,t),this}get names(){return w(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return re(re(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=ie(this.iterable,e,t),this}get names(){return w(super.names,this.iterable.names)}},ee=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};ee.kind=`func`;var S=class extends p{render(e){return`return `+super.render(e)}};S.kind=`return`;var C=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&w(e,this.catch.names),this.finally&&w(e,this.finally.names),e}},te=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};te.kind=`catch`;var ne=class extends m{render(e){return`finally`+super.render(e)}};ne.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
62
62
  `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new S;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(S)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new C;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new te(e),t(e)}return n&&(this._currNode=r.finally=new ne,this.code(n)),this._endBlockNode(te,ne)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new ee(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(ee)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function w(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function re(e,n){return n instanceof t._CodeOrName?w(e,n.names):e}function ie(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function ae(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function oe(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${de(e)}`}e.not=oe;var se=ue(e.operators.AND);function T(...e){return e.reduce(se)}e.and=T;var ce=ue(e.operators.OR);function le(...e){return e.reduce(ce)}e.or=le;function ue(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${de(n)} ${e} ${de(r)}`}function de(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),$=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;var t=Q(),n=P_();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0?!0:(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0?!0:(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;var _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),I_=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0});var t=Q();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),L_=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;var t=Q(),n=$(),r=I_();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}var u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),R_=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;var t=L_(),n=Q(),r=I_(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),z_=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.getRules=e.isJSONType=void 0;var t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),B_=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),V_=i((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;var t=z_(),n=B_(),r=L_(),i=Q(),a=$(),o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;var u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
63
63
  || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
64
64
  || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/stdio-LLTXMSZH-CQ-zxwTS.js","assets/chunk-zsgVPwQN.js","assets/client-DEFMLVFC.js","assets/preload-helper-XLr9-hSf.js","assets/schemas-79owEkeD.js","assets/json-schema-processors-DSIsU0go.js","assets/chunk-3GQAWCBQ-C-9Cm0Np.js","assets/chunk-QWQYAQCK-CyFuZlX8.js","assets/path-BzTN_bR6.js"])))=>i.map(i=>d[i]);
2
- import{n as e,t}from"./chunk-3GQAWCBQ-C-9Cm0Np.js";import{n}from"./chunk-QWQYAQCK-CyFuZlX8.js";import{c as r,i,n as a}from"./client-DEFMLVFC.js";import{a as o,i as s,o as c,r as l,t as u}from"./chunk-6E445R5C-ny1rw8Le.js";import{t as d}from"./preload-helper-XLr9-hSf.js";import{t as f}from"./chunk-RPN2XO5I-_4a18lz2.js";import{i as p,n as m,o as h,t as g}from"./path-BzTN_bR6.js";h(),g();var _=class{static{t(this,`BaseCodeExecutor`)}client;_connecting=!1;constructor(e){this.client=e}async ensureServersConnected(){let e=this.client.getServerNames(),t=Object.keys(this.client.getAllActiveSessions()),r=e.filter(e=>!t.includes(e));if(r.length>0&&!this._connecting){this._connecting=!0;try{n.debug(`Connecting to configured servers for code execution: ${r.join(`, `)}`),await this.client.createAllSessions()}finally{this._connecting=!1}}else if(r.length>0&&this._connecting){n.debug(`Waiting for ongoing server connection...`);let e=Date.now();for(;this._connecting&&Date.now()-e<5e3;)await new Promise(e=>setTimeout(e,100))}}getToolNamespaces(){let e=[],t=this.client.getAllActiveSessions();for(let[r,i]of Object.entries(t))if(r!==`code_mode`)try{let t=i.connector,a;try{a=t.tools}catch(e){n.warn(`Tools not available for server ${r}: ${e}`);continue}if(!a||a.length===0)continue;e.push({serverName:r,tools:a,session:i})}catch(e){n.warn(`Failed to load tools for server ${r}: ${e}`)}return e}createSearchToolsFunction(){return async(e=``,t=`full`)=>{let r=[],i=new Set,a=e.toLowerCase(),o=this.client.getAllActiveSessions();for(let[e,a]of Object.entries(o))if(e!==`code_mode`)try{let n=a.connector.tools;n&&n.length>0&&i.add(e);for(let i of n)t===`names`?r.push({name:i.name,server:e}):t===`descriptions`?r.push({name:i.name,server:e,description:i.description}):r.push({name:i.name,server:e,description:i.description,input_schema:i.inputSchema})}catch(t){n.warn(`Failed to search tools in server ${e}: ${t}`)}let s=r;return e&&(s=r.filter(e=>{let t=e.name.toLowerCase().includes(a),n=e.description?.toLowerCase().includes(a),r=e.server.toLowerCase().includes(a);return t||n||r})),{meta:{total_tools:r.length,namespaces:Array.from(i).sort(),result_count:s.length},results:s}}}},v=class extends _{static{t(this,`E2BCodeExecutor`)}e2bApiKey;codeExecSandbox=null;SandboxClass=null;timeoutMs;constructor(e,t){super(e),this.e2bApiKey=t.apiKey,this.timeoutMs=t.timeoutMs??3e5}async ensureSandboxClass(){if(!this.SandboxClass)try{this.SandboxClass=(await d(()=>import(`@e2b/code-interpreter`),[])).Sandbox}catch{throw Error(`@e2b/code-interpreter is not installed. The E2B code executor requires this optional dependency. Install it with: yarn add @e2b/code-interpreter`)}}async getOrCreateCodeExecSandbox(){return this.codeExecSandbox?this.codeExecSandbox:(await this.ensureSandboxClass(),n.debug(`Starting E2B sandbox for code execution...`),this.codeExecSandbox=await this.SandboxClass.create(`base`,{apiKey:this.e2bApiKey,timeoutMs:this.timeoutMs}),this.codeExecSandbox)}generateShim(e){let t=`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/stdio-ZCW4I5XD-CmtXCvzt.js","assets/chunk-zsgVPwQN.js","assets/client-6SIHYz8o.js","assets/preload-helper-XLr9-hSf.js","assets/schemas-79owEkeD.js","assets/json-schema-processors-DSIsU0go.js","assets/chunk-3GQAWCBQ-C-9Cm0Np.js","assets/chunk-QWQYAQCK-CyFuZlX8.js","assets/path-BzTN_bR6.js"])))=>i.map(i=>d[i]);
2
+ import{n as e,t}from"./chunk-3GQAWCBQ-C-9Cm0Np.js";import{n}from"./chunk-QWQYAQCK-CyFuZlX8.js";import{c as r,i,n as a}from"./client-6SIHYz8o.js";import{a as o,i as s,o as c,r as l,t as u}from"./chunk-PQMRWHFE-CV30_nBm.js";import{t as d}from"./preload-helper-XLr9-hSf.js";import{t as f}from"./chunk-RPN2XO5I-BI2C4Mwo.js";import{i as p,n as m,o as h,t as g}from"./path-BzTN_bR6.js";h(),g();var _=class{static{t(this,`BaseCodeExecutor`)}client;_connecting=!1;constructor(e){this.client=e}async ensureServersConnected(){let e=this.client.getServerNames(),t=Object.keys(this.client.getAllActiveSessions()),r=e.filter(e=>!t.includes(e));if(r.length>0&&!this._connecting){this._connecting=!0;try{n.debug(`Connecting to configured servers for code execution: ${r.join(`, `)}`),await this.client.createAllSessions()}finally{this._connecting=!1}}else if(r.length>0&&this._connecting){n.debug(`Waiting for ongoing server connection...`);let e=Date.now();for(;this._connecting&&Date.now()-e<5e3;)await new Promise(e=>setTimeout(e,100))}}getToolNamespaces(){let e=[],t=this.client.getAllActiveSessions();for(let[r,i]of Object.entries(t))if(r!==`code_mode`)try{let t=i.connector,a;try{a=t.tools}catch(e){n.warn(`Tools not available for server ${r}: ${e}`);continue}if(!a||a.length===0)continue;e.push({serverName:r,tools:a,session:i})}catch(e){n.warn(`Failed to load tools for server ${r}: ${e}`)}return e}createSearchToolsFunction(){return async(e=``,t=`full`)=>{let r=[],i=new Set,a=e.toLowerCase(),o=this.client.getAllActiveSessions();for(let[e,a]of Object.entries(o))if(e!==`code_mode`)try{let n=a.connector.tools;n&&n.length>0&&i.add(e);for(let i of n)t===`names`?r.push({name:i.name,server:e}):t===`descriptions`?r.push({name:i.name,server:e,description:i.description}):r.push({name:i.name,server:e,description:i.description,input_schema:i.inputSchema})}catch(t){n.warn(`Failed to search tools in server ${e}: ${t}`)}let s=r;return e&&(s=r.filter(e=>{let t=e.name.toLowerCase().includes(a),n=e.description?.toLowerCase().includes(a),r=e.server.toLowerCase().includes(a);return t||n||r})),{meta:{total_tools:r.length,namespaces:Array.from(i).sort(),result_count:s.length},results:s}}}},v=class extends _{static{t(this,`E2BCodeExecutor`)}e2bApiKey;codeExecSandbox=null;SandboxClass=null;timeoutMs;constructor(e,t){super(e),this.e2bApiKey=t.apiKey,this.timeoutMs=t.timeoutMs??3e5}async ensureSandboxClass(){if(!this.SandboxClass)try{this.SandboxClass=(await d(()=>import(`@e2b/code-interpreter`),[])).Sandbox}catch{throw Error(`@e2b/code-interpreter is not installed. The E2B code executor requires this optional dependency. Install it with: yarn add @e2b/code-interpreter`)}}async getOrCreateCodeExecSandbox(){return this.codeExecSandbox?this.codeExecSandbox:(await this.ensureSandboxClass(),n.debug(`Starting E2B sandbox for code execution...`),this.codeExecSandbox=await this.SandboxClass.create(`base`,{apiKey:this.e2bApiKey,timeoutMs:this.timeoutMs}),this.codeExecSandbox)}generateShim(e){let t=`
3
3
  // MCP Bridge Shim
4
4
  global.__callMcpTool = async (server, tool, args) => {
5
5
  const id = Math.random().toString(36).substring(7);
@@ -88,4 +88,4 @@ ${this.generateShim(c)}
88
88
  throw e;
89
89
  }
90
90
  })()
91
- `;o=await new y.Script(n,{filename:`agent_code.js`}).runInNewContext(t,{timeout:r,displayErrors:!0})}catch(e){s=e.message||String(e),(e.code===`ERR_SCRIPT_EXECUTION_TIMEOUT`||e.message===`Script execution timed out.`||typeof s==`string`&&(s.includes(`timed out`)||s.includes(`timeout`)))&&(s=`Script execution timed out`),e.stack&&n.debug(`Code execution error stack: ${e.stack}`)}let c=(Date.now()-a)/1e3;return{result:o,logs:i,error:s,execution_time:c}}async _buildContext(e){let n=t((...t)=>{e.push(t.map(e=>typeof e==`object`?JSON.stringify(e,null,2):String(e)).join(` `))},`logHandler`),r={console:{log:n,error:t((...e)=>{n(`[ERROR]`,...e)},`error`),warn:t((...e)=>{n(`[WARN]`,...e)},`warn`),info:n,debug:n},Object,Array,String,Number,Boolean,Date,Math,JSON,RegExp,Map,Set,Promise,parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,setTimeout,clearTimeout,search_tools:this.createSearchToolsFunction(),__tool_namespaces:[]},i={},a=this.getToolNamespaces();for(let{serverName:e,tools:t,session:n}of a){let a={};for(let e of t){let t=e.name;a[t]=async e=>{let r=await n.connector.callTool(t,e||{});if(r.content&&r.content.length>0){let e=r.content[0];if(e.type===`text`)try{return JSON.parse(e.text)}catch{return e.text}return e}return r}}r[e]=a,i[e]=!0}return r.__tool_namespaces=Object.keys(i),y.createContext(r)}async cleanup(){}},E=class extends a{static{t(this,`CodeModeConnector`)}mcpClient;_tools;constructor(e){super(),this.mcpClient=e,this.connected=!0,this._tools=this._createToolsList()}async connect(){this.connected=!0}async disconnect(){this.connected=!1}get publicIdentifier(){return{name:`code_mode`,version:`1.0.0`}}_createToolsList(){return[{name:`execute_code`,description:`Execute JavaScript/TypeScript code with access to MCP tools. This is the PRIMARY way to interact with MCP servers in code mode. Write code that discovers tools using search_tools(), calls tools as async functions (e.g., await github.get_pull_request(...)), processes data efficiently, and returns results. Use 'await' for async operations and 'return' to return values. Available in code: search_tools(), __tool_namespaces, and server.tool_name() functions.`,inputSchema:{type:`object`,properties:{code:{type:`string`,description:`JavaScript/TypeScript code to execute. Use 'await' for async operations. Use 'return' to return a value. Available: search_tools(), server.tool_name(), __tool_namespaces`},timeout:{type:`number`,description:`Execution timeout in milliseconds`,default:3e4}},required:[`code`]}},{name:`search_tools`,description:`Search and discover available MCP tools across all servers. Use this to find out what tools are available before writing code. Returns tool information including names, descriptions, and schemas. Can filter by query and control detail level.`,inputSchema:{type:`object`,properties:{query:{type:`string`,description:`Search query to filter tools by name or description`,default:``},detail_level:{type:`string`,description:`Detail level: 'names', 'descriptions', or 'full'`,enum:[`names`,`descriptions`,`full`],default:`full`}}}}]}get tools(){return this._tools}async initialize(){return this.toolsCache=this._tools,{capabilities:{},version:`1.0.0`}}async callTool(e,t){if(e===`execute_code`){let e=t.code,n=t.timeout||3e4,r=await this.mcpClient.executeCode(e,n);return{content:[{type:`text`,text:JSON.stringify(r)}]}}else if(e===`search_tools`){let e=t.query||``,n=t.detail_level,r=await this.mcpClient.searchTools(e,n&&n in[`names`,`descriptions`,`full`]?n:`full`);return{content:[{type:`text`,text:JSON.stringify(r)}]}}throw Error(`Unknown tool: ${e}`)}};function D(t){let{readFileSync:n}=e(`fs`),r=n(t,`utf-8`);return JSON.parse(r)}t(D,`loadConfigFile`);function O(e){return`requestedSchema`in e&&e.requestedSchema!=null}t(O,`hasRequestedSchema`);function k(e){let t={};if(!O(e))return t;let n=e.requestedSchema.properties??{};for(let[e,r]of Object.entries(n)){let n=r;if(`default`in n){let r=n.default;(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`))&&(t[e]=r)}}return t}t(k,`getDefaults`);function A(e,t){let n=k(e);return t==null?n:{...n,...t}}t(A,`applyDefaults`);function j(e){return{action:`accept`,content:k(e)}}t(j,`acceptWithDefaults`);function M(e){return{action:`accept`,content:e}}t(M,`accept`);function N(e){return{action:`decline`}}t(N,`decline`);function P(){return{action:`cancel`}}t(P,`cancel`);function F(e){return N(e)}t(F,`reject`);function I(e,t){if(!O(e))return{valid:!0};try{let n=f.convert(e.requestedSchema).safeParse(t);return n.success?{valid:!0}:{valid:!1,errors:n.error.issues.map(e=>e.path.length>0?`${e.path.join(`.`)}: ${e.message}`:e.message)}}catch{return{valid:!1,errors:[`Unsupported or invalid schema`]}}}t(I,`validate`);function L(e,t,r){let a=Object.keys(e.mcpServers??{}),o=!!(r.onSampling??r.samplingCallback),s=!!(r.onElicitation??r.elicitationCallback);i.getInstance().trackMCPClientInit({codeMode:t,sandbox:!1,allCallbacks:o&&s,verify:!1,servers:a,numServers:a.length,isBrowser:!1}).catch(e=>n.debug(`Failed to track MCPClient init: ${e}`))}t(L,`trackNodeClientInit`);var R=class e extends u{static{t(this,`MCPClient`)}static getPackageVersion(){return r()}codeMode=!1;_codeExecutor=null;_customCodeExecutor=null;_codeExecutorConfig=`vm`;_executorOptions;_globalCallbacks;constructor(e,t){e?super(typeof e==`string`?D(e):e):super();let n=!1,r=`vm`,i;t?.codeMode&&(typeof t.codeMode==`boolean`?n=t.codeMode:(n=t.codeMode.enabled,r=t.codeMode.executor??`vm`,i=t.codeMode.executorOptions)),this.codeMode=n,this._codeExecutorConfig=r,this._executorOptions=i;let a=this.config;this._globalCallbacks={onSampling:t?.onSampling??t?.samplingCallback??a?.onSampling??a?.samplingCallback,samplingCallback:t?.samplingCallback??a?.samplingCallback,onElicitation:t?.onElicitation??t?.elicitationCallback??a?.onElicitation??a?.elicitationCallback,elicitationCallback:t?.elicitationCallback??a?.elicitationCallback,onNotification:t?.onNotification??a?.onNotification},t?.samplingCallback&&!t?.onSampling&&console.warn(`[MCPClient] The "samplingCallback" option is deprecated. Use "onSampling" instead.`),t?.elicitationCallback&&!t?.onElicitation&&console.warn(`[MCPClient] The "elicitationCallback" option is deprecated. Use "onElicitation" instead.`),this.codeMode&&this._setupCodeModeConnector(),L(this.config,this.codeMode,this._globalCallbacks)}static fromDict(t,n){return new e(t,n)}static fromConfigFile(t,n){return new e(D(t),n)}saveConfig(e){let t=m.dirname(e);p.existsSync(t)||p.mkdirSync(t,{recursive:!0}),p.writeFileSync(e,JSON.stringify(this.config,null,2),`utf-8`)}async createConnectorFromConfig(e){let t=c(e,this._globalCallbacks),n={...e,clientInfo:e.clientInfo??this.config.clientInfo};if(`command`in n&&`args`in n){let{StdioConnector:e}=await d(async()=>{let{StdioConnector:e}=await import(`./stdio-LLTXMSZH-CQ-zxwTS.js`);return{StdioConnector:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])),r=n;return new e({command:r.command,args:r.args,env:r.env,clientInfo:o(n.clientInfo),onSampling:t.onSampling,onElicitation:t.onElicitation,onNotification:t.onNotification})}return s(n,{onSampling:t.onSampling,onElicitation:t.onElicitation,onNotification:t.onNotification})}_setupCodeModeConnector(){n.debug(`Code mode connector initialized as internal meta server`);let e=new l(new E(this));this.sessions.code_mode=e,this.activeSessions.push(`code_mode`)}_ensureCodeExecutor(){if(!this._codeExecutor){let e=this._codeExecutorConfig;if(e instanceof _)this._codeExecutor=e;else if(typeof e==`function`)throw this._customCodeExecutor=e,Error(`Custom executor function should be handled in executeCode`);else if(e===`e2b`){let e=this._executorOptions;if(e?.apiKey)this._codeExecutor=new v(this,e);else{n.warn(`E2B executor requires apiKey. Falling back to VM.`);try{this._codeExecutor=new T(this,this._executorOptions)}catch{throw Error(`VM executor is not available in this environment and E2B API key is not provided. Please provide an E2B API key or run in a Node.js environment.`)}}}else try{this._codeExecutor=new T(this,this._executorOptions)}catch{let e=this._executorOptions,t=e?.apiKey||{}.E2B_API_KEY;if(t)n.info(`VM executor not available in this environment. Falling back to E2B.`),this._codeExecutor=new v(this,{...e,apiKey:t});else throw Error(`VM executor is not available in this environment. Please provide an E2B API key via executorOptions or E2B_API_KEY environment variable, or run in a Node.js environment.`)}}return this._codeExecutor}async executeCode(e,t){if(!this.codeMode)throw Error(`Code execution mode is not enabled`);return this._customCodeExecutor?this._customCodeExecutor(e,t):this._ensureCodeExecutor().execute(e,t)}async searchTools(e=``,t=`full`){if(!this.codeMode)throw Error(`Code execution mode is not enabled`);return this._ensureCodeExecutor().createSearchToolsFunction()(e,t)}getServerNames(){let e=this.codeMode;return super.getServerNames().filter(t=>!e||t!==`code_mode`)}async close(){this._codeExecutor&&=(await this._codeExecutor.cleanup(),null),await this.closeAllSessions()}};export{R as MCPClient};
91
+ `;o=await new y.Script(n,{filename:`agent_code.js`}).runInNewContext(t,{timeout:r,displayErrors:!0})}catch(e){s=e.message||String(e),(e.code===`ERR_SCRIPT_EXECUTION_TIMEOUT`||e.message===`Script execution timed out.`||typeof s==`string`&&(s.includes(`timed out`)||s.includes(`timeout`)))&&(s=`Script execution timed out`),e.stack&&n.debug(`Code execution error stack: ${e.stack}`)}let c=(Date.now()-a)/1e3;return{result:o,logs:i,error:s,execution_time:c}}async _buildContext(e){let n=t((...t)=>{e.push(t.map(e=>typeof e==`object`?JSON.stringify(e,null,2):String(e)).join(` `))},`logHandler`),r={console:{log:n,error:t((...e)=>{n(`[ERROR]`,...e)},`error`),warn:t((...e)=>{n(`[WARN]`,...e)},`warn`),info:n,debug:n},Object,Array,String,Number,Boolean,Date,Math,JSON,RegExp,Map,Set,Promise,parseInt,parseFloat,isNaN,isFinite,encodeURI,decodeURI,encodeURIComponent,decodeURIComponent,setTimeout,clearTimeout,search_tools:this.createSearchToolsFunction(),__tool_namespaces:[]},i={},a=this.getToolNamespaces();for(let{serverName:e,tools:t,session:n}of a){let a={};for(let e of t){let t=e.name;a[t]=async e=>{let r=await n.connector.callTool(t,e||{});if(r.content&&r.content.length>0){let e=r.content[0];if(e.type===`text`)try{return JSON.parse(e.text)}catch{return e.text}return e}return r}}r[e]=a,i[e]=!0}return r.__tool_namespaces=Object.keys(i),y.createContext(r)}async cleanup(){}},E=class extends a{static{t(this,`CodeModeConnector`)}mcpClient;_tools;constructor(e){super(),this.mcpClient=e,this.connected=!0,this._tools=this._createToolsList()}async connect(){this.connected=!0}async disconnect(){this.connected=!1}get publicIdentifier(){return{name:`code_mode`,version:`1.0.0`}}_createToolsList(){return[{name:`execute_code`,description:`Execute JavaScript/TypeScript code with access to MCP tools. This is the PRIMARY way to interact with MCP servers in code mode. Write code that discovers tools using search_tools(), calls tools as async functions (e.g., await github.get_pull_request(...)), processes data efficiently, and returns results. Use 'await' for async operations and 'return' to return values. Available in code: search_tools(), __tool_namespaces, and server.tool_name() functions.`,inputSchema:{type:`object`,properties:{code:{type:`string`,description:`JavaScript/TypeScript code to execute. Use 'await' for async operations. Use 'return' to return a value. Available: search_tools(), server.tool_name(), __tool_namespaces`},timeout:{type:`number`,description:`Execution timeout in milliseconds`,default:3e4}},required:[`code`]}},{name:`search_tools`,description:`Search and discover available MCP tools across all servers. Use this to find out what tools are available before writing code. Returns tool information including names, descriptions, and schemas. Can filter by query and control detail level.`,inputSchema:{type:`object`,properties:{query:{type:`string`,description:`Search query to filter tools by name or description`,default:``},detail_level:{type:`string`,description:`Detail level: 'names', 'descriptions', or 'full'`,enum:[`names`,`descriptions`,`full`],default:`full`}}}}]}get tools(){return this._tools}async initialize(){return this.toolsCache=this._tools,{capabilities:{},version:`1.0.0`}}async callTool(e,t){if(e===`execute_code`){let e=t.code,n=t.timeout||3e4,r=await this.mcpClient.executeCode(e,n);return{content:[{type:`text`,text:JSON.stringify(r)}]}}else if(e===`search_tools`){let e=t.query||``,n=t.detail_level,r=await this.mcpClient.searchTools(e,n&&n in[`names`,`descriptions`,`full`]?n:`full`);return{content:[{type:`text`,text:JSON.stringify(r)}]}}throw Error(`Unknown tool: ${e}`)}};function D(t){let{readFileSync:n}=e(`fs`),r=n(t,`utf-8`);return JSON.parse(r)}t(D,`loadConfigFile`);function O(e){return`requestedSchema`in e&&e.requestedSchema!=null}t(O,`hasRequestedSchema`);function k(e){let t={};if(!O(e))return t;let n=e.requestedSchema.properties??{};for(let[e,r]of Object.entries(n)){let n=r;if(`default`in n){let r=n.default;(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`))&&(t[e]=r)}}return t}t(k,`getDefaults`);function A(e,t){let n=k(e);return t==null?n:{...n,...t}}t(A,`applyDefaults`);function j(e){return{action:`accept`,content:k(e)}}t(j,`acceptWithDefaults`);function M(e){return{action:`accept`,content:e}}t(M,`accept`);function N(e){return{action:`decline`}}t(N,`decline`);function P(){return{action:`cancel`}}t(P,`cancel`);function F(e){return N(e)}t(F,`reject`);function I(e,t){if(!O(e))return{valid:!0};try{let n=f.convert(e.requestedSchema).safeParse(t);return n.success?{valid:!0}:{valid:!1,errors:n.error.issues.map(e=>e.path.length>0?`${e.path.join(`.`)}: ${e.message}`:e.message)}}catch{return{valid:!1,errors:[`Unsupported or invalid schema`]}}}t(I,`validate`);function L(e,t,r){let a=Object.keys(e.mcpServers??{}),o=!!(r.onSampling??r.samplingCallback),s=!!(r.onElicitation??r.elicitationCallback);i.getInstance().trackMCPClientInit({codeMode:t,sandbox:!1,allCallbacks:o&&s,verify:!1,servers:a,numServers:a.length,isBrowser:!1}).catch(e=>n.debug(`Failed to track MCPClient init: ${e}`))}t(L,`trackNodeClientInit`);var R=class e extends u{static{t(this,`MCPClient`)}static getPackageVersion(){return r()}codeMode=!1;_codeExecutor=null;_customCodeExecutor=null;_codeExecutorConfig=`vm`;_executorOptions;_globalCallbacks;constructor(e,t){e?super(typeof e==`string`?D(e):e):super();let n=!1,r=`vm`,i;t?.codeMode&&(typeof t.codeMode==`boolean`?n=t.codeMode:(n=t.codeMode.enabled,r=t.codeMode.executor??`vm`,i=t.codeMode.executorOptions)),this.codeMode=n,this._codeExecutorConfig=r,this._executorOptions=i;let a=this.config;this._globalCallbacks={onSampling:t?.onSampling??t?.samplingCallback??a?.onSampling??a?.samplingCallback,samplingCallback:t?.samplingCallback??a?.samplingCallback,onElicitation:t?.onElicitation??t?.elicitationCallback??a?.onElicitation??a?.elicitationCallback,elicitationCallback:t?.elicitationCallback??a?.elicitationCallback,onNotification:t?.onNotification??a?.onNotification},t?.samplingCallback&&!t?.onSampling&&console.warn(`[MCPClient] The "samplingCallback" option is deprecated. Use "onSampling" instead.`),t?.elicitationCallback&&!t?.onElicitation&&console.warn(`[MCPClient] The "elicitationCallback" option is deprecated. Use "onElicitation" instead.`),this.codeMode&&this._setupCodeModeConnector(),L(this.config,this.codeMode,this._globalCallbacks)}static fromDict(t,n){return new e(t,n)}static fromConfigFile(t,n){return new e(D(t),n)}saveConfig(e){let t=m.dirname(e);p.existsSync(t)||p.mkdirSync(t,{recursive:!0}),p.writeFileSync(e,JSON.stringify(this.config,null,2),`utf-8`)}async createConnectorFromConfig(e){let t=c(e,this._globalCallbacks),n={...e,clientInfo:e.clientInfo??this.config.clientInfo};if(`command`in n&&`args`in n){let{StdioConnector:e}=await d(async()=>{let{StdioConnector:e}=await import(`./stdio-ZCW4I5XD-CmtXCvzt.js`);return{StdioConnector:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8])),r=n;return new e({command:r.command,args:r.args,env:r.env,clientInfo:o(n.clientInfo),onSampling:t.onSampling,onElicitation:t.onElicitation,onNotification:t.onNotification})}return s(n,{onSampling:t.onSampling,onElicitation:t.onElicitation,onNotification:t.onNotification})}_setupCodeModeConnector(){n.debug(`Code mode connector initialized as internal meta server`);let e=new l(new E(this));this.sessions.code_mode=e,this.activeSessions.push(`code_mode`)}_ensureCodeExecutor(){if(!this._codeExecutor){let e=this._codeExecutorConfig;if(e instanceof _)this._codeExecutor=e;else if(typeof e==`function`)throw this._customCodeExecutor=e,Error(`Custom executor function should be handled in executeCode`);else if(e===`e2b`){let e=this._executorOptions;if(e?.apiKey)this._codeExecutor=new v(this,e);else{n.warn(`E2B executor requires apiKey. Falling back to VM.`);try{this._codeExecutor=new T(this,this._executorOptions)}catch{throw Error(`VM executor is not available in this environment and E2B API key is not provided. Please provide an E2B API key or run in a Node.js environment.`)}}}else try{this._codeExecutor=new T(this,this._executorOptions)}catch{let e=this._executorOptions,t=e?.apiKey||{}.E2B_API_KEY;if(t)n.info(`VM executor not available in this environment. Falling back to E2B.`),this._codeExecutor=new v(this,{...e,apiKey:t});else throw Error(`VM executor is not available in this environment. Please provide an E2B API key via executorOptions or E2B_API_KEY environment variable, or run in a Node.js environment.`)}}return this._codeExecutor}async executeCode(e,t){if(!this.codeMode)throw Error(`Code execution mode is not enabled`);return this._customCodeExecutor?this._customCodeExecutor(e,t):this._ensureCodeExecutor().execute(e,t)}async searchTools(e=``,t=`full`){if(!this.codeMode)throw Error(`Code execution mode is not enabled`);return this._ensureCodeExecutor().createSearchToolsFunction()(e,t)}getServerNames(){let e=this.codeMode;return super.getServerNames().filter(t=>!e||t!==`code_mode`)}async close(){this._codeExecutor&&=(await this._codeExecutor.cleanup(),null),await this.closeAllSessions()}};export{R as MCPClient};
@@ -1,4 +1,4 @@
1
- import{S as e,Yn as t}from"./json-schema-processors-DSIsU0go.js";import{_ as n,d as r,l as i,m as a,o,p as s,r as c,v as l}from"./schemas-79owEkeD.js";import{An as u,Cn as d,Dn as f,En as p,G as m,Gt as h,Kt as ee,M as te,Zt as g,cr as _,d as ne,fr as re,g as ie,jn as ae,mn as v,nn as oe,nt as se,or as ce,ot as le,pr as ue,rn as de,rt as fe,tn as pe,w as me,wr as y,yn as he}from"./index-zqVFP8t5.js";import{E as ge,M as _e,p as ve,r as ye,s as be,t as xe,w as Se}from"./function_calling-XyGNNvjR.js";import"./tools-DWDA-ZTt.js";import"./chunk_array-cMM4je5w.js";import{a as Ce,i as we,o as Te,s as Ee}from"./llms-DmE4p8kW.js";function De(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}function b(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function x(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var Oe=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Oe=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function ke(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var Ae=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},S=class extends Error{},C=class e extends S{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new je({message:r,cause:Ae(n)});let a=n?.error;return t===400?new Ne(t,a,r,i):t===401?new Pe(t,a,r,i):t===403?new Fe(t,a,r,i):t===404?new Ie(t,a,r,i):t===409?new Le(t,a,r,i):t===422?new Re(t,a,r,i):t===429?new ze(t,a,r,i):t>=500?new Be(t,a,r,i):new e(t,a,r,i)}},w=class extends C{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},je=class extends C{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},Me=class extends je{constructor({message:e}={}){super({message:e??`Request timed out.`})}},Ne=class extends C{},Pe=class extends C{},Fe=class extends C{},Ie=class extends C{},Le=class extends C{},Re=class extends C{},ze=class extends C{},Be=class extends C{},Ve=class extends S{constructor(){super(`Could not parse response content as the length limit was reached`)}},He=class extends S{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},Ue=class extends Error{constructor(e){super(e)}},We=/^[a-z][a-z0-9+.-]*:/i,Ge=e=>We.test(e),T=e=>(T=Array.isArray,T(e)),Ke=T;function qe(e){return typeof e==`object`?e??{}:{}}function Je(e){if(!e)return!0;for(let t in e)return!1;return!0}function Ye(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Xe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ze=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new S(`${e} must be an integer`);if(t<0)throw new S(`${e} must be a positive integer`);return t},Qe=e=>{try{return JSON.parse(e)}catch{return}},$e=e=>new Promise(t=>setTimeout(t,e)),et=`6.17.0`,tt=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function nt(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var rt=()=>{let e=nt();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":et,"X-Stainless-OS":ot(Deno.build.os),"X-Stainless-Arch":at(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":et,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":et,"X-Stainless-OS":ot(globalThis.process.platform??`unknown`),"X-Stainless-Arch":at(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=it();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":et,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":et,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function it(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var at=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,ot=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),st,ct=()=>st??=rt();function lt(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ut(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function dt(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ut({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function ft(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function pt(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var mt=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),ht=`RFC3986`,gt=e=>String(e),_t={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:gt},vt=(e,t)=>(vt=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),vt(e,t)),E=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),yt=1024,bt=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=yt){let t=a.length>=yt?a.slice(e,e+yt):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=E[r];continue}if(r<2048){n[n.length]=E[192|r>>6]+E[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=E[224|r>>12]+E[128|r>>6&63]+E[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=E[240|r>>18]+E[128|r>>12&63]+E[128|r>>6&63]+E[128|r&63]}o+=n.join(``)}return o};function xt(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function St(e,t){if(T(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var Ct={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},wt=function(e,t){Array.prototype.push.apply(e,T(t)?t:[t])},Tt,D={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:bt,encodeValuesOnly:!1,format:ht,formatter:gt,indices:!1,serializeDate(e){return(Tt??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Et(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var Dt={};function Ot(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,ee,te){let g=e,_=te,ne=0,re=!1;for(;(_=_.get(Dt))!==void 0&&!re;){let t=_.get(e);if(ne+=1,t!==void 0){if(t===ne)throw RangeError(`Cyclic object value`);re=!0}_.get(Dt)===void 0&&(ne=0)}if(typeof l==`function`?g=l(t,g):g instanceof Date?g=f?.(g):n===`comma`&&T(g)&&(g=St(g,function(e){return e instanceof Date?f?.(e):e})),g===null){if(a)return c&&!h?c(t,D.encoder,ee,`key`,p):t;g=``}if(Et(g)||xt(g)){if(c){let e=h?t:c(t,D.encoder,ee,`key`,p);return[m?.(e)+`=`+m?.(c(g,D.encoder,ee,`value`,p))]}return[m?.(t)+`=`+m?.(String(g))]}let ie=[];if(g===void 0)return ie;let ae;if(n===`comma`&&T(g))h&&c&&(g=St(g,c)),ae=[{value:g.length>0?g.join(`,`)||null:void 0}];else if(T(l))ae=l;else{let e=Object.keys(g);ae=u?e.sort(u):e}let v=s?String(t).replace(/\./g,`%2E`):String(t),oe=r&&T(g)&&g.length===1?v+`[]`:v;if(i&&T(g)&&g.length===0)return oe+`[]`;for(let t=0;t<ae.length;++t){let _=ae[t],re=typeof _==`object`&&_.value!==void 0?_.value:g[_];if(o&&re===null)continue;let v=d&&s?_.replace(/\./g,`%2E`):_,se=T(g)?typeof n==`function`?n(oe,v):oe:oe+(d?`.`+v:`[`+v+`]`);te.set(e,ne);let ce=new WeakMap;ce.set(Dt,te),wt(ie,Ot(re,se,n,r,i,a,o,s,n===`comma`&&h&&T(g)?null:c,l,u,d,f,p,m,h,ee,ce))}return ie}function kt(e=D){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||D.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=ht;if(e.format!==void 0){if(!vt(_t,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=_t[n],i=D.filter;(typeof e.filter==`function`||T(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Ct?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:D.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:D.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:D.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:D.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:D.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?D.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:D.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:D.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:D.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:D.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:D.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:D.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:D.strictNullHandling}}function At(e,t={}){let n=e,r=kt(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):T(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Ct[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||wt(o,Ot(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function jt(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var Mt;function Nt(e){let t;return(Mt??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Pt;function Ft(e){let t;return(Pt??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var O,k,It=class{constructor(){O.set(this,void 0),k.set(this,void 0),b(this,O,new Uint8Array,`f`),b(this,k,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?Nt(e):e;b(this,O,jt([x(this,O,`f`),t]),`f`);let n=[],r;for(;(r=Lt(x(this,O,`f`),x(this,k,`f`)))!=null;){if(r.carriage&&x(this,k,`f`)==null){b(this,k,r.index,`f`);continue}if(x(this,k,`f`)!=null&&(r.index!==x(this,k,`f`)+1||r.carriage)){n.push(Ft(x(this,O,`f`).subarray(0,x(this,k,`f`)-1))),b(this,O,x(this,O,`f`).subarray(x(this,k,`f`)),`f`),b(this,k,null,`f`);continue}let e=x(this,k,`f`)===null?r.preceding:r.preceding-1,t=Ft(x(this,O,`f`).subarray(0,e));n.push(t),b(this,O,x(this,O,`f`).subarray(r.index),`f`),b(this,k,null,`f`)}return n}flush(){return x(this,O,`f`).length?this.decode(`
1
+ import{S as e,Yn as t}from"./json-schema-processors-DSIsU0go.js";import{_ as n,d as r,l as i,m as a,o,p as s,r as c,v as l}from"./schemas-79owEkeD.js";import{An as u,Cn as d,Dn as f,En as p,G as m,Gt as h,Kt as ee,M as te,Zt as g,cr as _,d as ne,fr as re,g as ie,jn as ae,mn as v,nn as oe,nt as se,or as ce,ot as le,pr as ue,rn as de,rt as fe,tn as pe,w as me,wr as y,yn as he}from"./index-B2Y-NYsA.js";import{E as ge,M as _e,p as ve,r as ye,s as be,t as xe,w as Se}from"./function_calling-BocD-RuD.js";import"./tools-DdqMuNxj.js";import"./chunk_array-Dt8Wg6B_.js";import{a as Ce,i as we,o as Te,s as Ee}from"./llms-DKXMVXWf.js";function De(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}function b(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function x(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var Oe=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Oe=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function ke(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var Ae=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},S=class extends Error{},C=class e extends S{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new je({message:r,cause:Ae(n)});let a=n?.error;return t===400?new Ne(t,a,r,i):t===401?new Pe(t,a,r,i):t===403?new Fe(t,a,r,i):t===404?new Ie(t,a,r,i):t===409?new Le(t,a,r,i):t===422?new Re(t,a,r,i):t===429?new ze(t,a,r,i):t>=500?new Be(t,a,r,i):new e(t,a,r,i)}},w=class extends C{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},je=class extends C{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},Me=class extends je{constructor({message:e}={}){super({message:e??`Request timed out.`})}},Ne=class extends C{},Pe=class extends C{},Fe=class extends C{},Ie=class extends C{},Le=class extends C{},Re=class extends C{},ze=class extends C{},Be=class extends C{},Ve=class extends S{constructor(){super(`Could not parse response content as the length limit was reached`)}},He=class extends S{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},Ue=class extends Error{constructor(e){super(e)}},We=/^[a-z][a-z0-9+.-]*:/i,Ge=e=>We.test(e),T=e=>(T=Array.isArray,T(e)),Ke=T;function qe(e){return typeof e==`object`?e??{}:{}}function Je(e){if(!e)return!0;for(let t in e)return!1;return!0}function Ye(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Xe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ze=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new S(`${e} must be an integer`);if(t<0)throw new S(`${e} must be a positive integer`);return t},Qe=e=>{try{return JSON.parse(e)}catch{return}},$e=e=>new Promise(t=>setTimeout(t,e)),et=`6.17.0`,tt=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function nt(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var rt=()=>{let e=nt();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":et,"X-Stainless-OS":ot(Deno.build.os),"X-Stainless-Arch":at(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":et,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":et,"X-Stainless-OS":ot(globalThis.process.platform??`unknown`),"X-Stainless-Arch":at(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=it();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":et,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":et,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function it(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var at=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,ot=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),st,ct=()=>st??=rt();function lt(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ut(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function dt(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ut({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function ft(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function pt(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var mt=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),ht=`RFC3986`,gt=e=>String(e),_t={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:gt},vt=(e,t)=>(vt=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),vt(e,t)),E=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),yt=1024,bt=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=yt){let t=a.length>=yt?a.slice(e,e+yt):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=E[r];continue}if(r<2048){n[n.length]=E[192|r>>6]+E[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=E[224|r>>12]+E[128|r>>6&63]+E[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=E[240|r>>18]+E[128|r>>12&63]+E[128|r>>6&63]+E[128|r&63]}o+=n.join(``)}return o};function xt(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function St(e,t){if(T(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var Ct={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},wt=function(e,t){Array.prototype.push.apply(e,T(t)?t:[t])},Tt,D={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:bt,encodeValuesOnly:!1,format:ht,formatter:gt,indices:!1,serializeDate(e){return(Tt??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Et(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var Dt={};function Ot(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,ee,te){let g=e,_=te,ne=0,re=!1;for(;(_=_.get(Dt))!==void 0&&!re;){let t=_.get(e);if(ne+=1,t!==void 0){if(t===ne)throw RangeError(`Cyclic object value`);re=!0}_.get(Dt)===void 0&&(ne=0)}if(typeof l==`function`?g=l(t,g):g instanceof Date?g=f?.(g):n===`comma`&&T(g)&&(g=St(g,function(e){return e instanceof Date?f?.(e):e})),g===null){if(a)return c&&!h?c(t,D.encoder,ee,`key`,p):t;g=``}if(Et(g)||xt(g)){if(c){let e=h?t:c(t,D.encoder,ee,`key`,p);return[m?.(e)+`=`+m?.(c(g,D.encoder,ee,`value`,p))]}return[m?.(t)+`=`+m?.(String(g))]}let ie=[];if(g===void 0)return ie;let ae;if(n===`comma`&&T(g))h&&c&&(g=St(g,c)),ae=[{value:g.length>0?g.join(`,`)||null:void 0}];else if(T(l))ae=l;else{let e=Object.keys(g);ae=u?e.sort(u):e}let v=s?String(t).replace(/\./g,`%2E`):String(t),oe=r&&T(g)&&g.length===1?v+`[]`:v;if(i&&T(g)&&g.length===0)return oe+`[]`;for(let t=0;t<ae.length;++t){let _=ae[t],re=typeof _==`object`&&_.value!==void 0?_.value:g[_];if(o&&re===null)continue;let v=d&&s?_.replace(/\./g,`%2E`):_,se=T(g)?typeof n==`function`?n(oe,v):oe:oe+(d?`.`+v:`[`+v+`]`);te.set(e,ne);let ce=new WeakMap;ce.set(Dt,te),wt(ie,Ot(re,se,n,r,i,a,o,s,n===`comma`&&h&&T(g)?null:c,l,u,d,f,p,m,h,ee,ce))}return ie}function kt(e=D){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||D.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=ht;if(e.format!==void 0){if(!vt(_t,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=_t[n],i=D.filter;(typeof e.filter==`function`||T(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Ct?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:D.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:D.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:D.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:D.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:D.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?D.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:D.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:D.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:D.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:D.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:D.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:D.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:D.strictNullHandling}}function At(e,t={}){let n=e,r=kt(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):T(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Ct[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||wt(o,Ot(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function jt(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var Mt;function Nt(e){let t;return(Mt??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Pt;function Ft(e){let t;return(Pt??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var O,k,It=class{constructor(){O.set(this,void 0),k.set(this,void 0),b(this,O,new Uint8Array,`f`),b(this,k,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?Nt(e):e;b(this,O,jt([x(this,O,`f`),t]),`f`);let n=[],r;for(;(r=Lt(x(this,O,`f`),x(this,k,`f`)))!=null;){if(r.carriage&&x(this,k,`f`)==null){b(this,k,r.index,`f`);continue}if(x(this,k,`f`)!=null&&(r.index!==x(this,k,`f`)+1||r.carriage)){n.push(Ft(x(this,O,`f`).subarray(0,x(this,k,`f`)-1))),b(this,O,x(this,O,`f`).subarray(x(this,k,`f`)),`f`),b(this,k,null,`f`);continue}let e=x(this,k,`f`)===null?r.preceding:r.preceding-1,t=Ft(x(this,O,`f`).subarray(0,e));n.push(t),b(this,O,x(this,O,`f`).subarray(r.index),`f`),b(this,k,null,`f`)}return n}flush(){return x(this,O,`f`).length?this.decode(`
2
2
  `):[]}};O=new WeakMap,k=new WeakMap,It.NEWLINE_CHARS=new Set([`
3
3
  `,`\r`]),It.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Lt(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Rt(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var zt={off:0,error:200,warn:300,info:400,debug:500},Bt=(e,t,n)=>{if(e){if(Ye(zt,e))return e;A(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(zt))}`)}};function Vt(){}function Ht(e,t,n){return!t||zt[e]>zt[n]?Vt:t[e].bind(t)}var Ut={error:Vt,warn:Vt,info:Vt,debug:Vt},Wt=new WeakMap;function A(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Ut;let r=Wt.get(t);if(r&&r[0]===n)return r[1];let i={error:Ht(`error`,t,n),warn:Ht(`warn`,t,n),info:Ht(`info`,t,n),debug:Ht(`debug`,t,n)};return Wt.set(t,[n,i]),i}var Gt=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),Kt,qt=class e{constructor(e,t,n){this.iterator=e,Kt.set(this,void 0),this.controller=t,b(this,Kt,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?A(r):console;async function*o(){if(i)throw new S("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let r of Jt(t,n))if(!e){if(r.data.startsWith(`[DONE]`)){e=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let e;try{e=JSON.parse(r.data)}catch(e){throw a.error(`Could not parse message into JSON:`,r.data),a.error(`From chunk:`,r.raw),e}if(e&&e.error)throw new C(void 0,e.error,void 0,t.headers);yield e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new C(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(ke(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new It,n=ft(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new S("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(ke(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(Kt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,x(this,Kt,`f`)),new e(()=>i(n),this.controller,x(this,Kt,`f`))]}toReadableStream(){let e=this,t;return ut({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=Nt(JSON.stringify(n)+`
4
4
  `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*Jt(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new S(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new S(`Attempted to iterate over a response with no body`);let n=new Xt,r=new It,i=ft(e.body);for await(let e of Yt(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*Yt(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Nt(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=Rt(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var Xt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
@@ -1,2 +1,2 @@
1
- import{En as e,G as t,I as n,Kt as r,Pn as i,cr as a,fr as o,g as s,nn as c,or as l,ot as u,qn as d,rn as f,tn as p,w as ee}from"./index-zqVFP8t5.js";import{A as te,M as m,O as ne,p as h,r as g,s as re,w as ie}from"./function_calling-XyGNNvjR.js";import"./chunk_array-cMM4je5w.js";function _(e){if(typeof e==`object`&&e){let t={...e};`additionalProperties`in t&&delete t.additionalProperties,`$schema`in t&&delete t.$schema,`strict`in t&&delete t.strict;for(let e in t)e in t&&(Array.isArray(t[e])?t[e]=t[e].map(_):typeof t[e]==`object`&&t[e]!==null&&(t[e]=_(t[e])));return t}return e}function v(e){let{$schema:n,...r}=_(t(e)?ee(e):e);return r}function ae(e){let{$schema:t,...n}=_(e);return n}function y(e,t,n=[]){if(typeof e!=`object`||!e)return;let r=e;if(Array.isArray(r.enum)&&r.enum.some(e=>e===``)){let e=n.length?` at path "${n.join(`.`)}"`:``,r=t?` in tool "${t}"`:``;throw Error(`Invalid enum: empty string not allowed${r}${e}. Gemini API rejects empty strings in enums.`)}if(r.type===`object`&&r.properties&&typeof r.properties==`object`)for(let[e,i]of Object.entries(r.properties))y(i,t,[...n,e]);r.items&&y(r.items,t,[...n,`[]`]);for(let e of[`anyOf`,`oneOf`,`allOf`]){let i=r[e];Array.isArray(i)&&i.forEach((r,i)=>y(r,t,[...n,`${e}[${i}]`]))}r.additionalProperties&&typeof r.additionalProperties==`object`&&y(r.additionalProperties,t,[...n,`additionalProperties`])}var b=[];for(let e=0;e<256;++e)b.push((e+256).toString(16).slice(1));function oe(e,t=0){return(b[e[t+0]]+b[e[t+1]]+b[e[t+2]]+b[e[t+3]]+`-`+b[e[t+4]]+b[e[t+5]]+`-`+b[e[t+6]]+b[e[t+7]]+`-`+b[e[t+8]]+b[e[t+9]]+`-`+b[e[t+10]]+b[e[t+11]]+b[e[t+12]]+b[e[t+13]]+b[e[t+14]]+b[e[t+15]]).toLowerCase()}var x,se=new Uint8Array(16);function ce(){if(!x){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);x=crypto.getRandomValues.bind(crypto)}return x(se)}var S={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function C(e,t,n){if(S.randomUUID&&!t&&!e)return S.randomUUID();e||={};let r=e.random??e.rng?.()??ce();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return oe(r)}var w=`__gemini_function_call_thought_signatures__`,le=`ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==`,ue=e=>e();function de(t){return e.isInstance(t)?t.role:t.type}function fe(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 Error(`Unknown / unsupported author: ${e}`)}}function pe(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 Error(`Invalid media content`)}function me(e,t){return t.map(e=>f(e)?e.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function he(e){return{providerName:`Google Gemini`,fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(t){if(!e)throw Error(`This model does not support images`);if(t.source_type===`url`){let e=o({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw Error(`This model does not support audio`);if(t.source_type===`url`){let e=o({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw Error(`This model does not support files`);if(t.source_type===`text`)return{text:t.text};if(t.source_type===`url`){let e=o({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)}}}function T(e,t){if(a(e))return l(e,he(t));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(!t)throw Error(`This model does not support images`);let n;if(typeof e.image_url==`string`)n=e.image_url;else if(typeof e.image_url==`object`&&`url`in e.image_url)n=e.image_url.url;else throw Error(`Please provide image as base64 encoded data URL`);let[r,i]=n.split(`,`);if(!r.startsWith(`data:`))throw Error(`Please provide image as base64 encoded data URL`);let[a,o]=r.replace(/^data:/,``).split(`;`);if(o!==`base64`)throw Error(`Please provide image as base64 encoded data URL`);return{inlineData:{data:i,mimeType:a}}}else if(e.type===`media`)return pe(e);else if(e.type===`tool_use`)return{functionCall:{name:e.name,args:e.input}};else if(e.type===`tool_call`)return{functionCall:{name:e.name,args:e.args}};else if(e.type?.includes(`/`)&&e.type.split(`/`).length===2&&`data`in e&&typeof e.data==`string`)return{inlineData:{mimeType:e.type,data:e.data}};else if(`functionCall`in e)return;else if(`type`in e)throw Error(`Unknown content type ${e.type}`);else throw Error(`Unknown content ${JSON.stringify(e)}`)}function ge(e,t,n,r){if(i(e)){let r=e.name??me(e,n);if(r===void 0)throw 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.`);let i=Array.isArray(e.content)?e.content.map(e=>T(e,t)).filter(e=>e!==void 0):e.content;return e.status===`error`?[{functionResponse:{name:r,response:{error:{details:i}}}}]:[{functionResponse:{name:r,response:{result:i}}}]}let a=[],o=[];typeof e.content==`string`&&e.content&&o.push({text:e.content}),Array.isArray(e.content)&&o.push(...e.content.map(e=>T(e,t)).filter(e=>e!==void 0));let s=e.additional_kwargs?.[w];return f(e)&&e.tool_calls?.length&&(a=e.tool_calls.map(e=>{let t=ue(()=>{if(e.id){let t=s?.[e.id];if(t)return t}return r?.includes(`gemini-3`)?le:``});return{functionCall:{name:e.name,args:e.args},...t?{thoughtSignature:t}:{}}})),[...o,...a]}function E(e,t,n=!1,r){return e.reduce((i,a,o)=>{if(!d(a))throw Error(`Unsupported message input`);let s=de(a);if(s===`system`&&o!==0)throw Error(`System message should be the first one`);let c=fe(s),l=i.content[i.content.length];if(!i.mergeWithPreviousContent&&l&&l.role===c)throw Error(`Google Generative AI requires alternate messages between authors`);let u=ge(a,t,e.slice(0,o),r);if(i.mergeWithPreviousContent){let e=i.content[i.content.length-1];if(!e)throw Error(`There was a problem parsing your system message. Please try a prompt without one.`);return e.parts.push(...u),{mergeWithPreviousContent:!1,content:i.content}}let f=c;(f===`function`||f===`system`&&!n)&&(f=`user`);let p={role:f,parts:u};return{mergeWithPreviousContent:s===`system`&&!n,content:[...i.content,p]}},{content:[],mergeWithPreviousContent:!1}).content}function _e(e,t){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};let[n]=e.candidates,{content:r,...i}=n,a=r.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:C()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.length===1&&`text`in s[0]&&s[0].text&&!s[0].thought?s[0].text:Array.isArray(s)&&s.length>0?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let c=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{}),l=``;return typeof o==`string`?l=o:Array.isArray(o)&&o.length>0&&(l=o.find(e=>`text`in e)?.text??l),{generations:[{text:l,message:new p({content:o??``,tool_calls:a?.map(e=>({type:`tool_call`,id:e.id,name:e.functionCall.name,args:e.functionCall.args})),additional_kwargs:{...i,[w]:c},usage_metadata:t?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:t?.usageMetadata?.input_tokens,completionTokens:t?.usageMetadata?.output_tokens,totalTokens:t?.usageMetadata?.total_tokens}}}}function ve(e,t){if(!e.candidates||e.candidates.length===0)return null;let[n]=e.candidates,{content:r,...i}=n,a=r.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:C()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.every(e=>`text`in e&&!e.thought)?s.map(e=>e.text).join(``):Array.isArray(s)?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let l=``;o&&typeof o==`string`?l=o:Array.isArray(o)&&(l=o.find(e=>`text`in e)?.text??``);let d=[];a&&d.push(...a.map(e=>({type:`tool_call_chunk`,id:e.id,name:e.functionCall.name,args:JSON.stringify(e.functionCall.args)})));let f=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{});return new u({text:l,message:new c({content:o||``,name:r?r.role:void 0,tool_call_chunks:d,additional_kwargs:{[w]:f},response_metadata:{model_provider:`google-genai`},usage_metadata:t.usageMetadata}),generationInfo:i})}function ye(e){return e.every(e=>`functionDeclarations`in e&&Array.isArray(e.functionDeclarations))?e:[{functionDeclarations:e.map(e=>{if(g(e)){let t=v(e.schema);return t.type===`object`&&`properties`in t&&Object.keys(t.properties).length===0?{name:e.name,description:e.description}:(y(t,e.name),{name:e.name,description:e.description,parameters:t})}if(h(e)){let t=ae(e.function.parameters);return y(t,e.function.name),{name:e.function.name,description:e.function.description??`A function available to call.`,parameters:t}}return e})}]}function D(e,t){let n={input_tokens:e?.promptTokenCount??0,output_tokens:e?.candidatesTokenCount??0,total_tokens:e?.totalTokenCount??0};if(e?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=e.cachedContentTokenCount),t===`gemini-3-pro-preview`){let t=Math.max(0,e?.promptTokenCount??-2e5),r=Math.max(0,e?.cachedContentTokenCount??-2e5);t&&(n.input_token_details={...n.input_token_details,over_200k:t}),r&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:r})}return n}var O=class extends ne{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;let t=await n(this.zodSchema,e);if(t.success)return t.data;throw new te(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return!(`tool_calls`in t)||!Array.isArray(t.tool_calls)?[]:t.tool_calls});if(t[0]===void 0)throw Error(`No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}},be;(function(e){e.STRING=`string`,e.NUMBER=`number`,e.INTEGER=`integer`,e.BOOLEAN=`boolean`,e.ARRAY=`array`,e.OBJECT=`object`})(be||={});var xe;(function(e){e.LANGUAGE_UNSPECIFIED=`language_unspecified`,e.PYTHON=`python`})(xe||={});var Se;(function(e){e.OUTCOME_UNSPECIFIED=`outcome_unspecified`,e.OUTCOME_OK=`outcome_ok`,e.OUTCOME_FAILED=`outcome_failed`,e.OUTCOME_DEADLINE_EXCEEDED=`outcome_deadline_exceeded`})(Se||={});var k=[`user`,`model`,`function`,`system`],Ce;(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`})(Ce||={});var we;(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`})(we||={});var Te;(function(e){e.HARM_PROBABILITY_UNSPECIFIED=`HARM_PROBABILITY_UNSPECIFIED`,e.NEGLIGIBLE=`NEGLIGIBLE`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(Te||={});var Ee;(function(e){e.BLOCKED_REASON_UNSPECIFIED=`BLOCKED_REASON_UNSPECIFIED`,e.SAFETY=`SAFETY`,e.OTHER=`OTHER`})(Ee||={});var A;(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`})(A||={});var De;(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`})(De||={});var j;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.AUTO=`AUTO`,e.ANY=`ANY`,e.NONE=`NONE`})(j||={});var Oe;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.MODE_DYNAMIC=`MODE_DYNAMIC`})(Oe||={});var M=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},N=class extends M{constructor(e,t){super(e),this.response=t}},P=class extends M{constructor(e,t,n,r){super(e),this.status=t,this.statusText=n,this.errorDetails=r}},F=class extends M{},I=class extends M{},ke=`https://generativelanguage.googleapis.com`,Ae=`v1beta`,je=`0.24.1`,Me=`genai-js`,L;(function(e){e.GENERATE_CONTENT=`generateContent`,e.STREAM_GENERATE_CONTENT=`streamGenerateContent`,e.COUNT_TOKENS=`countTokens`,e.EMBED_CONTENT=`embedContent`,e.BATCH_EMBED_CONTENTS=`batchEmbedContents`})(L||={});var Ne=class{constructor(e,t,n,r,i){this.model=e,this.task=t,this.apiKey=n,this.stream=r,this.requestOptions=i}toString(){let e=this.requestOptions?.apiVersion||Ae,t=`${this.requestOptions?.baseUrl||ke}/${e}/${this.model}:${this.task}`;return this.stream&&(t+=`?alt=sse`),t}};function Pe(e){let t=[];return e?.apiClient&&t.push(e.apiClient),t.push(`${Me}/${je}`),t.join(` `)}async function Fe(e){let t=new Headers;t.append(`Content-Type`,`application/json`),t.append(`x-goog-api-client`,Pe(e.requestOptions)),t.append(`x-goog-api-key`,e.apiKey);let n=e.requestOptions?.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(e){throw new F(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${e.message}`)}for(let[e,r]of n.entries()){if(e===`x-goog-api-key`)throw new F(`Cannot set reserved header name ${e}`);if(e===`x-goog-api-client`)throw new F(`Header name ${e} can only be set using the apiClient field`);t.append(e,r)}}return t}async function Ie(e,t,n,r,i,a){let o=new Ne(e,t,n,r,a);return{url:o.toString(),fetchOptions:Object.assign(Object.assign({},Be(a)),{method:`POST`,headers:await Fe(o),body:i})}}async function R(e,t,n,r,i,a={},o=fetch){let{url:s,fetchOptions:c}=await Ie(e,t,n,r,i,a);return Le(s,c,o)}async function Le(e,t,n=fetch){let r;try{r=await n(e,t)}catch(t){Re(t,e)}return r.ok||await ze(r,e),r}function Re(e,t){let n=e;throw n.name===`AbortError`?(n=new I(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof P||e instanceof F||(n=new M(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack),n}async function ze(e,t){let n=``,r;try{let t=await e.json();n=t.error.message,t.error.details&&(n+=` ${JSON.stringify(t.error.details)}`,r=t.error.details)}catch{}throw new P(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,r)}function Be(e){let t={};if(e?.signal!==void 0||e?.timeout>=0){let n=new AbortController;e?.timeout>=0&&setTimeout(()=>n.abort(),e.timeout),e?.signal&&e.signal.addEventListener(`abort`,()=>{n.abort()}),t.signal=n.signal}return t}function z(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.`),V(e.candidates[0]))throw new N(`${H(e)}`,e);return Ve(e)}else if(e.promptFeedback)throw new N(`Text not available. ${H(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.`),V(e.candidates[0]))throw new N(`${H(e)}`,e);return console.warn(`response.functionCall() is deprecated. Use response.functionCalls() instead.`),B(e)[0]}else if(e.promptFeedback)throw new N(`Function call not available. ${H(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.`),V(e.candidates[0]))throw new N(`${H(e)}`,e);return B(e)}else if(e.promptFeedback)throw new N(`Function call not available. ${H(e)}`,e)},e}function Ve(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.text&&t.push(n.text),n.executableCode&&t.push("\n```"+n.executableCode.language+`
1
+ import{En as e,G as t,I as n,Kt as r,Pn as i,cr as a,fr as o,g as s,nn as c,or as l,ot as u,qn as d,rn as f,tn as p,w as ee}from"./index-B2Y-NYsA.js";import{A as te,M as m,O as ne,p as h,r as g,s as re,w as ie}from"./function_calling-BocD-RuD.js";import"./chunk_array-Dt8Wg6B_.js";function _(e){if(typeof e==`object`&&e){let t={...e};`additionalProperties`in t&&delete t.additionalProperties,`$schema`in t&&delete t.$schema,`strict`in t&&delete t.strict;for(let e in t)e in t&&(Array.isArray(t[e])?t[e]=t[e].map(_):typeof t[e]==`object`&&t[e]!==null&&(t[e]=_(t[e])));return t}return e}function v(e){let{$schema:n,...r}=_(t(e)?ee(e):e);return r}function ae(e){let{$schema:t,...n}=_(e);return n}function y(e,t,n=[]){if(typeof e!=`object`||!e)return;let r=e;if(Array.isArray(r.enum)&&r.enum.some(e=>e===``)){let e=n.length?` at path "${n.join(`.`)}"`:``,r=t?` in tool "${t}"`:``;throw Error(`Invalid enum: empty string not allowed${r}${e}. Gemini API rejects empty strings in enums.`)}if(r.type===`object`&&r.properties&&typeof r.properties==`object`)for(let[e,i]of Object.entries(r.properties))y(i,t,[...n,e]);r.items&&y(r.items,t,[...n,`[]`]);for(let e of[`anyOf`,`oneOf`,`allOf`]){let i=r[e];Array.isArray(i)&&i.forEach((r,i)=>y(r,t,[...n,`${e}[${i}]`]))}r.additionalProperties&&typeof r.additionalProperties==`object`&&y(r.additionalProperties,t,[...n,`additionalProperties`])}var b=[];for(let e=0;e<256;++e)b.push((e+256).toString(16).slice(1));function oe(e,t=0){return(b[e[t+0]]+b[e[t+1]]+b[e[t+2]]+b[e[t+3]]+`-`+b[e[t+4]]+b[e[t+5]]+`-`+b[e[t+6]]+b[e[t+7]]+`-`+b[e[t+8]]+b[e[t+9]]+`-`+b[e[t+10]]+b[e[t+11]]+b[e[t+12]]+b[e[t+13]]+b[e[t+14]]+b[e[t+15]]).toLowerCase()}var x,se=new Uint8Array(16);function ce(){if(!x){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);x=crypto.getRandomValues.bind(crypto)}return x(se)}var S={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function C(e,t,n){if(S.randomUUID&&!t&&!e)return S.randomUUID();e||={};let r=e.random??e.rng?.()??ce();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return oe(r)}var w=`__gemini_function_call_thought_signatures__`,le=`ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==`,ue=e=>e();function de(t){return e.isInstance(t)?t.role:t.type}function fe(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 Error(`Unknown / unsupported author: ${e}`)}}function pe(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 Error(`Invalid media content`)}function me(e,t){return t.map(e=>f(e)?e.tool_calls??[]:[]).flat().find(t=>t.id===e.tool_call_id)?.name}function he(e){return{providerName:`Google Gemini`,fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(t){if(!e)throw Error(`This model does not support images`);if(t.source_type===`url`){let e=o({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardAudioBlock(t){if(!e)throw Error(`This model does not support audio`);if(t.source_type===`url`){let e=o({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)},fromStandardFileBlock(t){if(!e)throw Error(`This model does not support files`);if(t.source_type===`text`)return{text:t.text};if(t.source_type===`url`){let e=o({dataUrl:t.url});return e?{inlineData:{mimeType:e.mime_type,data:e.data}}:{fileData:{mimeType:t.mime_type??``,fileUri:t.url}}}if(t.source_type===`base64`)return{inlineData:{mimeType:t.mime_type??``,data:t.data}};throw Error(`Unsupported source type: ${t.source_type}`)}}}function T(e,t){if(a(e))return l(e,he(t));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(!t)throw Error(`This model does not support images`);let n;if(typeof e.image_url==`string`)n=e.image_url;else if(typeof e.image_url==`object`&&`url`in e.image_url)n=e.image_url.url;else throw Error(`Please provide image as base64 encoded data URL`);let[r,i]=n.split(`,`);if(!r.startsWith(`data:`))throw Error(`Please provide image as base64 encoded data URL`);let[a,o]=r.replace(/^data:/,``).split(`;`);if(o!==`base64`)throw Error(`Please provide image as base64 encoded data URL`);return{inlineData:{data:i,mimeType:a}}}else if(e.type===`media`)return pe(e);else if(e.type===`tool_use`)return{functionCall:{name:e.name,args:e.input}};else if(e.type===`tool_call`)return{functionCall:{name:e.name,args:e.args}};else if(e.type?.includes(`/`)&&e.type.split(`/`).length===2&&`data`in e&&typeof e.data==`string`)return{inlineData:{mimeType:e.type,data:e.data}};else if(`functionCall`in e)return;else if(`type`in e)throw Error(`Unknown content type ${e.type}`);else throw Error(`Unknown content ${JSON.stringify(e)}`)}function ge(e,t,n,r){if(i(e)){let r=e.name??me(e,n);if(r===void 0)throw 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.`);let i=Array.isArray(e.content)?e.content.map(e=>T(e,t)).filter(e=>e!==void 0):e.content;return e.status===`error`?[{functionResponse:{name:r,response:{error:{details:i}}}}]:[{functionResponse:{name:r,response:{result:i}}}]}let a=[],o=[];typeof e.content==`string`&&e.content&&o.push({text:e.content}),Array.isArray(e.content)&&o.push(...e.content.map(e=>T(e,t)).filter(e=>e!==void 0));let s=e.additional_kwargs?.[w];return f(e)&&e.tool_calls?.length&&(a=e.tool_calls.map(e=>{let t=ue(()=>{if(e.id){let t=s?.[e.id];if(t)return t}return r?.includes(`gemini-3`)?le:``});return{functionCall:{name:e.name,args:e.args},...t?{thoughtSignature:t}:{}}})),[...o,...a]}function E(e,t,n=!1,r){return e.reduce((i,a,o)=>{if(!d(a))throw Error(`Unsupported message input`);let s=de(a);if(s===`system`&&o!==0)throw Error(`System message should be the first one`);let c=fe(s),l=i.content[i.content.length];if(!i.mergeWithPreviousContent&&l&&l.role===c)throw Error(`Google Generative AI requires alternate messages between authors`);let u=ge(a,t,e.slice(0,o),r);if(i.mergeWithPreviousContent){let e=i.content[i.content.length-1];if(!e)throw Error(`There was a problem parsing your system message. Please try a prompt without one.`);return e.parts.push(...u),{mergeWithPreviousContent:!1,content:i.content}}let f=c;(f===`function`||f===`system`&&!n)&&(f=`user`);let p={role:f,parts:u};return{mergeWithPreviousContent:s===`system`&&!n,content:[...i.content,p]}},{content:[],mergeWithPreviousContent:!1}).content}function _e(e,t){if(!e.candidates||e.candidates.length===0||!e.candidates[0])return{generations:[],llmOutput:{filters:e.promptFeedback}};let[n]=e.candidates,{content:r,...i}=n,a=r.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:C()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.length===1&&`text`in s[0]&&s[0].text&&!s[0].thought?s[0].text:Array.isArray(s)&&s.length>0?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let c=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{}),l=``;return typeof o==`string`?l=o:Array.isArray(o)&&o.length>0&&(l=o.find(e=>`text`in e)?.text??l),{generations:[{text:l,message:new p({content:o??``,tool_calls:a?.map(e=>({type:`tool_call`,id:e.id,name:e.functionCall.name,args:e.functionCall.args})),additional_kwargs:{...i,[w]:c},usage_metadata:t?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:t?.usageMetadata?.input_tokens,completionTokens:t?.usageMetadata?.output_tokens,totalTokens:t?.usageMetadata?.total_tokens}}}}function ve(e,t){if(!e.candidates||e.candidates.length===0)return null;let[n]=e.candidates,{content:r,...i}=n,a=r.parts?.reduce((e,t)=>(`functionCall`in t&&t.functionCall&&e.push({...t,id:`id`in t.functionCall&&typeof t.functionCall.id==`string`?t.functionCall.id:C()}),e),[]),o,s=r?.parts;o=Array.isArray(s)&&s.every(e=>`text`in e&&!e.thought)?s.map(e=>e.text).join(``):Array.isArray(s)?s.map(e=>e.thought&&`text`in e&&e.text?{type:`thinking`,thinking:e.text,...e.thoughtSignature?{signature:e.thoughtSignature}:{}}:`text`in e?{type:`text`,text:e.text}:`inlineData`in e?{type:`inlineData`,inlineData:e.inlineData}:`functionCall`in e?{type:`functionCall`,functionCall:e.functionCall}:`functionResponse`in e?{type:`functionResponse`,functionResponse:e.functionResponse}:`fileData`in e?{type:`fileData`,fileData:e.fileData}:`executableCode`in e?{type:`executableCode`,executableCode:e.executableCode}:`codeExecutionResult`in e?{type:`codeExecutionResult`,codeExecutionResult:e.codeExecutionResult}:e):[];let l=``;o&&typeof o==`string`?l=o:Array.isArray(o)&&(l=o.find(e=>`text`in e)?.text??``);let d=[];a&&d.push(...a.map(e=>({type:`tool_call_chunk`,id:e.id,name:e.functionCall.name,args:JSON.stringify(e.functionCall.args)})));let f=a?.reduce((e,t)=>(`thoughtSignature`in t&&typeof t.thoughtSignature==`string`&&(e[t.id]=t.thoughtSignature),e),{});return new u({text:l,message:new c({content:o||``,name:r?r.role:void 0,tool_call_chunks:d,additional_kwargs:{[w]:f},response_metadata:{model_provider:`google-genai`},usage_metadata:t.usageMetadata}),generationInfo:i})}function ye(e){return e.every(e=>`functionDeclarations`in e&&Array.isArray(e.functionDeclarations))?e:[{functionDeclarations:e.map(e=>{if(g(e)){let t=v(e.schema);return t.type===`object`&&`properties`in t&&Object.keys(t.properties).length===0?{name:e.name,description:e.description}:(y(t,e.name),{name:e.name,description:e.description,parameters:t})}if(h(e)){let t=ae(e.function.parameters);return y(t,e.function.name),{name:e.function.name,description:e.function.description??`A function available to call.`,parameters:t}}return e})}]}function D(e,t){let n={input_tokens:e?.promptTokenCount??0,output_tokens:e?.candidatesTokenCount??0,total_tokens:e?.totalTokenCount??0};if(e?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=e.cachedContentTokenCount),t===`gemini-3-pro-preview`){let t=Math.max(0,e?.promptTokenCount??-2e5),r=Math.max(0,e?.cachedContentTokenCount??-2e5);t&&(n.input_token_details={...n.input_token_details,over_200k:t}),r&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:r})}return n}var O=class extends ne{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;let t=await n(this.zodSchema,e);if(t.success)return t.data;throw new te(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){let t=e.flatMap(e=>{let{message:t}=e;return!(`tool_calls`in t)||!Array.isArray(t.tool_calls)?[]:t.tool_calls});if(t[0]===void 0)throw Error(`No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.`);let[n]=t;return await this._validateResult(n.args)}},be;(function(e){e.STRING=`string`,e.NUMBER=`number`,e.INTEGER=`integer`,e.BOOLEAN=`boolean`,e.ARRAY=`array`,e.OBJECT=`object`})(be||={});var xe;(function(e){e.LANGUAGE_UNSPECIFIED=`language_unspecified`,e.PYTHON=`python`})(xe||={});var Se;(function(e){e.OUTCOME_UNSPECIFIED=`outcome_unspecified`,e.OUTCOME_OK=`outcome_ok`,e.OUTCOME_FAILED=`outcome_failed`,e.OUTCOME_DEADLINE_EXCEEDED=`outcome_deadline_exceeded`})(Se||={});var k=[`user`,`model`,`function`,`system`],Ce;(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`})(Ce||={});var we;(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`})(we||={});var Te;(function(e){e.HARM_PROBABILITY_UNSPECIFIED=`HARM_PROBABILITY_UNSPECIFIED`,e.NEGLIGIBLE=`NEGLIGIBLE`,e.LOW=`LOW`,e.MEDIUM=`MEDIUM`,e.HIGH=`HIGH`})(Te||={});var Ee;(function(e){e.BLOCKED_REASON_UNSPECIFIED=`BLOCKED_REASON_UNSPECIFIED`,e.SAFETY=`SAFETY`,e.OTHER=`OTHER`})(Ee||={});var A;(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`})(A||={});var De;(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`})(De||={});var j;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.AUTO=`AUTO`,e.ANY=`ANY`,e.NONE=`NONE`})(j||={});var Oe;(function(e){e.MODE_UNSPECIFIED=`MODE_UNSPECIFIED`,e.MODE_DYNAMIC=`MODE_DYNAMIC`})(Oe||={});var M=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},N=class extends M{constructor(e,t){super(e),this.response=t}},P=class extends M{constructor(e,t,n,r){super(e),this.status=t,this.statusText=n,this.errorDetails=r}},F=class extends M{},I=class extends M{},ke=`https://generativelanguage.googleapis.com`,Ae=`v1beta`,je=`0.24.1`,Me=`genai-js`,L;(function(e){e.GENERATE_CONTENT=`generateContent`,e.STREAM_GENERATE_CONTENT=`streamGenerateContent`,e.COUNT_TOKENS=`countTokens`,e.EMBED_CONTENT=`embedContent`,e.BATCH_EMBED_CONTENTS=`batchEmbedContents`})(L||={});var Ne=class{constructor(e,t,n,r,i){this.model=e,this.task=t,this.apiKey=n,this.stream=r,this.requestOptions=i}toString(){let e=this.requestOptions?.apiVersion||Ae,t=`${this.requestOptions?.baseUrl||ke}/${e}/${this.model}:${this.task}`;return this.stream&&(t+=`?alt=sse`),t}};function Pe(e){let t=[];return e?.apiClient&&t.push(e.apiClient),t.push(`${Me}/${je}`),t.join(` `)}async function Fe(e){let t=new Headers;t.append(`Content-Type`,`application/json`),t.append(`x-goog-api-client`,Pe(e.requestOptions)),t.append(`x-goog-api-key`,e.apiKey);let n=e.requestOptions?.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(e){throw new F(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${e.message}`)}for(let[e,r]of n.entries()){if(e===`x-goog-api-key`)throw new F(`Cannot set reserved header name ${e}`);if(e===`x-goog-api-client`)throw new F(`Header name ${e} can only be set using the apiClient field`);t.append(e,r)}}return t}async function Ie(e,t,n,r,i,a){let o=new Ne(e,t,n,r,a);return{url:o.toString(),fetchOptions:Object.assign(Object.assign({},Be(a)),{method:`POST`,headers:await Fe(o),body:i})}}async function R(e,t,n,r,i,a={},o=fetch){let{url:s,fetchOptions:c}=await Ie(e,t,n,r,i,a);return Le(s,c,o)}async function Le(e,t,n=fetch){let r;try{r=await n(e,t)}catch(t){Re(t,e)}return r.ok||await ze(r,e),r}function Re(e,t){let n=e;throw n.name===`AbortError`?(n=new I(`Request aborted when fetching ${t.toString()}: ${e.message}`),n.stack=e.stack):e instanceof P||e instanceof F||(n=new M(`Error fetching from ${t.toString()}: ${e.message}`),n.stack=e.stack),n}async function ze(e,t){let n=``,r;try{let t=await e.json();n=t.error.message,t.error.details&&(n+=` ${JSON.stringify(t.error.details)}`,r=t.error.details)}catch{}throw new P(`Error fetching from ${t.toString()}: [${e.status} ${e.statusText}] ${n}`,e.status,e.statusText,r)}function Be(e){let t={};if(e?.signal!==void 0||e?.timeout>=0){let n=new AbortController;e?.timeout>=0&&setTimeout(()=>n.abort(),e.timeout),e?.signal&&e.signal.addEventListener(`abort`,()=>{n.abort()}),t.signal=n.signal}return t}function z(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.`),V(e.candidates[0]))throw new N(`${H(e)}`,e);return Ve(e)}else if(e.promptFeedback)throw new N(`Text not available. ${H(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.`),V(e.candidates[0]))throw new N(`${H(e)}`,e);return console.warn(`response.functionCall() is deprecated. Use response.functionCalls() instead.`),B(e)[0]}else if(e.promptFeedback)throw new N(`Function call not available. ${H(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.`),V(e.candidates[0]))throw new N(`${H(e)}`,e);return B(e)}else if(e.promptFeedback)throw new N(`Function call not available. ${H(e)}`,e)},e}function Ve(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.text&&t.push(n.text),n.executableCode&&t.push("\n```"+n.executableCode.language+`
2
2
  `+n.executableCode.code+"\n```\n"),n.codeExecutionResult&&t.push("\n```\n"+n.codeExecutionResult.output+"\n```\n");return t.length>0?t.join(``):``}function B(e){let t=[];if(e.candidates?.[0].content?.parts)for(let n of e.candidates?.[0].content?.parts)n.functionCall&&t.push(n.functionCall);if(t.length>0)return t}var He=[A.RECITATION,A.SAFETY,A.LANGUAGE];function V(e){return!!e.finishReason&&He.includes(e.finishReason)}function H(e){let t=``;if((!e.candidates||e.candidates.length===0)&&e.promptFeedback)t+=`Response was blocked`,e.promptFeedback?.blockReason&&(t+=` due to ${e.promptFeedback.blockReason}`),e.promptFeedback?.blockReasonMessage&&(t+=`: ${e.promptFeedback.blockReasonMessage}`);else if(e.candidates?.[0]){let n=e.candidates[0];V(n)&&(t+=`Candidate was blocked due to ${n.finishReason}`,n.finishMessage&&(t+=`: ${n.finishMessage}`))}return t}function U(e){return this instanceof U?(this.v=e,this):new U(e)}function Ue(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i={},o(`next`),o(`throw`),o(`return`),i[Symbol.asyncIterator]=function(){return this},i;function o(e){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||s(e,t)})})}function s(e,t){try{c(r[e](t))}catch(e){d(a[0][3],e)}}function c(e){e.value instanceof U?Promise.resolve(e.value.v).then(l,u):d(a[0][2],e)}function l(e){s(`next`,e)}function u(e){s(`throw`,e)}function d(e,t){e(t),a.shift(),a.length&&s(a[0][0],a[0][1])}}var W=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function We(e){let[t,n]=qe(e.body.pipeThrough(new TextDecoderStream(`utf8`,{fatal:!0}))).tee();return{stream:Ke(t),response:Ge(n)}}async function Ge(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)return z(Je(t));t.push(r)}}function Ke(e){return Ue(this,arguments,function*(){let t=e.getReader();for(;;){let{value:e,done:n}=yield U(t.read());if(n)break;yield yield U(z(e))}})}function qe(e){let t=e.getReader();return new ReadableStream({start(e){let n=``;return r();function r(){return t.read().then(({value:t,done:i})=>{if(i){if(n.trim()){e.error(new M(`Failed to parse stream`));return}e.close();return}n+=t;let a=n.match(W),o;for(;a;){try{o=JSON.parse(a[1])}catch{e.error(new M(`Error parsing JSON response: "${a[1]}"`));return}e.enqueue(o),n=n.substring(a[0].length),a=n.match(W)}return r()}).catch(e=>{let t=e;throw t.stack=e.stack,t=t.name===`AbortError`?new I(`Request aborted when reading from the stream`):new M(`Error reading from the stream`),t})}}})}function Je(e){let t={promptFeedback:e[e.length-1]?.promptFeedback};for(let n of e){if(n.candidates){let e=0;for(let r of n.candidates)if(t.candidates||=[],t.candidates[e]||(t.candidates[e]={index:e}),t.candidates[e].citationMetadata=r.citationMetadata,t.candidates[e].groundingMetadata=r.groundingMetadata,t.candidates[e].finishReason=r.finishReason,t.candidates[e].finishMessage=r.finishMessage,t.candidates[e].safetyRatings=r.safetyRatings,r.content&&r.content.parts){t.candidates[e].content||(t.candidates[e].content={role:r.content.role||`user`,parts:[]});let n={};for(let i of r.content.parts)i.text&&(n.text=i.text),i.functionCall&&(n.functionCall=i.functionCall),i.executableCode&&(n.executableCode=i.executableCode),i.codeExecutionResult&&(n.codeExecutionResult=i.codeExecutionResult),Object.keys(n).length===0&&(n.text=``),t.candidates[e].content.parts.push(n)}e++}n.usageMetadata&&(t.usageMetadata=n.usageMetadata)}return t}async function G(e,t,n,r){return We(await R(t,L.STREAM_GENERATE_CONTENT,e,!0,JSON.stringify(n),r))}async function K(e,t,n,r){return{response:z(await(await R(t,L.GENERATE_CONTENT,e,!1,JSON.stringify(n),r)).json())}}function q(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 J(e){let t=[];if(typeof e==`string`)t=[{text:e}];else for(let n of e)typeof n==`string`?t.push({text:n}):t.push(n);return Ye(t)}function Ye(e){let t={role:`user`,parts:[]},n={role:`function`,parts:[]},r=!1,i=!1;for(let a of e)`functionResponse`in a?(n.parts.push(a),i=!0):(t.parts.push(a),r=!0);if(r&&i)throw new M(`Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.`);if(!r&&!i)throw new M(`No content is provided for sending chat message.`);return r?t:n}function Xe(e,t){let n={model:t?.model,generationConfig:t?.generationConfig,safetySettings:t?.safetySettings,tools:t?.tools,toolConfig:t?.toolConfig,systemInstruction:t?.systemInstruction,cachedContent:t?.cachedContent?.name,contents:[]},r=e.generateContentRequest!=null;if(e.contents){if(r)throw new F(`CountTokensRequest must have one of contents or generateContentRequest, not both.`);n.contents=e.contents}else if(r)n=Object.assign(Object.assign({},n),e.generateContentRequest);else{let t=J(e);n.contents=[t]}return{generateContentRequest:n}}function Y(e){let t;return t=e.contents?e:{contents:[J(e)]},e.systemInstruction&&(t.systemInstruction=q(e.systemInstruction)),t}function Ze(e){return typeof e==`string`||Array.isArray(e)?{content:J(e)}:e}var X=[`text`,`inlineData`,`functionCall`,`functionResponse`,`executableCode`,`codeExecutionResult`],Qe={user:[`text`,`inlineData`],function:[`functionResponse`],model:[`text`,`functionCall`,`executableCode`,`codeExecutionResult`],system:[`text`]};function $e(e){let t=!1;for(let n of e){let{role:e,parts:r}=n;if(!t&&e!==`user`)throw new M(`First content should be with role 'user', got ${e}`);if(!k.includes(e))throw new M(`Each item should include role field. Got ${e} but valid roles are: ${JSON.stringify(k)}`);if(!Array.isArray(r))throw new M(`Content should have 'parts' property with an array of Parts`);if(r.length===0)throw new M(`Each Content should have at least one part`);let i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let e of r)for(let t of X)t in e&&(i[t]+=1);let a=Qe[e];for(let t of X)if(!a.includes(t)&&i[t]>0)throw new M(`Content with role '${e}' can't contain '${t}' part`);t=!0}}function Z(e){if(e.candidates===void 0||e.candidates.length===0)return!1;let t=e.candidates[0]?.content;if(t===void 0||t.parts===void 0||t.parts.length===0)return!1;for(let e of t.parts)if(e===void 0||Object.keys(e).length===0||e.text!==void 0&&e.text===``)return!1;return!0}var Q=`SILENT_ERROR`,et=class{constructor(e,t,n,r={}){this.model=t,this.params=n,this._requestOptions=r,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,n?.history&&($e(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,t={}){await this._sendPromise;let n=J(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a;return this._sendPromise=this._sendPromise.then(()=>K(this._apiKey,this.model,r,i)).then(e=>{if(Z(e.response)){this._history.push(n);let t=Object.assign({parts:[],role:`model`},e.response.candidates?.[0].content);this._history.push(t)}else{let t=H(e.response);t&&console.warn(`sendMessage() was unsuccessful. ${t}. Inspect response object for details.`)}a=e}).catch(e=>{throw this._sendPromise=Promise.resolve(),e}),await this._sendPromise,a}async sendMessageStream(e,t={}){await this._sendPromise;let n=J(e),r={safetySettings:this.params?.safetySettings,generationConfig:this.params?.generationConfig,tools:this.params?.tools,toolConfig:this.params?.toolConfig,systemInstruction:this.params?.systemInstruction,cachedContent:this.params?.cachedContent,contents:[...this._history,n]},i=Object.assign(Object.assign({},this._requestOptions),t),a=G(this._apiKey,this.model,r,i);return this._sendPromise=this._sendPromise.then(()=>a).catch(e=>{throw Error(Q)}).then(e=>e.response).then(e=>{if(Z(e)){this._history.push(n);let t=Object.assign({},e.candidates[0].content);t.role||=`model`,this._history.push(t)}else{let t=H(e);t&&console.warn(`sendMessageStream() was unsuccessful. ${t}. Inspect response object for details.`)}}).catch(e=>{e.message!==Q&&console.error(e)}),a}};async function tt(e,t,n,r){return(await R(t,L.COUNT_TOKENS,e,!1,JSON.stringify(n),r)).json()}async function nt(e,t,n,r){return(await R(t,L.EMBED_CONTENT,e,!1,JSON.stringify(n),r)).json()}async function rt(e,t,n,r){let i=n.requests.map(e=>Object.assign(Object.assign({},e),{model:t}));return(await R(t,L.BATCH_EMBED_CONTENTS,e,!1,JSON.stringify({requests:i}),r)).json()}var $=class{constructor(e,t,n={}){this.apiKey=e,this._requestOptions=n,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=q(t.systemInstruction),this.cachedContent=t.cachedContent}async generateContent(e,t={}){let n=Y(e),r=Object.assign(Object.assign({},this._requestOptions),t);return K(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}async generateContentStream(e,t={}){let n=Y(e),r=Object.assign(Object.assign({},this._requestOptions),t);return G(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},n),r)}startChat(e){return new et(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent?.name},e),this._requestOptions)}async countTokens(e,t={}){let n=Xe(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),r=Object.assign(Object.assign({},this._requestOptions),t);return tt(this.apiKey,this.model,n,r)}async embedContent(e,t={}){let n=Ze(e),r=Object.assign(Object.assign({},this._requestOptions),t);return nt(this.apiKey,this.model,n,r)}async batchEmbedContents(e,t={}){let n=Object.assign(Object.assign({},this._requestOptions),t);return rt(this.apiKey,this.model,e,n)}},it=class{constructor(e){this.apiKey=e}getGenerativeModel(e,t){if(!e.model)throw new M(`Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })`);return new $(this.apiKey,e,t)}getGenerativeModelFromCachedContent(e,t,n){if(!e.name)throw new F("Cached content must contain a `name` field.");if(!e.model)throw new F("Cached content must contain a `model` field.");for(let n of[`model`,`systemInstruction`])if(t?.[n]&&e[n]&&t?.[n]!==e[n]){if(n===`model`&&(t.model.startsWith(`models/`)?t.model.replace(`models/`,``):t.model)===(e.model.startsWith(`models/`)?e.model.replace(`models/`,``):e.model))continue;throw new F(`Different value for "${n}" specified in modelParams (${t[n]}) and cachedContent (${e[n]})`)}let r=Object.assign(Object.assign({},t),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new $(this.apiKey,r,n)}};function at(e,t){let n=ot(e);return{tools:n,toolConfig:ct(n,t)}}function ot(e){let t=[],n=[];return e.forEach(e=>{if(g(e)){let[n]=ye([e]);n.functionDeclarations&&t.push(...n.functionDeclarations)}else if(h(e)){let{functionDeclarations:n}=st(e);if(n)t.push(...n);else throw Error(`Failed to convert OpenAI structured tool to GenerativeAI tool`)}else n.push(e)}),n.find(e=>`functionDeclarations`in e)?n.map(e=>{if(t?.length>0&&`functionDeclarations`in e){let n={functionDeclarations:[...e.functionDeclarations||[],...t]};return t=[],n}return e}):[...n,...t.length>0?[{functionDeclarations:t}]:[]]}function st(e){return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:_(e.function.parameters)}]}}function ct(e,t){if(!e.length||!t)return;let{toolChoice:n,allowedFunctionNames:r}=t,i={any:j.ANY,auto:j.AUTO,none:j.NONE};if(n&&[`any`,`auto`,`none`].includes(n))return{functionCallingConfig:{mode:i[n]??`MODE_UNSPECIFIED`,allowedFunctionNames:r}};if(typeof n==`string`||r)return{functionCallingConfig:{mode:j.ANY,allowedFunctionNames:[...r??[],...n&&typeof n==`string`?[n]:[]]}}}var lt={"gemini-embedding-001":{maxInputTokens:2048,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-lite-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-06-05":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-04-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-05-06":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-05-20":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-flash-preview":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash-preview-native-audio":{maxInputTokens:131072,imageInputs:!1,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-flash-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-lite-preview-06-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-image":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-pro-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-image-preview":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-1.5-flash-8b":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-pro-preview":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-flash":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-flash-lite-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-pro":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1}},ut=class extends re{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;thinkingConfig;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`)||this.model.startsWith(`gemini-3`)}constructor(e){if(super(e),this.model=e.model.replace(/^models\//,``),this.maxOutputTokens=e.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw Error("`maxOutputTokens` must be a positive integer");if(this.temperature=e.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw 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 Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw Error("`topP` must be below 1.");if(this.topK=e.topK??this.topK,this.topK&&this.topK<0)throw Error("`topK` must be a positive integer");if(this.stopSequences=e.stopSequences??this.stopSequences,this.apiKey=e.apiKey??r(`GOOGLE_API_KEY`),!this.apiKey)throw 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(e=>e.category)).size!==this.safetySettings.length)throw Error("The categories in `safetySettings` array must be unique");this.streaming=e.streaming??this.streaming,this.json=e.json,this.thinkingConfig=e.thinkingConfig??this.thinkingConfig,this.client=new it(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`}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{}}},{apiVersion:e.apiVersion,baseUrl:e.baseUrl,customHeaders:e.customHeaders}),this.streamUsage=e.streamUsage??this.streamUsage}useCachedContent(e,t,n){this.apiKey&&(this.client=new it(this.apiKey).getGenerativeModelFromCachedContent(e,t,n))}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,t){return this.withConfig({tools:at(e)?.tools,...t})}invocationParams(e){let t=e?.tools?.length?at(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),{...t?.tools?{tools:t.tools}:{},...t?.toolConfig?{toolConfig:t.toolConfig}:{}}}async _generate(e,t,n){t.signal?.throwIfAborted();let r=E(e,this._isMultimodalModel,this.useSystemInstruction,this.model),i=r;if(r[0].role===`system`){let[e]=r;this.client.systemInstruction=e,i=r.slice(1)}let a=this.invocationParams(t);if(this.streaming){let r={},i=this._streamResponseChunks(e,t,n),a=[];for await(let e of i){let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}return{generations:a.filter(e=>e!==void 0),llmOutput:{estimatedTokenUsage:r}}}let o=await this.completionWithRetry({...a,contents:i}),s;`usageMetadata`in o.response&&(s=D(o.response.usageMetadata,this.model));let c=_e(o.response,{usageMetadata:s});return c.generations?.length>0&&await n?.handleLLMNewToken(c.generations[0]?.text??``),c}async*_streamResponseChunks(e,t,n){let r=E(e,this._isMultimodalModel,this.useSystemInstruction,this.model),i=r;if(r[0].role===`system`){let[e]=r;this.client.systemInstruction=e,i=r.slice(1)}let a={...this.invocationParams(t),contents:i},o=await this.caller.callWithOptions({signal:t?.signal},async()=>{let{stream:e}=await this.client.generateContentStream(a,{signal:t?.signal});return e}),s,c=0,l=0,u=0,d=0;for await(let e of o){if(t.signal?.aborted)return;if(`usageMetadata`in e&&e.usageMetadata!==void 0&&this.streamUsage!==!1&&t.streamUsage!==!1){s=D(e.usageMetadata,this.model);let t=e.usageMetadata.promptTokenCount??0;s.input_tokens=Math.max(0,t-c),c=t;let n=e.usageMetadata.candidatesTokenCount??0;s.output_tokens=Math.max(0,n-l),l=n;let r=e.usageMetadata.totalTokenCount??0;s.total_tokens=Math.max(0,r-u),u=r}let r=ve(e,{usageMetadata:s,index:d});d+=1,r&&(yield r,await n?.handleLLMNewToken(r.text??``))}}async completionWithRetry(e,t){return this.caller.callWithOptions({signal:t?.signal},async()=>{try{return await this.client.generateContent(e,{signal:t?.signal})}catch(e){throw e.message?.includes(`400 Bad Request`)&&(e.status=400),e}})}get profile(){return lt[this.model]??{}}withStructuredOutput(e,n){let r=e,i=n?.name,a=n?.method,o=n?.includeRaw;if(a===`jsonMode`)throw Error(`ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.`);let c,l;if(a===`functionCalling`){let e=i??`extract`,n;if(t(r)){let t=v(r);n=[{functionDeclarations:[{name:e,description:t.description??`A function available to call.`,parameters:t}]}],l=new O({returnSingle:!0,keyName:e,zodSchema:r})}else{let t;typeof r.name==`string`&&typeof r.parameters==`object`&&r.parameters!=null?(t=r,t.parameters=_(r.parameters),e=r.name):t={name:e,description:r.description??``,parameters:_(r)},n=[{functionDeclarations:[t]}],l=new O({returnSingle:!0,keyName:e})}c=this.bindTools(n).withConfig({allowedFunctionNames:[e]})}else{let e=v(r);c=this.withConfig({responseSchema:e}),l=new ie}if(!o)return c.pipe(l).withConfig({runName:`ChatGoogleGenerativeAIStructuredOutput`});let u=m.assign({parsed:(e,t)=>l.invoke(e.raw,t)}),d=m.assign({parsed:()=>null}),f=u.withFallbacks({fallbacks:[d]});return s.from([{raw:c},f]).withConfig({runName:`StructuredOutputRunnable`})}};export{ut as ChatGoogleGenerativeAI};