@mcp-use/inspector 0.13.0-canary.18 → 0.13.0-canary.19

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.
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/winston-BgJDfsZt.js","assets/util-t-trnxQI.js","assets/index-DRz5BQNA.js","assets/path-DImnYYhy.js","assets/fs-u42MReIY.js","assets/path-MNZaYwxc.js","assets/index-BWMAhNJO.js","assets/index-DDtG6uBj.js","assets/index-BlTsCqBl.js","assets/llms-u9DMr6Pm.js","assets/embeddings-BON0Gj74.js","assets/index-Bp167cgV.js","assets/index-CmdaC4jK.js","assets/index-BMVGFw1P.js","assets/browser-gXOjyGah.js"])))=>i.map(i=>d[i]);
2
- var oJ=Object.defineProperty;var sJ=(e,t,n)=>t in e?oJ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Uf=(e,t,n)=>sJ(e,typeof t!="symbol"?t+"":t,n);function lJ(e,t){for(var n=0;n<t.length;n++){const a=t[n];if(typeof a!="string"&&!Array.isArray(a)){for(const r in a)if(r!=="default"&&!(r in e)){const i=Object.getOwnPropertyDescriptor(a,r);i&&Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:()=>a[r]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&a(s)}).observe(document,{childList:!0,subtree:!0});function n(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function a(r){if(r.ep)return;r.ep=!0;const i=n(r);fetch(r.href,i)}})();function ny(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function JTe(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function a(){var r=!1;try{r=this instanceof a}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(a){var r=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:function(){return e[a]}})}),n}var LS={exports:{}},zf={};var sM;function cJ(){if(sM)return zf;sM=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(a,r,i){var s=null;if(i!==void 0&&(s=""+i),r.key!==void 0&&(s=""+r.key),"key"in r){i={};for(var c in r)c!=="key"&&(i[c]=r[c])}else i=r;return r=i.ref,{$$typeof:e,type:a,key:s,ref:r!==void 0?r:null,props:i}}return zf.Fragment=t,zf.jsx=n,zf.jsxs=n,zf}var lM;function uJ(){return lM||(lM=1,LS.exports=cJ()),LS.exports}var f=uJ();const dJ="modulepreload",fJ=function(e){return"/inspector/"+e},cM={},Jn=function(t,n,a){let r=Promise.resolve();if(n&&n.length>0){let u=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),c=s?.nonce||s?.getAttribute("nonce");r=u(n.map(d=>{if(d=fJ(d),d in cM)return;cM[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":dJ,m||(g.as="script"),g.crossOrigin="",g.href=d,c&&g.setAttribute("nonce",c),document.head.appendChild(g),m)return new Promise((v,x)=>{g.addEventListener("load",v),g.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(s){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=s,window.dispatchEvent(c),!c.defaultPrevented)throw s}return r.then(s=>{for(const c of s||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};var pJ=Object.defineProperty,ze=(e,t)=>pJ(e,"name",{value:t,configurable:!0}),ks=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Jc={};async function sF(){if(typeof process<"u")try{const e=await Jn(()=>import("./fs-u42MReIY.js").then(n=>n.f),[]),t=await Jn(()=>import("./path-MNZaYwxc.js").then(n=>n.p),[]);return{fs:e.default,path:t.default}}catch{return{fs:null,path:null}}return{fs:null,path:null}}ze(sF,"getNodeModules");var ha=null;function lF(){if(typeof ks<"u")try{ha=ks("winston")}catch{}}ze(lF,"loadWinstonSync");async function cF(){return ha||(ha=await Jn(()=>import("./winston-BgJDfsZt.js").then(e=>e.w),__vite__mapDeps([0,1,2,3,4,5]))),ha}ze(cF,"getWinston");var n_="mcp-use";function Xb(){try{return typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")||typeof globalThis.EdgeRuntime<"u"||typeof globalThis.Deno<"u"?!1:typeof process<"u"&&!0&&typeof __dirname<"u"}catch{return!1}}ze(Xb,"isNodeJSEnvironment");var Au,mJ=(Au=class{_level;name;constructor(t=n_,n="info"){this.name=t,this._level=n}shouldLog(t){const n=["error","warn","info","http","verbose","debug","silly"],a=n.indexOf(this._level);return n.indexOf(t)<=a}formatMessage(t,n){return`${new Date().toLocaleTimeString("en-US",{hour12:!1})} [${this.name}] ${t}: ${n}`}error(t){this.shouldLog("error")&&console.error(this.formatMessage("error",t))}warn(t){this.shouldLog("warn")&&console.warn(this.formatMessage("warn",t))}info(t){this.shouldLog("info")&&console.info(this.formatMessage("info",t))}debug(t){this.shouldLog("debug")&&console.debug(this.formatMessage("debug",t))}http(t){this.shouldLog("http")&&console.log(this.formatMessage("http",t))}verbose(t){this.shouldLog("verbose")&&console.log(this.formatMessage("verbose",t))}silly(t){this.shouldLog("silly")&&console.log(this.formatMessage("silly",t))}get level(){return this._level}set level(t){this._level=t}},ze(Au,"SimpleConsoleLogger"),Au);function kb(e){switch((typeof process<"u"&&Jc?e:void 0)?.trim()){case"2":return"debug";case"1":return"info";default:return"info"}}ze(kb,"resolveLevel");var ko,uF=(ko=class{static get(t=n_){if(!Xb()){if(!this.simpleInstances[t]){const n=typeof process<"u"&&Jc?.DEBUG||void 0;this.simpleInstances[t]=new mJ(t,kb(n))}return this.simpleInstances[t]}if(!this.instances[t]){if(!ha)throw new Error("Winston not loaded - call Logger.configure() first");const{createLogger:n,format:a}=ha,{combine:r,timestamp:i,label:s,colorize:c,splat:u}=a;this.instances[t]=n({level:kb(Jc.DEBUG),format:r(c(),u(),s({label:t}),i({format:"HH:mm:ss"}),this.getFormatter()),transports:[new ha.transports.Console]})}return this.instances[t]}static getFormatter(){if(!ha)throw new Error("Winston not loaded");const{format:t}=ha,{printf:n}=t,a=n(({level:s,message:c,label:u,timestamp:d})=>`${d} [${u}] ${s}: ${c}`),r=n(({level:s,message:c,label:u,timestamp:d})=>`${d} [${u}] ${s.toUpperCase()}: ${c}`),i=n(({level:s,message:c,label:u,timestamp:d})=>`${d} [${u}] ${s.toUpperCase()}: ${c}`);switch(this.currentFormat){case"minimal":return a;case"detailed":return r;case"emoji":return i;default:return a}}static async configure(t={}){const{level:n,console:a=!0,file:r,format:i="minimal"}=t,s=typeof process<"u"&&Jc?.DEBUG||void 0,c=n??kb(s);if(this.currentFormat=i,!Xb()){Object.values(this.simpleInstances).forEach(y=>{y.level=c});return}if(await cF(),!ha)throw new Error("Failed to load winston");const u=this.get();u.level=c;const d=u;if(d.clear(),a&&d.add(new ha.transports.Console),r){const{fs:y,path:E}=await sF();if(y&&E){const _=E.dirname(E.resolve(r));y.existsSync(_)||y.mkdirSync(_,{recursive:!0}),d.add(new ha.transports.File({filename:r}))}}const{format:m}=ha,{combine:h,timestamp:g,label:v,colorize:x,splat:S}=m;Object.values(this.instances).forEach(y=>{y&&"format"in y&&(y.level=c,y.format=h(x(),S(),v({label:n_}),g({format:"HH:mm:ss"}),this.getFormatter()))})}static setDebug(t){let n;t===2||t===!0?n="debug":n="info",Object.values(this.simpleInstances).forEach(a=>{a.level=n}),Object.values(this.instances).forEach(a=>{a&&(a.level=n)}),typeof process<"u"&&Jc&&(Jc.DEBUG=t?t===!0?"2":String(t):"0")}static setFormat(t){this.currentFormat=t,this.configure({format:t})}},ze(ko,"Logger"),Uf(ko,"instances",{}),Uf(ko,"simpleInstances",{}),Uf(ko,"currentFormat","minimal"),ko);Xb()&&(lF(),ha&&uF.configure());var Ce=uF.get(),Tb={},dF=typeof globalThis.Deno<"u";function hJ(e){return dF?globalThis.Deno.env.get(e):Tb[e]}ze(hJ,"getEnv");function gJ(){return dF?globalThis.Deno.cwd():process.cwd()}ze(gJ,"getCwd");function El(){return globalThis.crypto.randomUUID()}ze(El,"generateUUID");var bJ="1.11.0-canary.18";function Jb(){return bJ}ze(Jb,"getPackageVersion");var Iu,Ci=(Iu=class{},ze(Iu,"BaseTelemetryEvent"),Iu),Ou,vJ=(Ou=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(Ou,"MCPAgentExecutionEvent"),Ou);function fF(e,t){const n=Array.from(e.registrations.tools.values()),a=Array.from(e.registrations.prompts.values()),r=Array.from(e.registrations.resources.values()),i=Array.from(e.registrations.resourceTemplates.values()),s=r.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,uri:m.config.uri??null,mime_type:m.config.mimeType??null})),c=s.filter(m=>m.mime_type==="text/html+skybridge"),u=s.filter(m=>m.mime_type==="text/uri-list"||m.mime_type==="text/html"),d=s.filter(m=>m.mime_type==="text/html+mcp");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(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,input_schema:m.config.schema?JSON.stringify(m.config.schema):null,output_schema:m.config.outputSchema?JSON.stringify(m.config.outputSchema):null})):null,resources:s.length>0?s:null,prompts:a.length>0?a.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,args:m.config.args?JSON.stringify(m.config.args):null})):null,templates:i.length>0?i.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null})):null,capabilities:{logging:!0,resources:{subscribe:!0,listChanged:!0}},appsSdkResources:c.length>0?c:null,appsSdkResourcesNumber:c.length,mcpUiResources:u.length>0?u:null,mcpUiResourcesNumber:u.length,mcpAppsResources:d.length>0?d:null,mcpAppsResourcesNumber:d.length}}ze(fF,"createServerRunEventData");var Du,yJ=(Du=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(Du,"ServerRunEvent"),Du),ju,wJ=(ju=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(ju,"ServerInitializeEvent"),ju),$u,SJ=($u=class extends Ci{constructor(t){super(),this.data=t}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}}},ze($u,"ServerToolCallEvent"),$u),Lu,xJ=(Lu=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(Lu,"ServerResourceCallEvent"),Lu),Mu,_J=(Mu=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(Mu,"ServerPromptCallEvent"),Mu),Pu,EJ=(Pu=class extends Ci{constructor(t){super(),this.data=t}get name(){return`server_context_${this.data.contextType}`}get properties(){return{context_type:this.data.contextType,notification_type:this.data.notificationType??null}}},ze(Pu,"ServerContextEvent"),Pu),Uu,kJ=(Uu=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(Uu,"MCPClientInitEvent"),Uu),zu,TJ=(zu=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(zu,"ConnectorInitEvent"),zu),Fu,NJ=(Fu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"client_add_server"}get properties(){const{serverName:t,serverConfig:n}=this.data,a=n.url;return{server_name:t,server_url_domain:a?this._extractHostname(a):null,transport:n.transport??null,has_auth:!!(n.authToken||n.authProvider)}}_extractHostname(t){try{return new URL(t).hostname}catch{return null}}},ze(Fu,"ClientAddServerEvent"),Fu),Bu,CJ=(Bu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"client_remove_server"}get properties(){return{server_name:this.data.serverName}}},ze(Bu,"ClientRemoveServerEvent"),Bu);function pF(e){return e._llm_type||e.constructor.name.toLowerCase()}ze(pF,"getModelProvider");function mF(e){if("_identifyingParams"in e){const t=e._identifyingParams;if(typeof t=="object"&&t!==null){for(const n of["model","modelName","model_name","modelId","model_id","deploymentName","deployment_name"])if(n in t)return String(t[n])}}return e.model||e.modelName||e.constructor.name}ze(mF,"getModelName");function RJ(e){return[pF(e),mF(e)]}ze(RJ,"extractModelInfo");var uM="mcp_use_user_id";function hF(){try{return typeof globalThis.Bun<"u"?"bun":typeof globalThis.Deno<"u"?"deno":typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")?"cloudflare-workers":typeof globalThis.EdgeRuntime<"u"?"edge":typeof window<"u"&&typeof document<"u"?"browser":typeof process<"u"&&typeof process.versions?.node<"u"?"node":"unknown"}catch{return"unknown"}}ze(hF,"detectRuntimeEnvironment");function gF(e){switch(e){case"node":case"bun":return"filesystem";case"browser":try{if(typeof localStorage<"u")return localStorage.setItem("__mcp_use_test__","1"),localStorage.removeItem("__mcp_use_test__"),"localStorage"}catch{}return"session-only";case"deno":return"session-only";default:return"session-only"}}ze(gF,"getStorageCapability");var MS=null;function bF(){return MS===null&&(MS=hF()),MS}ze(bF,"getRuntimeEnvironment");var Hu,AJ=(Hu=class{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,a=setTimeout(()=>n.abort(),this.timeout),r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(a),!r.ok)throw new Error(`HTTP error! status: ${r.status}`)}catch(n){Ce.debug(`Failed to send Scarf event: ${n}`)}}},ze(Hu,"ScarfEventLogger"),Hu),gi,vF=(gi=class{PROJECT_API_KEY="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";HOST="https://eu.i.posthog.com";SCARF_GATEWAY_URL="https://mcpuse.gateway.scarf.sh/events-ts";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogNodeClient=null;_posthogBrowserClient=null;_posthogLoading=null;_scarfClient=null;_runtimeEnvironment;_storageCapability;_source;_userIdPath=null;_versionDownloadPath=null;constructor(){this._runtimeEnvironment=bF(),this._storageCapability=gF(this._runtimeEnvironment),this._source=typeof process<"u"&&Tb?.MCP_USE_TELEMETRY_SOURCE||this._runtimeEnvironment;const t=this._checkTelemetryDisabled(),n=this._runtimeEnvironment!=="unknown";if(t)this._posthogNodeClient=null,this._posthogBrowserClient=null,this._scarfClient=null,Ce.debug("Telemetry disabled via environment/localStorage");else if(!n)this._posthogNodeClient=null,this._posthogBrowserClient=null,this._scarfClient=null,Ce.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`);else{if(Ce.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."),this._posthogLoading=this._initPostHog(),this._runtimeEnvironment!=="browser")try{this._scarfClient=new AJ(this.SCARF_GATEWAY_URL,3e3)}catch(a){Ce.warn(`Failed to initialize Scarf telemetry: ${a}`),this._scarfClient=null}else this._scarfClient=null;this._storageCapability==="filesystem"&&this._scarfClient&&setTimeout(()=>{this.trackPackageDownload({triggered_by:"initialization"}).catch(a=>Ce.debug(`Failed to track package download: ${a}`))},0)}}_checkTelemetryDisabled(){return typeof process<"u"&&Tb?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()==="false"||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}async _initPostHog(){this._runtimeEnvironment==="browser"?await this._initPostHogBrowser():await this._initPostHogNode()}async _initPostHogBrowser(){try{const t=await Jn(()=>import("./module-D4IOASh4.js"),[]),n=t.default||t.posthog;if(!n||typeof n.init!="function")throw new Error("posthog-js module did not export expected interface");n.init(this.PROJECT_API_KEY,{api_host:this.HOST,persistence:"localStorage",autocapture:!1,capture_pageview:!1,disable_session_recording:!0,loaded:ze(()=>{Ce.debug("PostHog browser client initialized")},"loaded")}),this._posthogBrowserClient=n}catch(t){Ce.warn(`Failed to initialize PostHog browser telemetry: ${t}`),this._posthogBrowserClient=null}}async _initPostHogNode(){try{const{PostHog:t}=await Jn(async()=>{const{PostHog:r}=await import("./posthog-node-CuYhrq1Q.js");return{PostHog:r}},[]),n=["cloudflare-workers","edge","deno"].includes(this._runtimeEnvironment),a={host:this.HOST,disableGeoip:!1};n&&(a.flushAt=1,a.flushInterval=0),this._posthogNodeClient=new t(this.PROJECT_API_KEY,a),Ce.debug("PostHog Node.js client initialized")}catch(t){Ce.warn(`Failed to initialize PostHog Node.js telemetry: ${t}`),this._posthogNodeClient=null}}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return gi.instance||(gi.instance=new gi),gi.instance}setSource(t){this._source=t,Ce.debug(`Telemetry source set to: ${t}`)}getSource(){return this._source}get isEnabled(){return this._posthogNodeClient!==null||this._posthogBrowserClient!==null||this._scarfClient!==null}get userId(){if(this._currUserId)return this._currUserId;try{switch(this._storageCapability){case"filesystem":this._currUserId=this._getUserIdFromFilesystem();break;case"localStorage":this._currUserId=this._getUserIdFromLocalStorage();break;case"session-only":default:try{this._currUserId=`session-${El()}`}catch{this._currUserId=`session-${Date.now()}-${Math.random().toString(36).substring(2,15)}`}break}}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}_getUserIdFromFilesystem(){try{let t,n,a;try{t=ks("fs"),n=ks("os"),a=ks("path")}catch{try{return`session-${El()}`}catch{return`session-${Date.now()}-${Math.random().toString(36).substring(2,15)}`}}if(this._userIdPath||(this._userIdPath=a.join(this._getCacheHome(n,a),"mcp_use_3","telemetry_user_id")),!t.existsSync(this._userIdPath)){t.mkdirSync(a.dirname(this._userIdPath),{recursive:!0});let s;try{s=El()}catch{s=`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}return t.writeFileSync(this._userIdPath,s),s}return t.readFileSync(this._userIdPath,"utf-8").trim()}catch{try{return`session-${El()}`}catch{return`session-${Date.now()}-${Math.random().toString(36).substring(2,15)}`}}}_getUserIdFromLocalStorage(){try{let t=localStorage.getItem(uM);if(!t){try{t=El()}catch{t=`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}localStorage.setItem(uM,t)}return t}catch{let n;try{n=`session-${El()}`}catch{n=`session-${Date.now()}-${Math.random().toString(36).substring(2,15)}`}return n}}_getCacheHome(t,n){const a=Tb.XDG_CACHE_HOME;if(a&&n.isAbsolute(a))return a;const r=t.homedir();return n.join(r,".cache")}async capture(t){if(this._posthogLoading&&await this._posthogLoading,!this._posthogNodeClient&&!this._posthogBrowserClient&&!this._scarfClient)return;const n=this.userId,a={...t.properties};if(a.mcp_use_version=Jb(),a.language="typescript",a.source=this._source,a.runtime=this._runtimeEnvironment,this._posthogNodeClient)try{this._posthogNodeClient.capture({distinctId:n,event:t.name,properties:a})}catch(r){Ce.debug(`Failed to track PostHog Node event ${t.name}: ${r}`)}if(this._posthogBrowserClient)try{this._posthogBrowserClient.capture(t.name,{...a,distinct_id:n})}catch(r){Ce.debug(`Failed to track PostHog Browser event ${t.name}: ${r}`)}if(this._scarfClient)try{const r={...a,user_id:n,event:t.name};await this._scarfClient.logEvent(r)}catch(r){Ce.debug(`Failed to track Scarf event ${t.name}: ${r}`)}}async trackPackageDownload(t){return this._trackPackageDownloadInternal(this.userId,t)}async _trackPackageDownloadInternal(t,n){if(this._scarfClient&&this._storageCapability==="filesystem")try{const a=ks("fs"),r=ks("path"),i=ks("os");this._versionDownloadPath||(this._versionDownloadPath=r.join(this._getCacheHome(i,r),"mcp_use","download_version"));const s=Jb();let c=!1,u=!1;if(!a.existsSync(this._versionDownloadPath))c=!0,u=!0,a.mkdirSync(r.dirname(this._versionDownloadPath),{recursive:!0}),a.writeFileSync(this._versionDownloadPath,s);else{const d=a.readFileSync(this._versionDownloadPath,"utf-8").trim();s>d&&(c=!0,u=!1,a.writeFileSync(this._versionDownloadPath,s))}if(c){Ce.debug(`Tracking package download event with properties: ${JSON.stringify(n)}`);const d={...n||{}};d.mcp_use_version=s,d.user_id=t,d.event="package_download",d.first_download=u,d.language="typescript",d.source=this._source,d.runtime=this._runtimeEnvironment,await this._scarfClient.logEvent(d)}}catch(a){Ce.debug(`Failed to track Scarf package_download event: ${a}`)}}async trackAgentExecution(t){if(!this.isEnabled)return;const n=new vJ(t);await this.capture(n)}async trackServerRunFromServer(t,n){if(!this.isEnabled)return;const a=fF(t,n),r=new yJ(a);await this.capture(r)}async trackServerInitialize(t){if(!this.isEnabled)return;const n=new wJ(t);await this.capture(n)}async trackServerToolCall(t){if(!this.isEnabled)return;const n=new SJ(t);await this.capture(n)}async trackServerResourceCall(t){if(!this.isEnabled)return;const n=new xJ(t);await this.capture(n)}async trackServerPromptCall(t){if(!this.isEnabled)return;const n=new _J(t);await this.capture(n)}async trackServerContext(t){if(!this.isEnabled)return;const n=new EJ(t);await this.capture(n)}async trackMCPClientInit(t){if(!this.isEnabled)return;const n=new kJ(t);await this.capture(n)}async trackConnectorInit(t){if(!this.isEnabled)return;const n=new TJ(t);await this.capture(n)}async trackClientAddServer(t,n){if(!this.isEnabled)return;const a=new NJ({serverName:t,serverConfig:n});await this.capture(a)}async trackClientRemoveServer(t){if(!this.isEnabled)return;const n=new CJ({serverName:t});await this.capture(n)}async trackUseMcpConnection(t){this.isEnabled&&await this.capture({name:"usemcp_connection",properties:{url_domain:new URL(t.url).hostname,transport_type:t.transportType,success:t.success,error_type:t.errorType??null,connection_time_ms:t.connectionTimeMs??null,has_oauth:t.hasOAuth,has_sampling:t.hasSampling,has_elicitation:t.hasElicitation}})}async trackUseMcpToolCall(t){this.isEnabled&&await this.capture({name:"usemcp_tool_call",properties:{tool_name:t.toolName,success:t.success,error_type:t.errorType??null,execution_time_ms:t.executionTimeMs??null}})}async trackUseMcpResourceRead(t){this.isEnabled&&await this.capture({name:"usemcp_resource_read",properties:{resource_uri_scheme:t.resourceUri.split(":")[0],success:t.success,error_type:t.errorType??null}})}identify(t,n){if(this._posthogBrowserClient)try{this._posthogBrowserClient.identify(t,n)}catch(a){Ce.debug(`Failed to identify user: ${a}`)}}reset(){if(this._posthogBrowserClient)try{this._posthogBrowserClient.reset()}catch(t){Ce.debug(`Failed to reset user: ${t}`)}this._currUserId=null}flush(){if(this._posthogNodeClient)try{this._posthogNodeClient.flush(),Ce.debug("PostHog client telemetry queue flushed")}catch(t){Ce.debug(`Failed to flush PostHog client: ${t}`)}}shutdown(){if(this._posthogNodeClient)try{this._posthogNodeClient.shutdown(),Ce.debug("PostHog client shutdown successfully")}catch(t){Ce.debug(`Error shutting down PostHog client: ${t}`)}}},ze(gi,"Telemetry"),Uf(gi,"instance",null),gi),zi=vF;function IJ(e){zi.getInstance().setSource(e)}ze(IJ,"setTelemetrySource");const yF=Object.freeze({status:"aborted"});function me(e,t,n){function a(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);const d=s.prototype,m=Object.keys(d);for(let h=0;h<m.length;h++){const g=m[h];g in c||(c[g]=d[g].bind(c))}}const r=n?.Parent??Object;class i extends r{}Object.defineProperty(i,"name",{value:e});function s(c){var u;const d=n?.Parent?new i:this;a(d,c),(u=d._zod).deferred??(u.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}const wF=Symbol("zod_brand");class $l extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ry extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const Qb={};function Gr(e){return e&&Object.assign(Qb,e),Qb}function OJ(e){return e}function DJ(e){return e}function jJ(e){}function $J(e){throw new Error("Unexpected value in exhaustive check")}function LJ(e){}function ok(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,r])=>t.indexOf(+a)===-1).map(([a,r])=>r)}function Pe(e,t="|"){return e.map(n=>ut(n)).join(t)}function ev(e,t){return typeof t=="bigint"?t.toString():t}function cm(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ec(e){return e==null}function ay(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function SF(e,t){const n=(e.toString().split(".")[1]||"").length,a=t.toString();let r=(a.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(a)){const u=a.match(/\d?e-(\d?)/);u?.[1]&&(r=Number.parseInt(u[1]))}const i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),c=Number.parseInt(t.toFixed(i).replace(".",""));return s%c/10**i}const dM=Symbol("evaluating");function Ht(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==dM)return a===void 0&&(a=dM,a=n()),a},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function MJ(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Gs(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Bo(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function PJ(e){return Bo(e._zod.def)}function UJ(e,t){return t?t.reduce((n,a)=>n?.[a],e):e}function zJ(e){const t=Object.keys(e),n=t.map(a=>e[a]);return Promise.all(n).then(a=>{const r={};for(let i=0;i<t.length;i++)r[t[i]]=a[i];return r})}function FJ(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let a=0;a<e;a++)n+=t[Math.floor(Math.random()*t.length)];return n}function r_(e){return JSON.stringify(e)}function xF(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const sk="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ju(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const _F=cm(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Fl(e){if(Ju(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Ju(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function iy(e){return Fl(e)?{...e}:Array.isArray(e)?[...e]:e}function BJ(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}const HJ=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},tv=new Set(["string","number","symbol"]),EF=new Set(["string","number","bigint","boolean","symbol","undefined"]);function $o(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ni(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function Ie(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function VJ(e){let t;return new Proxy({},{get(n,a,r){return t??(t=e()),Reflect.get(t,a,r)},set(n,a,r,i){return t??(t=e()),Reflect.set(t,a,r,i)},has(n,a){return t??(t=e()),Reflect.has(t,a)},deleteProperty(n,a){return t??(t=e()),Reflect.deleteProperty(t,a)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,a){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,a)},defineProperty(n,a,r){return t??(t=e()),Reflect.defineProperty(t,a,r)}})}function ut(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function kF(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const TF={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},NF={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function CF(e,t){const n=e._zod.def,a=Bo(e._zod.def,{get shape(){const r={};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return Gs(this,"shape",r),r},checks:[]});return ni(e,a)}function RF(e,t){const n=e._zod.def,a=Bo(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return Gs(this,"shape",r),r},checks:[]});return ni(e,a)}function AF(e,t){if(!Fl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const r=Bo(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Gs(this,"shape",i),i},checks:[]});return ni(e,r)}function IF(e,t){if(!Fl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...e._zod.def,get shape(){const a={...e._zod.def.shape,...t};return Gs(this,"shape",a),a},checks:e._zod.def.checks};return ni(e,n)}function OF(e,t){const n=Bo(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Gs(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:[]});return ni(e,n)}function DF(e,t,n){const a=Bo(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)i[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return Gs(this,"shape",i),i},checks:[]});return ni(t,a)}function jF(e,t,n){const a=Bo(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)i[s]=new e({type:"nonoptional",innerType:r[s]});return Gs(this,"shape",i),i},checks:[]});return ni(t,a)}function Rl(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function bi(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function qf(e){return typeof e=="string"?e:e?.message}function ti(e,t,n){const a={...e,path:e.path??[]};if(!e.message){const r=qf(e.inst?._zod.def?.error?.(e))??qf(t?.error?.(e))??qf(n.customError?.(e))??qf(n.localeError?.(e))??"Invalid input";a.message=r}return delete a.inst,delete a.continue,t?.reportInput||delete a.input,a}function oy(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function sy(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Qu(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}function GJ(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function $F(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);return n}function LF(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function WJ(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return $F(t+n)}function KJ(e){return LF(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ZJ(e){const t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");const n=new Uint8Array(t.length/2);for(let a=0;a<t.length;a+=2)n[a/2]=Number.parseInt(t.slice(a,a+2),16);return n}function YJ(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}class qJ{constructor(...t){}}const MF=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:NF,Class:qJ,NUMBER_FORMAT_RANGES:TF,aborted:Rl,allowsEval:_F,assert:LJ,assertEqual:OJ,assertIs:jJ,assertNever:$J,assertNotEqual:DJ,assignProp:Gs,base64ToUint8Array:$F,base64urlToUint8Array:WJ,cached:cm,captureStackTrace:sk,cleanEnum:GJ,cleanRegex:ay,clone:ni,cloneDef:PJ,createTransparentProxy:VJ,defineLazy:Ht,esc:r_,escapeRegex:$o,extend:AF,finalizeIssue:ti,floatSafeRemainder:SF,getElementAtPath:UJ,getEnumValues:ok,getLengthableOrigin:sy,getParsedType:HJ,getSizableOrigin:oy,hexToUint8Array:ZJ,isObject:Ju,isPlainObject:Fl,issue:Qu,joinValues:Pe,jsonStringifyReplacer:ev,merge:OF,mergeDefs:Bo,normalizeParams:Ie,nullish:ec,numKeys:BJ,objectClone:MJ,omit:RF,optionalKeys:kF,partial:DF,pick:CF,prefixIssues:bi,primitiveTypes:EF,promiseAllObject:zJ,propertyKeyTypes:tv,randomString:FJ,required:jF,safeExtend:IF,shallowClone:iy,slugify:xF,stringifyPrimitive:ut,uint8ArrayToBase64:LF,uint8ArrayToBase64url:KJ,uint8ArrayToHex:YJ,unwrapMessage:qf},Symbol.toStringTag,{value:"Module"})),PF=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ev,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},lk=me("$ZodError",PF),Ma=me("$ZodError",PF,{Parent:Error});function ck(e,t=n=>n.message){const n={},a=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):a.push(t(r));return{formErrors:a,fieldErrors:n}}function uk(e,t=n=>n.message){const n={_errors:[]},a=r=>{for(const i of r.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(s=>a({issues:s}));else if(i.code==="invalid_key")a({issues:i.issues});else if(i.code==="invalid_element")a({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let s=n,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(s[u]=s[u]||{_errors:[]},s[u]._errors.push(t(i))):s[u]=s[u]||{_errors:[]},s=s[u],c++}}};return a(e),n}function UF(e,t=n=>n.message){const n={errors:[]},a=(r,i=[])=>{var s,c;for(const u of r.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(d=>a({issues:d},u.path));else if(u.code==="invalid_key")a({issues:u.issues},u.path);else if(u.code==="invalid_element")a({issues:u.issues},u.path);else{const d=[...i,...u.path];if(d.length===0){n.errors.push(t(u));continue}let m=n,h=0;for(;h<d.length;){const g=d[h],v=h===d.length-1;typeof g=="string"?(m.properties??(m.properties={}),(s=m.properties)[g]??(s[g]={errors:[]}),m=m.properties[g]):(m.items??(m.items=[]),(c=m.items)[g]??(c[g]={errors:[]}),m=m.items[g]),v&&m.errors.push(t(u)),h++}}};return a(e),n}function zF(e){const t=[],n=e.map(a=>typeof a=="object"?a.key:a);for(const a of n)typeof a=="number"?t.push(`[${a}]`):typeof a=="symbol"?t.push(`[${JSON.stringify(String(a))}]`):/[^\w$]/.test(a)?t.push(`[${JSON.stringify(a)}]`):(t.length&&t.push("."),t.push(a));return t.join("")}function FF(e){const t=[],n=[...e.issues].sort((a,r)=>(a.path??[]).length-(r.path??[]).length);for(const a of n)t.push(`✖ ${a.message}`),a.path?.length&&t.push(` → at ${zF(a.path)}`);return t.join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/winston-CJYQWdxS.js","assets/util-t-trnxQI.js","assets/index-DRz5BQNA.js","assets/path-BChWcjOf.js","assets/fs-u42MReIY.js","assets/path-MNZaYwxc.js","assets/index-BUXkns-K.js","assets/index-kPmN3fDk.js","assets/index-CfKE-Cf4.js","assets/llms-BCoxDIc3.js","assets/embeddings-D7vUVvZ5.js","assets/index-BuYBGFlF.js","assets/index-9nm0CCqb.js","assets/index-CrVavwoh.js","assets/browser-BGOI9nSM.js"])))=>i.map(i=>d[i]);
2
+ var oJ=Object.defineProperty;var sJ=(e,t,n)=>t in e?oJ(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Uf=(e,t,n)=>sJ(e,typeof t!="symbol"?t+"":t,n);function lJ(e,t){for(var n=0;n<t.length;n++){const a=t[n];if(typeof a!="string"&&!Array.isArray(a)){for(const r in a)if(r!=="default"&&!(r in e)){const i=Object.getOwnPropertyDescriptor(a,r);i&&Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:()=>a[r]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&a(s)}).observe(document,{childList:!0,subtree:!0});function n(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function a(r){if(r.ep)return;r.ep=!0;const i=n(r);fetch(r.href,i)}})();function ny(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function JTe(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function a(){var r=!1;try{r=this instanceof a}catch{}return r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(a){var r=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(n,a,r.get?r:{enumerable:!0,get:function(){return e[a]}})}),n}var LS={exports:{}},zf={};var sM;function cJ(){if(sM)return zf;sM=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(a,r,i){var s=null;if(i!==void 0&&(s=""+i),r.key!==void 0&&(s=""+r.key),"key"in r){i={};for(var c in r)c!=="key"&&(i[c]=r[c])}else i=r;return r=i.ref,{$$typeof:e,type:a,key:s,ref:r!==void 0?r:null,props:i}}return zf.Fragment=t,zf.jsx=n,zf.jsxs=n,zf}var lM;function uJ(){return lM||(lM=1,LS.exports=cJ()),LS.exports}var f=uJ();const dJ="modulepreload",fJ=function(e){return"/inspector/"+e},cM={},Jn=function(t,n,a){let r=Promise.resolve();if(n&&n.length>0){let u=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),c=s?.nonce||s?.getAttribute("nonce");r=u(n.map(d=>{if(d=fJ(d),d in cM)return;cM[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":dJ,m||(g.as="script"),g.crossOrigin="",g.href=d,c&&g.setAttribute("nonce",c),document.head.appendChild(g),m)return new Promise((v,x)=>{g.addEventListener("load",v),g.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${d}`)))})}))}function i(s){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=s,window.dispatchEvent(c),!c.defaultPrevented)throw s}return r.then(s=>{for(const c of s||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})};var pJ=Object.defineProperty,ze=(e,t)=>pJ(e,"name",{value:t,configurable:!0}),ks=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),Jc={};async function sF(){if(typeof process<"u")try{const e=await Jn(()=>import("./fs-u42MReIY.js").then(n=>n.f),[]),t=await Jn(()=>import("./path-MNZaYwxc.js").then(n=>n.p),[]);return{fs:e.default,path:t.default}}catch{return{fs:null,path:null}}return{fs:null,path:null}}ze(sF,"getNodeModules");var ha=null;function lF(){if(typeof ks<"u")try{ha=ks("winston")}catch{}}ze(lF,"loadWinstonSync");async function cF(){return ha||(ha=await Jn(()=>import("./winston-CJYQWdxS.js").then(e=>e.w),__vite__mapDeps([0,1,2,3,4,5]))),ha}ze(cF,"getWinston");var n_="mcp-use";function Xb(){try{return typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")||typeof globalThis.EdgeRuntime<"u"||typeof globalThis.Deno<"u"?!1:typeof process<"u"&&!0&&typeof __dirname<"u"}catch{return!1}}ze(Xb,"isNodeJSEnvironment");var Au,mJ=(Au=class{_level;name;constructor(t=n_,n="info"){this.name=t,this._level=n}shouldLog(t){const n=["error","warn","info","http","verbose","debug","silly"],a=n.indexOf(this._level);return n.indexOf(t)<=a}formatMessage(t,n){return`${new Date().toLocaleTimeString("en-US",{hour12:!1})} [${this.name}] ${t}: ${n}`}error(t){this.shouldLog("error")&&console.error(this.formatMessage("error",t))}warn(t){this.shouldLog("warn")&&console.warn(this.formatMessage("warn",t))}info(t){this.shouldLog("info")&&console.info(this.formatMessage("info",t))}debug(t){this.shouldLog("debug")&&console.debug(this.formatMessage("debug",t))}http(t){this.shouldLog("http")&&console.log(this.formatMessage("http",t))}verbose(t){this.shouldLog("verbose")&&console.log(this.formatMessage("verbose",t))}silly(t){this.shouldLog("silly")&&console.log(this.formatMessage("silly",t))}get level(){return this._level}set level(t){this._level=t}},ze(Au,"SimpleConsoleLogger"),Au);function kb(e){switch((typeof process<"u"&&Jc?e:void 0)?.trim()){case"2":return"debug";case"1":return"info";default:return"info"}}ze(kb,"resolveLevel");var ko,uF=(ko=class{static get(t=n_){if(!Xb()){if(!this.simpleInstances[t]){const n=typeof process<"u"&&Jc?.DEBUG||void 0;this.simpleInstances[t]=new mJ(t,kb(n))}return this.simpleInstances[t]}if(!this.instances[t]){if(!ha)throw new Error("Winston not loaded - call Logger.configure() first");const{createLogger:n,format:a}=ha,{combine:r,timestamp:i,label:s,colorize:c,splat:u}=a;this.instances[t]=n({level:kb(Jc.DEBUG),format:r(c(),u(),s({label:t}),i({format:"HH:mm:ss"}),this.getFormatter()),transports:[new ha.transports.Console]})}return this.instances[t]}static getFormatter(){if(!ha)throw new Error("Winston not loaded");const{format:t}=ha,{printf:n}=t,a=n(({level:s,message:c,label:u,timestamp:d})=>`${d} [${u}] ${s}: ${c}`),r=n(({level:s,message:c,label:u,timestamp:d})=>`${d} [${u}] ${s.toUpperCase()}: ${c}`),i=n(({level:s,message:c,label:u,timestamp:d})=>`${d} [${u}] ${s.toUpperCase()}: ${c}`);switch(this.currentFormat){case"minimal":return a;case"detailed":return r;case"emoji":return i;default:return a}}static async configure(t={}){const{level:n,console:a=!0,file:r,format:i="minimal"}=t,s=typeof process<"u"&&Jc?.DEBUG||void 0,c=n??kb(s);if(this.currentFormat=i,!Xb()){Object.values(this.simpleInstances).forEach(y=>{y.level=c});return}if(await cF(),!ha)throw new Error("Failed to load winston");const u=this.get();u.level=c;const d=u;if(d.clear(),a&&d.add(new ha.transports.Console),r){const{fs:y,path:E}=await sF();if(y&&E){const _=E.dirname(E.resolve(r));y.existsSync(_)||y.mkdirSync(_,{recursive:!0}),d.add(new ha.transports.File({filename:r}))}}const{format:m}=ha,{combine:h,timestamp:g,label:v,colorize:x,splat:S}=m;Object.values(this.instances).forEach(y=>{y&&"format"in y&&(y.level=c,y.format=h(x(),S(),v({label:n_}),g({format:"HH:mm:ss"}),this.getFormatter()))})}static setDebug(t){let n;t===2||t===!0?n="debug":n="info",Object.values(this.simpleInstances).forEach(a=>{a.level=n}),Object.values(this.instances).forEach(a=>{a&&(a.level=n)}),typeof process<"u"&&Jc&&(Jc.DEBUG=t?t===!0?"2":String(t):"0")}static setFormat(t){this.currentFormat=t,this.configure({format:t})}},ze(ko,"Logger"),Uf(ko,"instances",{}),Uf(ko,"simpleInstances",{}),Uf(ko,"currentFormat","minimal"),ko);Xb()&&(lF(),ha&&uF.configure());var Ce=uF.get(),Tb={},dF=typeof globalThis.Deno<"u";function hJ(e){return dF?globalThis.Deno.env.get(e):Tb[e]}ze(hJ,"getEnv");function gJ(){return dF?globalThis.Deno.cwd():process.cwd()}ze(gJ,"getCwd");function El(){return globalThis.crypto.randomUUID()}ze(El,"generateUUID");var bJ="1.11.0-canary.19";function Jb(){return bJ}ze(Jb,"getPackageVersion");var Iu,Ci=(Iu=class{},ze(Iu,"BaseTelemetryEvent"),Iu),Ou,vJ=(Ou=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(Ou,"MCPAgentExecutionEvent"),Ou);function fF(e,t){const n=Array.from(e.registrations.tools.values()),a=Array.from(e.registrations.prompts.values()),r=Array.from(e.registrations.resources.values()),i=Array.from(e.registrations.resourceTemplates.values()),s=r.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,uri:m.config.uri??null,mime_type:m.config.mimeType??null})),c=s.filter(m=>m.mime_type==="text/html+skybridge"),u=s.filter(m=>m.mime_type==="text/uri-list"||m.mime_type==="text/html"),d=s.filter(m=>m.mime_type==="text/html+mcp");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(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,input_schema:m.config.schema?JSON.stringify(m.config.schema):null,output_schema:m.config.outputSchema?JSON.stringify(m.config.outputSchema):null})):null,resources:s.length>0?s:null,prompts:a.length>0?a.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null,args:m.config.args?JSON.stringify(m.config.args):null})):null,templates:i.length>0?i.map(m=>({name:m.config.name,title:m.config.title??null,description:m.config.description??null})):null,capabilities:{logging:!0,resources:{subscribe:!0,listChanged:!0}},appsSdkResources:c.length>0?c:null,appsSdkResourcesNumber:c.length,mcpUiResources:u.length>0?u:null,mcpUiResourcesNumber:u.length,mcpAppsResources:d.length>0?d:null,mcpAppsResourcesNumber:d.length}}ze(fF,"createServerRunEventData");var Du,yJ=(Du=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(Du,"ServerRunEvent"),Du),ju,wJ=(ju=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(ju,"ServerInitializeEvent"),ju),$u,SJ=($u=class extends Ci{constructor(t){super(),this.data=t}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}}},ze($u,"ServerToolCallEvent"),$u),Lu,xJ=(Lu=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(Lu,"ServerResourceCallEvent"),Lu),Mu,_J=(Mu=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(Mu,"ServerPromptCallEvent"),Mu),Pu,EJ=(Pu=class extends Ci{constructor(t){super(),this.data=t}get name(){return`server_context_${this.data.contextType}`}get properties(){return{context_type:this.data.contextType,notification_type:this.data.notificationType??null}}},ze(Pu,"ServerContextEvent"),Pu),Uu,kJ=(Uu=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(Uu,"MCPClientInitEvent"),Uu),zu,TJ=(zu=class extends Ci{constructor(t){super(),this.data=t}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}}},ze(zu,"ConnectorInitEvent"),zu),Fu,NJ=(Fu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"client_add_server"}get properties(){const{serverName:t,serverConfig:n}=this.data,a=n.url;return{server_name:t,server_url_domain:a?this._extractHostname(a):null,transport:n.transport??null,has_auth:!!(n.authToken||n.authProvider)}}_extractHostname(t){try{return new URL(t).hostname}catch{return null}}},ze(Fu,"ClientAddServerEvent"),Fu),Bu,CJ=(Bu=class extends Ci{constructor(t){super(),this.data=t}get name(){return"client_remove_server"}get properties(){return{server_name:this.data.serverName}}},ze(Bu,"ClientRemoveServerEvent"),Bu);function pF(e){return e._llm_type||e.constructor.name.toLowerCase()}ze(pF,"getModelProvider");function mF(e){if("_identifyingParams"in e){const t=e._identifyingParams;if(typeof t=="object"&&t!==null){for(const n of["model","modelName","model_name","modelId","model_id","deploymentName","deployment_name"])if(n in t)return String(t[n])}}return e.model||e.modelName||e.constructor.name}ze(mF,"getModelName");function RJ(e){return[pF(e),mF(e)]}ze(RJ,"extractModelInfo");var uM="mcp_use_user_id";function hF(){try{return typeof globalThis.Bun<"u"?"bun":typeof globalThis.Deno<"u"?"deno":typeof navigator<"u"&&navigator.userAgent?.includes("Cloudflare-Workers")?"cloudflare-workers":typeof globalThis.EdgeRuntime<"u"?"edge":typeof window<"u"&&typeof document<"u"?"browser":typeof process<"u"&&typeof process.versions?.node<"u"?"node":"unknown"}catch{return"unknown"}}ze(hF,"detectRuntimeEnvironment");function gF(e){switch(e){case"node":case"bun":return"filesystem";case"browser":try{if(typeof localStorage<"u")return localStorage.setItem("__mcp_use_test__","1"),localStorage.removeItem("__mcp_use_test__"),"localStorage"}catch{}return"session-only";case"deno":return"session-only";default:return"session-only"}}ze(gF,"getStorageCapability");var MS=null;function bF(){return MS===null&&(MS=hF()),MS}ze(bF,"getRuntimeEnvironment");var Hu,AJ=(Hu=class{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,a=setTimeout(()=>n.abort(),this.timeout),r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(a),!r.ok)throw new Error(`HTTP error! status: ${r.status}`)}catch(n){Ce.debug(`Failed to send Scarf event: ${n}`)}}},ze(Hu,"ScarfEventLogger"),Hu),gi,vF=(gi=class{PROJECT_API_KEY="phc_lyTtbYwvkdSbrcMQNPiKiiRWrrM1seyKIMjycSvItEI";HOST="https://eu.i.posthog.com";SCARF_GATEWAY_URL="https://mcpuse.gateway.scarf.sh/events-ts";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogNodeClient=null;_posthogBrowserClient=null;_posthogLoading=null;_scarfClient=null;_runtimeEnvironment;_storageCapability;_source;_userIdPath=null;_versionDownloadPath=null;constructor(){this._runtimeEnvironment=bF(),this._storageCapability=gF(this._runtimeEnvironment),this._source=typeof process<"u"&&Tb?.MCP_USE_TELEMETRY_SOURCE||this._runtimeEnvironment;const t=this._checkTelemetryDisabled(),n=this._runtimeEnvironment!=="unknown";if(t)this._posthogNodeClient=null,this._posthogBrowserClient=null,this._scarfClient=null,Ce.debug("Telemetry disabled via environment/localStorage");else if(!n)this._posthogNodeClient=null,this._posthogBrowserClient=null,this._scarfClient=null,Ce.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`);else{if(Ce.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."),this._posthogLoading=this._initPostHog(),this._runtimeEnvironment!=="browser")try{this._scarfClient=new AJ(this.SCARF_GATEWAY_URL,3e3)}catch(a){Ce.warn(`Failed to initialize Scarf telemetry: ${a}`),this._scarfClient=null}else this._scarfClient=null;this._storageCapability==="filesystem"&&this._scarfClient&&setTimeout(()=>{this.trackPackageDownload({triggered_by:"initialization"}).catch(a=>Ce.debug(`Failed to track package download: ${a}`))},0)}}_checkTelemetryDisabled(){return typeof process<"u"&&Tb?.MCP_USE_ANONYMIZED_TELEMETRY?.toLowerCase()==="false"||typeof localStorage<"u"&&localStorage.getItem("MCP_USE_ANONYMIZED_TELEMETRY")==="false"}async _initPostHog(){this._runtimeEnvironment==="browser"?await this._initPostHogBrowser():await this._initPostHogNode()}async _initPostHogBrowser(){try{const t=await Jn(()=>import("./module-D4IOASh4.js"),[]),n=t.default||t.posthog;if(!n||typeof n.init!="function")throw new Error("posthog-js module did not export expected interface");n.init(this.PROJECT_API_KEY,{api_host:this.HOST,persistence:"localStorage",autocapture:!1,capture_pageview:!1,disable_session_recording:!0,loaded:ze(()=>{Ce.debug("PostHog browser client initialized")},"loaded")}),this._posthogBrowserClient=n}catch(t){Ce.warn(`Failed to initialize PostHog browser telemetry: ${t}`),this._posthogBrowserClient=null}}async _initPostHogNode(){try{const{PostHog:t}=await Jn(async()=>{const{PostHog:r}=await import("./posthog-node-CuYhrq1Q.js");return{PostHog:r}},[]),n=["cloudflare-workers","edge","deno"].includes(this._runtimeEnvironment),a={host:this.HOST,disableGeoip:!1};n&&(a.flushAt=1,a.flushInterval=0),this._posthogNodeClient=new t(this.PROJECT_API_KEY,a),Ce.debug("PostHog Node.js client initialized")}catch(t){Ce.warn(`Failed to initialize PostHog Node.js telemetry: ${t}`),this._posthogNodeClient=null}}get runtimeEnvironment(){return this._runtimeEnvironment}get storageCapability(){return this._storageCapability}static getInstance(){return gi.instance||(gi.instance=new gi),gi.instance}setSource(t){this._source=t,Ce.debug(`Telemetry source set to: ${t}`)}getSource(){return this._source}get isEnabled(){return this._posthogNodeClient!==null||this._posthogBrowserClient!==null||this._scarfClient!==null}get userId(){if(this._currUserId)return this._currUserId;try{switch(this._storageCapability){case"filesystem":this._currUserId=this._getUserIdFromFilesystem();break;case"localStorage":this._currUserId=this._getUserIdFromLocalStorage();break;case"session-only":default:try{this._currUserId=`session-${El()}`}catch{this._currUserId=`session-${Date.now()}-${Math.random().toString(36).substring(2,15)}`}break}}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}_getUserIdFromFilesystem(){try{let t,n,a;try{t=ks("fs"),n=ks("os"),a=ks("path")}catch{try{return`session-${El()}`}catch{return`session-${Date.now()}-${Math.random().toString(36).substring(2,15)}`}}if(this._userIdPath||(this._userIdPath=a.join(this._getCacheHome(n,a),"mcp_use_3","telemetry_user_id")),!t.existsSync(this._userIdPath)){t.mkdirSync(a.dirname(this._userIdPath),{recursive:!0});let s;try{s=El()}catch{s=`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}return t.writeFileSync(this._userIdPath,s),s}return t.readFileSync(this._userIdPath,"utf-8").trim()}catch{try{return`session-${El()}`}catch{return`session-${Date.now()}-${Math.random().toString(36).substring(2,15)}`}}}_getUserIdFromLocalStorage(){try{let t=localStorage.getItem(uM);if(!t){try{t=El()}catch{t=`${Date.now()}-${Math.random().toString(36).substring(2,15)}`}localStorage.setItem(uM,t)}return t}catch{let n;try{n=`session-${El()}`}catch{n=`session-${Date.now()}-${Math.random().toString(36).substring(2,15)}`}return n}}_getCacheHome(t,n){const a=Tb.XDG_CACHE_HOME;if(a&&n.isAbsolute(a))return a;const r=t.homedir();return n.join(r,".cache")}async capture(t){if(this._posthogLoading&&await this._posthogLoading,!this._posthogNodeClient&&!this._posthogBrowserClient&&!this._scarfClient)return;const n=this.userId,a={...t.properties};if(a.mcp_use_version=Jb(),a.language="typescript",a.source=this._source,a.runtime=this._runtimeEnvironment,this._posthogNodeClient)try{this._posthogNodeClient.capture({distinctId:n,event:t.name,properties:a})}catch(r){Ce.debug(`Failed to track PostHog Node event ${t.name}: ${r}`)}if(this._posthogBrowserClient)try{this._posthogBrowserClient.capture(t.name,{...a,distinct_id:n})}catch(r){Ce.debug(`Failed to track PostHog Browser event ${t.name}: ${r}`)}if(this._scarfClient)try{const r={...a,user_id:n,event:t.name};await this._scarfClient.logEvent(r)}catch(r){Ce.debug(`Failed to track Scarf event ${t.name}: ${r}`)}}async trackPackageDownload(t){return this._trackPackageDownloadInternal(this.userId,t)}async _trackPackageDownloadInternal(t,n){if(this._scarfClient&&this._storageCapability==="filesystem")try{const a=ks("fs"),r=ks("path"),i=ks("os");this._versionDownloadPath||(this._versionDownloadPath=r.join(this._getCacheHome(i,r),"mcp_use","download_version"));const s=Jb();let c=!1,u=!1;if(!a.existsSync(this._versionDownloadPath))c=!0,u=!0,a.mkdirSync(r.dirname(this._versionDownloadPath),{recursive:!0}),a.writeFileSync(this._versionDownloadPath,s);else{const d=a.readFileSync(this._versionDownloadPath,"utf-8").trim();s>d&&(c=!0,u=!1,a.writeFileSync(this._versionDownloadPath,s))}if(c){Ce.debug(`Tracking package download event with properties: ${JSON.stringify(n)}`);const d={...n||{}};d.mcp_use_version=s,d.user_id=t,d.event="package_download",d.first_download=u,d.language="typescript",d.source=this._source,d.runtime=this._runtimeEnvironment,await this._scarfClient.logEvent(d)}}catch(a){Ce.debug(`Failed to track Scarf package_download event: ${a}`)}}async trackAgentExecution(t){if(!this.isEnabled)return;const n=new vJ(t);await this.capture(n)}async trackServerRunFromServer(t,n){if(!this.isEnabled)return;const a=fF(t,n),r=new yJ(a);await this.capture(r)}async trackServerInitialize(t){if(!this.isEnabled)return;const n=new wJ(t);await this.capture(n)}async trackServerToolCall(t){if(!this.isEnabled)return;const n=new SJ(t);await this.capture(n)}async trackServerResourceCall(t){if(!this.isEnabled)return;const n=new xJ(t);await this.capture(n)}async trackServerPromptCall(t){if(!this.isEnabled)return;const n=new _J(t);await this.capture(n)}async trackServerContext(t){if(!this.isEnabled)return;const n=new EJ(t);await this.capture(n)}async trackMCPClientInit(t){if(!this.isEnabled)return;const n=new kJ(t);await this.capture(n)}async trackConnectorInit(t){if(!this.isEnabled)return;const n=new TJ(t);await this.capture(n)}async trackClientAddServer(t,n){if(!this.isEnabled)return;const a=new NJ({serverName:t,serverConfig:n});await this.capture(a)}async trackClientRemoveServer(t){if(!this.isEnabled)return;const n=new CJ({serverName:t});await this.capture(n)}async trackUseMcpConnection(t){this.isEnabled&&await this.capture({name:"usemcp_connection",properties:{url_domain:new URL(t.url).hostname,transport_type:t.transportType,success:t.success,error_type:t.errorType??null,connection_time_ms:t.connectionTimeMs??null,has_oauth:t.hasOAuth,has_sampling:t.hasSampling,has_elicitation:t.hasElicitation}})}async trackUseMcpToolCall(t){this.isEnabled&&await this.capture({name:"usemcp_tool_call",properties:{tool_name:t.toolName,success:t.success,error_type:t.errorType??null,execution_time_ms:t.executionTimeMs??null}})}async trackUseMcpResourceRead(t){this.isEnabled&&await this.capture({name:"usemcp_resource_read",properties:{resource_uri_scheme:t.resourceUri.split(":")[0],success:t.success,error_type:t.errorType??null}})}identify(t,n){if(this._posthogBrowserClient)try{this._posthogBrowserClient.identify(t,n)}catch(a){Ce.debug(`Failed to identify user: ${a}`)}}reset(){if(this._posthogBrowserClient)try{this._posthogBrowserClient.reset()}catch(t){Ce.debug(`Failed to reset user: ${t}`)}this._currUserId=null}flush(){if(this._posthogNodeClient)try{this._posthogNodeClient.flush(),Ce.debug("PostHog client telemetry queue flushed")}catch(t){Ce.debug(`Failed to flush PostHog client: ${t}`)}}shutdown(){if(this._posthogNodeClient)try{this._posthogNodeClient.shutdown(),Ce.debug("PostHog client shutdown successfully")}catch(t){Ce.debug(`Error shutting down PostHog client: ${t}`)}}},ze(gi,"Telemetry"),Uf(gi,"instance",null),gi),zi=vF;function IJ(e){zi.getInstance().setSource(e)}ze(IJ,"setTelemetrySource");const yF=Object.freeze({status:"aborted"});function me(e,t,n){function a(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:s,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);const d=s.prototype,m=Object.keys(d);for(let h=0;h<m.length;h++){const g=m[h];g in c||(c[g]=d[g].bind(c))}}const r=n?.Parent??Object;class i extends r{}Object.defineProperty(i,"name",{value:e});function s(c){var u;const d=n?.Parent?new i:this;a(d,c),(u=d._zod).deferred??(u.deferred=[]);for(const m of d._zod.deferred)m();return d}return Object.defineProperty(s,"init",{value:a}),Object.defineProperty(s,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}const wF=Symbol("zod_brand");class $l extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ry extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const Qb={};function Gr(e){return e&&Object.assign(Qb,e),Qb}function OJ(e){return e}function DJ(e){return e}function jJ(e){}function $J(e){throw new Error("Unexpected value in exhaustive check")}function LJ(e){}function ok(e){const t=Object.values(e).filter(a=>typeof a=="number");return Object.entries(e).filter(([a,r])=>t.indexOf(+a)===-1).map(([a,r])=>r)}function Pe(e,t="|"){return e.map(n=>ut(n)).join(t)}function ev(e,t){return typeof t=="bigint"?t.toString():t}function cm(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function ec(e){return e==null}function ay(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function SF(e,t){const n=(e.toString().split(".")[1]||"").length,a=t.toString();let r=(a.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(a)){const u=a.match(/\d?e-(\d?)/);u?.[1]&&(r=Number.parseInt(u[1]))}const i=n>r?n:r,s=Number.parseInt(e.toFixed(i).replace(".","")),c=Number.parseInt(t.toFixed(i).replace(".",""));return s%c/10**i}const dM=Symbol("evaluating");function Ht(e,t,n){let a;Object.defineProperty(e,t,{get(){if(a!==dM)return a===void 0&&(a=dM,a=n()),a},set(r){Object.defineProperty(e,t,{value:r})},configurable:!0})}function MJ(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Gs(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Bo(...e){const t={};for(const n of e){const a=Object.getOwnPropertyDescriptors(n);Object.assign(t,a)}return Object.defineProperties({},t)}function PJ(e){return Bo(e._zod.def)}function UJ(e,t){return t?t.reduce((n,a)=>n?.[a],e):e}function zJ(e){const t=Object.keys(e),n=t.map(a=>e[a]);return Promise.all(n).then(a=>{const r={};for(let i=0;i<t.length;i++)r[t[i]]=a[i];return r})}function FJ(e=10){const t="abcdefghijklmnopqrstuvwxyz";let n="";for(let a=0;a<e;a++)n+=t[Math.floor(Math.random()*t.length)];return n}function r_(e){return JSON.stringify(e)}function xF(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const sk="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ju(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const _F=cm(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Fl(e){if(Ju(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Ju(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function iy(e){return Fl(e)?{...e}:Array.isArray(e)?[...e]:e}function BJ(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}const HJ=e=>{const t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},tv=new Set(["string","number","symbol"]),EF=new Set(["string","number","bigint","boolean","symbol","undefined"]);function $o(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ni(e,t,n){const a=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(a._zod.parent=e),a}function Ie(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function VJ(e){let t;return new Proxy({},{get(n,a,r){return t??(t=e()),Reflect.get(t,a,r)},set(n,a,r,i){return t??(t=e()),Reflect.set(t,a,r,i)},has(n,a){return t??(t=e()),Reflect.has(t,a)},deleteProperty(n,a){return t??(t=e()),Reflect.deleteProperty(t,a)},ownKeys(n){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(n,a){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,a)},defineProperty(n,a,r){return t??(t=e()),Reflect.defineProperty(t,a,r)}})}function ut(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function kF(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const TF={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},NF={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function CF(e,t){const n=e._zod.def,a=Bo(e._zod.def,{get shape(){const r={};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&(r[i]=n.shape[i])}return Gs(this,"shape",r),r},checks:[]});return ni(e,a)}function RF(e,t){const n=e._zod.def,a=Bo(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const i in t){if(!(i in n.shape))throw new Error(`Unrecognized key: "${i}"`);t[i]&&delete r[i]}return Gs(this,"shape",r),r},checks:[]});return ni(e,a)}function AF(e,t){if(!Fl(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const r=Bo(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Gs(this,"shape",i),i},checks:[]});return ni(e,r)}function IF(e,t){if(!Fl(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...e._zod.def,get shape(){const a={...e._zod.def.shape,...t};return Gs(this,"shape",a),a},checks:e._zod.def.checks};return ni(e,n)}function OF(e,t){const n=Bo(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Gs(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:[]});return ni(e,n)}function DF(e,t,n){const a=Bo(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=e?new e({type:"optional",innerType:r[s]}):r[s])}else for(const s in r)i[s]=e?new e({type:"optional",innerType:r[s]}):r[s];return Gs(this,"shape",i),i},checks:[]});return ni(t,a)}function jF(e,t,n){const a=Bo(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const s in n){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(i[s]=new e({type:"nonoptional",innerType:r[s]}))}else for(const s in r)i[s]=new e({type:"nonoptional",innerType:r[s]});return Gs(this,"shape",i),i},checks:[]});return ni(t,a)}function Rl(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function bi(e,t){return t.map(n=>{var a;return(a=n).path??(a.path=[]),n.path.unshift(e),n})}function qf(e){return typeof e=="string"?e:e?.message}function ti(e,t,n){const a={...e,path:e.path??[]};if(!e.message){const r=qf(e.inst?._zod.def?.error?.(e))??qf(t?.error?.(e))??qf(n.customError?.(e))??qf(n.localeError?.(e))??"Invalid input";a.message=r}return delete a.inst,delete a.continue,t?.reportInput||delete a.input,a}function oy(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function sy(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Qu(...e){const[t,n,a]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:a}:{...t}}function GJ(e){return Object.entries(e).filter(([t,n])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function $F(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);return n}function LF(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function WJ(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n="=".repeat((4-t.length%4)%4);return $F(t+n)}function KJ(e){return LF(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ZJ(e){const t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");const n=new Uint8Array(t.length/2);for(let a=0;a<t.length;a+=2)n[a/2]=Number.parseInt(t.slice(a,a+2),16);return n}function YJ(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}class qJ{constructor(...t){}}const MF=Object.freeze(Object.defineProperty({__proto__:null,BIGINT_FORMAT_RANGES:NF,Class:qJ,NUMBER_FORMAT_RANGES:TF,aborted:Rl,allowsEval:_F,assert:LJ,assertEqual:OJ,assertIs:jJ,assertNever:$J,assertNotEqual:DJ,assignProp:Gs,base64ToUint8Array:$F,base64urlToUint8Array:WJ,cached:cm,captureStackTrace:sk,cleanEnum:GJ,cleanRegex:ay,clone:ni,cloneDef:PJ,createTransparentProxy:VJ,defineLazy:Ht,esc:r_,escapeRegex:$o,extend:AF,finalizeIssue:ti,floatSafeRemainder:SF,getElementAtPath:UJ,getEnumValues:ok,getLengthableOrigin:sy,getParsedType:HJ,getSizableOrigin:oy,hexToUint8Array:ZJ,isObject:Ju,isPlainObject:Fl,issue:Qu,joinValues:Pe,jsonStringifyReplacer:ev,merge:OF,mergeDefs:Bo,normalizeParams:Ie,nullish:ec,numKeys:BJ,objectClone:MJ,omit:RF,optionalKeys:kF,partial:DF,pick:CF,prefixIssues:bi,primitiveTypes:EF,promiseAllObject:zJ,propertyKeyTypes:tv,randomString:FJ,required:jF,safeExtend:IF,shallowClone:iy,slugify:xF,stringifyPrimitive:ut,uint8ArrayToBase64:LF,uint8ArrayToBase64url:KJ,uint8ArrayToHex:YJ,unwrapMessage:qf},Symbol.toStringTag,{value:"Module"})),PF=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,ev,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},lk=me("$ZodError",PF),Ma=me("$ZodError",PF,{Parent:Error});function ck(e,t=n=>n.message){const n={},a=[];for(const r of e.issues)r.path.length>0?(n[r.path[0]]=n[r.path[0]]||[],n[r.path[0]].push(t(r))):a.push(t(r));return{formErrors:a,fieldErrors:n}}function uk(e,t=n=>n.message){const n={_errors:[]},a=r=>{for(const i of r.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(s=>a({issues:s}));else if(i.code==="invalid_key")a({issues:i.issues});else if(i.code==="invalid_element")a({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let s=n,c=0;for(;c<i.path.length;){const u=i.path[c];c===i.path.length-1?(s[u]=s[u]||{_errors:[]},s[u]._errors.push(t(i))):s[u]=s[u]||{_errors:[]},s=s[u],c++}}};return a(e),n}function UF(e,t=n=>n.message){const n={errors:[]},a=(r,i=[])=>{var s,c;for(const u of r.issues)if(u.code==="invalid_union"&&u.errors.length)u.errors.map(d=>a({issues:d},u.path));else if(u.code==="invalid_key")a({issues:u.issues},u.path);else if(u.code==="invalid_element")a({issues:u.issues},u.path);else{const d=[...i,...u.path];if(d.length===0){n.errors.push(t(u));continue}let m=n,h=0;for(;h<d.length;){const g=d[h],v=h===d.length-1;typeof g=="string"?(m.properties??(m.properties={}),(s=m.properties)[g]??(s[g]={errors:[]}),m=m.properties[g]):(m.items??(m.items=[]),(c=m.items)[g]??(c[g]={errors:[]}),m=m.items[g]),v&&m.errors.push(t(u)),h++}}};return a(e),n}function zF(e){const t=[],n=e.map(a=>typeof a=="object"?a.key:a);for(const a of n)typeof a=="number"?t.push(`[${a}]`):typeof a=="symbol"?t.push(`[${JSON.stringify(String(a))}]`):/[^\w$]/.test(a)?t.push(`[${JSON.stringify(a)}]`):(t.length&&t.push("."),t.push(a));return t.join("")}function FF(e){const t=[],n=[...e.issues].sort((a,r)=>(a.path??[]).length-(r.path??[]).length);for(const a of n)t.push(`✖ ${a.message}`),a.path?.length&&t.push(` → at ${zF(a.path)}`);return t.join(`
3
3
  `)}const um=e=>(t,n,a,r)=>{const i=a?Object.assign(a,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new $l;if(s.issues.length){const c=new(r?.Err??e)(s.issues.map(u=>ti(u,i,Gr())));throw sk(c,r?.callee),c}return s.value},a_=um(Ma),dm=e=>async(t,n,a,r)=>{const i=a?Object.assign(a,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){const c=new(r?.Err??e)(s.issues.map(u=>ti(u,i,Gr())));throw sk(c,r?.callee),c}return s.value},i_=dm(Ma),fm=e=>(t,n,a)=>{const r=a?{...a,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},r);if(i instanceof Promise)throw new $l;return i.issues.length?{success:!1,error:new(e??lk)(i.issues.map(s=>ti(s,r,Gr())))}:{success:!0,data:i.value}},dk=fm(Ma),pm=e=>async(t,n,a)=>{const r=a?Object.assign(a,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>ti(s,r,Gr())))}:{success:!0,data:i.value}},BF=pm(Ma),fk=e=>(t,n,a)=>{const r=a?Object.assign(a,{direction:"backward"}):{direction:"backward"};return um(e)(t,n,r)},XJ=fk(Ma),pk=e=>(t,n,a)=>um(e)(t,n,a),JJ=pk(Ma),mk=e=>async(t,n,a)=>{const r=a?Object.assign(a,{direction:"backward"}):{direction:"backward"};return dm(e)(t,n,r)},QJ=mk(Ma),hk=e=>async(t,n,a)=>dm(e)(t,n,a),eQ=hk(Ma),gk=e=>(t,n,a)=>{const r=a?Object.assign(a,{direction:"backward"}):{direction:"backward"};return fm(e)(t,n,r)},tQ=gk(Ma),bk=e=>(t,n,a)=>fm(e)(t,n,a),nQ=bk(Ma),vk=e=>async(t,n,a)=>{const r=a?Object.assign(a,{direction:"backward"}):{direction:"backward"};return pm(e)(t,n,r)},rQ=vk(Ma),yk=e=>async(t,n,a)=>pm(e)(t,n,a),aQ=yk(Ma),HF=/^[cC][^\s-]{8,}$/,VF=/^[0-9a-z]+$/,GF=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,WF=/^[0-9a-vA-V]{20}$/,KF=/^[A-Za-z0-9]{27}$/,ZF=/^[a-zA-Z0-9_-]{21}$/,YF=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,iQ=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,qF=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ed=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,oQ=ed(4),sQ=ed(6),lQ=ed(7),XF=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,cQ=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,uQ=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,JF=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,dQ=JF,fQ=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,pQ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function QF(){return new RegExp(pQ,"u")}const e3=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,t3=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,n3=e=>{const t=$o(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},r3=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,a3=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,i3=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,wk=/^[A-Za-z0-9_-]*$/,o3=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,s3=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,l3=/^\+(?:[0-9]){6,14}[0-9]$/,c3="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",u3=new RegExp(`^${c3}$`);function d3(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function f3(e){return new RegExp(`^${d3(e)}$`)}function p3(e){const t=d3({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const a=`${t}(?:${n.join("|")})`;return new RegExp(`^${c3}T(?:${a})$`)}const m3=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},h3=/^-?\d+n?$/,g3=/^-?\d+$/,b3=/^-?\d+(?:\.\d+)?/,v3=/^(?:true|false)$/i,y3=/^null$/i,w3=/^undefined$/i,S3=/^[^A-Z]*$/,x3=/^[^a-z]*$/,_3=/^[0-9a-fA-F]*$/;function mm(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function hm(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}const mQ=/^[0-9a-fA-F]{32}$/,hQ=mm(22,"=="),gQ=hm(22),bQ=/^[0-9a-fA-F]{40}$/,vQ=mm(27,"="),yQ=hm(27),wQ=/^[0-9a-fA-F]{64}$/,SQ=mm(43,"="),xQ=hm(43),_Q=/^[0-9a-fA-F]{96}$/,EQ=mm(64,""),kQ=hm(64),TQ=/^[0-9a-fA-F]{128}$/,NQ=mm(86,"=="),CQ=hm(86),Sk=Object.freeze(Object.defineProperty({__proto__:null,base64:i3,base64url:wk,bigint:h3,boolean:v3,browserEmail:fQ,cidrv4:r3,cidrv6:a3,cuid:HF,cuid2:VF,date:u3,datetime:p3,domain:s3,duration:YF,e164:l3,email:XF,emoji:QF,extendedDuration:iQ,guid:qF,hex:_3,hostname:o3,html5Email:cQ,idnEmail:dQ,integer:g3,ipv4:e3,ipv6:t3,ksuid:KF,lowercase:S3,mac:n3,md5_base64:hQ,md5_base64url:gQ,md5_hex:mQ,nanoid:ZF,null:y3,number:b3,rfc5322Email:uQ,sha1_base64:vQ,sha1_base64url:yQ,sha1_hex:bQ,sha256_base64:SQ,sha256_base64url:xQ,sha256_hex:wQ,sha384_base64:EQ,sha384_base64url:kQ,sha384_hex:_Q,sha512_base64:NQ,sha512_base64url:CQ,sha512_hex:TQ,string:m3,time:f3,ulid:GF,undefined:w3,unicodeEmail:JF,uppercase:x3,uuid:ed,uuid4:oQ,uuid6:sQ,uuid7:lQ,xid:WF},Symbol.toStringTag,{value:"Module"})),zn=me("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),E3={number:"number",bigint:"bigint",object:"date"},xk=me("$ZodCheckLessThan",(e,t)=>{zn.init(e,t);const n=E3[typeof t.value];e._zod.onattach.push(a=>{const r=a._zod.bag,i=(t.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?r.maximum=t.value:r.exclusiveMaximum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value<=t.value:a.value<t.value)||a.issues.push({origin:n,code:"too_big",maximum:t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),_k=me("$ZodCheckGreaterThan",(e,t)=>{zn.init(e,t);const n=E3[typeof t.value];e._zod.onattach.push(a=>{const r=a._zod.bag,i=(t.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?r.minimum=t.value:r.exclusiveMinimum=t.value)}),e._zod.check=a=>{(t.inclusive?a.value>=t.value:a.value>t.value)||a.issues.push({origin:n,code:"too_small",minimum:t.value,input:a.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),k3=me("$ZodCheckMultipleOf",(e,t)=>{zn.init(e,t),e._zod.onattach.push(n=>{var a;(a=n._zod.bag).multipleOf??(a.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):SF(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),T3=me("$ZodCheckNumberFormat",(e,t)=>{zn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),a=n?"int":"number",[r,i]=TF[t.format];e._zod.onattach.push(s=>{const c=s._zod.bag;c.format=t.format,c.minimum=r,c.maximum=i,n&&(c.pattern=g3)}),e._zod.check=s=>{const c=s.value;if(n){if(!Number.isInteger(c)){s.issues.push({expected:a,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?s.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,continue:!t.abort}):s.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:a,continue:!t.abort});return}}c<r&&s.issues.push({origin:"number",input:c,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),c>i&&s.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inst:e})}}),N3=me("$ZodCheckBigIntFormat",(e,t)=>{zn.init(e,t);const[n,a]=NF[t.format];e._zod.onattach.push(r=>{const i=r._zod.bag;i.format=t.format,i.minimum=n,i.maximum=a}),e._zod.check=r=>{const i=r.value;i<n&&r.issues.push({origin:"bigint",input:i,code:"too_small",minimum:n,inclusive:!0,inst:e,continue:!t.abort}),i>a&&r.issues.push({origin:"bigint",input:i,code:"too_big",maximum:a,inst:e})}}),C3=me("$ZodCheckMaxSize",(e,t)=>{var n;zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!ec(r)&&r.size!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const r=a.value;r.size<=t.maximum||a.issues.push({origin:oy(r),code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),R3=me("$ZodCheckMinSize",(e,t)=>{var n;zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!ec(r)&&r.size!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const r=a.value;r.size>=t.minimum||a.issues.push({origin:oy(r),code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),A3=me("$ZodCheckSizeEquals",(e,t)=>{var n;zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!ec(r)&&r.size!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag;r.minimum=t.size,r.maximum=t.size,r.size=t.size}),e._zod.check=a=>{const r=a.value,i=r.size;if(i===t.size)return;const s=i>t.size;a.issues.push({origin:oy(r),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:a.value,inst:e,continue:!t.abort})}}),I3=me("$ZodCheckMaxLength",(e,t)=>{var n;zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!ec(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<r&&(a._zod.bag.maximum=t.maximum)}),e._zod.check=a=>{const r=a.value;if(r.length<=t.maximum)return;const s=sy(r);a.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),O3=me("$ZodCheckMinLength",(e,t)=>{var n;zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!ec(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>r&&(a._zod.bag.minimum=t.minimum)}),e._zod.check=a=>{const r=a.value;if(r.length>=t.minimum)return;const s=sy(r);a.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),D3=me("$ZodCheckLengthEquals",(e,t)=>{var n;zn.init(e,t),(n=e._zod.def).when??(n.when=a=>{const r=a.value;return!ec(r)&&r.length!==void 0}),e._zod.onattach.push(a=>{const r=a._zod.bag;r.minimum=t.length,r.maximum=t.length,r.length=t.length}),e._zod.check=a=>{const r=a.value,i=r.length;if(i===t.length)return;const s=sy(r),c=i>t.length;a.issues.push({origin:s,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:a.value,inst:e,continue:!t.abort})}}),gm=me("$ZodCheckStringFormat",(e,t)=>{var n,a;zn.init(e,t),e._zod.onattach.push(r=>{const i=r._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:t.format,input:r.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(a=e._zod).check??(a.check=()=>{})}),j3=me("$ZodCheckRegex",(e,t)=>{gm.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),$3=me("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=S3),gm.init(e,t)}),L3=me("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=x3),gm.init(e,t)}),M3=me("$ZodCheckIncludes",(e,t)=>{zn.init(e,t);const n=$o(t.includes),a=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=a,e._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(a)}),e._zod.check=r=>{r.value.includes(t.includes,t.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:r.value,inst:e,continue:!t.abort})}}),P3=me("$ZodCheckStartsWith",(e,t)=>{zn.init(e,t);const n=new RegExp(`^${$o(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const r=a._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=a=>{a.value.startsWith(t.prefix)||a.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:a.value,inst:e,continue:!t.abort})}}),U3=me("$ZodCheckEndsWith",(e,t)=>{zn.init(e,t);const n=new RegExp(`.*${$o(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(a=>{const r=a._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(n)}),e._zod.check=a=>{a.value.endsWith(t.suffix)||a.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:a.value,inst:e,continue:!t.abort})}});function fM(e,t,n){e.issues.length&&t.issues.push(...bi(n,e.issues))}const z3=me("$ZodCheckProperty",(e,t)=>{zn.init(e,t),e._zod.check=n=>{const a=t.schema._zod.run({value:n.value[t.property],issues:[]},{});if(a instanceof Promise)return a.then(r=>fM(r,n,t.property));fM(a,n,t.property)}}),F3=me("$ZodCheckMimeType",(e,t)=>{zn.init(e,t);const n=new Set(t.mime);e._zod.onattach.push(a=>{a._zod.bag.mime=t.mime}),e._zod.check=a=>{n.has(a.value.type)||a.issues.push({code:"invalid_value",values:t.mime,input:a.value.type,inst:e,continue:!t.abort})}}),B3=me("$ZodCheckOverwrite",(e,t)=>{zn.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class H3{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const a=t.split(`
4
4
  `).filter(s=>s),r=Math.min(...a.map(s=>s.length-s.trimStart().length)),i=a.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(const s of i)this.content.push(s)}compile(){const t=Function,n=this?.args,r=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...n,r.join(`
5
5
  `))}}const V3={major:4,minor:2,patch:0},vt=me("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=V3;const a=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&a.unshift(e);for(const r of a)for(const i of r._zod.onattach)i(e);if(a.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const r=(s,c,u)=>{let d=Rl(s),m;for(const h of c){if(h._zod.def.when){if(!h._zod.def.when(s))continue}else if(d)continue;const g=s.issues.length,v=h._zod.check(s);if(v instanceof Promise&&u?.async===!1)throw new $l;if(m||v instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await v,s.issues.length!==g&&(d||(d=Rl(s,g)))});else{if(s.issues.length===g)continue;d||(d=Rl(s,g))}}return m?m.then(()=>s):s},i=(s,c,u)=>{if(Rl(s))return s.aborted=!0,s;const d=r(c,a,u);if(d instanceof Promise){if(u.async===!1)throw new $l;return d.then(m=>e._zod.parse(m,u))}return e._zod.parse(d,u)};e._zod.run=(s,c)=>{if(c.skipChecks)return e._zod.parse(s,c);if(c.direction==="backward"){const d=e._zod.parse({value:s.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(m=>i(m,s,c)):i(d,s,c)}const u=e._zod.parse(s,c);if(u instanceof Promise){if(c.async===!1)throw new $l;return u.then(d=>r(d,a,c))}return r(u,a,c)}}e["~standard"]={validate:r=>{try{const i=dk(e,r);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return BF(e,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),bm=me("$ZodString",(e,t)=>{vt.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??m3(e._zod.bag),e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Tn=me("$ZodStringFormat",(e,t)=>{gm.init(e,t),bm.init(e,t)}),G3=me("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=qF),Tn.init(e,t)}),W3=me("$ZodUUID",(e,t)=>{if(t.version){const a={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(a===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ed(a))}else t.pattern??(t.pattern=ed());Tn.init(e,t)}),K3=me("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=XF),Tn.init(e,t)}),Z3=me("$ZodURL",(e,t)=>{Tn.init(e,t),e._zod.check=n=>{try{const a=n.value.trim(),r=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(r.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=r.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Y3=me("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=QF()),Tn.init(e,t)}),q3=me("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=ZF),Tn.init(e,t)}),X3=me("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=HF),Tn.init(e,t)}),J3=me("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=VF),Tn.init(e,t)}),Q3=me("$ZodULID",(e,t)=>{t.pattern??(t.pattern=GF),Tn.init(e,t)}),eB=me("$ZodXID",(e,t)=>{t.pattern??(t.pattern=WF),Tn.init(e,t)}),tB=me("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=KF),Tn.init(e,t)}),nB=me("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=p3(t)),Tn.init(e,t)}),rB=me("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=u3),Tn.init(e,t)}),aB=me("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=f3(t)),Tn.init(e,t)}),iB=me("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=YF),Tn.init(e,t)}),oB=me("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=e3),Tn.init(e,t),e._zod.bag.format="ipv4"}),sB=me("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=t3),Tn.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),lB=me("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=n3(t.delimiter)),Tn.init(e,t),e._zod.bag.format="mac"}),cB=me("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=r3),Tn.init(e,t)}),uB=me("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=a3),Tn.init(e,t),e._zod.check=n=>{const a=n.value.split("/");try{if(a.length!==2)throw new Error;const[r,i]=a;if(!i)throw new Error;const s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Ek(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const dB=me("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=i3),Tn.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Ek(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function fB(e){if(!wk.test(e))return!1;const t=e.replace(/[-_]/g,a=>a==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Ek(n)}const pB=me("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=wk),Tn.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{fB(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),mB=me("$ZodE164",(e,t)=>{t.pattern??(t.pattern=l3),Tn.init(e,t)});function hB(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[a]=n;if(!a)return!1;const r=JSON.parse(atob(a));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||t&&(!("alg"in r)||r.alg!==t))}catch{return!1}}const gB=me("$ZodJWT",(e,t)=>{Tn.init(e,t),e._zod.check=n=>{hB(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),bB=me("$ZodCustomStringFormat",(e,t)=>{Tn.init(e,t),e._zod.check=n=>{t.fn(n.value)||n.issues.push({code:"invalid_format",format:t.format,input:n.value,inst:e,continue:!t.abort})}}),kk=me("$ZodNumber",(e,t)=>{vt.init(e,t),e._zod.pattern=e._zod.bag.pattern??b3,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const r=n.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return n;const i=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:r,inst:e,...i?{received:i}:{}}),n}}),vB=me("$ZodNumberFormat",(e,t)=>{T3.init(e,t),kk.init(e,t)}),Tk=me("$ZodBoolean",(e,t)=>{vt.init(e,t),e._zod.pattern=v3,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=!!n.value}catch{}const r=n.value;return typeof r=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:e}),n}}),Nk=me("$ZodBigInt",(e,t)=>{vt.init(e,t),e._zod.pattern=h3,e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:e}),n}}),yB=me("$ZodBigIntFormat",(e,t)=>{N3.init(e,t),Nk.init(e,t)}),wB=me("$ZodSymbol",(e,t)=>{vt.init(e,t),e._zod.parse=(n,a)=>{const r=n.value;return typeof r=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:e}),n}}),SB=me("$ZodUndefined",(e,t)=>{vt.init(e,t),e._zod.pattern=w3,e._zod.values=new Set([void 0]),e._zod.optin="optional",e._zod.optout="optional",e._zod.parse=(n,a)=>{const r=n.value;return typeof r>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:e}),n}}),xB=me("$ZodNull",(e,t)=>{vt.init(e,t),e._zod.pattern=y3,e._zod.values=new Set([null]),e._zod.parse=(n,a)=>{const r=n.value;return r===null||n.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),n}}),_B=me("$ZodAny",(e,t)=>{vt.init(e,t),e._zod.parse=n=>n}),EB=me("$ZodUnknown",(e,t)=>{vt.init(e,t),e._zod.parse=n=>n}),kB=me("$ZodNever",(e,t)=>{vt.init(e,t),e._zod.parse=(n,a)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)}),TB=me("$ZodVoid",(e,t)=>{vt.init(e,t),e._zod.parse=(n,a)=>{const r=n.value;return typeof r>"u"||n.issues.push({expected:"void",code:"invalid_type",input:r,inst:e}),n}}),NB=me("$ZodDate",(e,t)=>{vt.init(e,t),e._zod.parse=(n,a)=>{if(t.coerce)try{n.value=new Date(n.value)}catch{}const r=n.value,i=r instanceof Date;return i&&!Number.isNaN(r.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:r,...i?{received:"Invalid Date"}:{},inst:e}),n}});function pM(e,t,n){e.issues.length&&t.issues.push(...bi(n,e.issues)),t.value[n]=e.value}const CB=me("$ZodArray",(e,t)=>{vt.init(e,t),e._zod.parse=(n,a)=>{const r=n.value;if(!Array.isArray(r))return n.issues.push({expected:"array",code:"invalid_type",input:r,inst:e}),n;n.value=Array(r.length);const i=[];for(let s=0;s<r.length;s++){const c=r[s],u=t.element._zod.run({value:c,issues:[]},a);u instanceof Promise?i.push(u.then(d=>pM(d,n,s))):pM(u,n,s)}return i.length?Promise.all(i).then(()=>n):n}});function nv(e,t,n,a){e.issues.length&&t.issues.push(...bi(n,e.issues)),e.value===void 0?n in a&&(t.value[n]=void 0):t.value[n]=e.value}function RB(e){const t=Object.keys(e.shape);for(const a of t)if(!e.shape?.[a]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${a}": expected a Zod schema`);const n=kF(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function AB(e,t,n,a,r,i){const s=[],c=r.keySet,u=r.catchall._zod,d=u.def.type;for(const m in t){if(c.has(m))continue;if(d==="never"){s.push(m);continue}const h=u.run({value:t[m],issues:[]},a);h instanceof Promise?e.push(h.then(g=>nv(g,n,m,t))):nv(h,n,m,t)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const IB=me("$ZodObject",(e,t)=>{if(vt.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const c=t.shape;Object.defineProperty(t,"shape",{get:()=>{const u={...c};return Object.defineProperty(t,"shape",{value:u}),u}})}const a=cm(()=>RB(t));Ht(e._zod,"propValues",()=>{const c=t.shape,u={};for(const d in c){const m=c[d]._zod;if(m.values){u[d]??(u[d]=new Set);for(const h of m.values)u[d].add(h)}}return u});const r=Ju,i=t.catchall;let s;e._zod.parse=(c,u)=>{s??(s=a.value);const d=c.value;if(!r(d))return c.issues.push({expected:"object",code:"invalid_type",input:d,inst:e}),c;c.value={};const m=[],h=s.shape;for(const g of s.keys){const x=h[g]._zod.run({value:d[g],issues:[]},u);x instanceof Promise?m.push(x.then(S=>nv(S,c,g,d))):nv(x,c,g,d)}return i?AB(m,d,c,u,a.value,e):m.length?Promise.all(m).then(()=>c):c}}),OB=me("$ZodObjectJIT",(e,t)=>{IB.init(e,t);const n=e._zod.parse,a=cm(()=>RB(t)),r=g=>{const v=new H3(["shape","payload","ctx"]),x=a.value,S=k=>{const C=r_(k);return`shape[${C}]._zod.run({ value: input[${C}], issues: [] }, ctx)`};v.write("const input = payload.value;");const y=Object.create(null);let E=0;for(const k of x.keys)y[k]=`key_${E++}`;v.write("const newResult = {};");for(const k of x.keys){const C=y[k],R=r_(k);v.write(`const ${C} = ${S(k)};`),v.write(`
@@ -32,7 +32,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
32
32
  `;break;case"id":c=y.includes("\0")?void 0:y;break;case"retry":/^\d+$/.test(y)?a(parseInt(y,10)):n(new JP(`Invalid \`retry\` value: "${y}"`,{type:"invalid-retry",value:y,line:E}));break;default:n(new JP(`Unknown field "${S.length>20?`${S.slice(0,20)}…`:S}"`,{type:"unknown-field",field:S,value:y,line:E}));break}}function v(){u.length>0&&t({id:c,event:d||void 0,data:u.endsWith(`
33
33
  `)?u.slice(0,-1):u}),c=void 0,u="",d=""}function x(S={}){i&&S.consume&&h(i),s=!0,c=void 0,u="",d="",i=""}return{feed:m,reset:x}}function moe(e){const t=[];let n="",a=0;for(;a<e.length;){const r=e.indexOf("\r",a),i=e.indexOf(`
34
34
  `,a);let s=-1;if(r!==-1&&i!==-1?s=Math.min(r,i):r!==-1?r===e.length-1?s=-1:s=r:i!==-1&&(s=i),s===-1){n=e.slice(a);break}else{const c=e.slice(a,s);t.push(c),a=s+1,e[a-1]==="\r"&&e[a]===`
35
- `&&a++}}return[t,n]}class hoe extends TransformStream{constructor({onError:t,onRetry:n,onComment:a}={}){let r;super({start(i){r=QV({onEvent:s=>{i.enqueue(s)},onError(s){t==="terminate"?i.error(s):typeof t=="function"&&t(s)},onRetry:n,onComment:a})},transform(i){r.feed(i)}})}}const goe={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class kl extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class boe{constructor(t,n){var a;this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=n?.requestInit,this._authProvider=n?.authProvider,this._fetch=n?.fetch,this._fetchWithInit=UV(n?.fetch,n?.requestInit),this._sessionId=n?.sessionId,this._reconnectionOptions=(a=n?.reconnectionOptions)!==null&&a!==void 0?a:goe}async _authThenStart(){var t;if(!this._authProvider)throw new qa("No auth provider");let n;try{n=await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(a){throw(t=this.onerror)===null||t===void 0||t.call(this,a),a}if(n!=="AUTHORIZED")throw new qa;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const n={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(n.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(n["mcp-session-id"]=this._sessionId),this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const a=pv((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...a})}async _startOrAuthSse(t){var n,a,r,i;const{resumptionToken:s}=t;try{const c=await this._commonHeaders();c.set("Accept","text/event-stream"),s&&c.set("last-event-id",s);const u=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,{method:"GET",headers:c,signal:(a=this._abortController)===null||a===void 0?void 0:a.signal});if(!u.ok){if(await((r=u.body)===null||r===void 0?void 0:r.cancel()),u.status===401&&this._authProvider)return await this._authThenStart();if(u.status===405)return;throw new kl(u.status,`Failed to open SSE stream: ${u.statusText}`)}this._handleSseStream(u.body,t,!0)}catch(c){throw(i=this.onerror)===null||i===void 0||i.call(this,c),c}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const n=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(a,t),r)}_scheduleReconnection(t,n=0){var a;const r=this._reconnectionOptions.maxRetries;if(n>=r){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}const i=this._getNextReconnectionDelay(n);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{var c;(c=this.onerror)===null||c===void 0||c.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,n+1)})},i)}_handleSseStream(t,n,a){if(!t)return;const{onresumptiontoken:r,replayMessageId:i}=n;let s,c=!1,u=!1;(async()=>{var m,h,g,v;try{const x=t.pipeThrough(new TextDecoderStream).pipeThrough(new hoe({onRetry:E=>{this._serverRetryMs=E}})).getReader();for(;;){const{value:E,done:_}=await x.read();if(_)break;if(E.id&&(s=E.id,c=!0,r?.(E.id)),!!E.data&&(!E.event||E.event==="message"))try{const k=Cb.parse(JSON.parse(E.data));Qf(k)&&(u=!0,i!==void 0&&(k.id=i)),(m=this.onmessage)===null||m===void 0||m.call(this,k)}catch(k){(h=this.onerror)===null||h===void 0||h.call(this,k)}}(a||c)&&!u&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:r,replayMessageId:i},0)}catch(x){if((g=this.onerror)===null||g===void 0||g.call(this,new Error(`SSE stream disconnected: ${x}`)),(a||c)&&!u&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:r,replayMessageId:i},0)}catch(E){(v=this.onerror)===null||v===void 0||v.call(this,new Error(`Failed to reconnect: ${E instanceof Error?E.message:String(E)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new qa("No auth provider");if(await Co(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa("Failed to authorize")}async close(){var t,n;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(t=this._abortController)===null||t===void 0||t.abort(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(t,n){var a,r,i,s,c,u,d;try{const{resumptionToken:m,onresumptiontoken:h}=n||{};if(m){this._startOrAuthSse({resumptionToken:m,replayMessageId:d_(t)?t.id:void 0}).catch(k=>{var C;return(C=this.onerror)===null||C===void 0?void 0:C.call(this,k)});return}const g=await this._commonHeaders();g.set("content-type","application/json"),g.set("accept","application/json, text/event-stream");const v={...this._requestInit,method:"POST",headers:g,body:JSON.stringify(t),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},x=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,v),S=x.headers.get("mcp-session-id");if(S&&(this._sessionId=S),!x.ok){const k=await x.text().catch(()=>null);if(x.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new kl(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:C,scope:R}=Lp(x);if(this._resourceMetadataUrl=C,this._scope=R,await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa;return this._hasCompletedAuthFlow=!0,this.send(t)}if(x.status===403&&this._authProvider){const{resourceMetadataUrl:C,scope:R,error:I}=Lp(x);if(I==="insufficient_scope"){const A=x.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===A)throw new kl(403,"Server returned 403 after trying upscoping");if(R&&(this._scope=R),C&&(this._resourceMetadataUrl=C),this._lastUpscopingHeader=A??void 0,await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new qa;return this.send(t)}}throw new kl(x.status,`Error POSTing to endpoint: ${k}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,x.status===202){await((i=x.body)===null||i===void 0?void 0:i.cancel()),lre(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(k=>{var C;return(C=this.onerror)===null||C===void 0?void 0:C.call(this,k)});return}const E=(Array.isArray(t)?t:[t]).filter(k=>"method"in k&&"id"in k&&k.id!==void 0).length>0,_=x.headers.get("content-type");if(E)if(_?.includes("text/event-stream"))this._handleSseStream(x.body,{onresumptiontoken:h},!1);else if(_?.includes("application/json")){const k=await x.json(),C=Array.isArray(k)?k.map(R=>Cb.parse(R)):[Cb.parse(k)];for(const R of C)(s=this.onmessage)===null||s===void 0||s.call(this,R)}else throw await((c=x.body)===null||c===void 0?void 0:c.cancel()),new kl(-1,`Unexpected content type: ${_}`);else await((u=x.body)===null||u===void 0?void 0:u.cancel())}catch(m){throw(d=this.onerror)===null||d===void 0||d.call(this,m),m}}get sessionId(){return this._sessionId}async terminateSession(){var t,n,a,r;if(this._sessionId)try{const i=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:i,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},c=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,s);if(await((a=c.body)===null||a===void 0?void 0:a.cancel()),!c.ok&&c.status!==405)throw new kl(c.status,`Failed to terminate session: ${c.statusText}`);this._sessionId=void 0}catch(i){throw(r=this.onerror)===null||r===void 0||r.call(this,i),i}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,n){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:n?.onresumptiontoken})}}class QP extends Event{constructor(t,n){var a,r;super(t),this.code=(a=n?.code)!=null?a:void 0,this.message=(r=n?.message)!=null?r:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,a){return a(eU(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(eU(this),n)}}function voe(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function E_(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(E_).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${E_(e.cause)}`:e.message:`${e}`}function eU(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var e9=e=>{throw TypeError(e)},bN=(e,t,n)=>t.has(e)||e9("Cannot "+n),Ft=(e,t,n)=>(bN(e,t,"read from private field"),n?n.call(e):t.get(e)),ur=(e,t,n)=>t.has(e)?e9("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Mn=(e,t,n,a)=>(bN(e,t,"write to private field"),t.set(e,n),n),_o=(e,t,n)=>(bN(e,t,"access private method"),n),ba,Nl,Qc,Ab,vv,dp,uu,fp,Cs,eu,Su,tu,ep,fi,k_,T_,N_,tU,C_,R_,tp,A_,I_;class Ib extends EventTarget{constructor(t,n){var a,r;super(),ur(this,fi),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ur(this,ba),ur(this,Nl),ur(this,Qc),ur(this,Ab),ur(this,vv),ur(this,dp),ur(this,uu),ur(this,fp,null),ur(this,Cs),ur(this,eu),ur(this,Su,null),ur(this,tu,null),ur(this,ep,null),ur(this,T_,async i=>{var s;Ft(this,eu).reset();const{body:c,redirected:u,status:d,headers:m}=i;if(d===204){_o(this,fi,tp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Mn(this,Qc,new URL(i.url)):Mn(this,Qc,void 0),d!==200){_o(this,fi,tp).call(this,`Non-200 status code (${d})`,d);return}if(!(m.get("content-type")||"").startsWith("text/event-stream")){_o(this,fi,tp).call(this,'Invalid content type, expected "text/event-stream"',d);return}if(Ft(this,ba)===this.CLOSED)return;Mn(this,ba,this.OPEN);const h=new Event("open");if((s=Ft(this,ep))==null||s.call(this,h),this.dispatchEvent(h),typeof c!="object"||!c||!("getReader"in c)){_o(this,fi,tp).call(this,"Invalid response body, expected a web ReadableStream",d),this.close();return}const g=new TextDecoder,v=c.getReader();let x=!0;do{const{done:S,value:y}=await v.read();y&&Ft(this,eu).feed(g.decode(y,{stream:!S})),S&&(x=!1,Ft(this,eu).reset(),_o(this,fi,A_).call(this))}while(x)}),ur(this,N_,i=>{Mn(this,Cs,void 0),!(i.name==="AbortError"||i.type==="aborted")&&_o(this,fi,A_).call(this,E_(i))}),ur(this,C_,i=>{typeof i.id=="string"&&Mn(this,fp,i.id);const s=new MessageEvent(i.event||"message",{data:i.data,origin:Ft(this,Qc)?Ft(this,Qc).origin:Ft(this,Nl).origin,lastEventId:i.id||""});Ft(this,tu)&&(!i.event||i.event==="message")&&Ft(this,tu).call(this,s),this.dispatchEvent(s)}),ur(this,R_,i=>{Mn(this,dp,i)}),ur(this,I_,()=>{Mn(this,uu,void 0),Ft(this,ba)===this.CONNECTING&&_o(this,fi,k_).call(this)});try{if(t instanceof URL)Mn(this,Nl,t);else if(typeof t=="string")Mn(this,Nl,new URL(t,yoe()));else throw new Error("Invalid URL")}catch{throw voe("An invalid or illegal string was specified")}Mn(this,eu,QV({onEvent:Ft(this,C_),onRetry:Ft(this,R_)})),Mn(this,ba,this.CONNECTING),Mn(this,dp,3e3),Mn(this,vv,(a=n?.fetch)!=null?a:globalThis.fetch),Mn(this,Ab,(r=n?.withCredentials)!=null?r:!1),_o(this,fi,k_).call(this)}get readyState(){return Ft(this,ba)}get url(){return Ft(this,Nl).href}get withCredentials(){return Ft(this,Ab)}get onerror(){return Ft(this,Su)}set onerror(t){Mn(this,Su,t)}get onmessage(){return Ft(this,tu)}set onmessage(t){Mn(this,tu,t)}get onopen(){return Ft(this,ep)}set onopen(t){Mn(this,ep,t)}addEventListener(t,n,a){const r=n;super.addEventListener(t,r,a)}removeEventListener(t,n,a){const r=n;super.removeEventListener(t,r,a)}close(){Ft(this,uu)&&clearTimeout(Ft(this,uu)),Ft(this,ba)!==this.CLOSED&&(Ft(this,Cs)&&Ft(this,Cs).abort(),Mn(this,ba,this.CLOSED),Mn(this,Cs,void 0))}}ba=new WeakMap,Nl=new WeakMap,Qc=new WeakMap,Ab=new WeakMap,vv=new WeakMap,dp=new WeakMap,uu=new WeakMap,fp=new WeakMap,Cs=new WeakMap,eu=new WeakMap,Su=new WeakMap,tu=new WeakMap,ep=new WeakMap,fi=new WeakSet,k_=function(){Mn(this,ba,this.CONNECTING),Mn(this,Cs,new AbortController),Ft(this,vv)(Ft(this,Nl),_o(this,fi,tU).call(this)).then(Ft(this,T_)).catch(Ft(this,N_))},T_=new WeakMap,N_=new WeakMap,tU=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ft(this,fp)?{"Last-Event-ID":Ft(this,fp)}:void 0},cache:"no-store",signal:(e=Ft(this,Cs))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},C_=new WeakMap,R_=new WeakMap,tp=function(e,t){var n;Ft(this,ba)!==this.CLOSED&&Mn(this,ba,this.CLOSED);const a=new QP("error",{code:t,message:e});(n=Ft(this,Su))==null||n.call(this,a),this.dispatchEvent(a)},A_=function(e,t){var n;if(Ft(this,ba)===this.CLOSED)return;Mn(this,ba,this.CONNECTING);const a=new QP("error",{code:t,message:e});(n=Ft(this,Su))==null||n.call(this,a),this.dispatchEvent(a),Mn(this,uu,setTimeout(Ft(this,I_),Ft(this,dp)))},I_=new WeakMap,Ib.CONNECTING=0,Ib.OPEN=1,Ib.CLOSED=2;function yoe(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class woe extends Error{constructor(t,n,a){super(`SSE error: ${n}`),this.code=t,this.event=a}}class Soe{constructor(t,n){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=n?.eventSourceInit,this._requestInit=n?.requestInit,this._authProvider=n?.authProvider,this._fetch=n?.fetch,this._fetchWithInit=UV(n?.fetch,n?.requestInit)}async _authThenStart(){var t;if(!this._authProvider)throw new qa("No auth provider");let n;try{n=await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(a){throw(t=this.onerror)===null||t===void 0||t.call(this,a),a}if(n!=="AUTHORIZED")throw new qa;return await this._startOrAuth()}async _commonHeaders(){var t;const n={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(n.Authorization=`Bearer ${r.access_token}`)}this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const a=pv((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...a})}_startOrAuth(){var t,n,a;const r=(a=(n=(t=this===null||this===void 0?void 0:this._eventSourceInit)===null||t===void 0?void 0:t.fetch)!==null&&n!==void 0?n:this._fetch)!==null&&a!==void 0?a:fetch;return new Promise((i,s)=>{this._eventSource=new Ib(this._url.href,{...this._eventSourceInit,fetch:async(c,u)=>{const d=await this._commonHeaders();d.set("Accept","text/event-stream");const m=await r(c,{...u,headers:d});if(m.status===401&&m.headers.has("www-authenticate")){const{resourceMetadataUrl:h,scope:g}=Lp(m);this._resourceMetadataUrl=h,this._scope=g}return m}}),this._abortController=new AbortController,this._eventSource.onerror=c=>{var u;if(c.code===401&&this._authProvider){this._authThenStart().then(i,s);return}const d=new woe(c.code,c.message,c);s(d),(u=this.onerror)===null||u===void 0||u.call(this,d)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",c=>{var u;const d=c;try{if(this._endpoint=new URL(d.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(m){s(m),(u=this.onerror)===null||u===void 0||u.call(this,m),this.close();return}i()}),this._eventSource.onmessage=c=>{var u,d;const m=c;let h;try{h=Cb.parse(JSON.parse(m.data))}catch(g){(u=this.onerror)===null||u===void 0||u.call(this,g);return}(d=this.onmessage)===null||d===void 0||d.call(this,h)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new qa("No auth provider");if(await Co(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa("Failed to authorize")}async close(){var t,n,a;(t=this._abortController)===null||t===void 0||t.abort(),(n=this._eventSource)===null||n===void 0||n.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(t){var n,a,r,i;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const c={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},u=await((a=this._fetch)!==null&&a!==void 0?a:fetch)(this._endpoint,c);if(!u.ok){const d=await u.text().catch(()=>null);if(u.status===401&&this._authProvider){const{resourceMetadataUrl:m,scope:h}=Lp(u);if(this._resourceMetadataUrl=m,this._scope=h,await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${u.status}): ${d}`)}await((r=u.body)===null||r===void 0?void 0:r.cancel())}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}setProtocolVersion(t){this._protocolVersion=t}}var Vu,xoe=(Vu=class{connector;autoConnect;constructor(t,n=!0){this.connector=t,this.autoConnect=n}async connect(){await this.connector.connect()}async disconnect(){await this.connector.disconnect()}async initialize(){!this.isConnected&&this.autoConnect&&await this.connect(),await this.connector.initialize()}get isConnected(){return this.connector&&this.connector.isClientConnected}on(t,n){t==="notification"&&this.connector.onNotification(n)}async setRoots(t){return this.connector.setRoots(t)}getRoots(){return this.connector.getRoots()}get tools(){return this.connector.tools}async listTools(t){return this.connector.listTools(t)}get serverCapabilities(){return this.connector.serverCapabilities}get serverInfo(){return this.connector.serverInfo}async callTool(t,n={},a){return this.connector.callTool(t,n,a)}async listResources(t,n){return this.connector.listResources(t,n)}async listAllResources(t){return this.connector.listAllResources(t)}async listResourceTemplates(t){return this.connector.listResourceTemplates(t)}async readResource(t,n){return this.connector.readResource(t,n)}async subscribeToResource(t,n){return this.connector.subscribeToResource(t,n)}async unsubscribeFromResource(t,n){return this.connector.unsubscribeFromResource(t,n)}async listPrompts(){return this.connector.listPrompts()}async getPrompt(t,n){return this.connector.getPrompt(t,n)}async request(t,n=null,a){return this.connector.request(t,n,a)}},ze(Vu,"MCPSession"),Vu),Gu,_oe=(Gu=class{config={};sessions={};activeSessions=[];constructor(t){t&&(this.config=t)}static fromDict(t){throw new Error("fromDict must be implemented by concrete class")}addServer(t,n){this.config.mcpServers=this.config.mcpServers||{},this.config.mcpServers[t]=n,zi.getInstance().trackClientAddServer(t,n)}removeServer(t){this.config.mcpServers?.[t]&&(delete this.config.mcpServers[t],this.activeSessions=this.activeSessions.filter(n=>n!==t),zi.getInstance().trackClientRemoveServer(t))}getServerNames(){return Object.keys(this.config.mcpServers??{})}getServerConfig(t){return this.config.mcpServers?.[t]}getConfig(){return this.config??{}}async createSession(t,n=!0){const a=this.config.mcpServers??{};if(Object.keys(a).length===0&&Ce.warn("No MCP servers defined in config"),!a[t])throw new Error(`Server '${t}' not found in config`);const r=this.createConnectorFromConfig(a[t]),i=new xoe(r);return n&&await i.initialize(),this.sessions[t]=i,this.activeSessions.includes(t)||this.activeSessions.push(t),i}async createAllSessions(t=!0){const n=this.config.mcpServers??{};Object.keys(n).length===0&&Ce.warn("No MCP servers defined in config");for(const a of Object.keys(n))await this.createSession(a,t);return this.sessions}getSession(t){const n=this.sessions[t];return n||null}requireSession(t){const n=this.sessions[t];if(!n)throw new Error(`Session '${t}' not found. Available sessions: ${this.activeSessions.join(", ")||"none"}`);return n}getAllActiveSessions(){return Object.fromEntries(this.activeSessions.map(t=>[t,this.sessions[t]]))}async closeSession(t){const n=this.sessions[t];if(!n){Ce.warn(`No session exists for server ${t}, nothing to close`);return}try{Ce.debug(`Closing session for server ${t}`),await n.disconnect()}catch(a){Ce.error(`Error closing session for server '${t}': ${a}`)}finally{delete this.sessions[t],this.activeSessions=this.activeSessions.filter(a=>a!==t)}}async closeAllSessions(){const t=Object.keys(this.sessions),n=[];for(const a of t)try{Ce.debug(`Closing session for server ${a}`),await this.closeSession(a)}catch(r){const i=`Failed to close session for server '${a}': ${r}`;Ce.error(i),n.push(i)}n.length?Ce.error(`Encountered ${n.length} errors while closing sessions`):Ce.debug("All sessions closed successfully")}},ze(Gu,"BaseMCPClient"),Gu),Wu,Eoe=(Wu=class{client=null;connectionManager=null;toolsCache=null;capabilitiesCache=null;serverInfoCache=null;connected=!1;opts;notificationHandlers=[];rootsCache=[];constructor(t={}){this.opts=t,t.roots&&(this.rootsCache=[...t.roots])}trackConnectorInit(t){const n=this.constructor.name;vF.getInstance().trackConnectorInit({connectorType:n,...t}).catch(a=>Ce.debug(`Failed to track connector init: ${a}`))}onNotification(t){this.notificationHandlers.push(t),this.client&&this.setupNotificationHandler()}setupNotificationHandler(){this.client&&(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}for(const n of this.notificationHandlers)try{await n(t)}catch(a){Ce.error("Error in notification handler:",a)}})}async refreshToolsCache(){if(this.client)try{Ce.debug("[Auto] Refreshing tools cache due to list_changed notification");const t=await this.client.listTools();this.toolsCache=t.tools??[],Ce.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(t){Ce.warn("[Auto] Failed to refresh tools cache:",t)}}async onResourcesListChanged(){Ce.debug("[Auto] Resources list changed - clients should re-fetch if needed")}async onPromptsListChanged(){Ce.debug("[Auto] Prompts list changed - clients should re-fetch if needed")}async setRoots(t){this.rootsCache=[...t],this.client&&(Ce.debug(`Sending roots/list_changed notification with ${t.length} root(s)`),await this.client.sendRootsListChanged())}getRoots(){return[...this.rootsCache]}setupRootsHandler(){this.client&&this.client.setRequestHandler(RV,async(t,n)=>(Ce.debug(`Server requested roots list, returning ${this.rootsCache.length} root(s)`),{roots:this.rootsCache}))}setupSamplingHandler(){if(!this.client){Ce.debug("setupSamplingHandler: No client available");return}if(!this.opts.samplingCallback){Ce.debug("setupSamplingHandler: No sampling callback provided");return}Ce.debug("setupSamplingHandler: Setting up sampling request handler"),this.client.setRequestHandler(lN,async(t,n)=>(Ce.debug("Server requested sampling, forwarding to callback"),await this.opts.samplingCallback(t.params))),Ce.debug("setupSamplingHandler: Sampling handler registered successfully")}setupElicitationHandler(){if(!this.client){Ce.debug("setupElicitationHandler: No client available");return}if(!this.opts.elicitationCallback){Ce.debug("setupElicitationHandler: No elicitation callback provided");return}Ce.debug("setupElicitationHandler: Setting up elicitation request handler"),this.client.setRequestHandler(uN,async(t,n)=>(Ce.debug("Server requested elicitation, forwarding to callback"),await this.opts.elicitationCallback(t.params))),Ce.debug("setupElicitationHandler: Elicitation handler registered successfully")}async disconnect(){if(!this.connected){Ce.debug("Not connected to MCP implementation");return}Ce.debug("Disconnecting from MCP implementation"),await this.cleanupResources(),this.connected=!1,Ce.debug("Disconnected from MCP implementation")}get isClientConnected(){return this.client!=null}async initialize(t=this.opts.defaultRequestOptions??{}){if(!this.client)throw new Error("MCP client is not connected");Ce.debug("Caching server capabilities & tools");const n=this.client.getServerCapabilities();this.capabilitiesCache=n||null;const a=this.client.getServerVersion();this.serverInfoCache=a||null;const r=await this.client.listTools(void 0,t);return this.toolsCache=r.tools??[],Ce.debug(`Fetched ${this.toolsCache.length} tools from server`),Ce.debug("Server capabilities:",n),Ce.debug("Server info:",a),n}get tools(){if(!this.toolsCache)throw new Error("MCP client is not initialized; call initialize() first");return this.toolsCache}get serverCapabilities(){return this.capabilitiesCache||{}}get serverInfo(){return this.serverInfoCache}async callTool(t,n,a){if(!this.client)throw new Error("MCP client is not connected");const r=a?{...a}:void 0;r?.resetTimeoutOnProgress&&!r.onprogress&&(r.onprogress=()=>{},Ce.debug(`[BaseConnector] Added onprogress callback for tool '${t}' to enable progressToken`)),Ce.debug(`Calling tool '${t}' with args`,n);const i=await this.client.callTool({name:t,arguments:n},void 0,r);return Ce.debug(`Tool '${t}' returned`,i),i}async listTools(t){if(!this.client)throw new Error("MCP client is not connected");return(await this.client.listTools(void 0,t)).tools??[]}async listResources(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug("Listing resources",t?`with cursor: ${t}`:""),await this.client.listResources({cursor:t},n)}async listAllResources(t){if(!this.client)throw new Error("MCP client is not connected");if(!this.capabilitiesCache?.resources)return Ce.debug("Server does not advertise resources capability, skipping"),{resources:[]};try{Ce.debug("Listing all resources (with auto-pagination)");const n=[];let a;do{const r=await this.client.listResources({cursor:a},t);n.push(...r.resources||[]),a=r.nextCursor}while(a);return{resources:n}}catch(n){if(n.code===-32601)return Ce.debug("Server advertised resources but method not found"),{resources:[]};throw n}}async listResourceTemplates(t){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug("Listing resource templates"),await this.client.listResourceTemplates(void 0,t)}async readResource(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Reading resource ${t}`),await this.client.readResource({uri:t},n)}async subscribeToResource(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Subscribing to resource: ${t}`),await this.client.subscribeResource({uri:t},n)}async unsubscribeFromResource(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Unsubscribing from resource: ${t}`),await this.client.unsubscribeResource({uri:t},n)}async listPrompts(){if(!this.client)throw new Error("MCP client is not connected");if(!this.capabilitiesCache?.prompts)return Ce.debug("Server does not advertise prompts capability, skipping"),{prompts:[]};try{return Ce.debug("Listing prompts"),await this.client.listPrompts()}catch(t){if(t.code===-32601)return Ce.debug("Server advertised prompts but method not found"),{prompts:[]};throw t}}async getPrompt(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Getting prompt ${t}`),await this.client.getPrompt({name:t,arguments:n})}async request(t,n=null,a){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Sending raw request '${t}' with params`,n),await this.client.request({method:t,params:n??{}},void 0,a)}async cleanupResources(){const t=[];if(this.client)try{typeof this.client.close=="function"&&await this.client.close()}catch(n){const a=`Error closing client: ${n}`;Ce.warn(a),t.push(a)}finally{this.client=null}if(this.connectionManager)try{await this.connectionManager.stop()}catch(n){const a=`Error stopping connection manager: ${n}`;Ce.warn(a),t.push(a)}finally{this.connectionManager=null}this.toolsCache=null,t.length&&Ce.warn(`Resource cleanup finished with ${t.length} issue(s)`)}},ze(Wu,"BaseConnector"),Wu),Ku,koe=(Ku=class{_readyPromise;_readyResolver;_donePromise;_doneResolver;_exception=null;_connection=null;_task=null;_abortController=null;constructor(){this.reset()}async start(){if(this.reset(),Ce.debug(`Starting ${this.constructor.name}`),this._task=this.connectionTask(),await this._readyPromise,this._exception)throw this._exception;if(this._connection===null)throw new Error("Connection was not established");return this._connection}async stop(){if(this._task&&this._abortController){Ce.debug(`Cancelling ${this.constructor.name} task`),this._abortController.abort();try{await this._task}catch(t){t instanceof Error&&t.name==="AbortError"?Ce.debug(`${this.constructor.name} task aborted successfully`):Ce.warn(`Error stopping ${this.constructor.name} task: ${t}`)}}await this._donePromise,Ce.debug(`${this.constructor.name} task completed`)}reset(){this._readyPromise=new Promise(t=>this._readyResolver=t),this._donePromise=new Promise(t=>this._doneResolver=t),this._exception=null,this._connection=null,this._task=null,this._abortController=new AbortController}async connectionTask(){Ce.debug(`Running ${this.constructor.name} task`);try{this._connection=await this.establishConnection(),Ce.debug(`${this.constructor.name} connected successfully`),this._readyResolver(),await this.waitForAbort()}catch(t){this._exception=t,Ce.error(`Error in ${this.constructor.name} task: ${t}`),this._readyResolver()}finally{if(this._connection!==null){try{await this.closeConnection(this._connection)}catch(t){Ce.warn(`Error closing connection in ${this.constructor.name}: ${t}`)}this._connection=null}this._doneResolver()}}async waitForAbort(){return new Promise((t,n)=>{if(!this._abortController)return;const a=this._abortController.signal;if(a.aborted){t();return}const r=ze(()=>{a.removeEventListener("abort",r),t()},"onAbort");a.addEventListener("abort",r)})}},ze(Ku,"ConnectionManager"),Ku),Zu,Toe=(Zu=class extends koe{url;opts;_transport=null;reinitializing=!1;constructor(t,n){super(),this.url=typeof t=="string"?new URL(t):t,this.opts=n}async establishConnection(){const t=new Soe(this.url,this.opts),n=t.send.bind(t);return t.send=async a=>{const r=ze(async i=>{if(Array.isArray(i))for(const s of i)await n(s);else await n(i)},"sendMessage");try{await r(a)}catch(i){if(i?.code===404&&t.sessionId&&!this.reinitializing){Ce.warn("[SSE] Session not found (404), re-initializing per MCP spec..."),this.reinitializing=!0;try{t.sessionId=void 0,await this.reinitialize(t),Ce.info("[SSE] Re-initialization successful, retrying request"),await r(a)}finally{this.reinitializing=!1}}else throw i}},this._transport=t,Ce.debug(`${this.constructor.name} connected successfully`),t}async reinitialize(t){Ce.debug("[SSE] Re-initialization triggered")}async closeConnection(t){if(this._transport)try{await this._transport.close()}catch(n){Ce.warn(`Error closing SSE transport: ${n}`)}finally{this._transport=null}}},ze(Zu,"SseConnectionManager"),Zu),Yu,Noe=(Yu=class extends Eoe{baseUrl;headers;timeout;sseReadTimeout;clientInfo;preferSse;disableSseFallback;transportType=null;streamableTransport=null;constructor(t,n={}){super(n),this.baseUrl=t.replace(/\/$/,""),this.headers={...n.headers??{}},n.authToken&&(this.headers.Authorization=`Bearer ${n.authToken}`),this.timeout=n.timeout??3e4,this.sseReadTimeout=n.sseReadTimeout??3e5,this.clientInfo=n.clientInfo??{name:"http-connector",version:"1.0.0"},this.preferSse=n.preferSse??!1,this.disableSseFallback=n.disableSseFallback??!1}async connect(){if(this.connected){Ce.debug("Already connected to MCP implementation");return}const t=this.baseUrl;if(this.preferSse){Ce.debug(`Connecting to MCP implementation via HTTP/SSE: ${t}`),await this.connectWithSse(t);return}Ce.debug(`Connecting to MCP implementation via HTTP: ${t}`);try{Ce.info("🔄 Attempting streamable HTTP transport..."),await this.connectWithStreamableHttp(t),Ce.info("✅ Successfully connected via streamable HTTP")}catch(n){let a="Unknown error",r=!1;if(n instanceof kl){const i=n;r=i.code===401,i.code===400&&i.message.includes("Missing session ID")?(a="Server requires session ID (FastMCP compatibility) - using SSE transport",Ce.warn(`⚠️ ${a}`)):i.code===404||i.code===405?(a=`Server returned ${i.code} - server likely doesn't support streamable HTTP`,Ce.debug(a)):(a=`Server returned ${i.code}: ${i.message}`,Ce.debug(a))}else if(n instanceof Error){const i=n.toString(),s=n.message||"";r=i.includes("401")||s.includes("Unauthorized"),i.includes("Missing session ID")||i.includes("Bad Request: Missing session ID")||s.includes("FastMCP session ID error")?(a="Server requires session ID (FastMCP compatibility) - using SSE transport",Ce.warn(`⚠️ ${a}`)):i.includes("405 Method Not Allowed")||i.includes("404 Not Found")?(a="Server doesn't support streamable HTTP (405/404)",Ce.debug(a)):(a=`Streamable HTTP failed: ${n.message}`,Ce.debug(a))}if(r){Ce.info("Authentication required - skipping SSE fallback"),await this.cleanupResources();const i=new Error("Authentication required");throw i.code=401,i}if(this.disableSseFallback)throw Ce.info("SSE fallback disabled - failing connection"),await this.cleanupResources(),new Error(`Streamable HTTP connection failed: ${a}. SSE fallback is disabled.`);Ce.info("🔄 Falling back to SSE transport...");try{await this.connectWithSse(t)}catch(i){if(Ce.error("Failed to connect with both transports:"),Ce.error(` Streamable HTTP: ${a}`),Ce.error(` SSE: ${i}`),await this.cleanupResources(),i?.message?.includes("401")||i?.message?.includes("Unauthorized")){const c=new Error("Authentication required");throw c.code=401,c}throw new Error("Could not connect to server with any available transport")}}}async connectWithStreamableHttp(t){try{const n=new boe(new URL(t),{authProvider:this.opts.authProvider,requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2}});let a=n;if(this.opts.wrapTransport){const i=this.baseUrl;a=this.opts.wrapTransport(a,i)}const r={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};Ce.debug("Creating Client with capabilities:",JSON.stringify(r.capabilities,null,2)),this.client=new ZP(this.clientInfo,r),this.setupRootsHandler(),Ce.debug("Roots handler registered before connect");try{await this.client.connect(a,{timeout:Math.min(this.timeout,3e3)});const i=n.sessionId;i?Ce.debug(`Session ID obtained: ${i}`):Ce.warn("Session ID not available after connect - this may cause issues with SSE stream")}catch(i){if(i instanceof Error){const s=i.message||i.toString();if(s.includes("Missing session ID")||s.includes("Bad Request: Missing session ID")||s.includes("Mcp-Session-Id header is required")){const c=new Error(`Session ID error: ${s}. The SDK should automatically extract session ID from initialize response.`);throw c.cause=i,c}}throw i}this.streamableTransport=n,this.connectionManager={stop:ze(async()=>{if(this.streamableTransport)try{await this.streamableTransport.terminateSession(),await this.streamableTransport.close()}catch(i){Ce.warn(`Error closing Streamable HTTP transport: ${i}`)}finally{this.streamableTransport=null}},"stop")},this.connected=!0,this.transportType="streamable-http",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Ce.debug(`Successfully connected to MCP implementation via streamable HTTP: ${t}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (streamable-http)`})}catch(n){throw await this.cleanupResources(),n}}async connectWithSse(t){try{this.connectionManager=new Toe(t,{authProvider:this.opts.authProvider,requestInit:{headers:this.headers}});let n=await this.connectionManager.start();if(this.opts.wrapTransport){const r=this.baseUrl;n=this.opts.wrapTransport(n,r)}const a={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};Ce.debug("Creating Client with capabilities (SSE):",JSON.stringify(a.capabilities,null,2)),this.client=new ZP(this.clientInfo,a),this.setupRootsHandler(),Ce.debug("Roots handler registered before connect (SSE)"),await this.client.connect(n),this.connected=!0,this.transportType="sse",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Ce.debug(`Successfully connected to MCP implementation via HTTP/SSE: ${t}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (sse)`})}catch(n){throw await this.cleanupResources(),n}}get publicIdentifier(){return{type:"http",url:this.baseUrl,transport:this.transportType||"unknown"}}getTransportType(){return this.transportType}},ze(Yu,"HttpConnector"),Yu),zl,Coe=(zl=class extends _oe{static getPackageVersion(){return Jb()}constructor(t){super(t),this._trackClientInit()}_trackClientInit(){const t=Object.keys(this.config.mcpServers??{});zi.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(n=>Ce.debug(`Failed to track BrowserMCPClient init: ${n}`))}static fromDict(t){return new zl(t)}createConnectorFromConfig(t){const{url:n,headers:a,authToken:r,authProvider:i,wrapTransport:s,clientOptions:c,samplingCallback:u,elicitationCallback:d,disableSseFallback:m,preferSse:h}=t;if(!n)throw new Error("Server URL is required");const g={headers:a,authToken:r,authProvider:i,wrapTransport:s,clientOptions:c,samplingCallback:u,elicitationCallback:d,disableSseFallback:m,preferSse:h};return c?console.log("[BrowserMCPClient] Passing clientOptions to connector:",JSON.stringify(c,null,2)):console.warn("[BrowserMCPClient] No clientOptions provided to connector!"),new Noe(n,g)}},ze(zl,"BrowserMCPClient"),zl);function du(e){const t=ze(()=>{throw new Error(`Invalid url to pass to open(): ${e}`)},"abort");let n;try{n=new URL(e)}catch{t()}return n.protocol!=="https:"&&n.protocol!=="http:"&&t(),n.hostname!==encodeURIComponent(n.hostname)&&t(),n.username&&(n.username=encodeURIComponent(n.username)),n.password&&(n.password=encodeURIComponent(n.password)),n.pathname=n.pathname.slice(0,1)+encodeURIComponent(n.pathname.slice(1)).replace(/%2f/gi,"/"),n.search=n.search.slice(0,1)+Array.from(n.searchParams.entries()).map(t9).join("&"),n.hash=n.hash.slice(0,1)+encodeURIComponent(n.hash.slice(1)),n.href}ze(du,"sanitizeUrl");function t9([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:""}`}ze(t9,"sanitizeParam");var qu,Ob=(qu=class{serverUrl;storageKeyPrefix;serverUrlHash;clientName;clientUri;callbackUrl;preventAutoAuth;useRedirectFlow;onPopupWindow;constructor(t,n={}){this.serverUrl=t,this.storageKeyPrefix=n.storageKeyPrefix||"mcp:auth",this.serverUrlHash=this.hashString(t),this.clientName=n.clientName||"mcp-use",this.clientUri=n.clientUri||(typeof window<"u"?window.location.origin:""),this.callbackUrl=du(n.callbackUrl||(typeof window<"u"?new URL("/oauth/callback",window.location.origin).toString():"/oauth/callback")),this.preventAutoAuth=n.preventAutoAuth,this.useRedirectFlow=n.useRedirectFlow,this.onPopupWindow=n.onPopupWindow}get redirectUrl(){return du(this.callbackUrl)}get clientMetadata(){return{redirect_uris:[this.redirectUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:this.clientName,client_uri:this.clientUri}}async clientInformation(){const t=this.getKey("client_info"),n=localStorage.getItem(t);if(n)try{return JSON.parse(n)}catch(a){console.warn(`[${this.storageKeyPrefix}] Failed to parse client information:`,a),localStorage.removeItem(t);return}}async saveClientInformation(t){const n=this.getKey("client_info");localStorage.setItem(n,JSON.stringify(t))}async tokens(){const t=this.getKey("tokens"),n=localStorage.getItem(t);if(n)try{return JSON.parse(n)}catch(a){console.warn(`[${this.storageKeyPrefix}] Failed to parse tokens:`,a),localStorage.removeItem(t);return}}async saveTokens(t){const n=this.getKey("tokens");localStorage.setItem(n,JSON.stringify(t)),localStorage.removeItem(this.getKey("code_verifier")),localStorage.removeItem(this.getKey("last_auth_url"))}async saveCodeVerifier(t){const n=this.getKey("code_verifier");localStorage.setItem(n,t)}async codeVerifier(){const t=this.getKey("code_verifier"),n=localStorage.getItem(t);if(!n)throw new Error(`[${this.storageKeyPrefix}] Code verifier not found in storage for key ${t}. Auth flow likely corrupted or timed out.`);return n}async prepareAuthorizationUrl(t){const n=globalThis.crypto.randomUUID(),a=`${this.storageKeyPrefix}:state_${n}`,r={serverUrlHash:this.serverUrlHash,expiry:Date.now()+1e3*60*10,providerOptions:{serverUrl:this.serverUrl,storageKeyPrefix:this.storageKeyPrefix,clientName:this.clientName,clientUri:this.clientUri,callbackUrl:this.callbackUrl},flowType:this.useRedirectFlow?"redirect":"popup",returnUrl:this.useRedirectFlow&&typeof window<"u"?window.location.href:void 0};localStorage.setItem(a,JSON.stringify(r)),t.searchParams.set("state",n);const i=t.toString(),s=du(i);return localStorage.setItem(this.getKey("last_auth_url"),s),s}async redirectToAuthorization(t){const n=await this.prepareAuthorizationUrl(t);if(this.preventAutoAuth){console.info(`[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`);return}if(this.useRedirectFlow){console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`),window.location.href=n;return}const a="width=600,height=700,resizable=yes,scrollbars=yes,status=yes";try{const r=window.open(n,`mcp_auth_${this.serverUrlHash}`,a);this.onPopupWindow&&this.onPopupWindow(n,a,r),!r||r.closed||typeof r.closed>"u"?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(r.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(r){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,r)}}getLastAttemptedAuthUrl(){const t=localStorage.getItem(this.getKey("last_auth_url"));return t?du(t):null}clearStorage(){const t=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,n=`${this.storageKeyPrefix}:state_`,a=[];let r=0;for(let s=0;s<localStorage.length;s++){const c=localStorage.key(s);if(c){if(c.startsWith(t))a.push(c);else if(c.startsWith(n))try{const u=localStorage.getItem(c);u&&JSON.parse(u).serverUrlHash===this.serverUrlHash&&a.push(c)}catch(u){console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${c} during clearStorage:`,u)}}}return[...new Set(a)].forEach(s=>{localStorage.removeItem(s),r++}),r}hashString(t){let n=0;for(let a=0;a<t.length;a++){const r=t.charCodeAt(a);n=(n<<5)-n+r,n=n&n}return Math.abs(n).toString(16)}getKey(t){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${t}`}},ze(qu,"BrowserOAuthClientProvider"),qu);async function vN(){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),a=e.get("error"),r=e.get("error_description"),i="[mcp-callback]";console.log(`${i} Handling callback...`,{code:t,state:n,error:a,errorDescription:r});let s=null,c=null;const u=n?`mcp:auth:state_${n}`:null;try{if(a)throw new Error(`OAuth error: ${a} - ${r||"No description provided."}`);if(!t)throw new Error("Authorization code not found in callback query parameters.");if(!n||!u)throw new Error("State parameter not found or invalid in callback query parameters.");const d=localStorage.getItem(u);if(!d)throw new Error(`Invalid or expired state parameter "${n}". No matching state found in storage.`);try{c=JSON.parse(d)}catch{throw new Error("Failed to parse stored OAuth state.")}if(!c.expiry||c.expiry<Date.now())throw localStorage.removeItem(u),new Error("OAuth state has expired. Please try initiating authentication again.");if(!c.providerOptions)throw new Error("Stored state is missing required provider options.");const{serverUrl:m,...h}=c.providerOptions;console.log(`${i} Re-instantiating provider for server: ${m}`),s=new Ob(m,h),console.log(`${i} Calling SDK auth() to exchange code...`);const g=new URL(m).origin,v=await Co(s,{serverUrl:g,authorizationCode:t});if(v==="AUTHORIZED")if(console.log(`${i} Authorization successful via SDK auth().`),c.flowType==="redirect"&&c.returnUrl)console.log(`${i} Redirect flow complete. Returning to: ${c.returnUrl}`),localStorage.removeItem(u),window.location.href=c.returnUrl;else if(window.opener&&!window.opener.closed)console.log(`${i} Popup flow complete. Notifying opener...`),window.opener.postMessage({type:"mcp_auth_callback",success:!0},window.location.origin),localStorage.removeItem(u),window.close();else{console.warn(`${i} No opener window or return URL detected. Redirecting to root.`),localStorage.removeItem(u);const S=window.location.pathname.split("/").filter(Boolean),y=S.length>0&&S[S.length-1]==="callback"?"/"+S.slice(0,-2).join("/"):"/";window.location.href=y||"/"}else throw console.warn(`${i} SDK auth() returned unexpected status: ${v}`),new Error(`Unexpected result from authentication library: ${v}`)}catch(d){console.error(`${i} Error during OAuth callback handling:`,d);const m=d instanceof Error?d.message:String(d);window.opener&&!window.opener.closed&&window.opener.postMessage({type:"mcp_auth_callback",success:!1,error:m},window.location.origin);try{document.body.innerHTML="";const h=document.createElement("div");h.style.fontFamily="sans-serif",h.style.padding="20px";const g=document.createElement("h1");g.textContent="Authentication Error",h.appendChild(g);const v=document.createElement("p");v.style.color="red",v.style.backgroundColor="#ffebeb",v.style.border="1px solid red",v.style.padding="10px",v.style.borderRadius="4px",v.textContent=m,h.appendChild(v);const x=document.createElement("p");x.textContent="You can close this window or ";const S=document.createElement("a");if(S.href="#",S.textContent="click here to close",S.onclick=y=>(y.preventDefault(),window.close(),!1),x.appendChild(S),x.appendChild(document.createTextNode(".")),h.appendChild(x),d instanceof Error&&d.stack){const y=document.createElement("pre");y.style.fontSize="0.8em",y.style.color="#555",y.style.marginTop="20px",y.style.whiteSpace="pre-wrap",y.textContent=d.stack,h.appendChild(y)}document.body.appendChild(h)}catch(h){console.error(`${i} Could not display error in callback window:`,h)}u&&localStorage.removeItem(u),s&&(localStorage.removeItem(s.getKey("code_verifier")),localStorage.removeItem(s.getKey("last_auth_url")))}}ze(vN,"onMcpAuthorization");var tx={exports:{}},bt={};var nU;function Roe(){if(nU)return bt;nU=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),s=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),g=Symbol.iterator;function v(j){return j===null||typeof j!="object"?null:(j=g&&j[g]||j["@@iterator"],typeof j=="function"?j:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,y={};function E(j,V,z){this.props=j,this.context=V,this.refs=y,this.updater=z||x}E.prototype.isReactComponent={},E.prototype.setState=function(j,V){if(typeof j!="object"&&typeof j!="function"&&j!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,j,V,"setState")},E.prototype.forceUpdate=function(j){this.updater.enqueueForceUpdate(this,j,"forceUpdate")};function _(){}_.prototype=E.prototype;function k(j,V,z){this.props=j,this.context=V,this.refs=y,this.updater=z||x}var C=k.prototype=new _;C.constructor=k,S(C,E.prototype),C.isPureReactComponent=!0;var R=Array.isArray;function I(){}var A={H:null,A:null,T:null,S:null},O=Object.prototype.hasOwnProperty;function M(j,V,z){var $=z.ref;return{$$typeof:e,type:j,key:V,ref:$!==void 0?$:null,props:z}}function P(j,V){return M(j.type,V,j.props)}function B(j){return typeof j=="object"&&j!==null&&j.$$typeof===e}function K(j){var V={"=":"=0",":":"=2"};return"$"+j.replace(/[=:]/g,function(z){return V[z]})}var ee=/\/+/g;function te(j,V){return typeof j=="object"&&j!==null&&j.key!=null?K(""+j.key):V.toString(36)}function ae(j){switch(j.status){case"fulfilled":return j.value;case"rejected":throw j.reason;default:switch(typeof j.status=="string"?j.then(I,I):(j.status="pending",j.then(function(V){j.status==="pending"&&(j.status="fulfilled",j.value=V)},function(V){j.status==="pending"&&(j.status="rejected",j.reason=V)})),j.status){case"fulfilled":return j.value;case"rejected":throw j.reason}}throw j}function H(j,V,z,$,L){var F=typeof j;(F==="undefined"||F==="boolean")&&(j=null);var W=!1;if(j===null)W=!0;else switch(F){case"bigint":case"string":case"number":W=!0;break;case"object":switch(j.$$typeof){case e:case t:W=!0;break;case m:return W=j._init,H(W(j._payload),V,z,$,L)}}if(W)return L=L(j),W=$===""?"."+te(j,0):$,R(L)?(z="",W!=null&&(z=W.replace(ee,"$&/")+"/"),H(L,V,z,"",function(ce){return ce})):L!=null&&(B(L)&&(L=P(L,z+(L.key==null||j&&j.key===L.key?"":(""+L.key).replace(ee,"$&/")+"/")+W)),V.push(L)),1;W=0;var X=$===""?".":$+":";if(R(j))for(var ie=0;ie<j.length;ie++)$=j[ie],F=X+te($,ie),W+=H($,V,z,F,L);else if(ie=v(j),typeof ie=="function")for(j=ie.call(j),ie=0;!($=j.next()).done;)$=$.value,F=X+te($,ie++),W+=H($,V,z,F,L);else if(F==="object"){if(typeof j.then=="function")return H(ae(j),V,z,$,L);throw V=String(j),Error("Objects are not valid as a React child (found: "+(V==="[object Object]"?"object with keys {"+Object.keys(j).join(", ")+"}":V)+"). If you meant to render a collection of children, use an array instead.")}return W}function Z(j,V,z){if(j==null)return j;var $=[],L=0;return H(j,$,"","",function(F){return V.call(z,F,L++)}),$}function G(j){if(j._status===-1){var V=j._result;V=V(),V.then(function(z){(j._status===0||j._status===-1)&&(j._status=1,j._result=z)},function(z){(j._status===0||j._status===-1)&&(j._status=2,j._result=z)}),j._status===-1&&(j._status=0,j._result=V)}if(j._status===1)return j._result.default;throw j._result}var re=typeof reportError=="function"?reportError:function(j){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var V=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof j=="object"&&j!==null&&typeof j.message=="string"?String(j.message):String(j),error:j});if(!window.dispatchEvent(V))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",j);return}console.error(j)},ne={map:Z,forEach:function(j,V,z){Z(j,function(){V.apply(this,arguments)},z)},count:function(j){var V=0;return Z(j,function(){V++}),V},toArray:function(j){return Z(j,function(V){return V})||[]},only:function(j){if(!B(j))throw Error("React.Children.only expected to receive a single React element child.");return j}};return bt.Activity=h,bt.Children=ne,bt.Component=E,bt.Fragment=n,bt.Profiler=r,bt.PureComponent=k,bt.StrictMode=a,bt.Suspense=u,bt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,bt.__COMPILER_RUNTIME={__proto__:null,c:function(j){return A.H.useMemoCache(j)}},bt.cache=function(j){return function(){return j.apply(null,arguments)}},bt.cacheSignal=function(){return null},bt.cloneElement=function(j,V,z){if(j==null)throw Error("The argument must be a React element, but you passed "+j+".");var $=S({},j.props),L=j.key;if(V!=null)for(F in V.key!==void 0&&(L=""+V.key),V)!O.call(V,F)||F==="key"||F==="__self"||F==="__source"||F==="ref"&&V.ref===void 0||($[F]=V[F]);var F=arguments.length-2;if(F===1)$.children=z;else if(1<F){for(var W=Array(F),X=0;X<F;X++)W[X]=arguments[X+2];$.children=W}return M(j.type,L,$)},bt.createContext=function(j){return j={$$typeof:s,_currentValue:j,_currentValue2:j,_threadCount:0,Provider:null,Consumer:null},j.Provider=j,j.Consumer={$$typeof:i,_context:j},j},bt.createElement=function(j,V,z){var $,L={},F=null;if(V!=null)for($ in V.key!==void 0&&(F=""+V.key),V)O.call(V,$)&&$!=="key"&&$!=="__self"&&$!=="__source"&&(L[$]=V[$]);var W=arguments.length-2;if(W===1)L.children=z;else if(1<W){for(var X=Array(W),ie=0;ie<W;ie++)X[ie]=arguments[ie+2];L.children=X}if(j&&j.defaultProps)for($ in W=j.defaultProps,W)L[$]===void 0&&(L[$]=W[$]);return M(j,F,L)},bt.createRef=function(){return{current:null}},bt.forwardRef=function(j){return{$$typeof:c,render:j}},bt.isValidElement=B,bt.lazy=function(j){return{$$typeof:m,_payload:{_status:-1,_result:j},_init:G}},bt.memo=function(j,V){return{$$typeof:d,type:j,compare:V===void 0?null:V}},bt.startTransition=function(j){var V=A.T,z={};A.T=z;try{var $=j(),L=A.S;L!==null&&L(z,$),typeof $=="object"&&$!==null&&typeof $.then=="function"&&$.then(I,re)}catch(F){re(F)}finally{V!==null&&z.types!==null&&(V.types=z.types),A.T=V}},bt.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()},bt.use=function(j){return A.H.use(j)},bt.useActionState=function(j,V,z){return A.H.useActionState(j,V,z)},bt.useCallback=function(j,V){return A.H.useCallback(j,V)},bt.useContext=function(j){return A.H.useContext(j)},bt.useDebugValue=function(){},bt.useDeferredValue=function(j,V){return A.H.useDeferredValue(j,V)},bt.useEffect=function(j,V){return A.H.useEffect(j,V)},bt.useEffectEvent=function(j){return A.H.useEffectEvent(j)},bt.useId=function(){return A.H.useId()},bt.useImperativeHandle=function(j,V,z){return A.H.useImperativeHandle(j,V,z)},bt.useInsertionEffect=function(j,V){return A.H.useInsertionEffect(j,V)},bt.useLayoutEffect=function(j,V){return A.H.useLayoutEffect(j,V)},bt.useMemo=function(j,V){return A.H.useMemo(j,V)},bt.useOptimistic=function(j,V){return A.H.useOptimistic(j,V)},bt.useReducer=function(j,V,z){return A.H.useReducer(j,V,z)},bt.useRef=function(j){return A.H.useRef(j)},bt.useState=function(j){return A.H.useState(j)},bt.useSyncExternalStore=function(j,V,z){return A.H.useSyncExternalStore(j,V,z)},bt.useTransition=function(){return A.H.useTransition()},bt.version="19.2.3",bt}var rU;function yN(){return rU||(rU=1,tx.exports=Roe()),tx.exports}var w=yN();const ue=ny(w),kd=lJ({__proto__:null,default:ue},[w]);function O_(e,t){if(!e)throw new Error(t)}ze(O_,"assert");var aU=3e3,Aoe=5e3;function wN(e){const{url:t,enabled:n=!0,clientName:a,clientUri:r,callbackUrl:i=typeof window<"u"?du(new URL("/oauth/callback",window.location.origin).toString()):"/oauth/callback",storageKeyPrefix:s="mcp:auth",clientConfig:c={},customHeaders:u={},debug:d=!1,autoRetry:m=!1,autoReconnect:h=aU,transportType:g="auto",preventAutoAuth:v=!1,useRedirectFlow:x=!1,onPopupWindow:S,timeout:y=3e4,sseReadTimeout:E=3e5,wrapTransport:_,onNotification:k,samplingCallback:C,onElicitation:R}=e,[I,A]=w.useState("discovering"),[O,M]=w.useState([]),[P,B]=w.useState([]),[K,ee]=w.useState([]),[te,ae]=w.useState([]),[H,Z]=w.useState(),[G,re]=w.useState(),[ne,j]=w.useState(void 0),[V,z]=w.useState([]),[$,L]=w.useState(void 0),F=w.useRef(null),W=w.useRef(null),X=w.useRef(!1),ie=w.useRef(!0),ce=w.useRef(0),J=w.useRef(null),q=w.useRef(I),le=w.useRef(h),he=w.useRef(null);w.useEffect(()=>{q.current=I,le.current=h},[I,h]);const oe=w.useCallback((Be,Le,...Se)=>{const je=Se.length>0?`${Le} ${Se.map(Ue=>JSON.stringify(Ue)).join(" ")}`:Le;console[Be](`[useMcp] ${je}`),ie.current&&z(Ue=>[...Ue.slice(-100),{level:Be,message:je,timestamp:Date.now()}])},[]),Ne=w.useCallback(async(Be=!1)=>{if(Be||oe("info","Disconnecting..."),X.current=!1,J.current&&clearTimeout(J.current),J.current=null,F.current)try{const Le="inspector-server",Se=F.current.getSession(Le);Se&&Se._healthCheckCleanup&&(Se._healthCheckCleanup(),Se._healthCheckCleanup=null),await F.current.closeSession(Le)}catch(Le){Be||oe("warn","Error closing session:",Le)}F.current=null,ie.current&&!Be&&(A("discovering"),M([]),B([]),ee([]),ae([]),j(void 0),L(void 0))},[oe]),Ve=w.useCallback((Be,Le)=>{if(oe("error",Be,Le??""),ie.current){A("failed"),j(Be);const Se=W.current?.getLastAttemptedAuthUrl();Se&&(L(Se),oe("info","Manual authentication URL may be available.",Se))}X.current=!1,t&&zi.getInstance().trackUseMcpConnection({url:t,transportType:g,success:!1,errorType:Le?.name||"UnknownError",hasOAuth:!!W.current,hasSampling:!!C,hasElicitation:!!R}).catch(()=>{})},[oe,t,g,C,R]),_e=w.useCallback(async()=>{if(!n||!t){oe("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag.");return}if(X.current){oe("debug","Connection attempt already in progress.");return}if(!ie.current){oe("debug","Connect called after unmount, aborting.");return}X.current=!0,ce.current+=1,j(void 0),L(void 0),he.current=null,A("discovering"),oe("info",`Connecting attempt #${ce.current} to ${t}...`),W.current||(W.current=new Ob(t,{storageKeyPrefix:s,clientName:a,clientUri:r,callbackUrl:i,preventAutoAuth:v,useRedirectFlow:x,onPopupWindow:S}),oe("debug","BrowserOAuthClientProvider initialized in connect.")),F.current||(F.current=new Coe,oe("debug","BrowserMCPClient initialized in connect."));const Be=ze(async(Se,je=!1)=>{oe("info",`Attempting connection with transport: ${Se}`);try{const Ue="inspector-server",We={url:t,transport:Se==="sse"?"http":Se,disableSseFallback:Se==="http",preferSse:Se==="sse"};if(u&&Object.keys(u).length>0&&(We.headers=u),W.current){const Ze=await W.current.tokens();Ze?.access_token&&(We.headers={...We.headers,Authorization:`Bearer ${Ze.access_token}`})}F.current.addServer(Ue,{...We,authProvider:W.current,clientOptions:c,samplingCallback:C,elicitationCallback:R,wrapTransport:_?Ze=>(console.log("[useMcp] Applying transport wrapper for server:",Ue,"url:",t),_(Ze,t)):void 0});const Je=await F.current.createSession(Ue,!1);Je.on("notification",Ze=>{k?.(Ze),Ze.method==="notifications/tools/list_changed"?(oe("info","Tools list changed, auto-refreshing..."),nt().catch(dt=>oe("warn","Auto-refresh tools failed:",dt))):Ze.method==="notifications/resources/list_changed"?(oe("info","Resources list changed, auto-refreshing..."),ft().catch(dt=>oe("warn","Auto-refresh resources failed:",dt))):Ze.method==="notifications/prompts/list_changed"&&(oe("info","Prompts list changed, auto-refreshing..."),Et().catch(dt=>oe("warn","Auto-refresh prompts failed:",dt)))}),await Je.initialize(),oe("info","✅ Successfully connected to MCP server"),oe("info","Server info:",Je.connector.serverInfo),oe("info","Server capabilities:",Je.connector.serverCapabilities),console.log("[useMcp] Server info:",Je.connector.serverInfo),console.log("[useMcp] Server capabilities:",Je.connector.serverCapabilities),A("ready"),he.current=Se;const yt=ze(()=>{let Ze=null,dt=Date.now();const At=1e4,Qn=3e4;return Ze=setInterval(ze(async()=>{if(!ie.current||q.current!=="ready"){Ze&&(clearInterval(Ze),Ze=null);return}try{await Je.connector.listTools(),dt=Date.now()}catch{const $n=Date.now()-dt;$n>Qn&&(oe("warn",`Connection appears to be broken (no response for ${Math.round($n/1e3)}s), attempting to reconnect...`),Ze&&(clearInterval(Ze),Ze=null),le.current&&ie.current&&(A("discovering"),oe("info","Auto-reconnecting to MCP server..."),setTimeout(()=>{ie.current&&q.current==="discovering"&&_e()},typeof le.current=="number"?le.current:aU)))}},"checkConnectionHealth"),At),()=>{Ze&&(clearInterval(Ze),Ze=null)}},"setupConnectionMonitoring");if(h){const Ze=yt();Je._healthCheckCleanup=Ze}zi.getInstance().trackUseMcpConnection({url:t,transportType:Se,success:!0,hasOAuth:!!W.current,hasSampling:!!C,hasElicitation:!!R}).catch(()=>{}),M(Je.connector.tools||[]);const mt=await Je.connector.listAllResources();B(mt.resources||[]);const Mt=await Je.connector.listPrompts();ae(Mt.prompts||[]);const nn=Je.connector.serverInfo,Ke=Je.connector.serverCapabilities;return nn&&(console.log("[useMcp] Server info:",nn),Z(nn)),Ke&&(console.log("[useMcp] Server capabilities:",Ke),re(Ke)),"success"}catch(Ue){const We=Ue,Je=We?.message||String(Ue);if(We.code===401||Je.includes("401")||Je.includes("Unauthorized")){if(W.current){oe("info","Authentication required. OAuth provider available.");try{const{auth:yt}=await Jn(async()=>{const{auth:Mt}=await Promise.resolve().then(()=>XP);return{auth:Mt}},void 0),mt=new URL(t).origin;yt(W.current,{serverUrl:mt}).catch(()=>{}),setTimeout(()=>{if(ie.current){const Mt=W.current?.getLastAttemptedAuthUrl();Mt?(L(Mt),oe("info","Manual authentication URL available:",Mt)):oe("warn","Could not generate authentication URL")}},100)}catch(yt){oe("warn","Error generating auth URL:",yt)}return ie.current&&A("pending_auth"),X.current=!1,"auth_redirect"}return u&&Object.keys(u).length>0?(Ve("Authentication failed: Server returned 401 Unauthorized. Check your Authorization header value is correct."),"failed"):(Ve("Authentication required: Server returned 401 Unauthorized. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed")}return Ve(Je,We instanceof Error?We:new Error(String(We))),"failed"}},"tryConnectWithTransport");let Le="failed";if(g==="sse")oe("debug","Using SSE-only transport mode"),Le=await Be("sse");else if(g==="http")oe("debug","Using HTTP-only transport mode"),Le=await Be("http");else{oe("debug","Using auto transport mode (HTTP with SSE fallback)");const Se=await Be("http");Se==="fallback"&&ie.current&&q.current!=="authenticating"?(oe("info","HTTP failed, attempting SSE fallback..."),Le=await Be("sse")):Le=Se}(Le==="success"||Le==="failed"||Le==="auth_redirect")&&(X.current=!1),oe("debug",`Connection sequence finished with status: ${Le}`)},[oe,Ve,Ne,t,s,a,r,i,c.name,c.version,u,g,v,x,S,n,y,E]),ke=w.useCallback(async(Be,Le,Se)=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot call tool "${Be}".`);oe("info",`Calling tool: ${Be}`,Le);const je=Date.now();try{const We=F.current.getSession("inspector-server");if(!We)throw new Error("No active session found");const Je=await We.connector.callTool(Be,Le||{},Se);return oe("info",`Tool "${Be}" call successful:`,Je),zi.getInstance().trackUseMcpToolCall({toolName:Be,success:!0,executionTimeMs:Date.now()-je}).catch(()=>{}),Je}catch(Ue){throw oe("error",`Tool "${Be}" call failed:`,Ue),zi.getInstance().trackUseMcpToolCall({toolName:Be,success:!1,errorType:Ue instanceof Error?Ue.name:"UnknownError",executionTimeMs:Date.now()-je}).catch(()=>{}),Ue}},[I]),Fe=w.useCallback(()=>{q.current==="failed"?(oe("info","Retry requested..."),_e()):oe("warn",`Retry called but state is not 'failed' (state: ${q.current}). Ignoring.`)},[oe,_e]),pe=w.useCallback(async()=>{oe("info","Manual authentication requested...");const Be=q.current;if(Be==="failed")oe("info","Attempting to reconnect and authenticate via retry..."),Fe();else if(Be==="pending_auth"){oe("info","Proceeding with authentication from pending state...");try{O_(W.current,"Auth Provider not available for manual auth"),O_(t,"Server URL is required for authentication"),oe("info","Clearing all OAuth state and initiating fresh flow...");const Le=`${s}:${W.current.serverUrlHash}`;Object.keys(localStorage).forEach(We=>{We.startsWith(Le)&&(oe("debug",`Removing stale OAuth key: ${We}`),localStorage.removeItem(We)),We.startsWith(`${s}:state_`)&&(oe("debug",`Removing orphaned state: ${We}`),localStorage.removeItem(We))}),A("authenticating");const Se=new Ob(t,{storageKeyPrefix:s,clientName:a,clientUri:r,callbackUrl:i,preventAutoAuth:!1,useRedirectFlow:x,onPopupWindow:S});W.current=Se,oe("info","Triggering fresh OAuth authorization...");const{auth:je}=await Jn(async()=>{const{auth:We}=await Promise.resolve().then(()=>XP);return{auth:We}},void 0),Ue=new URL(t).origin;je(Se,{serverUrl:Ue}).catch(We=>{oe("info","OAuth flow initiated:",We instanceof Error?We.message:"Redirecting...")})}catch(Le){if(!ie.current)return;A("pending_auth"),oe("error",`Manual authentication failed: ${Le instanceof Error?Le.message:String(Le)}`)}}else if(Be==="authenticating"){oe("warn","Already attempting authentication. Check for blocked popups or wait for timeout.");const Le=W.current?.getLastAttemptedAuthUrl();Le&&!$&&(L(Le),oe("info","Manual authentication URL retrieved:",Le))}else oe("info",`Client not in a state requiring manual authentication trigger (state: ${Be}). If needed, try disconnecting and reconnecting.`)},[oe,Fe,$,t,x,S,s,a,r,i]),Oe=w.useCallback(()=>{if(W.current){const Be=W.current.clearStorage();oe("info",`Cleared ${Be} item(s) from localStorage for ${t}.`),L(void 0),Ne()}else oe("warn","Auth provider not initialized, cannot clear storage.")},[t,oe,Ne]),He=w.useCallback(async()=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot list resources.`);oe("info","Listing resources");try{const Le=F.current.getSession("inspector-server");if(!Le)throw new Error("No active session found");const Se=await Le.connector.listAllResources();B(Se.resources||[]),oe("info","Resources listed successfully")}catch(Be){throw oe("error","List resources failed:",Be),Be}},[I]),xe=w.useCallback(async Be=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot read resource.`);oe("info",`Reading resource: ${Be}`);try{const Se=F.current.getSession("inspector-server");if(!Se)throw new Error("No active session found");const je=await Se.connector.readResource(Be);return oe("info","Resource read successful:",je),zi.getInstance().trackUseMcpResourceRead({resourceUri:Be,success:!0}).catch(()=>{}),je}catch(Le){throw oe("error","Resource read failed:",Le),zi.getInstance().trackUseMcpResourceRead({resourceUri:Be,success:!1,errorType:Le instanceof Error?Le.name:"UnknownError"}).catch(()=>{}),Le}},[I]),at=w.useCallback(async()=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot list prompts.`);oe("info","Listing prompts");try{const Le=F.current.getSession("inspector-server");if(!Le)throw new Error("No active session found");const Se=await Le.connector.listPrompts();ae(Se.prompts||[]),oe("info","Prompts listed successfully")}catch(Be){throw oe("error","List prompts failed:",Be),Be}},[I]),nt=w.useCallback(async()=>{if(q.current!=="ready"||!F.current){oe("debug","Cannot refresh tools - client not ready");return}oe("debug","Refreshing tools list");try{const Le=F.current.getSession("inspector-server");if(!Le){oe("warn","No active session found for tools refresh");return}const Se=await Le.connector.listTools();M(Se||[]),oe("info","Tools list refreshed successfully")}catch(Be){oe("warn","Failed to refresh tools:",Be)}},[oe]),ft=w.useCallback(async()=>{if(q.current!=="ready"||!F.current){oe("debug","Cannot refresh resources - client not ready");return}oe("debug","Refreshing resources list");try{const Le=F.current.getSession("inspector-server");if(!Le){oe("warn","No active session found for resources refresh");return}const Se=await Le.connector.listAllResources();B(Se.resources||[]),oe("info","Resources list refreshed successfully")}catch(Be){oe("warn","Failed to refresh resources:",Be)}},[oe]),Et=w.useCallback(async()=>{if(q.current!=="ready"||!F.current){oe("debug","Cannot refresh prompts - client not ready");return}oe("debug","Refreshing prompts list");try{const Le=F.current.getSession("inspector-server");if(!Le){oe("warn","No active session found for prompts refresh");return}const Se=await Le.connector.listPrompts();ae(Se.prompts||[]),oe("info","Prompts list refreshed successfully")}catch(Be){oe("warn","Failed to refresh prompts:",Be)}},[oe]),pt=w.useCallback(async()=>{oe("info","Refreshing all lists (tools, resources, prompts)"),await Promise.all([nt(),ft(),Et()])},[nt,ft,Et,oe]),mn=w.useCallback(async(Be,Le)=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot get prompt.`);oe("info",`Getting prompt: ${Be}`,Le);try{const je=F.current.getSession("inspector-server");if(!je)throw new Error("No active session found");const Ue=await je.connector.getPrompt(Be,Le||{});return oe("info",`Prompt "${Be}" retrieved successfully:`,Ue),Ue}catch(Se){throw oe("error",`Prompt "${Be}" retrieval failed:`,Se),Se}},[I]),Pr=w.useRef(_e),St=w.useRef(Ve);return w.useEffect(()=>{Pr.current=_e,St.current=Ve}),w.useEffect(()=>{const Be=ze(Le=>{Le.origin===window.location.origin&&Le.data?.type==="mcp_auth_callback"&&(oe("info","Received auth callback message.",Le.data),J.current&&clearTimeout(J.current),J.current=null,Le.data.success?(oe("info","Authentication successful via popup. Reconnecting client..."),X.current&&oe("debug","Connection attempt already in progress, resetting flag to allow reconnection."),X.current=!1,setTimeout(()=>{ie.current&&(oe("debug","Initiating reconnection after successful auth callback."),Pr.current())},100)):St.current(`Authentication failed in callback: ${Le.data.error||"Unknown reason."}`))},"messageHandler");return window.addEventListener("message",Be),oe("debug","Auth callback message listener added."),()=>{window.removeEventListener("message",Be),oe("debug","Auth callback message listener removed."),J.current&&clearTimeout(J.current)}},[oe]),w.useEffect(()=>(ie.current=!0,!n||!t?(oe("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag."),A("discovering"),()=>{ie.current=!1}):(oe("debug","useMcp mounted, initiating connection."),ce.current=0,(!W.current||W.current.serverUrl!==t)&&(W.current=new Ob(t,{storageKeyPrefix:s,clientName:a,clientUri:r,callbackUrl:i,preventAutoAuth:v,useRedirectFlow:x,onPopupWindow:S}),oe("debug","BrowserOAuthClientProvider initialized/updated on mount/option change.")),_e(),()=>{ie.current=!1,oe("debug","useMcp unmounting, disconnecting."),Ne(!0)})),[t,n,s,i,a,r,c.name,c.version,x]),w.useEffect(()=>{let Be=null;if(I==="failed"&&m&&ce.current>0){const Le=typeof m=="number"?m:Aoe;oe("info",`Connection failed, auto-retrying in ${Le}ms...`),Be=setTimeout(()=>{ie.current&&q.current==="failed"&&Fe()},Le)}return()=>{Be&&clearTimeout(Be)}},[I,m,Fe,oe]),{state:I,tools:O,resources:P,resourceTemplates:K,prompts:te,serverInfo:H,capabilities:G,error:ne,log:V,authUrl:$,client:F.current,callTool:ke,readResource:xe,listResources:He,listPrompts:at,getPrompt:mn,refreshTools:nt,refreshResources:ft,refreshPrompts:Et,refreshAll:pt,retry:Fe,disconnect:Ne,authenticate:pe,clearStorage:Oe}}ze(wN,"useMcp");var Xu,Ioe=(Xu=class extends ue.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("Widget Error:",t,n)}render(){return this.state.hasError?ue.createElement("div",{className:"p-4 border border-red-500 bg-red-50 text-red-900 rounded-md dark:bg-red-900/20 dark:text-red-100"},ue.createElement("h3",{className:"font-bold mb-2"},"Widget Error"),ue.createElement("pre",{className:"text-sm whitespace-pre-wrap"},this.state.error?.message)):this.props.children}},ze(Xu,"ErrorBoundary"),Xu),pp="openai:set_globals";function di(e){return w.useSyncExternalStore(t=>{const n=ze(a=>{a.detail.globals[e]!==void 0&&t()},"handleSetGlobal");return typeof window<"u"&&window.addEventListener(pp,n),()=>{typeof window<"u"&&window.removeEventListener(pp,n)}},()=>typeof window<"u"&&window.openai?window.openai[e]:void 0)}ze(di,"useOpenAiGlobal");function Td(e){const[t,n]=w.useState(()=>typeof window<"u"&&!!window.openai);w.useEffect(()=>{if(typeof window<"u"&&window.openai){n(!0);return}const P=setInterval(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(P))},100),B=ze(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(P))},"handleSetGlobals");typeof window<"u"&&window.addEventListener(pp,B);const K=setTimeout(()=>{clearInterval(P),typeof window<"u"&&window.removeEventListener(pp,B)},5e3);return()=>{clearInterval(P),clearTimeout(K),typeof window<"u"&&window.removeEventListener(pp,B)}},[]);const a=w.useMemo(()=>t?"openai":"mcp-ui",[t]),r=typeof window<"u"?window.location.search:"",i=w.useMemo(()=>{const P=new URLSearchParams(r);return P.has("mcpUseParams")?JSON.parse(P.get("mcpUseParams")):{toolInput:{},toolOutput:{},toolId:""}},[r]),s=a==="openai"?di("toolInput"):i.toolInput,c=a==="openai"?di("toolOutput"):i.toolOutput,u=di("toolResponseMetadata"),d=w.useMemo(()=>{if(u&&typeof u=="object"){const P=u["mcp-use/props"];if(P)return P}return e||{}},[u,e]),m=di("widgetState"),h=di("theme"),g=di("displayMode"),v=di("safeArea"),x=di("maxHeight"),S=di("userAgent"),y=di("locale"),E=w.useMemo(()=>typeof window<"u"&&window.__mcpPublicUrl?window.__mcpPublicUrl.replace(/\/mcp-use\/public$/,""):"",[]),[_,k]=w.useState(null);w.useEffect(()=>{m!==void 0&&k(m)},[m]);const C=w.useCallback(async(P,B)=>{if(!window.openai?.callTool)throw new Error("window.openai.callTool is not available");return window.openai.callTool(P,B)},[]),R=w.useCallback(async P=>{if(!window.openai?.sendFollowUpMessage)throw new Error("window.openai.sendFollowUpMessage is not available");return window.openai.sendFollowUpMessage({prompt:P})},[]),I=w.useCallback(P=>{if(!window.openai?.openExternal)throw new Error("window.openai.openExternal is not available");window.openai.openExternal({href:P})},[]),A=w.useCallback(async P=>{if(!window.openai?.requestDisplayMode)throw new Error("window.openai.requestDisplayMode is not available");return window.openai.requestDisplayMode({mode:P})},[]),O=w.useCallback(async P=>{if(!window.openai?.setWidgetState)throw new Error("window.openai.setWidgetState is not available");const K=typeof P=="function"?P(m!==void 0?m:_):P;return k(K),window.openai.setWidgetState(K)},[m,_]),M=w.useMemo(()=>a==="openai"&&u===null,[a,u]);return{props:d,toolInput:s||{},output:c??null,metadata:u??null,state:_,setState:O,theme:h||"light",displayMode:g||"inline",safeArea:v||{insets:{top:0,bottom:0,left:0,right:0}},maxHeight:x||600,userAgent:S||{device:{type:"desktop"},capabilities:{hover:!0,touch:!1}},locale:y||"en",mcp_url:E,callTool:C,sendFollowUpMessage:R,openExternal:I,requestDisplayMode:A,isAvailable:t,isPending:M}}ze(Td,"useWidget");function Ooe(e){const{props:t}=Td(e);return t}ze(Ooe,"useWidgetProps");function Doe(){const{theme:e}=Td();return e}ze(Doe,"useWidgetTheme");function joe(e){const{state:t,setState:n}=Td();return w.useEffect(()=>{t===null&&e!==void 0&&window.openai?.setWidgetState&&n(e)},[]),[t,n]}ze(joe,"useWidgetState");var iU=ze(({children:e})=>{const{theme:t,isAvailable:n}=Td();console.log("theme",t);const[a,r]=w.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");w.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(prefers-color-scheme: dark)"),c=ze(u=>{r(u.matches?"dark":"light")},"handleChange");return s.addEventListener("change",c),()=>s.removeEventListener("change",c)},[]);const i=n?t:a;return w.useLayoutEffect(()=>{typeof document>"u"||(i==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark"))},[i]),ue.createElement(ue.Fragment,null,e)},"ThemeProvider");function n9({children:e,className:t="",position:n="top-right",attachTo:a,showLabels:r=!0,debugger:i=!1,viewControls:s=!1}){const{props:c,output:u,metadata:d,state:m,theme:h,displayMode:g,safeArea:v,maxHeight:x,userAgent:S,locale:y,isAvailable:E,callTool:_,sendFollowUpMessage:k,openExternal:C,requestDisplayMode:R,setState:I}=Td(),[A,O]=w.useState(!1),[M,P]=w.useState(!1),B=w.useRef(null),K=w.useRef(null),[ee,te]=w.useState([]),[ae,H]=w.useState(""),[Z,G]=w.useState("get-my-city"),[re,ne]=w.useState("{}"),[j,V]=w.useState("Test follow-up message"),[z,$]=w.useState("https://docs.mcp-use.com"),L=g==="fullscreen"&&E,F=g==="pip"&&E,W=typeof window<"u"&&window.location.pathname.includes("/inspector/api/");w.useEffect(()=>{const xe=setTimeout(()=>{if(typeof window<"u"&&window.openai)try{const at=Object.keys(window.openai);te(at)}catch{te([])}else te([])},100);return()=>{clearTimeout(xe)}},[]);const X=h==="dark",ie=ze(()=>{const xe=["absolute","z-[1000]","flex","gap-2","transition-opacity","duration-200","ease-in-out",A?"opacity-100":"opacity-0",A?"pointer-events-auto":"pointer-events-none"];switch(n){case"top-left":return[...xe,"top-4","left-4"];case"top-center":return[...xe,"top-4","left-1/2","-translate-x-1/2"];case"top-right":return[...xe,"top-4","right-4"];case"center-left":return[...xe,"top-1/2","left-4","-translate-y-1/2"];case"center-right":return[...xe,"top-1/2","right-4","-translate-y-1/2"];case"bottom-left":return[...xe,"bottom-4","left-4"];case"bottom-center":return[...xe,"bottom-4","left-1/2","-translate-x-1/2"];case"bottom-right":return[...xe,"bottom-4","right-4"];default:return[...xe,"top-4","right-4"]}},"getPositionClasses"),ce=ze(()=>{const at=v?.insets?.top?Math.max(16,v.insets.top+8):16,nt=v?.insets?.right?Math.max(16,v.insets.right+8):16,ft=v?.insets?.bottom?Math.max(16,v.insets.bottom+8):16,Et=v?.insets?.left?Math.max(16,v.insets.left+8):16,pt={};switch(n){case"top-left":pt.top=`${at}px`,pt.left=`${Et}px`;break;case"top-center":pt.top=`${at}px`;break;case"top-right":pt.top=`${at}px`,pt.right=`${nt}px`;break;case"center-left":pt.left=`${Et}px`;break;case"center-right":pt.right=`${nt}px`;break;case"bottom-left":pt.bottom=`${ft}px`,pt.left=`${Et}px`;break;case"bottom-center":pt.bottom=`${ft}px`;break;case"bottom-right":pt.bottom=`${ft}px`,pt.right=`${nt}px`;break;default:pt.top=`${at}px`,pt.right=`${nt}px`;break}return pt},"getPositionOffsetStyles");w.useEffect(()=>{if(!a)return;const xe=ze(()=>O(!0),"handleMouseEnter"),at=ze(()=>O(!1),"handleMouseLeave");return a.addEventListener("mouseenter",xe),a.addEventListener("mouseleave",at),()=>{a.removeEventListener("mouseenter",xe),a.removeEventListener("mouseleave",at)}},[a]),w.useEffect(()=>{if(!M)return;const xe=ze(at=>{K.current&&!K.current.contains(at.target)&&P(!1)},"handleClickOutside");return document.addEventListener("mousedown",xe),()=>{document.removeEventListener("mousedown",xe)}},[M]),w.useEffect(()=>(M?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[M]);const J=ze(()=>{P(!M)},"handleToggleOverlay"),q=ze(async()=>{try{H("Calling tool...");const xe=re.trim()?JSON.parse(re):{},at=await _(Z,xe);H(`Success: ${JSON.stringify(at,null,2)}`)}catch(xe){H(`Error: ${xe.message}`)}},"handleCallTool"),le=ze(async()=>{try{H("Sending follow-up message..."),await k(j),H("Follow-up message sent successfully")}catch(xe){H(`Error: ${xe.message}`)}},"handleSendFollowUpMessage"),he=ze(()=>{try{C(z),H(`Opened external link: ${z}`)}catch(xe){H(`Error: ${xe.message}`)}},"handleOpenExternal"),oe=ze(async xe=>{try{H(`Requesting display mode: ${xe}...`);const at=await R(xe);H(`Display mode granted: ${at.mode}`)}catch(at){H(`Error: ${at.message}`)}},"handleRequestDisplayMode"),Ne=ze(async()=>{try{const xe=m?{...m,debugTimestamp:new Date().toISOString()}:{debugTimestamp:new Date().toISOString()};H("Setting state..."),await I(xe),H(`State updated: ${JSON.stringify(xe,null,2)}`)}catch(xe){H(`Error: ${xe.message}`)}},"handleSetState"),Ve=ze(async()=>{try{await R("fullscreen")}catch(xe){console.error("Failed to go fullscreen:",xe)}},"handleFullscreen"),_e=ze(async()=>{try{await R("pip")}catch(xe){console.error("Failed to go pip:",xe)}},"handlePip"),ke=ze(()=>{const xe=["absolute","px-2","py-1","bg-black/90","text-white","rounded","text-xs","whitespace-nowrap","pointer-events-none","transition-opacity","duration-200","ease-in-out"];switch(n){case"top-right":return[...xe,"top-full","right-0","mt-2"];case"top-left":return[...xe,"top-full","left-0","mt-2"];case"top-center":return[...xe,"top-full","left-1/2","-translate-x-1/2","mt-2"];case"bottom-right":return[...xe,"bottom-full","right-0","mb-2"];case"bottom-left":return[...xe,"bottom-full","left-0","mb-2"];case"bottom-center":return[...xe,"bottom-full","left-1/2","-translate-x-1/2","mb-2"];case"center-left":return[...xe,"left-full","top-1/2","-translate-y-1/2","ml-2"];case"center-right":return[...xe,"right-full","top-1/2","-translate-y-1/2","mr-2"];default:return[...xe,"top-full","right-0","mt-2"]}},"getTooltipClasses"),Fe=ze(({onClick:xe,label:at,children:nt})=>{const[ft,Et]=w.useState(!1),pt=ke();return ue.createElement("button",{className:`p-2 ${X?"bg-white/10 hover:bg-white/20":"bg-black/70 hover:bg-black/90"} text-white border-none rounded-lg cursor-pointer flex items-center justify-center w-8 h-8 transition-colors duration-200 backdrop-blur-md ${X?"shadow-[0_2px_8px_rgba(0,0,0,0.3)]":"shadow-[0_2px_8px_rgba(0,0,0,0.2)]"} relative`,onMouseEnter:()=>Et(!0),onMouseLeave:()=>Et(!1),onClick:xe,"aria-label":at},ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"block"},nt),r&&ue.createElement("span",{className:`${pt.join(" ")} ${ft?"opacity-100":"opacity-0"}`},at))},"IconButton"),pe=ze(xe=>{if(xe===null)return"null";if(xe===void 0)return"undefined";if(typeof xe=="object")try{return JSON.stringify(xe,null,2)}catch{return String(xe)}return String(xe)},"formatValue"),Oe=ze(xe=>xe?`${xe.device?.type||"unknown"}`:"N/A","formatUserAgent"),He=ze(xe=>{if(!xe?.insets)return"N/A";const{top:at,bottom:nt,left:ft,right:Et}=xe.insets;return`T:${at} B:${nt} L:${ft} R:${Et}`},"formatSafeArea");return ue.createElement(ue.Fragment,null,ue.createElement("div",{ref:B,className:`${t} relative h-fit`,onMouseEnter:()=>!a&&O(!0),onMouseLeave:()=>!a&&O(!1)},ue.createElement("div",{className:ie().join(" "),style:ce()},!W&&ue.createElement(ue.Fragment,null,!L&&!F&&ue.createElement(ue.Fragment,null,(s===!0||s==="fullscreen")&&ue.createElement(Fe,{onClick:Ve,label:"Fullscreen"},ue.createElement("path",{d:"M15 3h6v6"}),ue.createElement("path",{d:"m21 3-7 7"}),ue.createElement("path",{d:"m3 21 7-7"}),ue.createElement("path",{d:"M9 21H3v-6"})),(s===!0||s==="pip")&&ue.createElement(Fe,{onClick:_e,label:"Picture in Picture"},ue.createElement("path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4"}),ue.createElement("rect",{width:"10",height:"7",x:"12",y:"13",rx:"2"}))),i&&ue.createElement(Fe,{onClick:J,label:"Debug Info"},ue.createElement("path",{d:"M12 20v-9"}),ue.createElement("path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z"}),ue.createElement("path",{d:"M14.12 3.88 16 2"}),ue.createElement("path",{d:"M21 21a4 4 0 0 0-3.81-4"}),ue.createElement("path",{d:"M21 5a4 4 0 0 1-3.55 3.97"}),ue.createElement("path",{d:"M22 13h-4"}),ue.createElement("path",{d:"M3 21a4 4 0 0 1 3.81-4"}),ue.createElement("path",{d:"M3 5a4 4 0 0 0 3.55 3.97"}),ue.createElement("path",{d:"M6 13H2"}),ue.createElement("path",{d:"m8 2 1.88 1.88"}),ue.createElement("path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13"})))),e),M&&i&&ue.createElement("div",{ref:K,className:"fixed inset-0 bg-black text-white font-mono text-xs z-[10000] overflow-auto p-4",onClick:xe=>{xe.target===K.current&&P(!1)}},ue.createElement("button",{onClick:()=>P(!1),className:"absolute top-4 right-4 bg-white/10 text-white border-none rounded w-8 h-8 cursor-pointer flex items-center justify-center text-lg leading-none","aria-label":"Close"},"×"),ue.createElement("div",{className:"max-w-[1200px] mx-auto pt-10"},ue.createElement("h1",{className:"text-lg font-bold mb-4 border-b border-gray-700 pb-2"},"Debug Info"),ue.createElement("table",{className:"w-full border-collapse border-spacing-0"},ue.createElement("tbody",null,ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Props"),ue.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},pe(c))),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Output"),ue.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},pe(u))),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Metadata"),ue.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},pe(d))),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"State"),ue.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},pe(m))),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Theme"),ue.createElement("td",{className:"p-2"},h)),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Display Mode"),ue.createElement("td",{className:"p-2"},g)),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Locale"),ue.createElement("td",{className:"p-2"},y)),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Max Height"),ue.createElement("td",{className:"p-2"},x,"px")),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"User Agent"),ue.createElement("td",{className:"p-2"},Oe(S))),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Safe Area"),ue.createElement("td",{className:"p-2"},He(v))),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"API Available"),ue.createElement("td",{className:"p-2"},E?"Yes":"No")),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"window.openai Keys"),ue.createElement("td",{className:"p-2"},ee.length>0?ee.join(", "):"N/A")))),ue.createElement("h2",{className:"text-base font-bold mt-8 mb-4 border-b border-gray-700 pb-2"},"Actions"),ue.createElement("div",{className:"flex flex-col gap-3"},ue.createElement("div",{className:"flex gap-2 items-center"},ue.createElement("input",{type:"text",value:Z,onChange:xe=>G(xe.target.value),placeholder:"Tool name",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs w-[150px]"}),ue.createElement("input",{type:"text",value:re,onChange:xe=>ne(xe.target.value),placeholder:'{"key": "value"}',className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),ue.createElement("button",{onClick:q,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Call Tool")),ue.createElement("div",{className:"flex gap-2 items-center"},ue.createElement("input",{type:"text",value:j,onChange:xe=>V(xe.target.value),placeholder:"Follow-up message",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),ue.createElement("button",{onClick:le,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Send Follow-Up")),ue.createElement("div",{className:"flex gap-2 items-center"},ue.createElement("input",{type:"text",value:z,onChange:xe=>$(xe.target.value),placeholder:"External URL",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),ue.createElement("button",{onClick:he,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Open Link")),ue.createElement("div",{className:"flex gap-2 items-center"},ue.createElement("span",{className:"w-[150px] text-xs"},"Display Mode:"),ue.createElement("button",{onClick:()=>oe("inline"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"Inline"),ue.createElement("button",{onClick:()=>oe("pip"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"PiP"),ue.createElement("button",{onClick:()=>oe("fullscreen"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"Fullscreen")),ue.createElement("div",{className:"flex gap-2 items-center"},ue.createElement("button",{onClick:Ne,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Set State (Add Timestamp)")),ae&&ue.createElement("div",{className:"mt-2 p-2 bg-[#1a1a1a] border border-gray-700 rounded whitespace-pre-wrap break-all text-[11px] max-h-[200px] overflow-auto"},ue.createElement("div",{className:"font-bold mb-1 text-gray-400"},"Result:"),ae,ue.createElement("button",{onClick:()=>H(""),className:"mt-2 py-1 px-2 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-[11px]"},"Clear"))))))}ze(n9,"WidgetControls");function r9(){if(typeof window>"u")return"/";const t=window.location.pathname.match(/^(\/inspector\/api\/dev-widget\/[^/]+)/);return t?t[1]:"/"}ze(r9,"getBasename");var $oe=150,Loe=5;function Moe({children:e,debugger:t=!1,viewControls:n=!1,autoSize:a=!1}){const r=r9(),i=w.useRef(null),s=w.useRef(0),c=w.useRef(null),u=w.useRef(!1),[d,m]=w.useState(null),[h,g]=w.useState(null),[v,x]=w.useState(!0);w.useEffect(()=>{let _=!0;return(async()=>{try{const k=await Jn(()=>import("./index-DQ__bbG6.js"),[]);_&&(m(()=>k.BrowserRouter),x(!1))}catch{_&&(g(new Error(`❌ react-router not installed!
35
+ `&&a++}}return[t,n]}class hoe extends TransformStream{constructor({onError:t,onRetry:n,onComment:a}={}){let r;super({start(i){r=QV({onEvent:s=>{i.enqueue(s)},onError(s){t==="terminate"?i.error(s):typeof t=="function"&&t(s)},onRetry:n,onComment:a})},transform(i){r.feed(i)}})}}const goe={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class kl extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class boe{constructor(t,n){var a;this._hasCompletedAuthFlow=!1,this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=n?.requestInit,this._authProvider=n?.authProvider,this._fetch=n?.fetch,this._fetchWithInit=UV(n?.fetch,n?.requestInit),this._sessionId=n?.sessionId,this._reconnectionOptions=(a=n?.reconnectionOptions)!==null&&a!==void 0?a:goe}async _authThenStart(){var t;if(!this._authProvider)throw new qa("No auth provider");let n;try{n=await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(a){throw(t=this.onerror)===null||t===void 0||t.call(this,a),a}if(n!=="AUTHORIZED")throw new qa;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const n={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(n.Authorization=`Bearer ${r.access_token}`)}this._sessionId&&(n["mcp-session-id"]=this._sessionId),this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const a=pv((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...a})}async _startOrAuthSse(t){var n,a,r,i;const{resumptionToken:s}=t;try{const c=await this._commonHeaders();c.set("Accept","text/event-stream"),s&&c.set("last-event-id",s);const u=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,{method:"GET",headers:c,signal:(a=this._abortController)===null||a===void 0?void 0:a.signal});if(!u.ok){if(await((r=u.body)===null||r===void 0?void 0:r.cancel()),u.status===401&&this._authProvider)return await this._authThenStart();if(u.status===405)return;throw new kl(u.status,`Failed to open SSE stream: ${u.statusText}`)}this._handleSseStream(u.body,t,!0)}catch(c){throw(i=this.onerror)===null||i===void 0||i.call(this,c),c}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const n=this._reconnectionOptions.initialReconnectionDelay,a=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(a,t),r)}_scheduleReconnection(t,n=0){var a;const r=this._reconnectionOptions.maxRetries;if(n>=r){(a=this.onerror)===null||a===void 0||a.call(this,new Error(`Maximum reconnection attempts (${r}) exceeded.`));return}const i=this._getNextReconnectionDelay(n);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(s=>{var c;(c=this.onerror)===null||c===void 0||c.call(this,new Error(`Failed to reconnect SSE stream: ${s instanceof Error?s.message:String(s)}`)),this._scheduleReconnection(t,n+1)})},i)}_handleSseStream(t,n,a){if(!t)return;const{onresumptiontoken:r,replayMessageId:i}=n;let s,c=!1,u=!1;(async()=>{var m,h,g,v;try{const x=t.pipeThrough(new TextDecoderStream).pipeThrough(new hoe({onRetry:E=>{this._serverRetryMs=E}})).getReader();for(;;){const{value:E,done:_}=await x.read();if(_)break;if(E.id&&(s=E.id,c=!0,r?.(E.id)),!!E.data&&(!E.event||E.event==="message"))try{const k=Cb.parse(JSON.parse(E.data));Qf(k)&&(u=!0,i!==void 0&&(k.id=i)),(m=this.onmessage)===null||m===void 0||m.call(this,k)}catch(k){(h=this.onerror)===null||h===void 0||h.call(this,k)}}(a||c)&&!u&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:r,replayMessageId:i},0)}catch(x){if((g=this.onerror)===null||g===void 0||g.call(this,new Error(`SSE stream disconnected: ${x}`)),(a||c)&&!u&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:r,replayMessageId:i},0)}catch(E){(v=this.onerror)===null||v===void 0||v.call(this,new Error(`Failed to reconnect: ${E instanceof Error?E.message:String(E)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new qa("No auth provider");if(await Co(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa("Failed to authorize")}async close(){var t,n;this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),(t=this._abortController)===null||t===void 0||t.abort(),(n=this.onclose)===null||n===void 0||n.call(this)}async send(t,n){var a,r,i,s,c,u,d;try{const{resumptionToken:m,onresumptiontoken:h}=n||{};if(m){this._startOrAuthSse({resumptionToken:m,replayMessageId:d_(t)?t.id:void 0}).catch(k=>{var C;return(C=this.onerror)===null||C===void 0?void 0:C.call(this,k)});return}const g=await this._commonHeaders();g.set("content-type","application/json"),g.set("accept","application/json, text/event-stream");const v={...this._requestInit,method:"POST",headers:g,body:JSON.stringify(t),signal:(a=this._abortController)===null||a===void 0?void 0:a.signal},x=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._url,v),S=x.headers.get("mcp-session-id");if(S&&(this._sessionId=S),!x.ok){const k=await x.text().catch(()=>null);if(x.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new kl(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:C,scope:R}=Lp(x);if(this._resourceMetadataUrl=C,this._scope=R,await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa;return this._hasCompletedAuthFlow=!0,this.send(t)}if(x.status===403&&this._authProvider){const{resourceMetadataUrl:C,scope:R,error:I}=Lp(x);if(I==="insufficient_scope"){const A=x.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===A)throw new kl(403,"Server returned 403 after trying upscoping");if(R&&(this._scope=R),C&&(this._resourceMetadataUrl=C),this._lastUpscopingHeader=A??void 0,await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new qa;return this.send(t)}}throw new kl(x.status,`Error POSTing to endpoint: ${k}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,x.status===202){await((i=x.body)===null||i===void 0?void 0:i.cancel()),lre(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(k=>{var C;return(C=this.onerror)===null||C===void 0?void 0:C.call(this,k)});return}const E=(Array.isArray(t)?t:[t]).filter(k=>"method"in k&&"id"in k&&k.id!==void 0).length>0,_=x.headers.get("content-type");if(E)if(_?.includes("text/event-stream"))this._handleSseStream(x.body,{onresumptiontoken:h},!1);else if(_?.includes("application/json")){const k=await x.json(),C=Array.isArray(k)?k.map(R=>Cb.parse(R)):[Cb.parse(k)];for(const R of C)(s=this.onmessage)===null||s===void 0||s.call(this,R)}else throw await((c=x.body)===null||c===void 0?void 0:c.cancel()),new kl(-1,`Unexpected content type: ${_}`);else await((u=x.body)===null||u===void 0?void 0:u.cancel())}catch(m){throw(d=this.onerror)===null||d===void 0||d.call(this,m),m}}get sessionId(){return this._sessionId}async terminateSession(){var t,n,a,r;if(this._sessionId)try{const i=await this._commonHeaders(),s={...this._requestInit,method:"DELETE",headers:i,signal:(t=this._abortController)===null||t===void 0?void 0:t.signal},c=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,s);if(await((a=c.body)===null||a===void 0?void 0:a.cancel()),!c.ok&&c.status!==405)throw new kl(c.status,`Failed to terminate session: ${c.statusText}`);this._sessionId=void 0}catch(i){throw(r=this.onerror)===null||r===void 0||r.call(this,i),i}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,n){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:n?.onresumptiontoken})}}class QP extends Event{constructor(t,n){var a,r;super(t),this.code=(a=n?.code)!=null?a:void 0,this.message=(r=n?.message)!=null?r:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,a){return a(eU(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(eU(this),n)}}function voe(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function E_(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(E_).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${E_(e.cause)}`:e.message:`${e}`}function eU(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var e9=e=>{throw TypeError(e)},bN=(e,t,n)=>t.has(e)||e9("Cannot "+n),Ft=(e,t,n)=>(bN(e,t,"read from private field"),n?n.call(e):t.get(e)),ur=(e,t,n)=>t.has(e)?e9("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Mn=(e,t,n,a)=>(bN(e,t,"write to private field"),t.set(e,n),n),_o=(e,t,n)=>(bN(e,t,"access private method"),n),ba,Nl,Qc,Ab,vv,dp,uu,fp,Cs,eu,Su,tu,ep,fi,k_,T_,N_,tU,C_,R_,tp,A_,I_;class Ib extends EventTarget{constructor(t,n){var a,r;super(),ur(this,fi),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,ur(this,ba),ur(this,Nl),ur(this,Qc),ur(this,Ab),ur(this,vv),ur(this,dp),ur(this,uu),ur(this,fp,null),ur(this,Cs),ur(this,eu),ur(this,Su,null),ur(this,tu,null),ur(this,ep,null),ur(this,T_,async i=>{var s;Ft(this,eu).reset();const{body:c,redirected:u,status:d,headers:m}=i;if(d===204){_o(this,fi,tp).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Mn(this,Qc,new URL(i.url)):Mn(this,Qc,void 0),d!==200){_o(this,fi,tp).call(this,`Non-200 status code (${d})`,d);return}if(!(m.get("content-type")||"").startsWith("text/event-stream")){_o(this,fi,tp).call(this,'Invalid content type, expected "text/event-stream"',d);return}if(Ft(this,ba)===this.CLOSED)return;Mn(this,ba,this.OPEN);const h=new Event("open");if((s=Ft(this,ep))==null||s.call(this,h),this.dispatchEvent(h),typeof c!="object"||!c||!("getReader"in c)){_o(this,fi,tp).call(this,"Invalid response body, expected a web ReadableStream",d),this.close();return}const g=new TextDecoder,v=c.getReader();let x=!0;do{const{done:S,value:y}=await v.read();y&&Ft(this,eu).feed(g.decode(y,{stream:!S})),S&&(x=!1,Ft(this,eu).reset(),_o(this,fi,A_).call(this))}while(x)}),ur(this,N_,i=>{Mn(this,Cs,void 0),!(i.name==="AbortError"||i.type==="aborted")&&_o(this,fi,A_).call(this,E_(i))}),ur(this,C_,i=>{typeof i.id=="string"&&Mn(this,fp,i.id);const s=new MessageEvent(i.event||"message",{data:i.data,origin:Ft(this,Qc)?Ft(this,Qc).origin:Ft(this,Nl).origin,lastEventId:i.id||""});Ft(this,tu)&&(!i.event||i.event==="message")&&Ft(this,tu).call(this,s),this.dispatchEvent(s)}),ur(this,R_,i=>{Mn(this,dp,i)}),ur(this,I_,()=>{Mn(this,uu,void 0),Ft(this,ba)===this.CONNECTING&&_o(this,fi,k_).call(this)});try{if(t instanceof URL)Mn(this,Nl,t);else if(typeof t=="string")Mn(this,Nl,new URL(t,yoe()));else throw new Error("Invalid URL")}catch{throw voe("An invalid or illegal string was specified")}Mn(this,eu,QV({onEvent:Ft(this,C_),onRetry:Ft(this,R_)})),Mn(this,ba,this.CONNECTING),Mn(this,dp,3e3),Mn(this,vv,(a=n?.fetch)!=null?a:globalThis.fetch),Mn(this,Ab,(r=n?.withCredentials)!=null?r:!1),_o(this,fi,k_).call(this)}get readyState(){return Ft(this,ba)}get url(){return Ft(this,Nl).href}get withCredentials(){return Ft(this,Ab)}get onerror(){return Ft(this,Su)}set onerror(t){Mn(this,Su,t)}get onmessage(){return Ft(this,tu)}set onmessage(t){Mn(this,tu,t)}get onopen(){return Ft(this,ep)}set onopen(t){Mn(this,ep,t)}addEventListener(t,n,a){const r=n;super.addEventListener(t,r,a)}removeEventListener(t,n,a){const r=n;super.removeEventListener(t,r,a)}close(){Ft(this,uu)&&clearTimeout(Ft(this,uu)),Ft(this,ba)!==this.CLOSED&&(Ft(this,Cs)&&Ft(this,Cs).abort(),Mn(this,ba,this.CLOSED),Mn(this,Cs,void 0))}}ba=new WeakMap,Nl=new WeakMap,Qc=new WeakMap,Ab=new WeakMap,vv=new WeakMap,dp=new WeakMap,uu=new WeakMap,fp=new WeakMap,Cs=new WeakMap,eu=new WeakMap,Su=new WeakMap,tu=new WeakMap,ep=new WeakMap,fi=new WeakSet,k_=function(){Mn(this,ba,this.CONNECTING),Mn(this,Cs,new AbortController),Ft(this,vv)(Ft(this,Nl),_o(this,fi,tU).call(this)).then(Ft(this,T_)).catch(Ft(this,N_))},T_=new WeakMap,N_=new WeakMap,tU=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Ft(this,fp)?{"Last-Event-ID":Ft(this,fp)}:void 0},cache:"no-store",signal:(e=Ft(this,Cs))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},C_=new WeakMap,R_=new WeakMap,tp=function(e,t){var n;Ft(this,ba)!==this.CLOSED&&Mn(this,ba,this.CLOSED);const a=new QP("error",{code:t,message:e});(n=Ft(this,Su))==null||n.call(this,a),this.dispatchEvent(a)},A_=function(e,t){var n;if(Ft(this,ba)===this.CLOSED)return;Mn(this,ba,this.CONNECTING);const a=new QP("error",{code:t,message:e});(n=Ft(this,Su))==null||n.call(this,a),this.dispatchEvent(a),Mn(this,uu,setTimeout(Ft(this,I_),Ft(this,dp)))},I_=new WeakMap,Ib.CONNECTING=0,Ib.OPEN=1,Ib.CLOSED=2;function yoe(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class woe extends Error{constructor(t,n,a){super(`SSE error: ${n}`),this.code=t,this.event=a}}class Soe{constructor(t,n){this._url=t,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=n?.eventSourceInit,this._requestInit=n?.requestInit,this._authProvider=n?.authProvider,this._fetch=n?.fetch,this._fetchWithInit=UV(n?.fetch,n?.requestInit)}async _authThenStart(){var t;if(!this._authProvider)throw new qa("No auth provider");let n;try{n=await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(a){throw(t=this.onerror)===null||t===void 0||t.call(this,a),a}if(n!=="AUTHORIZED")throw new qa;return await this._startOrAuth()}async _commonHeaders(){var t;const n={};if(this._authProvider){const r=await this._authProvider.tokens();r&&(n.Authorization=`Bearer ${r.access_token}`)}this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const a=pv((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...a})}_startOrAuth(){var t,n,a;const r=(a=(n=(t=this===null||this===void 0?void 0:this._eventSourceInit)===null||t===void 0?void 0:t.fetch)!==null&&n!==void 0?n:this._fetch)!==null&&a!==void 0?a:fetch;return new Promise((i,s)=>{this._eventSource=new Ib(this._url.href,{...this._eventSourceInit,fetch:async(c,u)=>{const d=await this._commonHeaders();d.set("Accept","text/event-stream");const m=await r(c,{...u,headers:d});if(m.status===401&&m.headers.has("www-authenticate")){const{resourceMetadataUrl:h,scope:g}=Lp(m);this._resourceMetadataUrl=h,this._scope=g}return m}}),this._abortController=new AbortController,this._eventSource.onerror=c=>{var u;if(c.code===401&&this._authProvider){this._authThenStart().then(i,s);return}const d=new woe(c.code,c.message,c);s(d),(u=this.onerror)===null||u===void 0||u.call(this,d)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",c=>{var u;const d=c;try{if(this._endpoint=new URL(d.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(m){s(m),(u=this.onerror)===null||u===void 0||u.call(this,m),this.close();return}i()}),this._eventSource.onmessage=c=>{var u,d;const m=c;let h;try{h=Cb.parse(JSON.parse(m.data))}catch(g){(u=this.onerror)===null||u===void 0||u.call(this,g);return}(d=this.onmessage)===null||d===void 0||d.call(this,h)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(t){if(!this._authProvider)throw new qa("No auth provider");if(await Co(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa("Failed to authorize")}async close(){var t,n,a;(t=this._abortController)===null||t===void 0||t.abort(),(n=this._eventSource)===null||n===void 0||n.close(),(a=this.onclose)===null||a===void 0||a.call(this)}async send(t){var n,a,r,i;if(!this._endpoint)throw new Error("Not connected");try{const s=await this._commonHeaders();s.set("content-type","application/json");const c={...this._requestInit,method:"POST",headers:s,body:JSON.stringify(t),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},u=await((a=this._fetch)!==null&&a!==void 0?a:fetch)(this._endpoint,c);if(!u.ok){const d=await u.text().catch(()=>null);if(u.status===401&&this._authProvider){const{resourceMetadataUrl:m,scope:h}=Lp(u);if(this._resourceMetadataUrl=m,this._scope=h,await Co(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new qa;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${u.status}): ${d}`)}await((r=u.body)===null||r===void 0?void 0:r.cancel())}catch(s){throw(i=this.onerror)===null||i===void 0||i.call(this,s),s}}setProtocolVersion(t){this._protocolVersion=t}}var Vu,xoe=(Vu=class{connector;autoConnect;constructor(t,n=!0){this.connector=t,this.autoConnect=n}async connect(){await this.connector.connect()}async disconnect(){await this.connector.disconnect()}async initialize(){!this.isConnected&&this.autoConnect&&await this.connect(),await this.connector.initialize()}get isConnected(){return this.connector&&this.connector.isClientConnected}on(t,n){t==="notification"&&this.connector.onNotification(n)}async setRoots(t){return this.connector.setRoots(t)}getRoots(){return this.connector.getRoots()}get tools(){return this.connector.tools}async listTools(t){return this.connector.listTools(t)}get serverCapabilities(){return this.connector.serverCapabilities}get serverInfo(){return this.connector.serverInfo}async callTool(t,n={},a){return this.connector.callTool(t,n,a)}async listResources(t,n){return this.connector.listResources(t,n)}async listAllResources(t){return this.connector.listAllResources(t)}async listResourceTemplates(t){return this.connector.listResourceTemplates(t)}async readResource(t,n){return this.connector.readResource(t,n)}async subscribeToResource(t,n){return this.connector.subscribeToResource(t,n)}async unsubscribeFromResource(t,n){return this.connector.unsubscribeFromResource(t,n)}async listPrompts(){return this.connector.listPrompts()}async getPrompt(t,n){return this.connector.getPrompt(t,n)}async request(t,n=null,a){return this.connector.request(t,n,a)}},ze(Vu,"MCPSession"),Vu),Gu,_oe=(Gu=class{config={};sessions={};activeSessions=[];constructor(t){t&&(this.config=t)}static fromDict(t){throw new Error("fromDict must be implemented by concrete class")}addServer(t,n){this.config.mcpServers=this.config.mcpServers||{},this.config.mcpServers[t]=n,zi.getInstance().trackClientAddServer(t,n)}removeServer(t){this.config.mcpServers?.[t]&&(delete this.config.mcpServers[t],this.activeSessions=this.activeSessions.filter(n=>n!==t),zi.getInstance().trackClientRemoveServer(t))}getServerNames(){return Object.keys(this.config.mcpServers??{})}getServerConfig(t){return this.config.mcpServers?.[t]}getConfig(){return this.config??{}}async createSession(t,n=!0){const a=this.config.mcpServers??{};if(Object.keys(a).length===0&&Ce.warn("No MCP servers defined in config"),!a[t])throw new Error(`Server '${t}' not found in config`);const r=this.createConnectorFromConfig(a[t]),i=new xoe(r);return n&&await i.initialize(),this.sessions[t]=i,this.activeSessions.includes(t)||this.activeSessions.push(t),i}async createAllSessions(t=!0){const n=this.config.mcpServers??{};Object.keys(n).length===0&&Ce.warn("No MCP servers defined in config");for(const a of Object.keys(n))await this.createSession(a,t);return this.sessions}getSession(t){const n=this.sessions[t];return n||null}requireSession(t){const n=this.sessions[t];if(!n)throw new Error(`Session '${t}' not found. Available sessions: ${this.activeSessions.join(", ")||"none"}`);return n}getAllActiveSessions(){return Object.fromEntries(this.activeSessions.map(t=>[t,this.sessions[t]]))}async closeSession(t){const n=this.sessions[t];if(!n){Ce.warn(`No session exists for server ${t}, nothing to close`);return}try{Ce.debug(`Closing session for server ${t}`),await n.disconnect()}catch(a){Ce.error(`Error closing session for server '${t}': ${a}`)}finally{delete this.sessions[t],this.activeSessions=this.activeSessions.filter(a=>a!==t)}}async closeAllSessions(){const t=Object.keys(this.sessions),n=[];for(const a of t)try{Ce.debug(`Closing session for server ${a}`),await this.closeSession(a)}catch(r){const i=`Failed to close session for server '${a}': ${r}`;Ce.error(i),n.push(i)}n.length?Ce.error(`Encountered ${n.length} errors while closing sessions`):Ce.debug("All sessions closed successfully")}},ze(Gu,"BaseMCPClient"),Gu),Wu,Eoe=(Wu=class{client=null;connectionManager=null;toolsCache=null;capabilitiesCache=null;serverInfoCache=null;connected=!1;opts;notificationHandlers=[];rootsCache=[];constructor(t={}){this.opts=t,t.roots&&(this.rootsCache=[...t.roots])}trackConnectorInit(t){const n=this.constructor.name;vF.getInstance().trackConnectorInit({connectorType:n,...t}).catch(a=>Ce.debug(`Failed to track connector init: ${a}`))}onNotification(t){this.notificationHandlers.push(t),this.client&&this.setupNotificationHandler()}setupNotificationHandler(){this.client&&(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}for(const n of this.notificationHandlers)try{await n(t)}catch(a){Ce.error("Error in notification handler:",a)}})}async refreshToolsCache(){if(this.client)try{Ce.debug("[Auto] Refreshing tools cache due to list_changed notification");const t=await this.client.listTools();this.toolsCache=t.tools??[],Ce.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(t){Ce.warn("[Auto] Failed to refresh tools cache:",t)}}async onResourcesListChanged(){Ce.debug("[Auto] Resources list changed - clients should re-fetch if needed")}async onPromptsListChanged(){Ce.debug("[Auto] Prompts list changed - clients should re-fetch if needed")}async setRoots(t){this.rootsCache=[...t],this.client&&(Ce.debug(`Sending roots/list_changed notification with ${t.length} root(s)`),await this.client.sendRootsListChanged())}getRoots(){return[...this.rootsCache]}setupRootsHandler(){this.client&&this.client.setRequestHandler(RV,async(t,n)=>(Ce.debug(`Server requested roots list, returning ${this.rootsCache.length} root(s)`),{roots:this.rootsCache}))}setupSamplingHandler(){if(!this.client){Ce.debug("setupSamplingHandler: No client available");return}if(!this.opts.samplingCallback){Ce.debug("setupSamplingHandler: No sampling callback provided");return}Ce.debug("setupSamplingHandler: Setting up sampling request handler"),this.client.setRequestHandler(lN,async(t,n)=>(Ce.debug("Server requested sampling, forwarding to callback"),await this.opts.samplingCallback(t.params))),Ce.debug("setupSamplingHandler: Sampling handler registered successfully")}setupElicitationHandler(){if(!this.client){Ce.debug("setupElicitationHandler: No client available");return}if(!this.opts.elicitationCallback){Ce.debug("setupElicitationHandler: No elicitation callback provided");return}Ce.debug("setupElicitationHandler: Setting up elicitation request handler"),this.client.setRequestHandler(uN,async(t,n)=>(Ce.debug("Server requested elicitation, forwarding to callback"),await this.opts.elicitationCallback(t.params))),Ce.debug("setupElicitationHandler: Elicitation handler registered successfully")}async disconnect(){if(!this.connected){Ce.debug("Not connected to MCP implementation");return}Ce.debug("Disconnecting from MCP implementation"),await this.cleanupResources(),this.connected=!1,Ce.debug("Disconnected from MCP implementation")}get isClientConnected(){return this.client!=null}async initialize(t=this.opts.defaultRequestOptions??{}){if(!this.client)throw new Error("MCP client is not connected");Ce.debug("Caching server capabilities & tools");const n=this.client.getServerCapabilities();this.capabilitiesCache=n||null;const a=this.client.getServerVersion();this.serverInfoCache=a||null;const r=await this.client.listTools(void 0,t);return this.toolsCache=r.tools??[],Ce.debug(`Fetched ${this.toolsCache.length} tools from server`),Ce.debug("Server capabilities:",n),Ce.debug("Server info:",a),n}get tools(){if(!this.toolsCache)throw new Error("MCP client is not initialized; call initialize() first");return this.toolsCache}get serverCapabilities(){return this.capabilitiesCache||{}}get serverInfo(){return this.serverInfoCache}async callTool(t,n,a){if(!this.client)throw new Error("MCP client is not connected");const r=a?{...a}:void 0;r?.resetTimeoutOnProgress&&!r.onprogress&&(r.onprogress=()=>{},Ce.debug(`[BaseConnector] Added onprogress callback for tool '${t}' to enable progressToken`)),Ce.debug(`Calling tool '${t}' with args`,n);const i=await this.client.callTool({name:t,arguments:n},void 0,r);return Ce.debug(`Tool '${t}' returned`,i),i}async listTools(t){if(!this.client)throw new Error("MCP client is not connected");return(await this.client.listTools(void 0,t)).tools??[]}async listResources(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug("Listing resources",t?`with cursor: ${t}`:""),await this.client.listResources({cursor:t},n)}async listAllResources(t){if(!this.client)throw new Error("MCP client is not connected");if(!this.capabilitiesCache?.resources)return Ce.debug("Server does not advertise resources capability, skipping"),{resources:[]};try{Ce.debug("Listing all resources (with auto-pagination)");const n=[];let a;do{const r=await this.client.listResources({cursor:a},t);n.push(...r.resources||[]),a=r.nextCursor}while(a);return{resources:n}}catch(n){if(n.code===-32601)return Ce.debug("Server advertised resources but method not found"),{resources:[]};throw n}}async listResourceTemplates(t){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug("Listing resource templates"),await this.client.listResourceTemplates(void 0,t)}async readResource(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Reading resource ${t}`),await this.client.readResource({uri:t},n)}async subscribeToResource(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Subscribing to resource: ${t}`),await this.client.subscribeResource({uri:t},n)}async unsubscribeFromResource(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Unsubscribing from resource: ${t}`),await this.client.unsubscribeResource({uri:t},n)}async listPrompts(){if(!this.client)throw new Error("MCP client is not connected");if(!this.capabilitiesCache?.prompts)return Ce.debug("Server does not advertise prompts capability, skipping"),{prompts:[]};try{return Ce.debug("Listing prompts"),await this.client.listPrompts()}catch(t){if(t.code===-32601)return Ce.debug("Server advertised prompts but method not found"),{prompts:[]};throw t}}async getPrompt(t,n){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Getting prompt ${t}`),await this.client.getPrompt({name:t,arguments:n})}async request(t,n=null,a){if(!this.client)throw new Error("MCP client is not connected");return Ce.debug(`Sending raw request '${t}' with params`,n),await this.client.request({method:t,params:n??{}},void 0,a)}async cleanupResources(){const t=[];if(this.client)try{typeof this.client.close=="function"&&await this.client.close()}catch(n){const a=`Error closing client: ${n}`;Ce.warn(a),t.push(a)}finally{this.client=null}if(this.connectionManager)try{await this.connectionManager.stop()}catch(n){const a=`Error stopping connection manager: ${n}`;Ce.warn(a),t.push(a)}finally{this.connectionManager=null}this.toolsCache=null,t.length&&Ce.warn(`Resource cleanup finished with ${t.length} issue(s)`)}},ze(Wu,"BaseConnector"),Wu),Ku,koe=(Ku=class{_readyPromise;_readyResolver;_donePromise;_doneResolver;_exception=null;_connection=null;_task=null;_abortController=null;constructor(){this.reset()}async start(){if(this.reset(),Ce.debug(`Starting ${this.constructor.name}`),this._task=this.connectionTask(),await this._readyPromise,this._exception)throw this._exception;if(this._connection===null)throw new Error("Connection was not established");return this._connection}async stop(){if(this._task&&this._abortController){Ce.debug(`Cancelling ${this.constructor.name} task`),this._abortController.abort();try{await this._task}catch(t){t instanceof Error&&t.name==="AbortError"?Ce.debug(`${this.constructor.name} task aborted successfully`):Ce.warn(`Error stopping ${this.constructor.name} task: ${t}`)}}await this._donePromise,Ce.debug(`${this.constructor.name} task completed`)}reset(){this._readyPromise=new Promise(t=>this._readyResolver=t),this._donePromise=new Promise(t=>this._doneResolver=t),this._exception=null,this._connection=null,this._task=null,this._abortController=new AbortController}async connectionTask(){Ce.debug(`Running ${this.constructor.name} task`);try{this._connection=await this.establishConnection(),Ce.debug(`${this.constructor.name} connected successfully`),this._readyResolver(),await this.waitForAbort()}catch(t){this._exception=t,Ce.error(`Error in ${this.constructor.name} task: ${t}`),this._readyResolver()}finally{if(this._connection!==null){try{await this.closeConnection(this._connection)}catch(t){Ce.warn(`Error closing connection in ${this.constructor.name}: ${t}`)}this._connection=null}this._doneResolver()}}async waitForAbort(){return new Promise((t,n)=>{if(!this._abortController)return;const a=this._abortController.signal;if(a.aborted){t();return}const r=ze(()=>{a.removeEventListener("abort",r),t()},"onAbort");a.addEventListener("abort",r)})}},ze(Ku,"ConnectionManager"),Ku),Zu,Toe=(Zu=class extends koe{url;opts;_transport=null;reinitializing=!1;constructor(t,n){super(),this.url=typeof t=="string"?new URL(t):t,this.opts=n}async establishConnection(){const t=new Soe(this.url,this.opts),n=t.send.bind(t);return t.send=async a=>{const r=ze(async i=>{if(Array.isArray(i))for(const s of i)await n(s);else await n(i)},"sendMessage");try{await r(a)}catch(i){if(i?.code===404&&t.sessionId&&!this.reinitializing){Ce.warn("[SSE] Session not found (404), re-initializing per MCP spec..."),this.reinitializing=!0;try{t.sessionId=void 0,await this.reinitialize(t),Ce.info("[SSE] Re-initialization successful, retrying request"),await r(a)}finally{this.reinitializing=!1}}else throw i}},this._transport=t,Ce.debug(`${this.constructor.name} connected successfully`),t}async reinitialize(t){Ce.debug("[SSE] Re-initialization triggered")}async closeConnection(t){if(this._transport)try{await this._transport.close()}catch(n){Ce.warn(`Error closing SSE transport: ${n}`)}finally{this._transport=null}}},ze(Zu,"SseConnectionManager"),Zu),Yu,Noe=(Yu=class extends Eoe{baseUrl;headers;timeout;sseReadTimeout;clientInfo;preferSse;disableSseFallback;transportType=null;streamableTransport=null;constructor(t,n={}){super(n),this.baseUrl=t.replace(/\/$/,""),this.headers={...n.headers??{}},n.authToken&&(this.headers.Authorization=`Bearer ${n.authToken}`),this.timeout=n.timeout??3e4,this.sseReadTimeout=n.sseReadTimeout??3e5,this.clientInfo=n.clientInfo??{name:"http-connector",version:"1.0.0"},this.preferSse=n.preferSse??!1,this.disableSseFallback=n.disableSseFallback??!1}async connect(){if(this.connected){Ce.debug("Already connected to MCP implementation");return}const t=this.baseUrl;if(this.preferSse){Ce.debug(`Connecting to MCP implementation via HTTP/SSE: ${t}`),await this.connectWithSse(t);return}Ce.debug(`Connecting to MCP implementation via HTTP: ${t}`);try{Ce.info("🔄 Attempting streamable HTTP transport..."),await this.connectWithStreamableHttp(t),Ce.info("✅ Successfully connected via streamable HTTP")}catch(n){let a="Unknown error",r=!1;if(n instanceof kl){const i=n;r=i.code===401,i.code===400&&i.message.includes("Missing session ID")?(a="Server requires session ID (FastMCP compatibility) - using SSE transport",Ce.warn(`⚠️ ${a}`)):i.code===404||i.code===405?(a=`Server returned ${i.code} - server likely doesn't support streamable HTTP`,Ce.debug(a)):(a=`Server returned ${i.code}: ${i.message}`,Ce.debug(a))}else if(n instanceof Error){const i=n.toString(),s=n.message||"";r=i.includes("401")||s.includes("Unauthorized"),i.includes("Missing session ID")||i.includes("Bad Request: Missing session ID")||s.includes("FastMCP session ID error")?(a="Server requires session ID (FastMCP compatibility) - using SSE transport",Ce.warn(`⚠️ ${a}`)):i.includes("405 Method Not Allowed")||i.includes("404 Not Found")?(a="Server doesn't support streamable HTTP (405/404)",Ce.debug(a)):(a=`Streamable HTTP failed: ${n.message}`,Ce.debug(a))}if(r){Ce.info("Authentication required - skipping SSE fallback"),await this.cleanupResources();const i=new Error("Authentication required");throw i.code=401,i}if(this.disableSseFallback)throw Ce.info("SSE fallback disabled - failing connection"),await this.cleanupResources(),new Error(`Streamable HTTP connection failed: ${a}. SSE fallback is disabled.`);Ce.info("🔄 Falling back to SSE transport...");try{await this.connectWithSse(t)}catch(i){if(Ce.error("Failed to connect with both transports:"),Ce.error(` Streamable HTTP: ${a}`),Ce.error(` SSE: ${i}`),await this.cleanupResources(),i?.message?.includes("401")||i?.message?.includes("Unauthorized")){const c=new Error("Authentication required");throw c.code=401,c}throw new Error("Could not connect to server with any available transport")}}}async connectWithStreamableHttp(t){try{const n=new boe(new URL(t),{authProvider:this.opts.authProvider,requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2}});let a=n;if(this.opts.wrapTransport){const i=this.baseUrl;a=this.opts.wrapTransport(a,i)}const r={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};Ce.debug("Creating Client with capabilities:",JSON.stringify(r.capabilities,null,2)),this.client=new ZP(this.clientInfo,r),this.setupRootsHandler(),Ce.debug("Roots handler registered before connect");try{await this.client.connect(a,{timeout:Math.min(this.timeout,3e3)});const i=n.sessionId;i?Ce.debug(`Session ID obtained: ${i}`):Ce.warn("Session ID not available after connect - this may cause issues with SSE stream")}catch(i){if(i instanceof Error){const s=i.message||i.toString();if(s.includes("Missing session ID")||s.includes("Bad Request: Missing session ID")||s.includes("Mcp-Session-Id header is required")){const c=new Error(`Session ID error: ${s}. The SDK should automatically extract session ID from initialize response.`);throw c.cause=i,c}}throw i}this.streamableTransport=n,this.connectionManager={stop:ze(async()=>{if(this.streamableTransport)try{await this.streamableTransport.terminateSession(),await this.streamableTransport.close()}catch(i){Ce.warn(`Error closing Streamable HTTP transport: ${i}`)}finally{this.streamableTransport=null}},"stop")},this.connected=!0,this.transportType="streamable-http",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Ce.debug(`Successfully connected to MCP implementation via streamable HTTP: ${t}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (streamable-http)`})}catch(n){throw await this.cleanupResources(),n}}async connectWithSse(t){try{this.connectionManager=new Toe(t,{authProvider:this.opts.authProvider,requestInit:{headers:this.headers}});let n=await this.connectionManager.start();if(this.opts.wrapTransport){const r=this.baseUrl;n=this.opts.wrapTransport(n,r)}const a={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};Ce.debug("Creating Client with capabilities (SSE):",JSON.stringify(a.capabilities,null,2)),this.client=new ZP(this.clientInfo,a),this.setupRootsHandler(),Ce.debug("Roots handler registered before connect (SSE)"),await this.client.connect(n),this.connected=!0,this.transportType="sse",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),Ce.debug(`Successfully connected to MCP implementation via HTTP/SSE: ${t}`),this.trackConnectorInit({serverUrl:this.baseUrl,publicIdentifier:`${this.baseUrl} (sse)`})}catch(n){throw await this.cleanupResources(),n}}get publicIdentifier(){return{type:"http",url:this.baseUrl,transport:this.transportType||"unknown"}}getTransportType(){return this.transportType}},ze(Yu,"HttpConnector"),Yu),zl,Coe=(zl=class extends _oe{static getPackageVersion(){return Jb()}constructor(t){super(t),this._trackClientInit()}_trackClientInit(){const t=Object.keys(this.config.mcpServers??{});zi.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(n=>Ce.debug(`Failed to track BrowserMCPClient init: ${n}`))}static fromDict(t){return new zl(t)}createConnectorFromConfig(t){const{url:n,headers:a,authToken:r,authProvider:i,wrapTransport:s,clientOptions:c,samplingCallback:u,elicitationCallback:d,disableSseFallback:m,preferSse:h}=t;if(!n)throw new Error("Server URL is required");const g={headers:a,authToken:r,authProvider:i,wrapTransport:s,clientOptions:c,samplingCallback:u,elicitationCallback:d,disableSseFallback:m,preferSse:h};return c?console.log("[BrowserMCPClient] Passing clientOptions to connector:",JSON.stringify(c,null,2)):console.warn("[BrowserMCPClient] No clientOptions provided to connector!"),new Noe(n,g)}},ze(zl,"BrowserMCPClient"),zl);function du(e){const t=ze(()=>{throw new Error(`Invalid url to pass to open(): ${e}`)},"abort");let n;try{n=new URL(e)}catch{t()}return n.protocol!=="https:"&&n.protocol!=="http:"&&t(),n.hostname!==encodeURIComponent(n.hostname)&&t(),n.username&&(n.username=encodeURIComponent(n.username)),n.password&&(n.password=encodeURIComponent(n.password)),n.pathname=n.pathname.slice(0,1)+encodeURIComponent(n.pathname.slice(1)).replace(/%2f/gi,"/"),n.search=n.search.slice(0,1)+Array.from(n.searchParams.entries()).map(t9).join("&"),n.hash=n.hash.slice(0,1)+encodeURIComponent(n.hash.slice(1)),n.href}ze(du,"sanitizeUrl");function t9([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:""}`}ze(t9,"sanitizeParam");var qu,Ob=(qu=class{serverUrl;storageKeyPrefix;serverUrlHash;clientName;clientUri;callbackUrl;preventAutoAuth;useRedirectFlow;onPopupWindow;constructor(t,n={}){this.serverUrl=t,this.storageKeyPrefix=n.storageKeyPrefix||"mcp:auth",this.serverUrlHash=this.hashString(t),this.clientName=n.clientName||"mcp-use",this.clientUri=n.clientUri||(typeof window<"u"?window.location.origin:""),this.callbackUrl=du(n.callbackUrl||(typeof window<"u"?new URL("/oauth/callback",window.location.origin).toString():"/oauth/callback")),this.preventAutoAuth=n.preventAutoAuth,this.useRedirectFlow=n.useRedirectFlow,this.onPopupWindow=n.onPopupWindow}get redirectUrl(){return du(this.callbackUrl)}get clientMetadata(){return{redirect_uris:[this.redirectUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:this.clientName,client_uri:this.clientUri}}async clientInformation(){const t=this.getKey("client_info"),n=localStorage.getItem(t);if(n)try{return JSON.parse(n)}catch(a){console.warn(`[${this.storageKeyPrefix}] Failed to parse client information:`,a),localStorage.removeItem(t);return}}async saveClientInformation(t){const n=this.getKey("client_info");localStorage.setItem(n,JSON.stringify(t))}async tokens(){const t=this.getKey("tokens"),n=localStorage.getItem(t);if(n)try{return JSON.parse(n)}catch(a){console.warn(`[${this.storageKeyPrefix}] Failed to parse tokens:`,a),localStorage.removeItem(t);return}}async saveTokens(t){const n=this.getKey("tokens");localStorage.setItem(n,JSON.stringify(t)),localStorage.removeItem(this.getKey("code_verifier")),localStorage.removeItem(this.getKey("last_auth_url"))}async saveCodeVerifier(t){const n=this.getKey("code_verifier");localStorage.setItem(n,t)}async codeVerifier(){const t=this.getKey("code_verifier"),n=localStorage.getItem(t);if(!n)throw new Error(`[${this.storageKeyPrefix}] Code verifier not found in storage for key ${t}. Auth flow likely corrupted or timed out.`);return n}async prepareAuthorizationUrl(t){const n=globalThis.crypto.randomUUID(),a=`${this.storageKeyPrefix}:state_${n}`,r={serverUrlHash:this.serverUrlHash,expiry:Date.now()+1e3*60*10,providerOptions:{serverUrl:this.serverUrl,storageKeyPrefix:this.storageKeyPrefix,clientName:this.clientName,clientUri:this.clientUri,callbackUrl:this.callbackUrl},flowType:this.useRedirectFlow?"redirect":"popup",returnUrl:this.useRedirectFlow&&typeof window<"u"?window.location.href:void 0};localStorage.setItem(a,JSON.stringify(r)),t.searchParams.set("state",n);const i=t.toString(),s=du(i);return localStorage.setItem(this.getKey("last_auth_url"),s),s}async redirectToAuthorization(t){const n=await this.prepareAuthorizationUrl(t);if(this.preventAutoAuth){console.info(`[${this.storageKeyPrefix}] Auto-auth prevented. Authorization URL stored for manual trigger.`);return}if(this.useRedirectFlow){console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL (full-page redirect).`),window.location.href=n;return}const a="width=600,height=700,resizable=yes,scrollbars=yes,status=yes";try{const r=window.open(n,`mcp_auth_${this.serverUrlHash}`,a);this.onPopupWindow&&this.onPopupWindow(n,a,r),!r||r.closed||typeof r.closed>"u"?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(r.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(r){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,r)}}getLastAttemptedAuthUrl(){const t=localStorage.getItem(this.getKey("last_auth_url"));return t?du(t):null}clearStorage(){const t=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,n=`${this.storageKeyPrefix}:state_`,a=[];let r=0;for(let s=0;s<localStorage.length;s++){const c=localStorage.key(s);if(c){if(c.startsWith(t))a.push(c);else if(c.startsWith(n))try{const u=localStorage.getItem(c);u&&JSON.parse(u).serverUrlHash===this.serverUrlHash&&a.push(c)}catch(u){console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${c} during clearStorage:`,u)}}}return[...new Set(a)].forEach(s=>{localStorage.removeItem(s),r++}),r}hashString(t){let n=0;for(let a=0;a<t.length;a++){const r=t.charCodeAt(a);n=(n<<5)-n+r,n=n&n}return Math.abs(n).toString(16)}getKey(t){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${t}`}},ze(qu,"BrowserOAuthClientProvider"),qu);async function vN(){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),a=e.get("error"),r=e.get("error_description"),i="[mcp-callback]";console.log(`${i} Handling callback...`,{code:t,state:n,error:a,errorDescription:r});let s=null,c=null;const u=n?`mcp:auth:state_${n}`:null;try{if(a)throw new Error(`OAuth error: ${a} - ${r||"No description provided."}`);if(!t)throw new Error("Authorization code not found in callback query parameters.");if(!n||!u)throw new Error("State parameter not found or invalid in callback query parameters.");const d=localStorage.getItem(u);if(!d)throw new Error(`Invalid or expired state parameter "${n}". No matching state found in storage.`);try{c=JSON.parse(d)}catch{throw new Error("Failed to parse stored OAuth state.")}if(!c.expiry||c.expiry<Date.now())throw localStorage.removeItem(u),new Error("OAuth state has expired. Please try initiating authentication again.");if(!c.providerOptions)throw new Error("Stored state is missing required provider options.");const{serverUrl:m,...h}=c.providerOptions;console.log(`${i} Re-instantiating provider for server: ${m}`),s=new Ob(m,h),console.log(`${i} Calling SDK auth() to exchange code...`);const g=new URL(m).origin,v=await Co(s,{serverUrl:g,authorizationCode:t});if(v==="AUTHORIZED")if(console.log(`${i} Authorization successful via SDK auth().`),c.flowType==="redirect"&&c.returnUrl)console.log(`${i} Redirect flow complete. Returning to: ${c.returnUrl}`),localStorage.removeItem(u),window.location.href=c.returnUrl;else if(window.opener&&!window.opener.closed)console.log(`${i} Popup flow complete. Notifying opener...`),window.opener.postMessage({type:"mcp_auth_callback",success:!0},window.location.origin),localStorage.removeItem(u),window.close();else{console.warn(`${i} No opener window or return URL detected. Redirecting to root.`),localStorage.removeItem(u);const S=window.location.pathname.split("/").filter(Boolean),y=S.length>0&&S[S.length-1]==="callback"?"/"+S.slice(0,-2).join("/"):"/";window.location.href=y||"/"}else throw console.warn(`${i} SDK auth() returned unexpected status: ${v}`),new Error(`Unexpected result from authentication library: ${v}`)}catch(d){console.error(`${i} Error during OAuth callback handling:`,d);const m=d instanceof Error?d.message:String(d);window.opener&&!window.opener.closed&&window.opener.postMessage({type:"mcp_auth_callback",success:!1,error:m},window.location.origin);try{document.body.innerHTML="";const h=document.createElement("div");h.style.fontFamily="sans-serif",h.style.padding="20px";const g=document.createElement("h1");g.textContent="Authentication Error",h.appendChild(g);const v=document.createElement("p");v.style.color="red",v.style.backgroundColor="#ffebeb",v.style.border="1px solid red",v.style.padding="10px",v.style.borderRadius="4px",v.textContent=m,h.appendChild(v);const x=document.createElement("p");x.textContent="You can close this window or ";const S=document.createElement("a");if(S.href="#",S.textContent="click here to close",S.onclick=y=>(y.preventDefault(),window.close(),!1),x.appendChild(S),x.appendChild(document.createTextNode(".")),h.appendChild(x),d instanceof Error&&d.stack){const y=document.createElement("pre");y.style.fontSize="0.8em",y.style.color="#555",y.style.marginTop="20px",y.style.whiteSpace="pre-wrap",y.textContent=d.stack,h.appendChild(y)}document.body.appendChild(h)}catch(h){console.error(`${i} Could not display error in callback window:`,h)}u&&localStorage.removeItem(u),s&&(localStorage.removeItem(s.getKey("code_verifier")),localStorage.removeItem(s.getKey("last_auth_url")))}}ze(vN,"onMcpAuthorization");var tx={exports:{}},bt={};var nU;function Roe(){if(nU)return bt;nU=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),s=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),g=Symbol.iterator;function v(j){return j===null||typeof j!="object"?null:(j=g&&j[g]||j["@@iterator"],typeof j=="function"?j:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},S=Object.assign,y={};function E(j,V,z){this.props=j,this.context=V,this.refs=y,this.updater=z||x}E.prototype.isReactComponent={},E.prototype.setState=function(j,V){if(typeof j!="object"&&typeof j!="function"&&j!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,j,V,"setState")},E.prototype.forceUpdate=function(j){this.updater.enqueueForceUpdate(this,j,"forceUpdate")};function _(){}_.prototype=E.prototype;function k(j,V,z){this.props=j,this.context=V,this.refs=y,this.updater=z||x}var C=k.prototype=new _;C.constructor=k,S(C,E.prototype),C.isPureReactComponent=!0;var R=Array.isArray;function I(){}var A={H:null,A:null,T:null,S:null},O=Object.prototype.hasOwnProperty;function M(j,V,z){var $=z.ref;return{$$typeof:e,type:j,key:V,ref:$!==void 0?$:null,props:z}}function P(j,V){return M(j.type,V,j.props)}function B(j){return typeof j=="object"&&j!==null&&j.$$typeof===e}function K(j){var V={"=":"=0",":":"=2"};return"$"+j.replace(/[=:]/g,function(z){return V[z]})}var ee=/\/+/g;function te(j,V){return typeof j=="object"&&j!==null&&j.key!=null?K(""+j.key):V.toString(36)}function ae(j){switch(j.status){case"fulfilled":return j.value;case"rejected":throw j.reason;default:switch(typeof j.status=="string"?j.then(I,I):(j.status="pending",j.then(function(V){j.status==="pending"&&(j.status="fulfilled",j.value=V)},function(V){j.status==="pending"&&(j.status="rejected",j.reason=V)})),j.status){case"fulfilled":return j.value;case"rejected":throw j.reason}}throw j}function H(j,V,z,$,L){var F=typeof j;(F==="undefined"||F==="boolean")&&(j=null);var W=!1;if(j===null)W=!0;else switch(F){case"bigint":case"string":case"number":W=!0;break;case"object":switch(j.$$typeof){case e:case t:W=!0;break;case m:return W=j._init,H(W(j._payload),V,z,$,L)}}if(W)return L=L(j),W=$===""?"."+te(j,0):$,R(L)?(z="",W!=null&&(z=W.replace(ee,"$&/")+"/"),H(L,V,z,"",function(ce){return ce})):L!=null&&(B(L)&&(L=P(L,z+(L.key==null||j&&j.key===L.key?"":(""+L.key).replace(ee,"$&/")+"/")+W)),V.push(L)),1;W=0;var X=$===""?".":$+":";if(R(j))for(var ie=0;ie<j.length;ie++)$=j[ie],F=X+te($,ie),W+=H($,V,z,F,L);else if(ie=v(j),typeof ie=="function")for(j=ie.call(j),ie=0;!($=j.next()).done;)$=$.value,F=X+te($,ie++),W+=H($,V,z,F,L);else if(F==="object"){if(typeof j.then=="function")return H(ae(j),V,z,$,L);throw V=String(j),Error("Objects are not valid as a React child (found: "+(V==="[object Object]"?"object with keys {"+Object.keys(j).join(", ")+"}":V)+"). If you meant to render a collection of children, use an array instead.")}return W}function Z(j,V,z){if(j==null)return j;var $=[],L=0;return H(j,$,"","",function(F){return V.call(z,F,L++)}),$}function G(j){if(j._status===-1){var V=j._result;V=V(),V.then(function(z){(j._status===0||j._status===-1)&&(j._status=1,j._result=z)},function(z){(j._status===0||j._status===-1)&&(j._status=2,j._result=z)}),j._status===-1&&(j._status=0,j._result=V)}if(j._status===1)return j._result.default;throw j._result}var re=typeof reportError=="function"?reportError:function(j){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var V=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof j=="object"&&j!==null&&typeof j.message=="string"?String(j.message):String(j),error:j});if(!window.dispatchEvent(V))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",j);return}console.error(j)},ne={map:Z,forEach:function(j,V,z){Z(j,function(){V.apply(this,arguments)},z)},count:function(j){var V=0;return Z(j,function(){V++}),V},toArray:function(j){return Z(j,function(V){return V})||[]},only:function(j){if(!B(j))throw Error("React.Children.only expected to receive a single React element child.");return j}};return bt.Activity=h,bt.Children=ne,bt.Component=E,bt.Fragment=n,bt.Profiler=r,bt.PureComponent=k,bt.StrictMode=a,bt.Suspense=u,bt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,bt.__COMPILER_RUNTIME={__proto__:null,c:function(j){return A.H.useMemoCache(j)}},bt.cache=function(j){return function(){return j.apply(null,arguments)}},bt.cacheSignal=function(){return null},bt.cloneElement=function(j,V,z){if(j==null)throw Error("The argument must be a React element, but you passed "+j+".");var $=S({},j.props),L=j.key;if(V!=null)for(F in V.key!==void 0&&(L=""+V.key),V)!O.call(V,F)||F==="key"||F==="__self"||F==="__source"||F==="ref"&&V.ref===void 0||($[F]=V[F]);var F=arguments.length-2;if(F===1)$.children=z;else if(1<F){for(var W=Array(F),X=0;X<F;X++)W[X]=arguments[X+2];$.children=W}return M(j.type,L,$)},bt.createContext=function(j){return j={$$typeof:s,_currentValue:j,_currentValue2:j,_threadCount:0,Provider:null,Consumer:null},j.Provider=j,j.Consumer={$$typeof:i,_context:j},j},bt.createElement=function(j,V,z){var $,L={},F=null;if(V!=null)for($ in V.key!==void 0&&(F=""+V.key),V)O.call(V,$)&&$!=="key"&&$!=="__self"&&$!=="__source"&&(L[$]=V[$]);var W=arguments.length-2;if(W===1)L.children=z;else if(1<W){for(var X=Array(W),ie=0;ie<W;ie++)X[ie]=arguments[ie+2];L.children=X}if(j&&j.defaultProps)for($ in W=j.defaultProps,W)L[$]===void 0&&(L[$]=W[$]);return M(j,F,L)},bt.createRef=function(){return{current:null}},bt.forwardRef=function(j){return{$$typeof:c,render:j}},bt.isValidElement=B,bt.lazy=function(j){return{$$typeof:m,_payload:{_status:-1,_result:j},_init:G}},bt.memo=function(j,V){return{$$typeof:d,type:j,compare:V===void 0?null:V}},bt.startTransition=function(j){var V=A.T,z={};A.T=z;try{var $=j(),L=A.S;L!==null&&L(z,$),typeof $=="object"&&$!==null&&typeof $.then=="function"&&$.then(I,re)}catch(F){re(F)}finally{V!==null&&z.types!==null&&(V.types=z.types),A.T=V}},bt.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()},bt.use=function(j){return A.H.use(j)},bt.useActionState=function(j,V,z){return A.H.useActionState(j,V,z)},bt.useCallback=function(j,V){return A.H.useCallback(j,V)},bt.useContext=function(j){return A.H.useContext(j)},bt.useDebugValue=function(){},bt.useDeferredValue=function(j,V){return A.H.useDeferredValue(j,V)},bt.useEffect=function(j,V){return A.H.useEffect(j,V)},bt.useEffectEvent=function(j){return A.H.useEffectEvent(j)},bt.useId=function(){return A.H.useId()},bt.useImperativeHandle=function(j,V,z){return A.H.useImperativeHandle(j,V,z)},bt.useInsertionEffect=function(j,V){return A.H.useInsertionEffect(j,V)},bt.useLayoutEffect=function(j,V){return A.H.useLayoutEffect(j,V)},bt.useMemo=function(j,V){return A.H.useMemo(j,V)},bt.useOptimistic=function(j,V){return A.H.useOptimistic(j,V)},bt.useReducer=function(j,V,z){return A.H.useReducer(j,V,z)},bt.useRef=function(j){return A.H.useRef(j)},bt.useState=function(j){return A.H.useState(j)},bt.useSyncExternalStore=function(j,V,z){return A.H.useSyncExternalStore(j,V,z)},bt.useTransition=function(){return A.H.useTransition()},bt.version="19.2.3",bt}var rU;function yN(){return rU||(rU=1,tx.exports=Roe()),tx.exports}var w=yN();const ue=ny(w),kd=lJ({__proto__:null,default:ue},[w]);function O_(e,t){if(!e)throw new Error(t)}ze(O_,"assert");var aU=3e3,Aoe=5e3;function wN(e){const{url:t,enabled:n=!0,clientName:a,clientUri:r,callbackUrl:i=typeof window<"u"?du(new URL("/oauth/callback",window.location.origin).toString()):"/oauth/callback",storageKeyPrefix:s="mcp:auth",clientConfig:c={},customHeaders:u={},debug:d=!1,autoRetry:m=!1,autoReconnect:h=aU,transportType:g="auto",preventAutoAuth:v=!1,useRedirectFlow:x=!1,onPopupWindow:S,timeout:y=3e4,sseReadTimeout:E=3e5,wrapTransport:_,onNotification:k,samplingCallback:C,onElicitation:R}=e,[I,A]=w.useState("discovering"),[O,M]=w.useState([]),[P,B]=w.useState([]),[K,ee]=w.useState([]),[te,ae]=w.useState([]),[H,Z]=w.useState(),[G,re]=w.useState(),[ne,j]=w.useState(void 0),[V,z]=w.useState([]),[$,L]=w.useState(void 0),F=w.useRef(null),W=w.useRef(null),X=w.useRef(!1),ie=w.useRef(!0),ce=w.useRef(0),J=w.useRef(null),q=w.useRef(I),le=w.useRef(h),he=w.useRef(null);w.useEffect(()=>{q.current=I,le.current=h},[I,h]);const oe=w.useCallback((Be,Le,...Se)=>{const je=Se.length>0?`${Le} ${Se.map(Ue=>JSON.stringify(Ue)).join(" ")}`:Le;console[Be](`[useMcp] ${je}`),ie.current&&z(Ue=>[...Ue.slice(-100),{level:Be,message:je,timestamp:Date.now()}])},[]),Ne=w.useCallback(async(Be=!1)=>{if(Be||oe("info","Disconnecting..."),X.current=!1,J.current&&clearTimeout(J.current),J.current=null,F.current)try{const Le="inspector-server",Se=F.current.getSession(Le);Se&&Se._healthCheckCleanup&&(Se._healthCheckCleanup(),Se._healthCheckCleanup=null),await F.current.closeSession(Le)}catch(Le){Be||oe("warn","Error closing session:",Le)}F.current=null,ie.current&&!Be&&(A("discovering"),M([]),B([]),ee([]),ae([]),j(void 0),L(void 0))},[oe]),Ve=w.useCallback((Be,Le)=>{if(oe("error",Be,Le??""),ie.current){A("failed"),j(Be);const Se=W.current?.getLastAttemptedAuthUrl();Se&&(L(Se),oe("info","Manual authentication URL may be available.",Se))}X.current=!1,t&&zi.getInstance().trackUseMcpConnection({url:t,transportType:g,success:!1,errorType:Le?.name||"UnknownError",hasOAuth:!!W.current,hasSampling:!!C,hasElicitation:!!R}).catch(()=>{})},[oe,t,g,C,R]),_e=w.useCallback(async()=>{if(!n||!t){oe("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag.");return}if(X.current){oe("debug","Connection attempt already in progress.");return}if(!ie.current){oe("debug","Connect called after unmount, aborting.");return}X.current=!0,ce.current+=1,j(void 0),L(void 0),he.current=null,A("discovering"),oe("info",`Connecting attempt #${ce.current} to ${t}...`),W.current||(W.current=new Ob(t,{storageKeyPrefix:s,clientName:a,clientUri:r,callbackUrl:i,preventAutoAuth:v,useRedirectFlow:x,onPopupWindow:S}),oe("debug","BrowserOAuthClientProvider initialized in connect.")),F.current||(F.current=new Coe,oe("debug","BrowserMCPClient initialized in connect."));const Be=ze(async(Se,je=!1)=>{oe("info",`Attempting connection with transport: ${Se}`);try{const Ue="inspector-server",We={url:t,transport:Se==="sse"?"http":Se,disableSseFallback:Se==="http",preferSse:Se==="sse"};if(u&&Object.keys(u).length>0&&(We.headers=u),W.current){const Ze=await W.current.tokens();Ze?.access_token&&(We.headers={...We.headers,Authorization:`Bearer ${Ze.access_token}`})}F.current.addServer(Ue,{...We,authProvider:W.current,clientOptions:c,samplingCallback:C,elicitationCallback:R,wrapTransport:_?Ze=>(console.log("[useMcp] Applying transport wrapper for server:",Ue,"url:",t),_(Ze,t)):void 0});const Je=await F.current.createSession(Ue,!1);Je.on("notification",Ze=>{k?.(Ze),Ze.method==="notifications/tools/list_changed"?(oe("info","Tools list changed, auto-refreshing..."),nt().catch(dt=>oe("warn","Auto-refresh tools failed:",dt))):Ze.method==="notifications/resources/list_changed"?(oe("info","Resources list changed, auto-refreshing..."),ft().catch(dt=>oe("warn","Auto-refresh resources failed:",dt))):Ze.method==="notifications/prompts/list_changed"&&(oe("info","Prompts list changed, auto-refreshing..."),Et().catch(dt=>oe("warn","Auto-refresh prompts failed:",dt)))}),await Je.initialize(),oe("info","✅ Successfully connected to MCP server"),oe("info","Server info:",Je.connector.serverInfo),oe("info","Server capabilities:",Je.connector.serverCapabilities),console.log("[useMcp] Server info:",Je.connector.serverInfo),console.log("[useMcp] Server capabilities:",Je.connector.serverCapabilities),A("ready"),he.current=Se;const yt=ze(()=>{let Ze=null,dt=Date.now();const At=1e4,Qn=3e4;return Ze=setInterval(ze(async()=>{if(!ie.current||q.current!=="ready"){Ze&&(clearInterval(Ze),Ze=null);return}try{await Je.connector.listTools(),dt=Date.now()}catch{const $n=Date.now()-dt;$n>Qn&&(oe("warn",`Connection appears to be broken (no response for ${Math.round($n/1e3)}s), attempting to reconnect...`),Ze&&(clearInterval(Ze),Ze=null),le.current&&ie.current&&(A("discovering"),oe("info","Auto-reconnecting to MCP server..."),setTimeout(()=>{ie.current&&q.current==="discovering"&&_e()},typeof le.current=="number"?le.current:aU)))}},"checkConnectionHealth"),At),()=>{Ze&&(clearInterval(Ze),Ze=null)}},"setupConnectionMonitoring");if(h){const Ze=yt();Je._healthCheckCleanup=Ze}zi.getInstance().trackUseMcpConnection({url:t,transportType:Se,success:!0,hasOAuth:!!W.current,hasSampling:!!C,hasElicitation:!!R}).catch(()=>{}),M(Je.connector.tools||[]);const mt=await Je.connector.listAllResources();B(mt.resources||[]);const Mt=await Je.connector.listPrompts();ae(Mt.prompts||[]);const nn=Je.connector.serverInfo,Ke=Je.connector.serverCapabilities;return nn&&(console.log("[useMcp] Server info:",nn),Z(nn)),Ke&&(console.log("[useMcp] Server capabilities:",Ke),re(Ke)),"success"}catch(Ue){const We=Ue,Je=We?.message||String(Ue);if(We.code===401||Je.includes("401")||Je.includes("Unauthorized")){if(W.current){oe("info","Authentication required. OAuth provider available.");try{const{auth:yt}=await Jn(async()=>{const{auth:Mt}=await Promise.resolve().then(()=>XP);return{auth:Mt}},void 0),mt=new URL(t).origin;yt(W.current,{serverUrl:mt}).catch(()=>{}),setTimeout(()=>{if(ie.current){const Mt=W.current?.getLastAttemptedAuthUrl();Mt?(L(Mt),oe("info","Manual authentication URL available:",Mt)):oe("warn","Could not generate authentication URL")}},100)}catch(yt){oe("warn","Error generating auth URL:",yt)}return ie.current&&A("pending_auth"),X.current=!1,"auth_redirect"}return u&&Object.keys(u).length>0?(Ve("Authentication failed: Server returned 401 Unauthorized. Check your Authorization header value is correct."),"failed"):(Ve("Authentication required: Server returned 401 Unauthorized. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed")}return Ve(Je,We instanceof Error?We:new Error(String(We))),"failed"}},"tryConnectWithTransport");let Le="failed";if(g==="sse")oe("debug","Using SSE-only transport mode"),Le=await Be("sse");else if(g==="http")oe("debug","Using HTTP-only transport mode"),Le=await Be("http");else{oe("debug","Using auto transport mode (HTTP with SSE fallback)");const Se=await Be("http");Se==="fallback"&&ie.current&&q.current!=="authenticating"?(oe("info","HTTP failed, attempting SSE fallback..."),Le=await Be("sse")):Le=Se}(Le==="success"||Le==="failed"||Le==="auth_redirect")&&(X.current=!1),oe("debug",`Connection sequence finished with status: ${Le}`)},[oe,Ve,Ne,t,s,a,r,i,c.name,c.version,u,g,v,x,S,n,y,E]),ke=w.useCallback(async(Be,Le,Se)=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot call tool "${Be}".`);oe("info",`Calling tool: ${Be}`,Le);const je=Date.now();try{const We=F.current.getSession("inspector-server");if(!We)throw new Error("No active session found");const Je=await We.connector.callTool(Be,Le||{},Se);return oe("info",`Tool "${Be}" call successful:`,Je),zi.getInstance().trackUseMcpToolCall({toolName:Be,success:!0,executionTimeMs:Date.now()-je}).catch(()=>{}),Je}catch(Ue){throw oe("error",`Tool "${Be}" call failed:`,Ue),zi.getInstance().trackUseMcpToolCall({toolName:Be,success:!1,errorType:Ue instanceof Error?Ue.name:"UnknownError",executionTimeMs:Date.now()-je}).catch(()=>{}),Ue}},[I]),Fe=w.useCallback(()=>{q.current==="failed"?(oe("info","Retry requested..."),_e()):oe("warn",`Retry called but state is not 'failed' (state: ${q.current}). Ignoring.`)},[oe,_e]),pe=w.useCallback(async()=>{oe("info","Manual authentication requested...");const Be=q.current;if(Be==="failed")oe("info","Attempting to reconnect and authenticate via retry..."),Fe();else if(Be==="pending_auth"){oe("info","Proceeding with authentication from pending state...");try{O_(W.current,"Auth Provider not available for manual auth"),O_(t,"Server URL is required for authentication"),oe("info","Clearing all OAuth state and initiating fresh flow...");const Le=`${s}:${W.current.serverUrlHash}`;Object.keys(localStorage).forEach(We=>{We.startsWith(Le)&&(oe("debug",`Removing stale OAuth key: ${We}`),localStorage.removeItem(We)),We.startsWith(`${s}:state_`)&&(oe("debug",`Removing orphaned state: ${We}`),localStorage.removeItem(We))}),A("authenticating");const Se=new Ob(t,{storageKeyPrefix:s,clientName:a,clientUri:r,callbackUrl:i,preventAutoAuth:!1,useRedirectFlow:x,onPopupWindow:S});W.current=Se,oe("info","Triggering fresh OAuth authorization...");const{auth:je}=await Jn(async()=>{const{auth:We}=await Promise.resolve().then(()=>XP);return{auth:We}},void 0),Ue=new URL(t).origin;je(Se,{serverUrl:Ue}).catch(We=>{oe("info","OAuth flow initiated:",We instanceof Error?We.message:"Redirecting...")})}catch(Le){if(!ie.current)return;A("pending_auth"),oe("error",`Manual authentication failed: ${Le instanceof Error?Le.message:String(Le)}`)}}else if(Be==="authenticating"){oe("warn","Already attempting authentication. Check for blocked popups or wait for timeout.");const Le=W.current?.getLastAttemptedAuthUrl();Le&&!$&&(L(Le),oe("info","Manual authentication URL retrieved:",Le))}else oe("info",`Client not in a state requiring manual authentication trigger (state: ${Be}). If needed, try disconnecting and reconnecting.`)},[oe,Fe,$,t,x,S,s,a,r,i]),Oe=w.useCallback(()=>{if(W.current){const Be=W.current.clearStorage();oe("info",`Cleared ${Be} item(s) from localStorage for ${t}.`),L(void 0),Ne()}else oe("warn","Auth provider not initialized, cannot clear storage.")},[t,oe,Ne]),He=w.useCallback(async()=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot list resources.`);oe("info","Listing resources");try{const Le=F.current.getSession("inspector-server");if(!Le)throw new Error("No active session found");const Se=await Le.connector.listAllResources();B(Se.resources||[]),oe("info","Resources listed successfully")}catch(Be){throw oe("error","List resources failed:",Be),Be}},[I]),xe=w.useCallback(async Be=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot read resource.`);oe("info",`Reading resource: ${Be}`);try{const Se=F.current.getSession("inspector-server");if(!Se)throw new Error("No active session found");const je=await Se.connector.readResource(Be);return oe("info","Resource read successful:",je),zi.getInstance().trackUseMcpResourceRead({resourceUri:Be,success:!0}).catch(()=>{}),je}catch(Le){throw oe("error","Resource read failed:",Le),zi.getInstance().trackUseMcpResourceRead({resourceUri:Be,success:!1,errorType:Le instanceof Error?Le.name:"UnknownError"}).catch(()=>{}),Le}},[I]),at=w.useCallback(async()=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot list prompts.`);oe("info","Listing prompts");try{const Le=F.current.getSession("inspector-server");if(!Le)throw new Error("No active session found");const Se=await Le.connector.listPrompts();ae(Se.prompts||[]),oe("info","Prompts listed successfully")}catch(Be){throw oe("error","List prompts failed:",Be),Be}},[I]),nt=w.useCallback(async()=>{if(q.current!=="ready"||!F.current){oe("debug","Cannot refresh tools - client not ready");return}oe("debug","Refreshing tools list");try{const Le=F.current.getSession("inspector-server");if(!Le){oe("warn","No active session found for tools refresh");return}const Se=await Le.connector.listTools();M(Se||[]),oe("info","Tools list refreshed successfully")}catch(Be){oe("warn","Failed to refresh tools:",Be)}},[oe]),ft=w.useCallback(async()=>{if(q.current!=="ready"||!F.current){oe("debug","Cannot refresh resources - client not ready");return}oe("debug","Refreshing resources list");try{const Le=F.current.getSession("inspector-server");if(!Le){oe("warn","No active session found for resources refresh");return}const Se=await Le.connector.listAllResources();B(Se.resources||[]),oe("info","Resources list refreshed successfully")}catch(Be){oe("warn","Failed to refresh resources:",Be)}},[oe]),Et=w.useCallback(async()=>{if(q.current!=="ready"||!F.current){oe("debug","Cannot refresh prompts - client not ready");return}oe("debug","Refreshing prompts list");try{const Le=F.current.getSession("inspector-server");if(!Le){oe("warn","No active session found for prompts refresh");return}const Se=await Le.connector.listPrompts();ae(Se.prompts||[]),oe("info","Prompts list refreshed successfully")}catch(Be){oe("warn","Failed to refresh prompts:",Be)}},[oe]),pt=w.useCallback(async()=>{oe("info","Refreshing all lists (tools, resources, prompts)"),await Promise.all([nt(),ft(),Et()])},[nt,ft,Et,oe]),mn=w.useCallback(async(Be,Le)=>{if(q.current!=="ready"||!F.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot get prompt.`);oe("info",`Getting prompt: ${Be}`,Le);try{const je=F.current.getSession("inspector-server");if(!je)throw new Error("No active session found");const Ue=await je.connector.getPrompt(Be,Le||{});return oe("info",`Prompt "${Be}" retrieved successfully:`,Ue),Ue}catch(Se){throw oe("error",`Prompt "${Be}" retrieval failed:`,Se),Se}},[I]),Pr=w.useRef(_e),St=w.useRef(Ve);return w.useEffect(()=>{Pr.current=_e,St.current=Ve}),w.useEffect(()=>{const Be=ze(Le=>{Le.origin===window.location.origin&&Le.data?.type==="mcp_auth_callback"&&(oe("info","Received auth callback message.",Le.data),J.current&&clearTimeout(J.current),J.current=null,Le.data.success?(oe("info","Authentication successful via popup. Reconnecting client..."),X.current&&oe("debug","Connection attempt already in progress, resetting flag to allow reconnection."),X.current=!1,setTimeout(()=>{ie.current&&(oe("debug","Initiating reconnection after successful auth callback."),Pr.current())},100)):St.current(`Authentication failed in callback: ${Le.data.error||"Unknown reason."}`))},"messageHandler");return window.addEventListener("message",Be),oe("debug","Auth callback message listener added."),()=>{window.removeEventListener("message",Be),oe("debug","Auth callback message listener removed."),J.current&&clearTimeout(J.current)}},[oe]),w.useEffect(()=>(ie.current=!0,!n||!t?(oe("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag."),A("discovering"),()=>{ie.current=!1}):(oe("debug","useMcp mounted, initiating connection."),ce.current=0,(!W.current||W.current.serverUrl!==t)&&(W.current=new Ob(t,{storageKeyPrefix:s,clientName:a,clientUri:r,callbackUrl:i,preventAutoAuth:v,useRedirectFlow:x,onPopupWindow:S}),oe("debug","BrowserOAuthClientProvider initialized/updated on mount/option change.")),_e(),()=>{ie.current=!1,oe("debug","useMcp unmounting, disconnecting."),Ne(!0)})),[t,n,s,i,a,r,c.name,c.version,x]),w.useEffect(()=>{let Be=null;if(I==="failed"&&m&&ce.current>0){const Le=typeof m=="number"?m:Aoe;oe("info",`Connection failed, auto-retrying in ${Le}ms...`),Be=setTimeout(()=>{ie.current&&q.current==="failed"&&Fe()},Le)}return()=>{Be&&clearTimeout(Be)}},[I,m,Fe,oe]),{state:I,tools:O,resources:P,resourceTemplates:K,prompts:te,serverInfo:H,capabilities:G,error:ne,log:V,authUrl:$,client:F.current,callTool:ke,readResource:xe,listResources:He,listPrompts:at,getPrompt:mn,refreshTools:nt,refreshResources:ft,refreshPrompts:Et,refreshAll:pt,retry:Fe,disconnect:Ne,authenticate:pe,clearStorage:Oe}}ze(wN,"useMcp");var Xu,Ioe=(Xu=class extends ue.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("Widget Error:",t,n)}render(){return this.state.hasError?ue.createElement("div",{className:"p-4 border border-red-500 bg-red-50 text-red-900 rounded-md dark:bg-red-900/20 dark:text-red-100"},ue.createElement("h3",{className:"font-bold mb-2"},"Widget Error"),ue.createElement("pre",{className:"text-sm whitespace-pre-wrap"},this.state.error?.message)):this.props.children}},ze(Xu,"ErrorBoundary"),Xu),pp="openai:set_globals";function di(e){return w.useSyncExternalStore(t=>{const n=ze(a=>{a.detail.globals[e]!==void 0&&t()},"handleSetGlobal");return typeof window<"u"&&window.addEventListener(pp,n),()=>{typeof window<"u"&&window.removeEventListener(pp,n)}},()=>typeof window<"u"&&window.openai?window.openai[e]:void 0)}ze(di,"useOpenAiGlobal");function Td(e){const[t,n]=w.useState(()=>typeof window<"u"&&!!window.openai);w.useEffect(()=>{if(typeof window<"u"&&window.openai){n(!0);return}const P=setInterval(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(P))},100),B=ze(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(P))},"handleSetGlobals");typeof window<"u"&&window.addEventListener(pp,B);const K=setTimeout(()=>{clearInterval(P),typeof window<"u"&&window.removeEventListener(pp,B)},5e3);return()=>{clearInterval(P),clearTimeout(K),typeof window<"u"&&window.removeEventListener(pp,B)}},[]);const a=w.useMemo(()=>t?"openai":"mcp-ui",[t]),r=typeof window<"u"?window.location.search:"",i=w.useMemo(()=>{const P=new URLSearchParams(r);return P.has("mcpUseParams")?JSON.parse(P.get("mcpUseParams")):{toolInput:{},toolOutput:{},toolId:""}},[r]),s=a==="openai"?di("toolInput"):i.toolInput,c=a==="openai"?di("toolOutput"):i.toolOutput,u=di("toolResponseMetadata"),d=w.useMemo(()=>{if(u&&typeof u=="object"){const P=u["mcp-use/props"];if(P)return P}return e||{}},[u,e]),m=di("widgetState"),h=di("theme"),g=di("displayMode"),v=di("safeArea"),x=di("maxHeight"),S=di("userAgent"),y=di("locale"),E=w.useMemo(()=>typeof window<"u"&&window.__mcpPublicUrl?window.__mcpPublicUrl.replace(/\/mcp-use\/public$/,""):"",[]),[_,k]=w.useState(null);w.useEffect(()=>{m!==void 0&&k(m)},[m]);const C=w.useCallback(async(P,B)=>{if(!window.openai?.callTool)throw new Error("window.openai.callTool is not available");return window.openai.callTool(P,B)},[]),R=w.useCallback(async P=>{if(!window.openai?.sendFollowUpMessage)throw new Error("window.openai.sendFollowUpMessage is not available");return window.openai.sendFollowUpMessage({prompt:P})},[]),I=w.useCallback(P=>{if(!window.openai?.openExternal)throw new Error("window.openai.openExternal is not available");window.openai.openExternal({href:P})},[]),A=w.useCallback(async P=>{if(!window.openai?.requestDisplayMode)throw new Error("window.openai.requestDisplayMode is not available");return window.openai.requestDisplayMode({mode:P})},[]),O=w.useCallback(async P=>{if(!window.openai?.setWidgetState)throw new Error("window.openai.setWidgetState is not available");const K=typeof P=="function"?P(m!==void 0?m:_):P;return k(K),window.openai.setWidgetState(K)},[m,_]),M=w.useMemo(()=>a==="openai"&&u===null,[a,u]);return{props:d,toolInput:s||{},output:c??null,metadata:u??null,state:_,setState:O,theme:h||"light",displayMode:g||"inline",safeArea:v||{insets:{top:0,bottom:0,left:0,right:0}},maxHeight:x||600,userAgent:S||{device:{type:"desktop"},capabilities:{hover:!0,touch:!1}},locale:y||"en",mcp_url:E,callTool:C,sendFollowUpMessage:R,openExternal:I,requestDisplayMode:A,isAvailable:t,isPending:M}}ze(Td,"useWidget");function Ooe(e){const{props:t}=Td(e);return t}ze(Ooe,"useWidgetProps");function Doe(){const{theme:e}=Td();return e}ze(Doe,"useWidgetTheme");function joe(e){const{state:t,setState:n}=Td();return w.useEffect(()=>{t===null&&e!==void 0&&window.openai?.setWidgetState&&n(e)},[]),[t,n]}ze(joe,"useWidgetState");var iU=ze(({children:e})=>{const{theme:t,isAvailable:n}=Td();console.log("theme",t);const[a,r]=w.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");w.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(prefers-color-scheme: dark)"),c=ze(u=>{r(u.matches?"dark":"light")},"handleChange");return s.addEventListener("change",c),()=>s.removeEventListener("change",c)},[]);const i=n?t:a;return w.useLayoutEffect(()=>{typeof document>"u"||(i==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark"))},[i]),ue.createElement(ue.Fragment,null,e)},"ThemeProvider");function n9({children:e,className:t="",position:n="top-right",attachTo:a,showLabels:r=!0,debugger:i=!1,viewControls:s=!1}){const{props:c,output:u,metadata:d,state:m,theme:h,displayMode:g,safeArea:v,maxHeight:x,userAgent:S,locale:y,isAvailable:E,callTool:_,sendFollowUpMessage:k,openExternal:C,requestDisplayMode:R,setState:I}=Td(),[A,O]=w.useState(!1),[M,P]=w.useState(!1),B=w.useRef(null),K=w.useRef(null),[ee,te]=w.useState([]),[ae,H]=w.useState(""),[Z,G]=w.useState("get-my-city"),[re,ne]=w.useState("{}"),[j,V]=w.useState("Test follow-up message"),[z,$]=w.useState("https://docs.mcp-use.com"),L=g==="fullscreen"&&E,F=g==="pip"&&E,W=typeof window<"u"&&window.location.pathname.includes("/inspector/api/");w.useEffect(()=>{const xe=setTimeout(()=>{if(typeof window<"u"&&window.openai)try{const at=Object.keys(window.openai);te(at)}catch{te([])}else te([])},100);return()=>{clearTimeout(xe)}},[]);const X=h==="dark",ie=ze(()=>{const xe=["absolute","z-[1000]","flex","gap-2","transition-opacity","duration-200","ease-in-out",A?"opacity-100":"opacity-0",A?"pointer-events-auto":"pointer-events-none"];switch(n){case"top-left":return[...xe,"top-4","left-4"];case"top-center":return[...xe,"top-4","left-1/2","-translate-x-1/2"];case"top-right":return[...xe,"top-4","right-4"];case"center-left":return[...xe,"top-1/2","left-4","-translate-y-1/2"];case"center-right":return[...xe,"top-1/2","right-4","-translate-y-1/2"];case"bottom-left":return[...xe,"bottom-4","left-4"];case"bottom-center":return[...xe,"bottom-4","left-1/2","-translate-x-1/2"];case"bottom-right":return[...xe,"bottom-4","right-4"];default:return[...xe,"top-4","right-4"]}},"getPositionClasses"),ce=ze(()=>{const at=v?.insets?.top?Math.max(16,v.insets.top+8):16,nt=v?.insets?.right?Math.max(16,v.insets.right+8):16,ft=v?.insets?.bottom?Math.max(16,v.insets.bottom+8):16,Et=v?.insets?.left?Math.max(16,v.insets.left+8):16,pt={};switch(n){case"top-left":pt.top=`${at}px`,pt.left=`${Et}px`;break;case"top-center":pt.top=`${at}px`;break;case"top-right":pt.top=`${at}px`,pt.right=`${nt}px`;break;case"center-left":pt.left=`${Et}px`;break;case"center-right":pt.right=`${nt}px`;break;case"bottom-left":pt.bottom=`${ft}px`,pt.left=`${Et}px`;break;case"bottom-center":pt.bottom=`${ft}px`;break;case"bottom-right":pt.bottom=`${ft}px`,pt.right=`${nt}px`;break;default:pt.top=`${at}px`,pt.right=`${nt}px`;break}return pt},"getPositionOffsetStyles");w.useEffect(()=>{if(!a)return;const xe=ze(()=>O(!0),"handleMouseEnter"),at=ze(()=>O(!1),"handleMouseLeave");return a.addEventListener("mouseenter",xe),a.addEventListener("mouseleave",at),()=>{a.removeEventListener("mouseenter",xe),a.removeEventListener("mouseleave",at)}},[a]),w.useEffect(()=>{if(!M)return;const xe=ze(at=>{K.current&&!K.current.contains(at.target)&&P(!1)},"handleClickOutside");return document.addEventListener("mousedown",xe),()=>{document.removeEventListener("mousedown",xe)}},[M]),w.useEffect(()=>(M?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[M]);const J=ze(()=>{P(!M)},"handleToggleOverlay"),q=ze(async()=>{try{H("Calling tool...");const xe=re.trim()?JSON.parse(re):{},at=await _(Z,xe);H(`Success: ${JSON.stringify(at,null,2)}`)}catch(xe){H(`Error: ${xe.message}`)}},"handleCallTool"),le=ze(async()=>{try{H("Sending follow-up message..."),await k(j),H("Follow-up message sent successfully")}catch(xe){H(`Error: ${xe.message}`)}},"handleSendFollowUpMessage"),he=ze(()=>{try{C(z),H(`Opened external link: ${z}`)}catch(xe){H(`Error: ${xe.message}`)}},"handleOpenExternal"),oe=ze(async xe=>{try{H(`Requesting display mode: ${xe}...`);const at=await R(xe);H(`Display mode granted: ${at.mode}`)}catch(at){H(`Error: ${at.message}`)}},"handleRequestDisplayMode"),Ne=ze(async()=>{try{const xe=m?{...m,debugTimestamp:new Date().toISOString()}:{debugTimestamp:new Date().toISOString()};H("Setting state..."),await I(xe),H(`State updated: ${JSON.stringify(xe,null,2)}`)}catch(xe){H(`Error: ${xe.message}`)}},"handleSetState"),Ve=ze(async()=>{try{await R("fullscreen")}catch(xe){console.error("Failed to go fullscreen:",xe)}},"handleFullscreen"),_e=ze(async()=>{try{await R("pip")}catch(xe){console.error("Failed to go pip:",xe)}},"handlePip"),ke=ze(()=>{const xe=["absolute","px-2","py-1","bg-black/90","text-white","rounded","text-xs","whitespace-nowrap","pointer-events-none","transition-opacity","duration-200","ease-in-out"];switch(n){case"top-right":return[...xe,"top-full","right-0","mt-2"];case"top-left":return[...xe,"top-full","left-0","mt-2"];case"top-center":return[...xe,"top-full","left-1/2","-translate-x-1/2","mt-2"];case"bottom-right":return[...xe,"bottom-full","right-0","mb-2"];case"bottom-left":return[...xe,"bottom-full","left-0","mb-2"];case"bottom-center":return[...xe,"bottom-full","left-1/2","-translate-x-1/2","mb-2"];case"center-left":return[...xe,"left-full","top-1/2","-translate-y-1/2","ml-2"];case"center-right":return[...xe,"right-full","top-1/2","-translate-y-1/2","mr-2"];default:return[...xe,"top-full","right-0","mt-2"]}},"getTooltipClasses"),Fe=ze(({onClick:xe,label:at,children:nt})=>{const[ft,Et]=w.useState(!1),pt=ke();return ue.createElement("button",{className:`p-2 ${X?"bg-white/10 hover:bg-white/20":"bg-black/70 hover:bg-black/90"} text-white border-none rounded-lg cursor-pointer flex items-center justify-center w-8 h-8 transition-colors duration-200 backdrop-blur-md ${X?"shadow-[0_2px_8px_rgba(0,0,0,0.3)]":"shadow-[0_2px_8px_rgba(0,0,0,0.2)]"} relative`,onMouseEnter:()=>Et(!0),onMouseLeave:()=>Et(!1),onClick:xe,"aria-label":at},ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"block"},nt),r&&ue.createElement("span",{className:`${pt.join(" ")} ${ft?"opacity-100":"opacity-0"}`},at))},"IconButton"),pe=ze(xe=>{if(xe===null)return"null";if(xe===void 0)return"undefined";if(typeof xe=="object")try{return JSON.stringify(xe,null,2)}catch{return String(xe)}return String(xe)},"formatValue"),Oe=ze(xe=>xe?`${xe.device?.type||"unknown"}`:"N/A","formatUserAgent"),He=ze(xe=>{if(!xe?.insets)return"N/A";const{top:at,bottom:nt,left:ft,right:Et}=xe.insets;return`T:${at} B:${nt} L:${ft} R:${Et}`},"formatSafeArea");return ue.createElement(ue.Fragment,null,ue.createElement("div",{ref:B,className:`${t} relative h-fit`,onMouseEnter:()=>!a&&O(!0),onMouseLeave:()=>!a&&O(!1)},ue.createElement("div",{className:ie().join(" "),style:ce()},!W&&ue.createElement(ue.Fragment,null,!L&&!F&&ue.createElement(ue.Fragment,null,(s===!0||s==="fullscreen")&&ue.createElement(Fe,{onClick:Ve,label:"Fullscreen"},ue.createElement("path",{d:"M15 3h6v6"}),ue.createElement("path",{d:"m21 3-7 7"}),ue.createElement("path",{d:"m3 21 7-7"}),ue.createElement("path",{d:"M9 21H3v-6"})),(s===!0||s==="pip")&&ue.createElement(Fe,{onClick:_e,label:"Picture in Picture"},ue.createElement("path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4"}),ue.createElement("rect",{width:"10",height:"7",x:"12",y:"13",rx:"2"}))),i&&ue.createElement(Fe,{onClick:J,label:"Debug Info"},ue.createElement("path",{d:"M12 20v-9"}),ue.createElement("path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z"}),ue.createElement("path",{d:"M14.12 3.88 16 2"}),ue.createElement("path",{d:"M21 21a4 4 0 0 0-3.81-4"}),ue.createElement("path",{d:"M21 5a4 4 0 0 1-3.55 3.97"}),ue.createElement("path",{d:"M22 13h-4"}),ue.createElement("path",{d:"M3 21a4 4 0 0 1 3.81-4"}),ue.createElement("path",{d:"M3 5a4 4 0 0 0 3.55 3.97"}),ue.createElement("path",{d:"M6 13H2"}),ue.createElement("path",{d:"m8 2 1.88 1.88"}),ue.createElement("path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13"})))),e),M&&i&&ue.createElement("div",{ref:K,className:"fixed inset-0 bg-black text-white font-mono text-xs z-[10000] overflow-auto p-4",onClick:xe=>{xe.target===K.current&&P(!1)}},ue.createElement("button",{onClick:()=>P(!1),className:"absolute top-4 right-4 bg-white/10 text-white border-none rounded w-8 h-8 cursor-pointer flex items-center justify-center text-lg leading-none","aria-label":"Close"},"×"),ue.createElement("div",{className:"max-w-[1200px] mx-auto pt-10"},ue.createElement("h1",{className:"text-lg font-bold mb-4 border-b border-gray-700 pb-2"},"Debug Info"),ue.createElement("table",{className:"w-full border-collapse border-spacing-0"},ue.createElement("tbody",null,ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Props"),ue.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},pe(c))),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Output"),ue.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},pe(u))),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Metadata"),ue.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},pe(d))),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"State"),ue.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},pe(m))),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Theme"),ue.createElement("td",{className:"p-2"},h)),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Display Mode"),ue.createElement("td",{className:"p-2"},g)),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Locale"),ue.createElement("td",{className:"p-2"},y)),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Max Height"),ue.createElement("td",{className:"p-2"},x,"px")),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"User Agent"),ue.createElement("td",{className:"p-2"},Oe(S))),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Safe Area"),ue.createElement("td",{className:"p-2"},He(v))),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"API Available"),ue.createElement("td",{className:"p-2"},E?"Yes":"No")),ue.createElement("tr",{className:"border-b border-gray-700"},ue.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"window.openai Keys"),ue.createElement("td",{className:"p-2"},ee.length>0?ee.join(", "):"N/A")))),ue.createElement("h2",{className:"text-base font-bold mt-8 mb-4 border-b border-gray-700 pb-2"},"Actions"),ue.createElement("div",{className:"flex flex-col gap-3"},ue.createElement("div",{className:"flex gap-2 items-center"},ue.createElement("input",{type:"text",value:Z,onChange:xe=>G(xe.target.value),placeholder:"Tool name",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs w-[150px]"}),ue.createElement("input",{type:"text",value:re,onChange:xe=>ne(xe.target.value),placeholder:'{"key": "value"}',className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),ue.createElement("button",{onClick:q,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Call Tool")),ue.createElement("div",{className:"flex gap-2 items-center"},ue.createElement("input",{type:"text",value:j,onChange:xe=>V(xe.target.value),placeholder:"Follow-up message",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),ue.createElement("button",{onClick:le,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Send Follow-Up")),ue.createElement("div",{className:"flex gap-2 items-center"},ue.createElement("input",{type:"text",value:z,onChange:xe=>$(xe.target.value),placeholder:"External URL",className:"py-1.5 px-2 bg-[#1a1a1a] text-white border border-gray-700 rounded font-mono text-xs flex-1"}),ue.createElement("button",{onClick:he,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Open Link")),ue.createElement("div",{className:"flex gap-2 items-center"},ue.createElement("span",{className:"w-[150px] text-xs"},"Display Mode:"),ue.createElement("button",{onClick:()=>oe("inline"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"Inline"),ue.createElement("button",{onClick:()=>oe("pip"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"PiP"),ue.createElement("button",{onClick:()=>oe("fullscreen"),className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs flex-1"},"Fullscreen")),ue.createElement("div",{className:"flex gap-2 items-center"},ue.createElement("button",{onClick:Ne,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Set State (Add Timestamp)")),ae&&ue.createElement("div",{className:"mt-2 p-2 bg-[#1a1a1a] border border-gray-700 rounded whitespace-pre-wrap break-all text-[11px] max-h-[200px] overflow-auto"},ue.createElement("div",{className:"font-bold mb-1 text-gray-400"},"Result:"),ae,ue.createElement("button",{onClick:()=>H(""),className:"mt-2 py-1 px-2 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-[11px]"},"Clear"))))))}ze(n9,"WidgetControls");function r9(){if(typeof window>"u")return"/";const t=window.location.pathname.match(/^(\/inspector\/api\/dev-widget\/[^/]+)/);return t?t[1]:"/"}ze(r9,"getBasename");var $oe=150,Loe=5;function Moe({children:e,debugger:t=!1,viewControls:n=!1,autoSize:a=!1}){const r=r9(),i=w.useRef(null),s=w.useRef(0),c=w.useRef(null),u=w.useRef(!1),[d,m]=w.useState(null),[h,g]=w.useState(null),[v,x]=w.useState(!0);w.useEffect(()=>{let _=!0;return(async()=>{try{const k=await Jn(()=>import("./index-B1hPkVl-.js"),[]);_&&(m(()=>k.BrowserRouter),x(!1))}catch{_&&(g(new Error(`❌ react-router not installed!
36
36
 
37
37
  To use MCP widgets with McpUseProvider, you need to install:
38
38
 
@@ -90,7 +90,7 @@ Please change the parent <Route path="${_}"> to <Route path="${_==="/"?"*":`${_}
90
90
  `)},GU=function(){var e=parseInt(document.body.getAttribute(_u)||"0",10);return isFinite(e)?e:0},Gde=function(){w.useEffect(function(){return document.body.setAttribute(_u,(GU()+1).toString()),function(){var e=GU()-1;e<=0?document.body.removeAttribute(_u):document.body.setAttribute(_u,e.toString())}},[])},Wde=function(e){var t=e.noRelative,n=e.noImportant,a=e.gapMode,r=a===void 0?"margin":a;Gde();var i=w.useMemo(function(){return Bde(r)},[r]);return w.createElement(Hde,{styles:Vde(i,!t,r,n?"":"!important")})},B_=!1;if(typeof window<"u")try{var sb=Object.defineProperty({},"passive",{get:function(){return B_=!0,!0}});window.addEventListener("test",sb,sb),window.removeEventListener("test",sb,sb)}catch{B_=!1}var Zc=B_?{passive:!1}:!1,Kde=function(e){return e.tagName==="TEXTAREA"},E8=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Kde(e)&&n[t]==="visible")},Zde=function(e){return E8(e,"overflowY")},Yde=function(e){return E8(e,"overflowX")},WU=function(e,t){var n=t.ownerDocument,a=t;do{typeof ShadowRoot<"u"&&a instanceof ShadowRoot&&(a=a.host);var r=k8(e,a);if(r){var i=T8(e,a),s=i[1],c=i[2];if(s>c)return!0}a=a.parentNode}while(a&&a!==n.body);return!1},qde=function(e){var t=e.scrollTop,n=e.scrollHeight,a=e.clientHeight;return[t,n,a]},Xde=function(e){var t=e.scrollLeft,n=e.scrollWidth,a=e.clientWidth;return[t,n,a]},k8=function(e,t){return e==="v"?Zde(t):Yde(t)},T8=function(e,t){return e==="v"?qde(t):Xde(t)},Jde=function(e,t){return e==="h"&&t==="rtl"?-1:1},Qde=function(e,t,n,a,r){var i=Jde(e,window.getComputedStyle(t).direction),s=i*a,c=n.target,u=t.contains(c),d=!1,m=s>0,h=0,g=0;do{if(!c)break;var v=T8(e,c),x=v[0],S=v[1],y=v[2],E=S-y-i*x;(x||E)&&k8(e,c)&&(h+=E,g+=x);var _=c.parentNode;c=_&&_.nodeType===Node.DOCUMENT_FRAGMENT_NODE?_.host:_}while(!u&&c!==document.body||u&&(t.contains(c)||t===c));return(m&&Math.abs(h)<1||!m&&Math.abs(g)<1)&&(d=!0),d},lb=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},KU=function(e){return[e.deltaX,e.deltaY]},ZU=function(e){return e&&"current"in e?e.current:e},efe=function(e,t){return e[0]===t[0]&&e[1]===t[1]},tfe=function(e){return`
91
91
  .block-interactivity-`.concat(e,` {pointer-events: none;}
92
92
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
93
- `)},nfe=0,Yc=[];function rfe(e){var t=w.useRef([]),n=w.useRef([0,0]),a=w.useRef(),r=w.useState(nfe++)[0],i=w.useState(_8)[0],s=w.useRef(e);w.useEffect(function(){s.current=e},[e]),w.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(r));var S=Ede([e.lockRef.current],(e.shards||[]).map(ZU),!0).filter(Boolean);return S.forEach(function(y){return y.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),S.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(r))})}}},[e.inert,e.lockRef.current,e.shards]);var c=w.useCallback(function(S,y){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!s.current.allowPinchZoom;var E=lb(S),_=n.current,k="deltaX"in S?S.deltaX:_[0]-E[0],C="deltaY"in S?S.deltaY:_[1]-E[1],R,I=S.target,A=Math.abs(k)>Math.abs(C)?"h":"v";if("touches"in S&&A==="h"&&I.type==="range")return!1;var O=window.getSelection(),M=O&&O.anchorNode,P=M?M===I||M.contains(I):!1;if(P)return!1;var B=WU(A,I);if(!B)return!0;if(B?R=A:(R=A==="v"?"h":"v",B=WU(A,I)),!B)return!1;if(!a.current&&"changedTouches"in S&&(k||C)&&(a.current=R),!R)return!0;var K=a.current||R;return Qde(K,y,S,K==="h"?k:C)},[]),u=w.useCallback(function(S){var y=S;if(!(!Yc.length||Yc[Yc.length-1]!==i)){var E="deltaY"in y?KU(y):lb(y),_=t.current.filter(function(R){return R.name===y.type&&(R.target===y.target||y.target===R.shadowParent)&&efe(R.delta,E)})[0];if(_&&_.should){y.cancelable&&y.preventDefault();return}if(!_){var k=(s.current.shards||[]).map(ZU).filter(Boolean).filter(function(R){return R.contains(y.target)}),C=k.length>0?c(y,k[0]):!s.current.noIsolation;C&&y.cancelable&&y.preventDefault()}}},[]),d=w.useCallback(function(S,y,E,_){var k={name:S,delta:y,target:E,should:_,shadowParent:afe(E)};t.current.push(k),setTimeout(function(){t.current=t.current.filter(function(C){return C!==k})},1)},[]),m=w.useCallback(function(S){n.current=lb(S),a.current=void 0},[]),h=w.useCallback(function(S){d(S.type,KU(S),S.target,c(S,e.lockRef.current))},[]),g=w.useCallback(function(S){d(S.type,lb(S),S.target,c(S,e.lockRef.current))},[]);w.useEffect(function(){return Yc.push(i),e.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:g}),document.addEventListener("wheel",u,Zc),document.addEventListener("touchmove",u,Zc),document.addEventListener("touchstart",m,Zc),function(){Yc=Yc.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,Zc),document.removeEventListener("touchmove",u,Zc),document.removeEventListener("touchstart",m,Zc)}},[]);var v=e.removeScrollBar,x=e.inert;return w.createElement(w.Fragment,null,x?w.createElement(i,{styles:tfe(r)}):null,v?w.createElement(Wde,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function afe(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const ife=Dde(x8,rfe);var Om=w.forwardRef(function(e,t){return w.createElement(By,Fi({},e,{ref:t,sideCar:ife}))});Om.classNames=By.classNames;var H_=["Enter"," "],ofe=["ArrowDown","PageUp","Home"],N8=["ArrowUp","PageDown","End"],sfe=[...ofe,...N8],lfe={ltr:[...H_,"ArrowRight"],rtl:[...H_,"ArrowLeft"]},cfe={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Dm="Menu",[zp,ufe,dfe]=NN(Dm),[nc,C8]=Ii(Dm,[dfe,Zs,m8]),Hy=Zs(),R8=m8(),[ffe,rc]=nc(Dm),[pfe,jm]=nc(Dm),A8=e=>{const{__scopeMenu:t,open:n=!1,children:a,dir:r,onOpenChange:i,modal:s=!0}=e,c=Hy(t),[u,d]=w.useState(null),m=w.useRef(!1),h=Zi(i),g=CN(r);return w.useEffect(()=>{const v=()=>{m.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>m.current=!1;return document.addEventListener("keydown",v,{capture:!0}),()=>{document.removeEventListener("keydown",v,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.jsx(Py,{...c,children:f.jsx(ffe,{scope:t,open:n,onOpenChange:h,content:u,onContentChange:d,children:f.jsx(pfe,{scope:t,onClose:w.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:m,dir:g,modal:s,children:a})})})};A8.displayName=Dm;var mfe="MenuAnchor",PN=w.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e,r=Hy(n);return f.jsx(Am,{...r,...a,ref:t})});PN.displayName=mfe;var UN="MenuPortal",[hfe,I8]=nc(UN,{forceMount:void 0}),O8=e=>{const{__scopeMenu:t,forceMount:n,children:a,container:r}=e,i=rc(UN,t);return f.jsx(hfe,{scope:t,forceMount:n,children:f.jsx(Ua,{present:n||i.open,children:f.jsx(Ld,{asChild:!0,container:r,children:a})})})};O8.displayName=UN;var Qa="MenuContent",[gfe,zN]=nc(Qa),D8=w.forwardRef((e,t)=>{const n=I8(Qa,e.__scopeMenu),{forceMount:a=n.forceMount,...r}=e,i=rc(Qa,e.__scopeMenu),s=jm(Qa,e.__scopeMenu);return f.jsx(zp.Provider,{scope:e.__scopeMenu,children:f.jsx(Ua,{present:a||i.open,children:f.jsx(zp.Slot,{scope:e.__scopeMenu,children:s.modal?f.jsx(bfe,{...r,ref:t}):f.jsx(vfe,{...r,ref:t})})})})}),bfe=w.forwardRef((e,t)=>{const n=rc(Qa,e.__scopeMenu),a=w.useRef(null),r=Jt(t,a);return w.useEffect(()=>{const i=a.current;if(i)return Fy(i)},[]),f.jsx(FN,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ge(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vfe=w.forwardRef((e,t)=>{const n=rc(Qa,e.__scopeMenu);return f.jsx(FN,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yfe=Vl("MenuContent.ScrollLock"),FN=w.forwardRef((e,t)=>{const{__scopeMenu:n,loop:a=!1,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:c,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:v,disableOutsideScroll:x,...S}=e,y=rc(Qa,n),E=jm(Qa,n),_=Hy(n),k=R8(n),C=ufe(n),[R,I]=w.useState(null),A=w.useRef(null),O=Jt(t,A,y.onContentChange),M=w.useRef(0),P=w.useRef(""),B=w.useRef(0),K=w.useRef(null),ee=w.useRef("right"),te=w.useRef(0),ae=x?Om:w.Fragment,H=x?{as:yfe,allowPinchZoom:!0}:void 0,Z=re=>{const ne=P.current+re,j=C().filter(W=>!W.disabled),V=document.activeElement,z=j.find(W=>W.ref.current===V)?.textValue,$=j.map(W=>W.textValue),L=Ife($,ne,z),F=j.find(W=>W.textValue===L)?.ref.current;(function W(X){P.current=X,window.clearTimeout(M.current),X!==""&&(M.current=window.setTimeout(()=>W(""),1e3))})(ne),F&&setTimeout(()=>F.focus())};w.useEffect(()=>()=>window.clearTimeout(M.current),[]),Dy();const G=w.useCallback(re=>ee.current===K.current?.side&&Dfe(re,K.current?.area),[]);return f.jsx(gfe,{scope:n,searchRef:P,onItemEnter:w.useCallback(re=>{G(re)&&re.preventDefault()},[G]),onItemLeave:w.useCallback(re=>{G(re)||(A.current?.focus(),I(null))},[G]),onTriggerLeave:w.useCallback(re=>{G(re)&&re.preventDefault()},[G]),pointerGraceTimerRef:B,onPointerGraceIntentChange:w.useCallback(re=>{K.current=re},[]),children:f.jsx(ae,{...H,children:f.jsx(Cm,{asChild:!0,trapped:r,onMountAutoFocus:Ge(i,re=>{re.preventDefault(),A.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:f.jsx(Dd,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:d,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:v,children:f.jsx(yde,{asChild:!0,...k,dir:E.dir,orientation:"vertical",loop:a,currentTabStopId:R,onCurrentTabStopIdChange:I,onEntryFocus:Ge(u,re=>{E.isUsingKeyboardRef.current||re.preventDefault()}),preventScrollOnEntryFocus:!0,children:f.jsx(Uy,{role:"menu","aria-orientation":"vertical","data-state":Y8(y.open),"data-radix-menu-content":"",dir:E.dir,..._,...S,ref:O,style:{outline:"none",...S.style},onKeyDown:Ge(S.onKeyDown,re=>{const j=re.target.closest("[data-radix-menu-content]")===re.currentTarget,V=re.ctrlKey||re.altKey||re.metaKey,z=re.key.length===1;j&&(re.key==="Tab"&&re.preventDefault(),!V&&z&&Z(re.key));const $=A.current;if(re.target!==$||!sfe.includes(re.key))return;re.preventDefault();const F=C().filter(W=>!W.disabled).map(W=>W.ref.current);N8.includes(re.key)&&F.reverse(),Rfe(F)}),onBlur:Ge(e.onBlur,re=>{re.currentTarget.contains(re.target)||(window.clearTimeout(M.current),P.current="")}),onPointerMove:Ge(e.onPointerMove,Fp(re=>{const ne=re.target,j=te.current!==re.clientX;if(re.currentTarget.contains(ne)&&j){const V=re.clientX>te.current?"right":"left";ee.current=V,te.current=re.clientX}}))})})})})})})});D8.displayName=Qa;var wfe="MenuGroup",BN=w.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e;return f.jsx(_t.div,{role:"group",...a,ref:t})});BN.displayName=wfe;var Sfe="MenuLabel",j8=w.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e;return f.jsx(_t.div,{...a,ref:t})});j8.displayName=Sfe;var Tv="MenuItem",YU="menu.itemSelect",Vy=w.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:a,...r}=e,i=w.useRef(null),s=jm(Tv,e.__scopeMenu),c=zN(Tv,e.__scopeMenu),u=Jt(t,i),d=w.useRef(!1),m=()=>{const h=i.current;if(!n&&h){const g=new CustomEvent(YU,{bubbles:!0,cancelable:!0});h.addEventListener(YU,v=>a?.(v),{once:!0}),B9(h,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.jsx($8,{...r,ref:u,disabled:n,onClick:Ge(e.onClick,m),onPointerDown:h=>{e.onPointerDown?.(h),d.current=!0},onPointerUp:Ge(e.onPointerUp,h=>{d.current||h.currentTarget?.click()}),onKeyDown:Ge(e.onKeyDown,h=>{const g=c.searchRef.current!=="";n||g&&h.key===" "||H_.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});Vy.displayName=Tv;var $8=w.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:a=!1,textValue:r,...i}=e,s=zN(Tv,n),c=R8(n),u=w.useRef(null),d=Jt(t,u),[m,h]=w.useState(!1),[g,v]=w.useState("");return w.useEffect(()=>{const x=u.current;x&&v((x.textContent??"").trim())},[i.children]),f.jsx(zp.ItemSlot,{scope:n,disabled:a,textValue:r??g,children:f.jsx(wde,{asChild:!0,...c,focusable:!a,children:f.jsx(_t.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":a||void 0,"data-disabled":a?"":void 0,...i,ref:d,onPointerMove:Ge(e.onPointerMove,Fp(x=>{a?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ge(e.onPointerLeave,Fp(x=>s.onItemLeave(x))),onFocus:Ge(e.onFocus,()=>h(!0)),onBlur:Ge(e.onBlur,()=>h(!1))})})})}),xfe="MenuCheckboxItem",L8=w.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:a,...r}=e;return f.jsx(F8,{scope:e.__scopeMenu,checked:n,children:f.jsx(Vy,{role:"menuitemcheckbox","aria-checked":Nv(n)?"mixed":n,...r,ref:t,"data-state":VN(n),onSelect:Ge(r.onSelect,()=>a?.(Nv(n)?!0:!n),{checkForDefaultPrevented:!1})})})});L8.displayName=xfe;var M8="MenuRadioGroup",[_fe,Efe]=nc(M8,{value:void 0,onValueChange:()=>{}}),P8=w.forwardRef((e,t)=>{const{value:n,onValueChange:a,...r}=e,i=Zi(a);return f.jsx(_fe,{scope:e.__scopeMenu,value:n,onValueChange:i,children:f.jsx(BN,{...r,ref:t})})});P8.displayName=M8;var U8="MenuRadioItem",z8=w.forwardRef((e,t)=>{const{value:n,...a}=e,r=Efe(U8,e.__scopeMenu),i=n===r.value;return f.jsx(F8,{scope:e.__scopeMenu,checked:i,children:f.jsx(Vy,{role:"menuitemradio","aria-checked":i,...a,ref:t,"data-state":VN(i),onSelect:Ge(a.onSelect,()=>r.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});z8.displayName=U8;var HN="MenuItemIndicator",[F8,kfe]=nc(HN,{checked:!1}),B8=w.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:a,...r}=e,i=kfe(HN,n);return f.jsx(Ua,{present:a||Nv(i.checked)||i.checked===!0,children:f.jsx(_t.span,{...r,ref:t,"data-state":VN(i.checked)})})});B8.displayName=HN;var Tfe="MenuSeparator",H8=w.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e;return f.jsx(_t.div,{role:"separator","aria-orientation":"horizontal",...a,ref:t})});H8.displayName=Tfe;var Nfe="MenuArrow",V8=w.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e,r=Hy(n);return f.jsx(zy,{...r,...a,ref:t})});V8.displayName=Nfe;var Cfe="MenuSub",[QTe,G8]=nc(Cfe),np="MenuSubTrigger",W8=w.forwardRef((e,t)=>{const n=rc(np,e.__scopeMenu),a=jm(np,e.__scopeMenu),r=G8(np,e.__scopeMenu),i=zN(np,e.__scopeMenu),s=w.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},m=w.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return w.useEffect(()=>m,[m]),w.useEffect(()=>{const h=c.current;return()=>{window.clearTimeout(h),u(null)}},[c,u]),f.jsx(PN,{asChild:!0,...d,children:f.jsx($8,{id:r.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":r.contentId,"data-state":Y8(n.open),...e,ref:Ki(t,r.onTriggerChange),onClick:h=>{e.onClick?.(h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ge(e.onPointerMove,Fp(h=>{i.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:Ge(e.onPointerLeave,Fp(h=>{m();const g=n.content?.getBoundingClientRect();if(g){const v=n.content?.dataset.side,x=v==="right",S=x?-5:5,y=g[x?"left":"right"],E=g[x?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+S,y:h.clientY},{x:y,y:g.top},{x:E,y:g.top},{x:E,y:g.bottom},{x:y,y:g.bottom}],side:v}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(h),h.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:Ge(e.onKeyDown,h=>{const g=i.searchRef.current!=="";e.disabled||g&&h.key===" "||lfe[a.dir].includes(h.key)&&(n.onOpenChange(!0),n.content?.focus(),h.preventDefault())})})})});W8.displayName=np;var K8="MenuSubContent",Z8=w.forwardRef((e,t)=>{const n=I8(Qa,e.__scopeMenu),{forceMount:a=n.forceMount,...r}=e,i=rc(Qa,e.__scopeMenu),s=jm(Qa,e.__scopeMenu),c=G8(K8,e.__scopeMenu),u=w.useRef(null),d=Jt(t,u);return f.jsx(zp.Provider,{scope:e.__scopeMenu,children:f.jsx(Ua,{present:a||i.open,children:f.jsx(zp.Slot,{scope:e.__scopeMenu,children:f.jsx(FN,{id:c.contentId,"aria-labelledby":c.triggerId,...r,ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{s.isUsingKeyboardRef.current&&u.current?.focus(),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:Ge(e.onFocusOutside,m=>{m.target!==c.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:Ge(e.onEscapeKeyDown,m=>{s.onClose(),m.preventDefault()}),onKeyDown:Ge(e.onKeyDown,m=>{const h=m.currentTarget.contains(m.target),g=cfe[s.dir].includes(m.key);h&&g&&(i.onOpenChange(!1),c.trigger?.focus(),m.preventDefault())})})})})})});Z8.displayName=K8;function Y8(e){return e?"open":"closed"}function Nv(e){return e==="indeterminate"}function VN(e){return Nv(e)?"indeterminate":e?"checked":"unchecked"}function Rfe(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Afe(e,t){return e.map((n,a)=>e[(t+a)%e.length])}function Ife(e,t,n){const r=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=Afe(e,Math.max(i,0));r.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(r.toLowerCase()));return u!==n?u:void 0}function Ofe(e,t){const{x:n,y:a}=e;let r=!1;for(let i=0,s=t.length-1;i<t.length;s=i++){const c=t[i],u=t[s],d=c.x,m=c.y,h=u.x,g=u.y;m>a!=g>a&&n<(h-d)*(a-m)/(g-m)+d&&(r=!r)}return r}function Dfe(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Ofe(n,t)}function Fp(e){return t=>t.pointerType==="mouse"?e(t):void 0}var jfe=A8,$fe=PN,Lfe=O8,Mfe=D8,Pfe=BN,Ufe=j8,zfe=Vy,Ffe=L8,Bfe=P8,Hfe=z8,Vfe=B8,Gfe=H8,Wfe=V8,Kfe=W8,Zfe=Z8,Gy="DropdownMenu",[Yfe]=Ii(Gy,[C8]),ia=C8(),[qfe,q8]=Yfe(Gy),X8=e=>{const{__scopeDropdownMenu:t,children:n,dir:a,open:r,defaultOpen:i,onOpenChange:s,modal:c=!0}=e,u=ia(t),d=w.useRef(null),[m,h]=Mo({prop:r,defaultProp:i??!1,onChange:s,caller:Gy});return f.jsx(qfe,{scope:t,triggerId:jr(),triggerRef:d,contentId:jr(),open:m,onOpenChange:h,onOpenToggle:w.useCallback(()=>h(g=>!g),[h]),modal:c,children:f.jsx(jfe,{...u,open:m,onOpenChange:h,dir:a,modal:c,children:n})})};X8.displayName=Gy;var J8="DropdownMenuTrigger",Q8=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:a=!1,...r}=e,i=q8(J8,n),s=ia(n);return f.jsx($fe,{asChild:!0,...s,children:f.jsx(_t.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":a?"":void 0,disabled:a,...r,ref:Ki(t,i.triggerRef),onPointerDown:Ge(e.onPointerDown,c=>{!a&&c.button===0&&c.ctrlKey===!1&&(i.onOpenToggle(),i.open||c.preventDefault())}),onKeyDown:Ge(e.onKeyDown,c=>{a||(["Enter"," "].includes(c.key)&&i.onOpenToggle(),c.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});Q8.displayName=J8;var Xfe="DropdownMenuPortal",eG=e=>{const{__scopeDropdownMenu:t,...n}=e,a=ia(t);return f.jsx(Lfe,{...a,...n})};eG.displayName=Xfe;var tG="DropdownMenuContent",nG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=q8(tG,n),i=ia(n),s=w.useRef(!1);return f.jsx(Mfe,{id:r.contentId,"aria-labelledby":r.triggerId,...i,...a,ref:t,onCloseAutoFocus:Ge(e.onCloseAutoFocus,c=>{s.current||r.triggerRef.current?.focus(),s.current=!1,c.preventDefault()}),onInteractOutside:Ge(e.onInteractOutside,c=>{const u=c.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,m=u.button===2||d;(!r.modal||m)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});nG.displayName=tG;var Jfe="DropdownMenuGroup",Qfe=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Pfe,{...r,...a,ref:t})});Qfe.displayName=Jfe;var epe="DropdownMenuLabel",rG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Ufe,{...r,...a,ref:t})});rG.displayName=epe;var tpe="DropdownMenuItem",aG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(zfe,{...r,...a,ref:t})});aG.displayName=tpe;var npe="DropdownMenuCheckboxItem",iG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Ffe,{...r,...a,ref:t})});iG.displayName=npe;var rpe="DropdownMenuRadioGroup",ape=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Bfe,{...r,...a,ref:t})});ape.displayName=rpe;var ipe="DropdownMenuRadioItem",oG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Hfe,{...r,...a,ref:t})});oG.displayName=ipe;var ope="DropdownMenuItemIndicator",spe=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Vfe,{...r,...a,ref:t})});spe.displayName=ope;var lpe="DropdownMenuSeparator",sG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Gfe,{...r,...a,ref:t})});sG.displayName=lpe;var cpe="DropdownMenuArrow",upe=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Wfe,{...r,...a,ref:t})});upe.displayName=cpe;var dpe="DropdownMenuSubTrigger",lG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Kfe,{...r,...a,ref:t})});lG.displayName=dpe;var fpe="DropdownMenuSubContent",cG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Zfe,{...r,...a,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});cG.displayName=fpe;var ppe=X8,mpe=Q8,hpe=eG,uG=nG,dG=rG,fG=aG,gpe=iG,bpe=oG,pG=sG,vpe=lG,ype=cG;const V_=ppe,G_=mpe;vpe.displayName;ype.displayName;function Cv({ref:e,className:t,sideOffset:n=4,...a}){return f.jsx(hpe,{children:f.jsx(uG,{ref:e,sideOffset:n,className:De("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})})}Cv.displayName=uG.displayName;function Ro({ref:e,className:t,inset:n,...a}){return f.jsx(fG,{ref:e,className:De("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n&&"pl-8",t),...a})}Ro.displayName=fG.displayName;gpe.displayName;bpe.displayName;function W_({ref:e,className:t,inset:n,...a}){return f.jsx(dG,{ref:e,className:De("px-2 py-1.5 text-sm font-semibold",n&&"pl-8",t),...a})}W_.displayName=dG.displayName;function rp({ref:e,className:t,...n}){return f.jsx(pG,{ref:e,className:De("-mx-1 my-1 h-px bg-muted",t),...n})}rp.displayName=pG.displayName;var wpe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Go=wpe.reduce((e,t)=>{const n=_9(`Primitive.${t}`),a=w.forwardRef((r,i)=>{const{asChild:s,...c}=r,u=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),f.jsx(u,{...c,ref:i})});return a.displayName=`Primitive.${t}`,{...e,[t]:a}},{}),Spe="Label",mG=w.forwardRef((e,t)=>f.jsx(Go.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));mG.displayName=Spe;var xpe=mG;function Kt({className:e,...t}){return f.jsx(xpe,{"data-slot":"label",className:De("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function Md({message:e,className:t="",vertical:n,noBorder:a}){return f.jsx("div",{className:De(`mt-2 rounded-md p-6 ${t}`,!a&&"border"),children:f.jsxs("p",{className:De("text-sm text-muted-foreground flex items-center gap-4",n&&"flex-col"),children:[f.jsx("svg",{width:"40",height:"40",viewBox:"0 0 273 273",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:"flex-shrink-0",children:f.jsx("g",{stroke:"none",strokeWidth:"1",fill:"none",fillRule:"evenodd",children:f.jsxs("g",{transform:"translate(5.320900, 5.320900)",fillRule:"nonzero",className:"stroke-black dark:stroke-white",strokeWidth:"4",children:[f.jsx("path",{d:"M49.953025,-2.10854389 C63.26892,-2.21867124 76.6185256,2.70621155 86.9019463,12.6653164 L86.9019463,12.6653164 L87.505627,13.2592944 C97.5154947,23.2654892 102.640454,36.3074513 102.880738,49.4222247 C103.08932,77.4533067 113.877287,105.391753 135.242867,126.757333 C156.613383,148.127849 184.559216,158.914875 212.568138,159.119313 L212.568138,159.119313 L213.212264,159.134159 C225.843948,159.517566 238.363557,164.434972 248.121998,173.886137 L248.121998,173.886137 L248.725621,174.480088 C258.982114,184.732164 264.11035,198.171134 264.11035,211.6101 C264.11035,225.04592 258.984514,238.481745 248.732867,248.732867 C238.592792,258.872942 225.336706,263.997882 212.046872,264.107794 C198.731075,264.21792 185.381569,259.293085 175.098248,249.334078 L175.098248,249.334078 L174.494602,248.740134 C163.75802,238.008189 158.640853,223.784027 159.143413,209.719372 C158.258245,182.640933 147.489786,155.83332 126.828333,135.171867 C106.351297,114.694831 79.8363505,103.934873 53.0237258,102.891841 L53.0237258,102.891841 L52.2811438,102.865674 C38.4791718,103.347421 24.5325234,98.4328111 13.8776628,88.1140866 L13.8776628,88.1140866 L13.2739843,87.5201168 C3.12895117,77.3789607 -1.9984796,64.1195994 -2.10841888,50.8264755 C-2.21854669,37.5105567 2.70635908,24.1609269 12.6655135,13.8774565 L12.6655135,13.8774565 L13.2594878,13.2737797 C23.4005926,3.12880025 36.659927,-1.99860507 49.953025,-2.10854389 Z"}),f.jsx("circle",{cx:"50",cy:"212.0001",r:"52.5"}),f.jsx("circle",{cx:"212.0001",cy:"50",r:"52.5"})]})})}),e]})})}function hG({className:e,color:t,children:n,grayscaled:a=!1}){const r=w.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[1]||"0")}return a?0:.2},[t,a]),i=w.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[0]||"0.5")}return a?.3:.4},[t,a]),s=w.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[2]||"0")}return Math.floor(Math.random()*360)},[t]),c=w.useMemo(()=>t||`oklch(${Math.min(i,1)} ${r} ${s})`,[s,r,i]),u=w.useMemo(()=>`oklch(${Math.min(i*2,1)} ${r} ${s})`,[s,r,i,t]),d=w.useMemo(()=>Math.floor(Math.random()*360),[s]),m=w.useMemo(()=>"1000%",[]);return f.jsx("section",{className:De("relative w-full h-full overflow-hidden",e),style:{background:`${u}`},children:f.jsxs("div",{className:"isolate relative w-full h-full",children:[f.jsx("div",{className:"noise w-full h-full",style:{background:`linear-gradient(${d}deg, ${c}, transparent), url(https://grainy-gradients.vercel.app/noise.svg)`,filter:`contrast(120%) brightness(${m})`}}),n&&f.jsx("div",{className:"relative z-10 w-full h-full",children:n})]})})}function GN(e){const t=w.useRef({value:e,previous:e});return w.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Wy="Switch",[_pe]=Ii(Wy),[Epe,kpe]=_pe(Wy),gG=w.forwardRef((e,t)=>{const{__scopeSwitch:n,name:a,checked:r,defaultChecked:i,required:s,disabled:c,value:u="on",onCheckedChange:d,form:m,...h}=e,[g,v]=w.useState(null),x=Jt(t,k=>v(k)),S=w.useRef(!1),y=g?m||!!g.closest("form"):!0,[E,_]=Mo({prop:r,defaultProp:i??!1,onChange:d,caller:Wy});return f.jsxs(Epe,{scope:n,checked:E,disabled:c,children:[f.jsx(_t.button,{type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":wG(E),"data-disabled":c?"":void 0,disabled:c,value:u,...h,ref:x,onClick:Ge(e.onClick,k=>{_(C=>!C),y&&(S.current=k.isPropagationStopped(),S.current||k.stopPropagation())})}),y&&f.jsx(yG,{control:g,bubbles:!S.current,name:a,value:u,checked:E,required:s,disabled:c,form:m,style:{transform:"translateX(-100%)"}})]})});gG.displayName=Wy;var bG="SwitchThumb",vG=w.forwardRef((e,t)=>{const{__scopeSwitch:n,...a}=e,r=kpe(bG,n);return f.jsx(_t.span,{"data-state":wG(r.checked),"data-disabled":r.disabled?"":void 0,...a,ref:t})});vG.displayName=bG;var Tpe="SwitchBubbleInput",yG=w.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:a=!0,...r},i)=>{const s=w.useRef(null),c=Jt(s,i),u=GN(n),d=$N(t);return w.useEffect(()=>{const m=s.current;if(!m)return;const h=window.HTMLInputElement.prototype,v=Object.getOwnPropertyDescriptor(h,"checked").set;if(u!==n&&v){const x=new Event("click",{bubbles:a});v.call(m,n),m.dispatchEvent(x)}},[u,n,a]),f.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...r,tabIndex:-1,ref:c,style:{...r.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});yG.displayName=Tpe;function wG(e){return e?"checked":"unchecked"}var SG=gG,Npe=vG;function Ky({ref:e,className:t,...n}){return f.jsx(SG,{className:De("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",t),...n,ref:e,children:f.jsx(Npe,{className:De("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})})}Ky.displayName=SG.displayName;var xG=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Cpe="VisuallyHidden",_G=w.forwardRef((e,t)=>f.jsx(_t.span,{...e,ref:t,style:{...xG,...e.style}}));_G.displayName=Cpe;var Rpe=_G,[Zy]=Ii("Tooltip",[Zs]),Yy=Zs(),EG="TooltipProvider",Ape=700,K_="tooltip.open",[Ipe,WN]=Zy(EG),kG=e=>{const{__scopeTooltip:t,delayDuration:n=Ape,skipDelayDuration:a=300,disableHoverableContent:r=!1,children:i}=e,s=w.useRef(!0),c=w.useRef(!1),u=w.useRef(0);return w.useEffect(()=>{const d=u.current;return()=>window.clearTimeout(d)},[]),f.jsx(Ipe,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:w.useCallback(()=>{window.clearTimeout(u.current),s.current=!1},[]),onClose:w.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>s.current=!0,a)},[a]),isPointerInTransitRef:c,onPointerInTransitChange:w.useCallback(d=>{c.current=d},[]),disableHoverableContent:r,children:i})};kG.displayName=EG;var Bp="Tooltip",[Ope,$m]=Zy(Bp),TG=e=>{const{__scopeTooltip:t,children:n,open:a,defaultOpen:r,onOpenChange:i,disableHoverableContent:s,delayDuration:c}=e,u=WN(Bp,e.__scopeTooltip),d=Yy(t),[m,h]=w.useState(null),g=jr(),v=w.useRef(0),x=s??u.disableHoverableContent,S=c??u.delayDuration,y=w.useRef(!1),[E,_]=Mo({prop:a,defaultProp:r??!1,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(K_))):u.onClose(),i?.(A)},caller:Bp}),k=w.useMemo(()=>E?y.current?"delayed-open":"instant-open":"closed",[E]),C=w.useCallback(()=>{window.clearTimeout(v.current),v.current=0,y.current=!1,_(!0)},[_]),R=w.useCallback(()=>{window.clearTimeout(v.current),v.current=0,_(!1)},[_]),I=w.useCallback(()=>{window.clearTimeout(v.current),v.current=window.setTimeout(()=>{y.current=!0,_(!0),v.current=0},S)},[S,_]);return w.useEffect(()=>()=>{v.current&&(window.clearTimeout(v.current),v.current=0)},[]),f.jsx(Py,{...d,children:f.jsx(Ope,{scope:t,contentId:g,open:E,stateAttribute:k,trigger:m,onTriggerChange:h,onTriggerEnter:w.useCallback(()=>{u.isOpenDelayedRef.current?I():C()},[u.isOpenDelayedRef,I,C]),onTriggerLeave:w.useCallback(()=>{x?R():(window.clearTimeout(v.current),v.current=0)},[R,x]),onOpen:C,onClose:R,disableHoverableContent:x,children:n})})};TG.displayName=Bp;var Z_="TooltipTrigger",NG=w.forwardRef((e,t)=>{const{__scopeTooltip:n,...a}=e,r=$m(Z_,n),i=WN(Z_,n),s=Yy(n),c=w.useRef(null),u=Jt(t,c,r.onTriggerChange),d=w.useRef(!1),m=w.useRef(!1),h=w.useCallback(()=>d.current=!1,[]);return w.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),f.jsx(Am,{asChild:!0,...s,children:f.jsx(_t.button,{"aria-describedby":r.open?r.contentId:void 0,"data-state":r.stateAttribute,...a,ref:u,onPointerMove:Ge(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!i.isPointerInTransitRef.current&&(r.onTriggerEnter(),m.current=!0)}),onPointerLeave:Ge(e.onPointerLeave,()=>{r.onTriggerLeave(),m.current=!1}),onPointerDown:Ge(e.onPointerDown,()=>{r.open&&r.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:Ge(e.onFocus,()=>{d.current||r.onOpen()}),onBlur:Ge(e.onBlur,r.onClose),onClick:Ge(e.onClick,r.onClose)})})});NG.displayName=Z_;var KN="TooltipPortal",[Dpe,jpe]=Zy(KN,{forceMount:void 0}),CG=e=>{const{__scopeTooltip:t,forceMount:n,children:a,container:r}=e,i=$m(KN,t);return f.jsx(Dpe,{scope:t,forceMount:n,children:f.jsx(Ua,{present:n||i.open,children:f.jsx(Ld,{asChild:!0,container:r,children:a})})})};CG.displayName=KN;var dd="TooltipContent",RG=w.forwardRef((e,t)=>{const n=jpe(dd,e.__scopeTooltip),{forceMount:a=n.forceMount,side:r="top",...i}=e,s=$m(dd,e.__scopeTooltip);return f.jsx(Ua,{present:a||s.open,children:s.disableHoverableContent?f.jsx(AG,{side:r,...i,ref:t}):f.jsx($pe,{side:r,...i,ref:t})})}),$pe=w.forwardRef((e,t)=>{const n=$m(dd,e.__scopeTooltip),a=WN(dd,e.__scopeTooltip),r=w.useRef(null),i=Jt(t,r),[s,c]=w.useState(null),{trigger:u,onClose:d}=n,m=r.current,{onPointerInTransitChange:h}=a,g=w.useCallback(()=>{c(null),h(!1)},[h]),v=w.useCallback((x,S)=>{const y=x.currentTarget,E={x:x.clientX,y:x.clientY},_=Upe(E,y.getBoundingClientRect()),k=zpe(E,_),C=Fpe(S.getBoundingClientRect()),R=Hpe([...k,...C]);c(R),h(!0)},[h]);return w.useEffect(()=>()=>g(),[g]),w.useEffect(()=>{if(u&&m){const x=y=>v(y,m),S=y=>v(y,u);return u.addEventListener("pointerleave",x),m.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",x),m.removeEventListener("pointerleave",S)}}},[u,m,v,g]),w.useEffect(()=>{if(s){const x=S=>{const y=S.target,E={x:S.clientX,y:S.clientY},_=u?.contains(y)||m?.contains(y),k=!Bpe(E,s);_?g():k&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,m,s,d,g]),f.jsx(AG,{...e,ref:i})}),[Lpe,Mpe]=Zy(Bp,{isInside:!1}),Ppe=vce("TooltipContent"),AG=w.forwardRef((e,t)=>{const{__scopeTooltip:n,children:a,"aria-label":r,onEscapeKeyDown:i,onPointerDownOutside:s,...c}=e,u=$m(dd,n),d=Yy(n),{onClose:m}=u;return w.useEffect(()=>(document.addEventListener(K_,m),()=>document.removeEventListener(K_,m)),[m]),w.useEffect(()=>{if(u.trigger){const h=g=>{g.target?.contains(u.trigger)&&m()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[u.trigger,m]),f.jsx(Dd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:h=>h.preventDefault(),onDismiss:m,children:f.jsxs(Uy,{"data-state":u.stateAttribute,...d,...c,ref:t,style:{...c.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[f.jsx(Ppe,{children:a}),f.jsx(Lpe,{scope:n,isInside:!0,children:f.jsx(Rpe,{id:u.contentId,role:"tooltip",children:r||a})})]})})});RG.displayName=dd;var IG="TooltipArrow",OG=w.forwardRef((e,t)=>{const{__scopeTooltip:n,...a}=e,r=Yy(n);return Mpe(IG,n).isInside?null:f.jsx(zy,{...r,...a,ref:t})});OG.displayName=IG;function Upe(e,t){const n=Math.abs(t.top-e.y),a=Math.abs(t.bottom-e.y),r=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,a,r,i)){case i:return"left";case r:return"right";case n:return"top";case a:return"bottom";default:throw new Error("unreachable")}}function zpe(e,t,n=5){const a=[];switch(t){case"top":a.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":a.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":a.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":a.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return a}function Fpe(e){const{top:t,right:n,bottom:a,left:r}=e;return[{x:r,y:t},{x:n,y:t},{x:n,y:a},{x:r,y:a}]}function Bpe(e,t){const{x:n,y:a}=e;let r=!1;for(let i=0,s=t.length-1;i<t.length;s=i++){const c=t[i],u=t[s],d=c.x,m=c.y,h=u.x,g=u.y;m>a!=g>a&&n<(h-d)*(a-m)/(g-m)+d&&(r=!r)}return r}function Hpe(e){const t=e.slice();return t.sort((n,a)=>n.x<a.x?-1:n.x>a.x?1:n.y<a.y?-1:n.y>a.y?1:0),Vpe(t)}function Vpe(e){if(e.length<=1)return e.slice();const t=[];for(let a=0;a<e.length;a++){const r=e[a];for(;t.length>=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(r.y-s.y)>=(i.y-s.y)*(r.x-s.x))t.pop();else break}t.push(r)}t.pop();const n=[];for(let a=e.length-1;a>=0;a--){const r=e[a];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(r.y-s.y)>=(i.y-s.y)*(r.x-s.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var Gpe=kG,Wpe=TG,Kpe=NG,Zpe=CG,Ype=RG,qpe=OG;function ZN({delayDuration:e=0,...t}){return f.jsx(Gpe,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Nt({...e}){return f.jsx(ZN,{children:f.jsx(Wpe,{"data-slot":"tooltip",...e})})}function Ct({...e}){return f.jsx(Kpe,{"data-slot":"tooltip-trigger",...e})}function Rt({className:e,sideOffset:t=0,children:n,...a}){return f.jsx(Zpe,{children:f.jsxs(Ype,{"data-slot":"tooltip-content",sideOffset:t,className:De("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...a,children:[n,f.jsx(qpe,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}class Xpe{name="mcp_inspector_open";properties;constructor(t){this.properties={server_url:t.serverUrl,connection_count:t.connectionCount}}}class qU{name="mcp_tool_execution";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId,success:t.success,duration:t.duration,error:t.error}}}class XU{name="mcp_resource_read";properties;constructor(t){this.properties={resource_uri:t.resourceUri,server_id:t.serverId,success:t.success,error:t.error}}}class JU{name="mcp_prompt_call";properties;constructor(t){this.properties={prompt_name:t.promptName,server_id:t.serverId,success:t.success,error:t.error}}}class QU{name="mcp_chat_message";properties;constructor(t){this.properties={server_id:t.serverId,provider:t.provider,model:t.model,message_count:t.messageCount,tool_calls_count:t.toolCallsCount,success:t.success,execution_mode:t.executionMode,duration:t.duration,error:t.error}}}class Jpe{name="mcp_server_added";properties;constructor(t){this.properties={server_id:t.serverId,server_url:t.serverUrl,connection_type:t.connectionType,via_proxy:t.viaProxy}}}class Qpe{name="mcp_server_removed";properties;constructor(t){this.properties={server_id:t.serverId}}}class eme{name="mcp_command_palette_open";properties;constructor(t){this.properties={trigger:t.trigger}}}class tme{name="mcp_tool_saved";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId}}}function wx(){try{return"0.13.0-canary.18"}catch{return"0.0.0"}}var nme={};function Sx(){try{return typeof window<"u"&&typeof document<"u"}catch{return!1}}class ez{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,a=setTimeout(()=>n.abort(),this.timeout),r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(a),!r.ok)throw new Error(`HTTP error! status: ${r.status}`)}catch{}}}function ys(e){return`mcp_inspector_telemetry_${e}`}class vr{static instance=null;POSTHOG_PROXY_URL="/inspector/api/tel/posthog";SCARF_PROXY_URL="/inspector/api/tel/scarf";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogClient=null;_scarfClient=null;_source="inspector";constructor(){const t=Sx(),n=this.isTelemetryDisabled();if(this._source=this.getStoredSource()||"inspector",n)this._posthogClient=null,this._scarfClient=null;else if(!t)this._posthogClient=null,this._scarfClient=null;else{try{this._posthogClient=new ez(this.POSTHOG_PROXY_URL,3e3)}catch{this._posthogClient=null}try{this._scarfClient=new ez(this.SCARF_PROXY_URL,3e3)}catch{this._scarfClient=null}}}isTelemetryDisabled(){return typeof localStorage<"u"&&localStorage.getItem(ys("disabled"))==="true"||typeof process<"u"&&nme?.MCP_USE_ANONYMIZED_TELEMETRY==="false"}getStoredSource(){return typeof localStorage<"u"?localStorage.getItem(ys("source")):null}static getInstance(){return vr.instance||(vr.instance=new vr),vr.instance}setSource(t){this._source=t,typeof localStorage<"u"&&localStorage.setItem(ys("source"),t)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!Sx())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{const t=localStorage.getItem(ys("user_id"));if(t)this._currUserId=t;else{const n=this.generateUserId();localStorage.setItem(ys("user_id"),n),this._currUserId=n}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(()=>{})}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}generateUserId(){const t=window.crypto;if(t){const n=new Uint8Array(16);t.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;const a=Array.from(n).map(r=>r.toString(16).padStart(2,"0")).join("");return a.slice(0,8)+"-"+a.slice(8,12)+"-"+a.slice(12,16)+"-"+a.slice(16,20)+"-"+a.slice(20,32)}else return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const a=Math.random()*16|0;return(n==="x"?a:a&3|8).toString(16)})}async capture(t){if(!(!this._posthogClient&&!this._scarfClient)){if(this._posthogClient)try{const n={event:t.name,user_id:this.userId,properties:{...t.properties,mcp_use_version:wx(),language:"typescript",source:this._source,package:"inspector"}};await this._posthogClient.logEvent(n)}catch{}if(this._scarfClient)try{const n={};n.mcp_use_version=wx(),n.user_id=this.userId,n.event=t.name,n.language="typescript",n.source=this._source,n.package="inspector",await this._scarfClient.logEvent(n)}catch{}}}async trackPackageDownload(t){if(this._scarfClient&&Sx())try{const n=wx();let a=!1,r=!1;const i=localStorage.getItem(ys("download_version"));if(i?n>i&&(a=!0,r=!1,localStorage.setItem(ys("download_version"),n)):(a=!0,r=!0,localStorage.setItem(ys("download_version"),n)),a){const s={...t||{}};s.mcp_use_version=n,s.user_id=this.userId,s.event="package_download",s.first_download=r,s.language="typescript",s.source=this._source,s.package="inspector",await this._scarfClient.logEvent(s)}}catch{}}async trackInspectorOpen(t){const n=new Xpe(t);await this.capture(n)}}const rme={model:"stub-model",stopReason:"endTurn",role:"assistant",content:{type:"text",text:"positive"}};function ame({requestId:e,serverName:t,onViewDetails:n,onApprove:a,onDeny:r}){return f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{children:[f.jsx("strong",{children:"Sampling Request Received"}),f.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["New request from ",t]})]}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:i=>{i.stopPropagation(),n()},children:"View Details"}),f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:i=>{i.stopPropagation(),a(rme)},children:"Approve"}),f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:i=>{i.stopPropagation(),r()},children:"Deny"})]})]})}function ime({requestId:e,serverName:t,mode:n,message:a,url:r,onViewDetails:i,onOpenUrl:s,onCancel:c}){return f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{children:[f.jsx("strong",{children:"Elicitation Request Received"}),f.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["From ",t,": ",a]}),n==="url"&&r&&f.jsx("p",{className:"text-xs text-muted-foreground mt-1 font-mono",children:r})]}),f.jsxs("div",{className:"flex gap-2 flex-wrap",children:[f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:u=>{u.stopPropagation(),i()},children:"View Details"}),n==="url"&&s&&f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:u=>{u.stopPropagation(),s()},children:"Open URL"}),f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:u=>{u.stopPropagation(),c()},children:"Cancel"})]})]})}const cb=()=>{},ub=()=>{},db=()=>{},fb=()=>{},DG=w.createContext(null);function YN(){const e=w.use(DG);if(!e)throw new Error("useMcpContext must be used within a McpProvider");return e}function ome({url:e,name:t,proxyConfig:n,transportType:a,connectionId:r,onUpdate:i,onRemove:s}){const c=typeof window<"u"?new URL("/inspector/oauth/callback",window.location.origin).toString():"/inspector/oauth/callback";let u=e,d={};if(n?.proxyAddress){const $=new URL(n.proxyAddress),L=new URL(e);u=`${$.origin}${$.pathname}${L.pathname}${L.search}`,d["X-Target-URL"]=e}n?.customHeaders&&(d={...d,...n.customHeaders});const[m,h]=w.useState([]),g=w.useRef(0),[v,x]=w.useState([]),S=w.useRef(0),y=w.useMemo(()=>m.map($=>({id:$.id,request:$.request,timestamp:$.timestamp,serverName:$.serverName})),[m]),E=w.useMemo(()=>v.map($=>({id:$.id,request:$.request,timestamp:$.timestamp,serverName:$.serverName})),[v]),_=w.useRef(null),[k,C]=w.useState(!1),R=w.useRef(!1);w.useEffect(()=>{typeof window<"u"&&!R.current&&(R.current=!0,Jn(()=>import("./transport-wrapper-browser-BI4dDu3b.js"),[]).then($=>{_.current=$.wrapTransportForLogging,C(!0),console.log("[McpContext] Transport wrapper loaded")}).catch($=>{console.error("[McpContext] Failed to load transport wrapper:",$)}))},[]);const I=w.useMemo(()=>{if(!(!k||!_.current))return($,L)=>{const F=r;return console.log("[McpContext] Applying transport wrapper, serverId:",F,"from connector:",L),_.current($,F)}},[k,r]),A=`mcp-inspector-notifications-${r}`,O=500,[M,P]=w.useState([]);w.useEffect(()=>{try{const $=localStorage.getItem(A);if($){const L=JSON.parse($);Array.isArray(L)&&P(L)}}catch($){console.error("Failed to load notifications from localStorage:",$)}},[A]),w.useEffect(()=>{try{localStorage.setItem(A,JSON.stringify(M))}catch($){console.error("Failed to save notifications to localStorage:",$)}},[M,A]);const B=w.useCallback($=>{P(L=>L.map(F=>F.id===$?{...F,read:!0}:F))},[]),K=w.useCallback(()=>{P($=>$.map(L=>({...L,read:!0})))},[]),ee=w.useCallback(()=>{P([])},[]),te=w.useCallback($=>{P(L=>{const F=[$,...L];return F.length>O?F.slice(0,O):F})},[]),ae=w.useCallback(($,L)=>{h(F=>{const W=F.find(X=>X.id===$);return W?(W.resolve(L),F.filter(X=>X.id!==$)):F})},[]),H=w.useCallback(($,L)=>{h(F=>{const W=F.find(X=>X.id===$);return W?(W.reject(new Error(L||"User rejected sampling request")),F.filter(X=>X.id!==$)):F})},[]),Z=w.useCallback(($,L)=>{x(F=>{const W=F.find(X=>X.id===$);return W?(W.resolve(L),F.filter(X=>X.id!==$)):F})},[]),G=w.useCallback(($,L)=>{x(F=>{const W=F.find(X=>X.id===$);return W?(W.reject(new Error(L||"User rejected elicitation request")),F.filter(X=>X.id!==$)):F})},[]),re=w.useCallback(async $=>new Promise((L,F)=>{const W=`sampling-${g.current++}`,X={id:W,request:{params:$},timestamp:Date.now(),serverName:t,resolve:L,reject:F};h(ie=>[...ie,X]),typeof window<"u"&&Jn(async()=>{const{toast:ie}=await Promise.resolve().then(()=>sz);return{toast:ie}},void 0).then(({toast:ie})=>{const ce=ie(f.jsx(ame,{requestId:W,serverName:t,onViewDetails:()=>{const J=new globalThis.CustomEvent("navigate-to-sampling",{detail:{requestId:W}});window.dispatchEvent(J),ie.dismiss(ce)},onApprove:J=>{h(q=>{const le=q.find(he=>he.id===W);return le?(le.resolve(J),ie.success("Sampling request approved"),q.filter(he=>he.id!==W)):q}),ie.dismiss(ce)},onDeny:()=>{h(J=>{const q=J.find(le=>le.id===W);return q?(q.reject(new Error("User denied sampling request from toast")),ie.error("Sampling request denied"),J.filter(le=>le.id!==W)):J}),ie.dismiss(ce)}}),{duration:5e3})})}),[t]),ne=w.useCallback(async $=>new Promise((L,F)=>{const W=`elicitation-${S.current++}`,X={id:W,request:$,timestamp:Date.now(),serverName:t,resolve:L,reject:F};x(ie=>[...ie,X]),typeof window<"u"&&Jn(async()=>{const{toast:ie}=await Promise.resolve().then(()=>sz);return{toast:ie}},void 0).then(({toast:ie})=>{const ce=ie(f.jsx(ime,{requestId:W,serverName:t,mode:$.mode||"form",message:$.message,url:$.mode==="url"?$.url:void 0,onViewDetails:()=>{const J=new globalThis.CustomEvent("navigate-to-elicitation",{detail:{requestId:W}});window.dispatchEvent(J),ie.dismiss(ce)},onOpenUrl:$.mode==="url"?()=>{window.open($.url,"_blank"),ie.dismiss(ce)}:void 0,onCancel:()=>{x(J=>{const q=J.find(le=>le.id===W);return q?(q.reject(new Error("User cancelled elicitation request from toast")),ie.error("Elicitation request cancelled"),J.filter(le=>le.id!==W)):J}),ie.dismiss(ce)}}),{duration:5e3})})}),[t]),j=wN({url:u,callbackUrl:c,timeout:5e3,customHeaders:Object.keys(d).length>0?d:void 0,transportType:a||"http",preventAutoAuth:!0,useRedirectFlow:!0,enabled:k,wrapTransport:I,onNotification:$=>{te({id:globalThis.crypto.randomUUID(),method:$.method,params:$.params,timestamp:Date.now(),read:!1})},samplingCallback:re,onElicitation:ne}),V=w.useRef(i),z=w.useRef(null);return w.useEffect(()=>{V.current=i},[i]),w.useEffect(()=>{if(typeof queueMicrotask<"u")queueMicrotask(()=>{j.state==="ready"&&j.serverInfo&&console.log("[McpContext] Server info available:",j.serverInfo);const $=M.filter(W=>!W.read).length,L={id:r,url:e,name:j.serverInfo?.name||t,state:j.state,tools:j.tools,resources:j.resources,prompts:j.prompts,error:j.error??null,authUrl:j.authUrl??null,customHeaders:d,transportType:a,proxyConfig:n,serverInfo:j.serverInfo,capabilities:j.capabilities,notifications:M,unreadNotificationCount:$,markNotificationRead:B,markAllNotificationsRead:K,clearNotifications:ee,pendingSamplingRequests:y,approveSampling:ae,rejectSampling:H,pendingElicitationRequests:E,approveElicitation:Z,rejectElicitation:G,callTool:j.callTool,readResource:j.readResource,listPrompts:j.listPrompts,getPrompt:j.getPrompt,authenticate:j.authenticate,retry:j.retry,clearStorage:j.clearStorage,disconnect:j.disconnect,client:j.client},F=z.current;(!F||F.state!==L.state||F.error!==L.error||F.authUrl!==L.authUrl||F.name!==L.name||F.tools.length!==L.tools.length||F.resources.length!==L.resources.length||F.prompts.length!==L.prompts.length||F.serverInfo!==L.serverInfo||F.capabilities!==L.capabilities||F.notifications.length!==L.notifications.length||F.unreadNotificationCount!==L.unreadNotificationCount||F.pendingSamplingRequests.length!==L.pendingSamplingRequests.length||F.pendingElicitationRequests.length!==L.pendingElicitationRequests.length||!F.client)&&(z.current=L,V.current(L))});else{const $=M.filter(W=>!W.read).length,L={id:r,url:e,name:j.serverInfo?.name||t,state:j.state,tools:j.tools,resources:j.resources,prompts:j.prompts,error:j.error??null,authUrl:j.authUrl??null,customHeaders:d,transportType:a,proxyConfig:n,serverInfo:j.serverInfo,capabilities:j.capabilities,notifications:M,unreadNotificationCount:$,markNotificationRead:B,markAllNotificationsRead:K,clearNotifications:ee,pendingSamplingRequests:y,approveSampling:ae,rejectSampling:H,pendingElicitationRequests:E,approveElicitation:Z,rejectElicitation:G,callTool:j.callTool,readResource:j.readResource,listPrompts:j.listPrompts,getPrompt:j.getPrompt,authenticate:j.authenticate,retry:j.retry,clearStorage:j.clearStorage,disconnect:j.disconnect,client:j.client},F=z.current;(!F||F.state!==L.state||F.error!==L.error||F.authUrl!==L.authUrl||F.name!==L.name||F.tools.length!==L.tools.length||F.resources.length!==L.resources.length||F.prompts.length!==L.prompts.length||F.serverInfo!==L.serverInfo||F.capabilities!==L.capabilities||F.notifications.length!==L.notifications.length||F.unreadNotificationCount!==L.unreadNotificationCount||F.pendingSamplingRequests.length!==L.pendingSamplingRequests.length||F.pendingElicitationRequests.length!==L.pendingElicitationRequests.length||!F.client)&&(z.current=L,V.current(L))}},[e,t,a,n,d,r,j.state,j.tools,j.resources,j.prompts,j.error,j.authUrl,j.serverInfo,j.capabilities,j.client,M,B,K,ee,j.callTool,j.readResource,j.listPrompts,j.getPrompt,j.authenticate,j.retry,j.clearStorage,m,ae,H,E,Z,G]),null}function sme({children:e}){const[t,n]=w.useState([]),[a,r]=w.useState(!1),[i,s]=w.useState(!0),[c,u]=w.useState([]);w.useEffect(()=>{try{const y=localStorage.getItem("mcp-inspector-connections");if(y){const _=JSON.parse(y);Array.isArray(_)&&(u(_),n(_.map(k=>({id:k.id||k.url,url:k.url,name:k.name||"MCP Server",state:"discovering",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:k.proxyConfig?.customHeaders,transportType:k.transportType,proxyConfig:k.proxyConfig,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}))))}const E=localStorage.getItem("mcp-inspector-auto-connect");E!==null&&s(E==="true")}catch(y){console.error("Failed to load connections from localStorage:",y)}finally{r(!0)}},[]),w.useEffect(()=>{a&&localStorage.setItem("mcp-inspector-connections",JSON.stringify(c))},[c,a]),w.useEffect(()=>{a&&localStorage.setItem("mcp-inspector-auto-connect",String(i))},[i,a]);const d=w.useCallback((y,E,_,k)=>{const C=c.find(A=>A.url===y),R=t.find(A=>A.url===y);if(C&&R){if(JSON.stringify(C.proxyConfig)!==JSON.stringify(_)&&_){u(O=>O.filter(M=>M.url!==y)),n(O=>O.filter(M=>M.url!==y)),setTimeout(()=>{const O={id:y,url:y,name:E||C.name||"MCP Server",proxyConfig:_,transportType:k||C.transportType};u(M=>[...M,O]),n(M=>[...M,{id:y,url:y,name:E||C.name||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:_?.customHeaders,transportType:k||C.transportType,proxyConfig:_,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}])},10);return}return}if(C&&!R){(_||k)&&u(A=>A.map(O=>O.url===y?{...O,proxyConfig:_||O.proxyConfig,transportType:k||O.transportType,name:E||O.name}:O)),n(A=>[...A,{id:C.id||y,url:y,name:E||C.name||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:_?.customHeaders||C.proxyConfig?.customHeaders,transportType:k||C.transportType,proxyConfig:_||C.proxyConfig,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}]);return}const I={id:y,url:y,name:E||"MCP Server",proxyConfig:_,transportType:k};u(A=>[...A,I]),n(A=>[...A,{id:y,url:y,name:E||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:_?.customHeaders,transportType:k,proxyConfig:_,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}])},[c,t]),m=w.useCallback(y=>{const E=t.find(k=>k.id===y);E&&(console.log(`[McpContext] Cleaning up connection: ${y}`),E.disconnect&&(console.log(`[McpContext] Disconnecting from server: ${y}`),E.disconnect()),E.clearStorage&&(console.log(`[McpContext] Clearing OAuth storage for connection: ${y}`),E.clearStorage())),u(k=>k.filter(C=>C.id!==y)),n(k=>k.filter(C=>C.id!==y));const _=localStorage.getItem("mcp-inspector-connections");if(_)try{const C=JSON.parse(_).filter(R=>(R.id||R.url)!==y);localStorage.setItem("mcp-inspector-connections",JSON.stringify(C))}catch(k){console.error("Failed to update localStorage on remove:",k)}vr.getInstance().capture(new Qpe({serverId:y}))},[t]),h=w.useCallback((y,E)=>{u(_=>_.map(k=>k.id===y||k.url===y?{...k,...E}:k)),n(_=>_.map(k=>k.id===y?{...k,...E}:k))},[]),g=w.useCallback(y=>{n(E=>{const _=E.findIndex(R=>R.id===y.id);if(_===-1)return E;const k=E[_];if(k.state===y.state&&k.tools===y.tools&&k.resources===y.resources&&k.prompts===y.prompts&&k.error===y.error&&k.serverInfo===y.serverInfo&&k.client===y.client&&k.notifications===y.notifications&&k.unreadNotificationCount===y.unreadNotificationCount&&k.pendingSamplingRequests.length===y.pendingSamplingRequests.length&&k.pendingElicitationRequests.length===y.pendingElicitationRequests.length)return E;const C=[...E];return C[_]=y,C})},[]),v=w.useCallback(y=>{console.log("Connect requested for:",y)},[]),x=w.useCallback(y=>{console.log("Disconnect requested for:",y)},[]),S=w.useMemo(()=>({connections:t,addConnection:d,removeConnection:m,updateConnectionConfig:h,autoConnect:i,setAutoConnect:s,connectServer:v,disconnectServer:x,configLoaded:a}),[t,d,m,h,i,v,x,a]);return f.jsxs(DG.Provider,{value:S,children:[e,a&&i&&c.map(y=>{const E=`${y.id||y.url}-${y.proxyConfig?.proxyAddress?"proxy":"direct"}`;return console.warn("[McpContext] Rendering McpConnectionWrapper with key:",E,"proxyConfig:",y.proxyConfig),f.jsx(ome,{url:y.url,name:y.name,proxyConfig:y.proxyConfig,transportType:y.transportType,connectionId:y.id||y.url,onUpdate:g,onRemove:()=>m(y.id||y.url)},E)})]})}const lme=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),cme=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),tz=e=>{const t=cme(e);return t.charAt(0).toUpperCase()+t.slice(1)},jG=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),ume=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var dme={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const fme=w.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:r="",children:i,iconNode:s,...c},u)=>w.createElement("svg",{ref:u,...dme,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:jG("lucide",r),...!i&&!ume(c)&&{"aria-hidden":"true"},...c},[...s.map(([d,m])=>w.createElement(d,m)),...Array.isArray(i)?i:[i]]));const et=(e,t)=>{const n=w.forwardRef(({className:a,...r},i)=>w.createElement(fme,{ref:i,iconNode:t,className:jG(`lucide-${lme(tz(e))}`,`lucide-${e}`,a),...r}));return n.displayName=tz(e),n};const pme=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],mme=et("arrow-down-to-line",pme);const hme=[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]],gme=et("arrow-up-from-line",hme);const bme=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],vme=et("arrow-up",bme);const yme=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],qN=et("bell",yme);const wme=[["path",{d:"m11 10 3 3",key:"fzmg1i"}],["path",{d:"M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z",key:"p4q2r7"}],["path",{d:"M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031",key:"wy6l02"}]],$G=et("brush",wme);const Sme=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],xme=et("bug",Sme);const _me=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ra=et("check",_me);const Eme=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ac=et("chevron-down",Eme);const kme=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],qy=et("chevron-left",kme);const Tme=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],LG=et("chevron-right",Tme);const Nme=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Cme=et("chevron-up",Nme);const Rme=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],Ame=et("chevrons-up-down",Rme);const Ime=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]],nz=et("circle-minus",Ime);const Ome=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],fd=et("clock",Ome);const Dme=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],XN=et("code",Dme);const jme=[["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}]],$me=et("cog",jme);const Lme=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],Mme=et("command",Lme);const Pme=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],$r=et("copy",Pme);const Ume=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Xy=et("database",Ume);const zme=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],Lm=et("download",zme);const Fme=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],Bme=et("ellipsis-vertical",Fme);const Hme=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Y_=et("external-link",Hme);const Vme=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],MG=et("eye-off",Vme);const Gme=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],q_=et("eye",Gme);const Wme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Kme=et("file-code",Wme);const Zme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]],Yme=et("file-image",Zme);const qme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],JN=et("file-text",qme);const Xme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],Jme=et("file",Xme);const Qme=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],ehe=et("folder-open",Qme);const the=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],nhe=et("globe",the);const rhe=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],ahe=et("grip-vertical",rhe);const ihe=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],PG=et("hash",ihe);const ohe=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Rv=et("history",ohe);const she=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],UG=et("key",she);const lhe=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],zs=et("loader-circle",lhe);const che=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],QN=et("maximize-2",che);const uhe=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],eC=et("maximize",uhe);const dhe=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],fhe=et("message-circle",dhe);const phe=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Hp=et("message-square",phe);const mhe=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],hhe=et("minimize",mhe);const ghe=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],rz=et("monitor",ghe);const bhe=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],vhe=et("moon",bhe);const yhe=[["path",{d:"M2 10h6V4",key:"zwrco"}],["path",{d:"m2 4 6 6",key:"ug085t"}],["path",{d:"M21 10V7a2 2 0 0 0-2-2h-7",key:"git5jr"}],["path",{d:"M3 14v2a2 2 0 0 0 2 2h3",key:"1f7fh3"}],["rect",{x:"12",y:"14",width:"10",height:"7",rx:"1",key:"1wjs3o"}]],whe=et("picture-in-picture",yhe);const She=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],zG=et("play",She);const xhe=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],FG=et("plus",xhe);const _he=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],az=et("rotate-ccw",_he);const Ehe=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],tC=et("save",Ehe);const khe=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Pd=et("search",khe);const The=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Nhe=et("send",The);const Che=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],Rhe=et("server",Che);const Ahe=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Eu=et("settings",Ahe);const Ihe=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],Ohe=et("shield",Ihe);const Dhe=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],jhe=et("sparkles",Dhe);const $he=[["path",{d:"M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344",key:"2acyp4"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],BG=et("square-check-big",$he);const Lhe=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],Mhe=et("square-pen",Lhe);const Phe=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M20 12h.01",key:"1ykeid"}],["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M4 12h.01",key:"158zrr"}],["path",{d:"M17.657 6.343h.01",key:"31pqzk"}],["path",{d:"M17.657 17.657h.01",key:"jehnf4"}],["path",{d:"M6.343 17.657h.01",key:"gdk6ow"}],["path",{d:"M6.343 6.343h.01",key:"1uurf0"}]],Uhe=et("sun-dim",Phe);const zhe=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],xx=et("terminal",zhe);const Fhe=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Fs=et("trash-2",Fhe);const Bhe=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Hhe=et("trash",Bhe);const Vhe=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],Wl=et("wrench",Vhe);const Ghe=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ji=et("x",Ghe);const Whe=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],Vp=et("zap",Whe);function Khe(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const Zhe=e=>{switch(e){case"success":return Xhe;case"info":return Qhe;case"warning":return Jhe;case"error":return ege;default:return null}},Yhe=Array(12).fill(0),qhe=({visible:e,className:t})=>ue.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ue.createElement("div",{className:"sonner-spinner"},Yhe.map((n,a)=>ue.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${a}`})))),Xhe=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ue.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),Jhe=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ue.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),Qhe=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ue.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),ege=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ue.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),tge=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ue.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ue.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),nge=()=>{const[e,t]=ue.useState(document.hidden);return ue.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let X_=1;class rge{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:a,...r}=t,i=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:X_++,s=this.toasts.find(u=>u.id===i),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),s?this.toasts=this.toasts.map(u=>u.id===i?(this.publish({...u,...t,id:i,title:a}),{...u,...t,id:i,dismissible:c,title:a}):u):this.addToast({title:a,...r,dismissible:c,id:i}),i},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(a=>a({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let a;n.loading!==void 0&&(a=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const r=Promise.resolve(t instanceof Function?t():t);let i=a!==void 0,s;const c=r.then(async d=>{if(s=["resolve",d],ue.isValidElement(d))i=!1,this.create({id:a,type:"default",message:d});else if(ige(d)&&!d.ok){i=!1;const h=typeof n.error=="function"?await n.error(`HTTP error! status: ${d.status}`):n.error,g=typeof n.description=="function"?await n.description(`HTTP error! status: ${d.status}`):n.description,x=typeof h=="object"&&!ue.isValidElement(h)?h:{message:h};this.create({id:a,type:"error",description:g,...x})}else if(d instanceof Error){i=!1;const h=typeof n.error=="function"?await n.error(d):n.error,g=typeof n.description=="function"?await n.description(d):n.description,x=typeof h=="object"&&!ue.isValidElement(h)?h:{message:h};this.create({id:a,type:"error",description:g,...x})}else if(n.success!==void 0){i=!1;const h=typeof n.success=="function"?await n.success(d):n.success,g=typeof n.description=="function"?await n.description(d):n.description,x=typeof h=="object"&&!ue.isValidElement(h)?h:{message:h};this.create({id:a,type:"success",description:g,...x})}}).catch(async d=>{if(s=["reject",d],n.error!==void 0){i=!1;const m=typeof n.error=="function"?await n.error(d):n.error,h=typeof n.description=="function"?await n.description(d):n.description,v=typeof m=="object"&&!ue.isValidElement(m)?m:{message:m};this.create({id:a,type:"error",description:h,...v})}}).finally(()=>{i&&(this.dismiss(a),a=void 0),n.finally==null||n.finally.call(n)}),u=()=>new Promise((d,m)=>c.then(()=>s[0]==="reject"?m(s[1]):d(s[1])).catch(m));return typeof a!="string"&&typeof a!="number"?{unwrap:u}:Object.assign(a,{unwrap:u})},this.custom=(t,n)=>{const a=n?.id||X_++;return this.create({jsx:t(a),id:a,...n}),a},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const ga=new rge,age=(e,t)=>{const n=t?.id||X_++;return ga.addToast({title:e,...t,id:n}),n},ige=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",oge=age,sge=()=>ga.toasts,lge=()=>ga.getActiveToasts(),Xt=Object.assign(oge,{success:ga.success,info:ga.info,warning:ga.warning,error:ga.error,custom:ga.custom,message:ga.message,promise:ga.promise,dismiss:ga.dismiss,loading:ga.loading},{getHistory:sge,getToasts:lge});Khe("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function pb(e){return e.label!==void 0}const cge=3,uge="24px",dge="16px",iz=4e3,fge=356,pge=14,mge=45,hge=200;function Ui(...e){return e.filter(Boolean).join(" ")}function gge(e){const[t,n]=e.split("-"),a=[];return t&&a.push(t),n&&a.push(n),a}const bge=e=>{var t,n,a,r,i,s,c,u,d;const{invert:m,toast:h,unstyled:g,interacting:v,setHeights:x,visibleToasts:S,heights:y,index:E,toasts:_,expanded:k,removeToast:C,defaultRichColors:R,closeButton:I,style:A,cancelButtonStyle:O,actionButtonStyle:M,className:P="",descriptionClassName:B="",duration:K,position:ee,gap:te,expandByDefault:ae,classNames:H,icons:Z,closeButtonAriaLabel:G="Close toast"}=e,[re,ne]=ue.useState(null),[j,V]=ue.useState(null),[z,$]=ue.useState(!1),[L,F]=ue.useState(!1),[W,X]=ue.useState(!1),[ie,ce]=ue.useState(!1),[J,q]=ue.useState(!1),[le,he]=ue.useState(0),[oe,Ne]=ue.useState(0),Ve=ue.useRef(h.duration||K||iz),_e=ue.useRef(null),ke=ue.useRef(null),Fe=E===0,pe=E+1<=S,Oe=h.type,He=h.dismissible!==!1,xe=h.className||"",at=h.descriptionClassName||"",nt=ue.useMemo(()=>y.findIndex(Ke=>Ke.toastId===h.id)||0,[y,h.id]),ft=ue.useMemo(()=>{var Ke;return(Ke=h.closeButton)!=null?Ke:I},[h.closeButton,I]),Et=ue.useMemo(()=>h.duration||K||iz,[h.duration,K]),pt=ue.useRef(0),mn=ue.useRef(0),Pr=ue.useRef(0),St=ue.useRef(null),[Be,Le]=ee.split("-"),Se=ue.useMemo(()=>y.reduce((Ke,Ze,dt)=>dt>=nt?Ke:Ke+Ze.height,0),[y,nt]),je=nge(),Ue=h.invert||m,We=Oe==="loading";mn.current=ue.useMemo(()=>nt*te+Se,[nt,Se]),ue.useEffect(()=>{Ve.current=Et},[Et]),ue.useEffect(()=>{$(!0)},[]),ue.useEffect(()=>{const Ke=ke.current;if(Ke){const Ze=Ke.getBoundingClientRect().height;return Ne(Ze),x(dt=>[{toastId:h.id,height:Ze,position:h.position},...dt]),()=>x(dt=>dt.filter(At=>At.toastId!==h.id))}},[x,h.id]),ue.useLayoutEffect(()=>{if(!z)return;const Ke=ke.current,Ze=Ke.style.height;Ke.style.height="auto";const dt=Ke.getBoundingClientRect().height;Ke.style.height=Ze,Ne(dt),x(At=>At.find(ln=>ln.toastId===h.id)?At.map(ln=>ln.toastId===h.id?{...ln,height:dt}:ln):[{toastId:h.id,height:dt,position:h.position},...At])},[z,h.title,h.description,x,h.id,h.jsx,h.action,h.cancel]);const Je=ue.useCallback(()=>{F(!0),he(mn.current),x(Ke=>Ke.filter(Ze=>Ze.toastId!==h.id)),setTimeout(()=>{C(h)},hge)},[h,C,x,mn]);ue.useEffect(()=>{if(h.promise&&Oe==="loading"||h.duration===1/0||h.type==="loading")return;let Ke;return k||v||je?(()=>{if(Pr.current<pt.current){const At=new Date().getTime()-pt.current;Ve.current=Ve.current-At}Pr.current=new Date().getTime()})():Ve.current!==1/0&&(pt.current=new Date().getTime(),Ke=setTimeout(()=>{h.onAutoClose==null||h.onAutoClose.call(h,h),Je()},Ve.current)),()=>clearTimeout(Ke)},[k,v,h,Oe,je,Je]),ue.useEffect(()=>{h.delete&&(Je(),h.onDismiss==null||h.onDismiss.call(h,h))},[Je,h.delete]);function yt(){var Ke;if(Z?.loading){var Ze;return ue.createElement("div",{className:Ui(H?.loader,h==null||(Ze=h.classNames)==null?void 0:Ze.loader,"sonner-loader"),"data-visible":Oe==="loading"},Z.loading)}return ue.createElement(qhe,{className:Ui(H?.loader,h==null||(Ke=h.classNames)==null?void 0:Ke.loader),visible:Oe==="loading"})}const mt=h.icon||Z?.[Oe]||Zhe(Oe);var Mt,nn;return ue.createElement("li",{tabIndex:0,ref:ke,className:Ui(P,xe,H?.toast,h==null||(t=h.classNames)==null?void 0:t.toast,H?.default,H?.[Oe],h==null||(n=h.classNames)==null?void 0:n[Oe]),"data-sonner-toast":"","data-rich-colors":(Mt=h.richColors)!=null?Mt:R,"data-styled":!(h.jsx||h.unstyled||g),"data-mounted":z,"data-promise":!!h.promise,"data-swiped":J,"data-removed":L,"data-visible":pe,"data-y-position":Be,"data-x-position":Le,"data-index":E,"data-front":Fe,"data-swiping":W,"data-dismissible":He,"data-type":Oe,"data-invert":Ue,"data-swipe-out":ie,"data-swipe-direction":j,"data-expanded":!!(k||ae&&z),"data-testid":h.testId,style:{"--index":E,"--toasts-before":E,"--z-index":_.length-E,"--offset":`${L?le:mn.current}px`,"--initial-height":ae?"auto":`${oe}px`,...A,...h.style},onDragEnd:()=>{X(!1),ne(null),St.current=null},onPointerDown:Ke=>{Ke.button!==2&&(We||!He||(_e.current=new Date,he(mn.current),Ke.target.setPointerCapture(Ke.pointerId),Ke.target.tagName!=="BUTTON"&&(X(!0),St.current={x:Ke.clientX,y:Ke.clientY})))},onPointerUp:()=>{var Ke,Ze,dt;if(ie||!He)return;St.current=null;const At=Number(((Ke=ke.current)==null?void 0:Ke.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Qn=Number(((Ze=ke.current)==null?void 0:Ze.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),ln=new Date().getTime()-((dt=_e.current)==null?void 0:dt.getTime()),Vn=re==="x"?At:Qn,$n=Math.abs(Vn)/ln;if(Math.abs(Vn)>=mge||$n>.11){he(mn.current),h.onDismiss==null||h.onDismiss.call(h,h),V(re==="x"?At>0?"right":"left":Qn>0?"down":"up"),Je(),ce(!0);return}else{var yn,fn;(yn=ke.current)==null||yn.style.setProperty("--swipe-amount-x","0px"),(fn=ke.current)==null||fn.style.setProperty("--swipe-amount-y","0px")}q(!1),X(!1),ne(null)},onPointerMove:Ke=>{var Ze,dt,At;if(!St.current||!He||((Ze=window.getSelection())==null?void 0:Ze.toString().length)>0)return;const ln=Ke.clientY-St.current.y,Vn=Ke.clientX-St.current.x;var $n;const yn=($n=e.swipeDirections)!=null?$n:gge(ee);!re&&(Math.abs(Vn)>1||Math.abs(ln)>1)&&ne(Math.abs(Vn)>Math.abs(ln)?"x":"y");let fn={x:0,y:0};const oa=Qt=>1/(1.5+Math.abs(Qt)/20);if(re==="y"){if(yn.includes("top")||yn.includes("bottom"))if(yn.includes("top")&&ln<0||yn.includes("bottom")&&ln>0)fn.y=ln;else{const Qt=ln*oa(ln);fn.y=Math.abs(Qt)<Math.abs(ln)?Qt:ln}}else if(re==="x"&&(yn.includes("left")||yn.includes("right")))if(yn.includes("left")&&Vn<0||yn.includes("right")&&Vn>0)fn.x=Vn;else{const Qt=Vn*oa(Vn);fn.x=Math.abs(Qt)<Math.abs(Vn)?Qt:Vn}(Math.abs(fn.x)>0||Math.abs(fn.y)>0)&&q(!0),(dt=ke.current)==null||dt.style.setProperty("--swipe-amount-x",`${fn.x}px`),(At=ke.current)==null||At.style.setProperty("--swipe-amount-y",`${fn.y}px`)}},ft&&!h.jsx&&Oe!=="loading"?ue.createElement("button",{"aria-label":G,"data-disabled":We,"data-close-button":!0,onClick:We||!He?()=>{}:()=>{Je(),h.onDismiss==null||h.onDismiss.call(h,h)},className:Ui(H?.closeButton,h==null||(a=h.classNames)==null?void 0:a.closeButton)},(nn=Z?.close)!=null?nn:tge):null,(Oe||h.icon||h.promise)&&h.icon!==null&&(Z?.[Oe]!==null||h.icon)?ue.createElement("div",{"data-icon":"",className:Ui(H?.icon,h==null||(r=h.classNames)==null?void 0:r.icon)},h.promise||h.type==="loading"&&!h.icon?h.icon||yt():null,h.type!=="loading"?mt:null):null,ue.createElement("div",{"data-content":"",className:Ui(H?.content,h==null||(i=h.classNames)==null?void 0:i.content)},ue.createElement("div",{"data-title":"",className:Ui(H?.title,h==null||(s=h.classNames)==null?void 0:s.title)},h.jsx?h.jsx:typeof h.title=="function"?h.title():h.title),h.description?ue.createElement("div",{"data-description":"",className:Ui(B,at,H?.description,h==null||(c=h.classNames)==null?void 0:c.description)},typeof h.description=="function"?h.description():h.description):null),ue.isValidElement(h.cancel)?h.cancel:h.cancel&&pb(h.cancel)?ue.createElement("button",{"data-button":!0,"data-cancel":!0,style:h.cancelButtonStyle||O,onClick:Ke=>{pb(h.cancel)&&He&&(h.cancel.onClick==null||h.cancel.onClick.call(h.cancel,Ke),Je())},className:Ui(H?.cancelButton,h==null||(u=h.classNames)==null?void 0:u.cancelButton)},h.cancel.label):null,ue.isValidElement(h.action)?h.action:h.action&&pb(h.action)?ue.createElement("button",{"data-button":!0,"data-action":!0,style:h.actionButtonStyle||M,onClick:Ke=>{pb(h.action)&&(h.action.onClick==null||h.action.onClick.call(h.action,Ke),!Ke.defaultPrevented&&Je())},className:Ui(H?.actionButton,h==null||(d=h.classNames)==null?void 0:d.actionButton)},h.action.label):null)};function oz(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function vge(e,t){const n={};return[e,t].forEach((a,r)=>{const i=r===1,s=i?"--mobile-offset":"--offset",c=i?dge:uge;function u(d){["top","right","bottom","left"].forEach(m=>{n[`${s}-${m}`]=typeof d=="number"?`${d}px`:d})}typeof a=="number"||typeof a=="string"?u(a):typeof a=="object"?["top","right","bottom","left"].forEach(d=>{a[d]===void 0?n[`${s}-${d}`]=c:n[`${s}-${d}`]=typeof a[d]=="number"?`${a[d]}px`:a[d]}):u(c)}),n}const HG=ue.forwardRef(function(t,n){const{id:a,invert:r,position:i="bottom-right",hotkey:s=["altKey","KeyT"],expand:c,closeButton:u,className:d,offset:m,mobileOffset:h,theme:g="light",richColors:v,duration:x,style:S,visibleToasts:y=cge,toastOptions:E,dir:_=oz(),gap:k=pge,icons:C,containerAriaLabel:R="Notifications"}=t,[I,A]=ue.useState([]),O=ue.useMemo(()=>a?I.filter(z=>z.toasterId===a):I.filter(z=>!z.toasterId),[I,a]),M=ue.useMemo(()=>Array.from(new Set([i].concat(O.filter(z=>z.position).map(z=>z.position)))),[O,i]),[P,B]=ue.useState([]),[K,ee]=ue.useState(!1),[te,ae]=ue.useState(!1),[H,Z]=ue.useState(g!=="system"?g:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),G=ue.useRef(null),re=s.join("+").replace(/Key/g,"").replace(/Digit/g,""),ne=ue.useRef(null),j=ue.useRef(!1),V=ue.useCallback(z=>{A($=>{var L;return(L=$.find(F=>F.id===z.id))!=null&&L.delete||ga.dismiss(z.id),$.filter(({id:F})=>F!==z.id)})},[]);return ue.useEffect(()=>ga.subscribe(z=>{if(z.dismiss){requestAnimationFrame(()=>{A($=>$.map(L=>L.id===z.id?{...L,delete:!0}:L))});return}setTimeout(()=>{z9.flushSync(()=>{A($=>{const L=$.findIndex(F=>F.id===z.id);return L!==-1?[...$.slice(0,L),{...$[L],...z},...$.slice(L+1)]:[z,...$]})})})}),[I]),ue.useEffect(()=>{if(g!=="system"){Z(g);return}if(g==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Z("dark"):Z("light")),typeof window>"u")return;const z=window.matchMedia("(prefers-color-scheme: dark)");try{z.addEventListener("change",({matches:$})=>{Z($?"dark":"light")})}catch{z.addListener(({matches:L})=>{try{Z(L?"dark":"light")}catch(F){console.error(F)}})}},[g]),ue.useEffect(()=>{I.length<=1&&ee(!1)},[I]),ue.useEffect(()=>{const z=$=>{var L;if(s.every(X=>$[X]||$.code===X)){var W;ee(!0),(W=G.current)==null||W.focus()}$.code==="Escape"&&(document.activeElement===G.current||(L=G.current)!=null&&L.contains(document.activeElement))&&ee(!1)};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[s]),ue.useEffect(()=>{if(G.current)return()=>{ne.current&&(ne.current.focus({preventScroll:!0}),ne.current=null,j.current=!1)}},[G.current]),ue.createElement("section",{ref:n,"aria-label":`${R} ${re}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},M.map((z,$)=>{var L;const[F,W]=z.split("-");return O.length?ue.createElement("ol",{key:z,dir:_==="auto"?oz():_,tabIndex:-1,ref:G,className:d,"data-sonner-toaster":!0,"data-sonner-theme":H,"data-y-position":F,"data-x-position":W,style:{"--front-toast-height":`${((L=P[0])==null?void 0:L.height)||0}px`,"--width":`${fge}px`,"--gap":`${k}px`,...S,...vge(m,h)},onBlur:X=>{j.current&&!X.currentTarget.contains(X.relatedTarget)&&(j.current=!1,ne.current&&(ne.current.focus({preventScroll:!0}),ne.current=null))},onFocus:X=>{X.target instanceof HTMLElement&&X.target.dataset.dismissible==="false"||j.current||(j.current=!0,ne.current=X.relatedTarget)},onMouseEnter:()=>ee(!0),onMouseMove:()=>ee(!0),onMouseLeave:()=>{te||ee(!1)},onDragEnd:()=>ee(!1),onPointerDown:X=>{X.target instanceof HTMLElement&&X.target.dataset.dismissible==="false"||ae(!0)},onPointerUp:()=>ae(!1)},O.filter(X=>!X.position&&$===0||X.position===z).map((X,ie)=>{var ce,J;return ue.createElement(bge,{key:X.id,icons:C,index:ie,toast:X,defaultRichColors:v,duration:(ce=E?.duration)!=null?ce:x,className:E?.className,descriptionClassName:E?.descriptionClassName,invert:r,visibleToasts:y,closeButton:(J=E?.closeButton)!=null?J:u,interacting:te,position:z,style:E?.style,unstyled:E?.unstyled,classNames:E?.classNames,cancelButtonStyle:E?.cancelButtonStyle,actionButtonStyle:E?.actionButtonStyle,closeButtonAriaLabel:E?.closeButtonAriaLabel,removeToast:V,toasts:O.filter(q=>q.position==X.position),heights:P.filter(q=>q.position==X.position),setHeights:B,expandByDefault:c,gap:k,expanded:K,swipeDirections:t.swipeDirections})})):null}))}),sz=Object.freeze(Object.defineProperty({__proto__:null,Toaster:HG,toast:Xt},Symbol.toStringTag,{value:"Module"}));var Jy="Dialog",[VG]=Ii(Jy),[yge,Oi]=VG(Jy),GG=e=>{const{__scopeDialog:t,children:n,open:a,defaultOpen:r,onOpenChange:i,modal:s=!0}=e,c=w.useRef(null),u=w.useRef(null),[d,m]=Mo({prop:a,defaultProp:r??!1,onChange:i,caller:Jy});return f.jsx(yge,{scope:t,triggerRef:c,contentRef:u,contentId:jr(),titleId:jr(),descriptionId:jr(),open:d,onOpenChange:m,onOpenToggle:w.useCallback(()=>m(h=>!h),[m]),modal:s,children:n})};GG.displayName=Jy;var WG="DialogTrigger",KG=w.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(WG,n),i=Jt(t,r.triggerRef);return f.jsx(_t.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":aC(r.open),...a,ref:i,onClick:Ge(e.onClick,r.onOpenToggle)})});KG.displayName=WG;var nC="DialogPortal",[wge,ZG]=VG(nC,{forceMount:void 0}),YG=e=>{const{__scopeDialog:t,forceMount:n,children:a,container:r}=e,i=Oi(nC,t);return f.jsx(wge,{scope:t,forceMount:n,children:w.Children.map(a,s=>f.jsx(Ua,{present:n||i.open,children:f.jsx(Ld,{asChild:!0,container:r,children:s})}))})};YG.displayName=nC;var Av="DialogOverlay",qG=w.forwardRef((e,t)=>{const n=ZG(Av,e.__scopeDialog),{forceMount:a=n.forceMount,...r}=e,i=Oi(Av,e.__scopeDialog);return i.modal?f.jsx(Ua,{present:a||i.open,children:f.jsx(xge,{...r,ref:t})}):null});qG.displayName=Av;var Sge=Vl("DialogOverlay.RemoveScroll"),xge=w.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(Av,n);return f.jsx(Om,{as:Sge,allowPinchZoom:!0,shards:[r.contentRef],children:f.jsx(_t.div,{"data-state":aC(r.open),...a,ref:t,style:{pointerEvents:"auto",...a.style}})})}),Kl="DialogContent",XG=w.forwardRef((e,t)=>{const n=ZG(Kl,e.__scopeDialog),{forceMount:a=n.forceMount,...r}=e,i=Oi(Kl,e.__scopeDialog);return f.jsx(Ua,{present:a||i.open,children:i.modal?f.jsx(_ge,{...r,ref:t}):f.jsx(Ege,{...r,ref:t})})});XG.displayName=Kl;var _ge=w.forwardRef((e,t)=>{const n=Oi(Kl,e.__scopeDialog),a=w.useRef(null),r=Jt(t,n.contentRef,a);return w.useEffect(()=>{const i=a.current;if(i)return Fy(i)},[]),f.jsx(JG,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ge(e.onCloseAutoFocus,i=>{i.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ge(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,c=s.button===0&&s.ctrlKey===!0;(s.button===2||c)&&i.preventDefault()}),onFocusOutside:Ge(e.onFocusOutside,i=>i.preventDefault())})}),Ege=w.forwardRef((e,t)=>{const n=Oi(Kl,e.__scopeDialog),a=w.useRef(!1),r=w.useRef(!1);return f.jsx(JG,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{e.onCloseAutoFocus?.(i),i.defaultPrevented||(a.current||n.triggerRef.current?.focus(),i.preventDefault()),a.current=!1,r.current=!1},onInteractOutside:i=>{e.onInteractOutside?.(i),i.defaultPrevented||(a.current=!0,i.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const s=i.target;n.triggerRef.current?.contains(s)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&r.current&&i.preventDefault()}})}),JG=w.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:a,onOpenAutoFocus:r,onCloseAutoFocus:i,...s}=e,c=Oi(Kl,n),u=w.useRef(null),d=Jt(t,u);return Dy(),f.jsxs(f.Fragment,{children:[f.jsx(Cm,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:r,onUnmountAutoFocus:i,children:f.jsx(Dd,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":aC(c.open),...s,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),f.jsxs(f.Fragment,{children:[f.jsx(kge,{titleId:c.titleId}),f.jsx(Nge,{contentRef:u,descriptionId:c.descriptionId})]})]})}),rC="DialogTitle",QG=w.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(rC,n);return f.jsx(_t.h2,{id:r.titleId,...a,ref:t})});QG.displayName=rC;var e7="DialogDescription",t7=w.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(e7,n);return f.jsx(_t.p,{id:r.descriptionId,...a,ref:t})});t7.displayName=e7;var n7="DialogClose",r7=w.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(n7,n);return f.jsx(_t.button,{type:"button",...a,ref:t,onClick:Ge(e.onClick,()=>r.onOpenChange(!1))})});r7.displayName=n7;function aC(e){return e?"open":"closed"}var a7="DialogTitleWarning",[eNe,i7]=fce(a7,{contentName:Kl,titleName:rC,docsSlug:"dialog"}),kge=({titleId:e})=>{const t=i7(a7),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
93
+ `)},nfe=0,Yc=[];function rfe(e){var t=w.useRef([]),n=w.useRef([0,0]),a=w.useRef(),r=w.useState(nfe++)[0],i=w.useState(_8)[0],s=w.useRef(e);w.useEffect(function(){s.current=e},[e]),w.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(r));var S=Ede([e.lockRef.current],(e.shards||[]).map(ZU),!0).filter(Boolean);return S.forEach(function(y){return y.classList.add("allow-interactivity-".concat(r))}),function(){document.body.classList.remove("block-interactivity-".concat(r)),S.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(r))})}}},[e.inert,e.lockRef.current,e.shards]);var c=w.useCallback(function(S,y){if("touches"in S&&S.touches.length===2||S.type==="wheel"&&S.ctrlKey)return!s.current.allowPinchZoom;var E=lb(S),_=n.current,k="deltaX"in S?S.deltaX:_[0]-E[0],C="deltaY"in S?S.deltaY:_[1]-E[1],R,I=S.target,A=Math.abs(k)>Math.abs(C)?"h":"v";if("touches"in S&&A==="h"&&I.type==="range")return!1;var O=window.getSelection(),M=O&&O.anchorNode,P=M?M===I||M.contains(I):!1;if(P)return!1;var B=WU(A,I);if(!B)return!0;if(B?R=A:(R=A==="v"?"h":"v",B=WU(A,I)),!B)return!1;if(!a.current&&"changedTouches"in S&&(k||C)&&(a.current=R),!R)return!0;var K=a.current||R;return Qde(K,y,S,K==="h"?k:C)},[]),u=w.useCallback(function(S){var y=S;if(!(!Yc.length||Yc[Yc.length-1]!==i)){var E="deltaY"in y?KU(y):lb(y),_=t.current.filter(function(R){return R.name===y.type&&(R.target===y.target||y.target===R.shadowParent)&&efe(R.delta,E)})[0];if(_&&_.should){y.cancelable&&y.preventDefault();return}if(!_){var k=(s.current.shards||[]).map(ZU).filter(Boolean).filter(function(R){return R.contains(y.target)}),C=k.length>0?c(y,k[0]):!s.current.noIsolation;C&&y.cancelable&&y.preventDefault()}}},[]),d=w.useCallback(function(S,y,E,_){var k={name:S,delta:y,target:E,should:_,shadowParent:afe(E)};t.current.push(k),setTimeout(function(){t.current=t.current.filter(function(C){return C!==k})},1)},[]),m=w.useCallback(function(S){n.current=lb(S),a.current=void 0},[]),h=w.useCallback(function(S){d(S.type,KU(S),S.target,c(S,e.lockRef.current))},[]),g=w.useCallback(function(S){d(S.type,lb(S),S.target,c(S,e.lockRef.current))},[]);w.useEffect(function(){return Yc.push(i),e.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:g}),document.addEventListener("wheel",u,Zc),document.addEventListener("touchmove",u,Zc),document.addEventListener("touchstart",m,Zc),function(){Yc=Yc.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,Zc),document.removeEventListener("touchmove",u,Zc),document.removeEventListener("touchstart",m,Zc)}},[]);var v=e.removeScrollBar,x=e.inert;return w.createElement(w.Fragment,null,x?w.createElement(i,{styles:tfe(r)}):null,v?w.createElement(Wde,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function afe(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const ife=Dde(x8,rfe);var Om=w.forwardRef(function(e,t){return w.createElement(By,Fi({},e,{ref:t,sideCar:ife}))});Om.classNames=By.classNames;var H_=["Enter"," "],ofe=["ArrowDown","PageUp","Home"],N8=["ArrowUp","PageDown","End"],sfe=[...ofe,...N8],lfe={ltr:[...H_,"ArrowRight"],rtl:[...H_,"ArrowLeft"]},cfe={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Dm="Menu",[zp,ufe,dfe]=NN(Dm),[nc,C8]=Ii(Dm,[dfe,Zs,m8]),Hy=Zs(),R8=m8(),[ffe,rc]=nc(Dm),[pfe,jm]=nc(Dm),A8=e=>{const{__scopeMenu:t,open:n=!1,children:a,dir:r,onOpenChange:i,modal:s=!0}=e,c=Hy(t),[u,d]=w.useState(null),m=w.useRef(!1),h=Zi(i),g=CN(r);return w.useEffect(()=>{const v=()=>{m.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>m.current=!1;return document.addEventListener("keydown",v,{capture:!0}),()=>{document.removeEventListener("keydown",v,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.jsx(Py,{...c,children:f.jsx(ffe,{scope:t,open:n,onOpenChange:h,content:u,onContentChange:d,children:f.jsx(pfe,{scope:t,onClose:w.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:m,dir:g,modal:s,children:a})})})};A8.displayName=Dm;var mfe="MenuAnchor",PN=w.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e,r=Hy(n);return f.jsx(Am,{...r,...a,ref:t})});PN.displayName=mfe;var UN="MenuPortal",[hfe,I8]=nc(UN,{forceMount:void 0}),O8=e=>{const{__scopeMenu:t,forceMount:n,children:a,container:r}=e,i=rc(UN,t);return f.jsx(hfe,{scope:t,forceMount:n,children:f.jsx(Ua,{present:n||i.open,children:f.jsx(Ld,{asChild:!0,container:r,children:a})})})};O8.displayName=UN;var Qa="MenuContent",[gfe,zN]=nc(Qa),D8=w.forwardRef((e,t)=>{const n=I8(Qa,e.__scopeMenu),{forceMount:a=n.forceMount,...r}=e,i=rc(Qa,e.__scopeMenu),s=jm(Qa,e.__scopeMenu);return f.jsx(zp.Provider,{scope:e.__scopeMenu,children:f.jsx(Ua,{present:a||i.open,children:f.jsx(zp.Slot,{scope:e.__scopeMenu,children:s.modal?f.jsx(bfe,{...r,ref:t}):f.jsx(vfe,{...r,ref:t})})})})}),bfe=w.forwardRef((e,t)=>{const n=rc(Qa,e.__scopeMenu),a=w.useRef(null),r=Jt(t,a);return w.useEffect(()=>{const i=a.current;if(i)return Fy(i)},[]),f.jsx(FN,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ge(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),vfe=w.forwardRef((e,t)=>{const n=rc(Qa,e.__scopeMenu);return f.jsx(FN,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),yfe=Vl("MenuContent.ScrollLock"),FN=w.forwardRef((e,t)=>{const{__scopeMenu:n,loop:a=!1,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:c,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:v,disableOutsideScroll:x,...S}=e,y=rc(Qa,n),E=jm(Qa,n),_=Hy(n),k=R8(n),C=ufe(n),[R,I]=w.useState(null),A=w.useRef(null),O=Jt(t,A,y.onContentChange),M=w.useRef(0),P=w.useRef(""),B=w.useRef(0),K=w.useRef(null),ee=w.useRef("right"),te=w.useRef(0),ae=x?Om:w.Fragment,H=x?{as:yfe,allowPinchZoom:!0}:void 0,Z=re=>{const ne=P.current+re,j=C().filter(W=>!W.disabled),V=document.activeElement,z=j.find(W=>W.ref.current===V)?.textValue,$=j.map(W=>W.textValue),L=Ife($,ne,z),F=j.find(W=>W.textValue===L)?.ref.current;(function W(X){P.current=X,window.clearTimeout(M.current),X!==""&&(M.current=window.setTimeout(()=>W(""),1e3))})(ne),F&&setTimeout(()=>F.focus())};w.useEffect(()=>()=>window.clearTimeout(M.current),[]),Dy();const G=w.useCallback(re=>ee.current===K.current?.side&&Dfe(re,K.current?.area),[]);return f.jsx(gfe,{scope:n,searchRef:P,onItemEnter:w.useCallback(re=>{G(re)&&re.preventDefault()},[G]),onItemLeave:w.useCallback(re=>{G(re)||(A.current?.focus(),I(null))},[G]),onTriggerLeave:w.useCallback(re=>{G(re)&&re.preventDefault()},[G]),pointerGraceTimerRef:B,onPointerGraceIntentChange:w.useCallback(re=>{K.current=re},[]),children:f.jsx(ae,{...H,children:f.jsx(Cm,{asChild:!0,trapped:r,onMountAutoFocus:Ge(i,re=>{re.preventDefault(),A.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:f.jsx(Dd,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:d,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:v,children:f.jsx(yde,{asChild:!0,...k,dir:E.dir,orientation:"vertical",loop:a,currentTabStopId:R,onCurrentTabStopIdChange:I,onEntryFocus:Ge(u,re=>{E.isUsingKeyboardRef.current||re.preventDefault()}),preventScrollOnEntryFocus:!0,children:f.jsx(Uy,{role:"menu","aria-orientation":"vertical","data-state":Y8(y.open),"data-radix-menu-content":"",dir:E.dir,..._,...S,ref:O,style:{outline:"none",...S.style},onKeyDown:Ge(S.onKeyDown,re=>{const j=re.target.closest("[data-radix-menu-content]")===re.currentTarget,V=re.ctrlKey||re.altKey||re.metaKey,z=re.key.length===1;j&&(re.key==="Tab"&&re.preventDefault(),!V&&z&&Z(re.key));const $=A.current;if(re.target!==$||!sfe.includes(re.key))return;re.preventDefault();const F=C().filter(W=>!W.disabled).map(W=>W.ref.current);N8.includes(re.key)&&F.reverse(),Rfe(F)}),onBlur:Ge(e.onBlur,re=>{re.currentTarget.contains(re.target)||(window.clearTimeout(M.current),P.current="")}),onPointerMove:Ge(e.onPointerMove,Fp(re=>{const ne=re.target,j=te.current!==re.clientX;if(re.currentTarget.contains(ne)&&j){const V=re.clientX>te.current?"right":"left";ee.current=V,te.current=re.clientX}}))})})})})})})});D8.displayName=Qa;var wfe="MenuGroup",BN=w.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e;return f.jsx(_t.div,{role:"group",...a,ref:t})});BN.displayName=wfe;var Sfe="MenuLabel",j8=w.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e;return f.jsx(_t.div,{...a,ref:t})});j8.displayName=Sfe;var Tv="MenuItem",YU="menu.itemSelect",Vy=w.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:a,...r}=e,i=w.useRef(null),s=jm(Tv,e.__scopeMenu),c=zN(Tv,e.__scopeMenu),u=Jt(t,i),d=w.useRef(!1),m=()=>{const h=i.current;if(!n&&h){const g=new CustomEvent(YU,{bubbles:!0,cancelable:!0});h.addEventListener(YU,v=>a?.(v),{once:!0}),B9(h,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.jsx($8,{...r,ref:u,disabled:n,onClick:Ge(e.onClick,m),onPointerDown:h=>{e.onPointerDown?.(h),d.current=!0},onPointerUp:Ge(e.onPointerUp,h=>{d.current||h.currentTarget?.click()}),onKeyDown:Ge(e.onKeyDown,h=>{const g=c.searchRef.current!=="";n||g&&h.key===" "||H_.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});Vy.displayName=Tv;var $8=w.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:a=!1,textValue:r,...i}=e,s=zN(Tv,n),c=R8(n),u=w.useRef(null),d=Jt(t,u),[m,h]=w.useState(!1),[g,v]=w.useState("");return w.useEffect(()=>{const x=u.current;x&&v((x.textContent??"").trim())},[i.children]),f.jsx(zp.ItemSlot,{scope:n,disabled:a,textValue:r??g,children:f.jsx(wde,{asChild:!0,...c,focusable:!a,children:f.jsx(_t.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":a||void 0,"data-disabled":a?"":void 0,...i,ref:d,onPointerMove:Ge(e.onPointerMove,Fp(x=>{a?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ge(e.onPointerLeave,Fp(x=>s.onItemLeave(x))),onFocus:Ge(e.onFocus,()=>h(!0)),onBlur:Ge(e.onBlur,()=>h(!1))})})})}),xfe="MenuCheckboxItem",L8=w.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:a,...r}=e;return f.jsx(F8,{scope:e.__scopeMenu,checked:n,children:f.jsx(Vy,{role:"menuitemcheckbox","aria-checked":Nv(n)?"mixed":n,...r,ref:t,"data-state":VN(n),onSelect:Ge(r.onSelect,()=>a?.(Nv(n)?!0:!n),{checkForDefaultPrevented:!1})})})});L8.displayName=xfe;var M8="MenuRadioGroup",[_fe,Efe]=nc(M8,{value:void 0,onValueChange:()=>{}}),P8=w.forwardRef((e,t)=>{const{value:n,onValueChange:a,...r}=e,i=Zi(a);return f.jsx(_fe,{scope:e.__scopeMenu,value:n,onValueChange:i,children:f.jsx(BN,{...r,ref:t})})});P8.displayName=M8;var U8="MenuRadioItem",z8=w.forwardRef((e,t)=>{const{value:n,...a}=e,r=Efe(U8,e.__scopeMenu),i=n===r.value;return f.jsx(F8,{scope:e.__scopeMenu,checked:i,children:f.jsx(Vy,{role:"menuitemradio","aria-checked":i,...a,ref:t,"data-state":VN(i),onSelect:Ge(a.onSelect,()=>r.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});z8.displayName=U8;var HN="MenuItemIndicator",[F8,kfe]=nc(HN,{checked:!1}),B8=w.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:a,...r}=e,i=kfe(HN,n);return f.jsx(Ua,{present:a||Nv(i.checked)||i.checked===!0,children:f.jsx(_t.span,{...r,ref:t,"data-state":VN(i.checked)})})});B8.displayName=HN;var Tfe="MenuSeparator",H8=w.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e;return f.jsx(_t.div,{role:"separator","aria-orientation":"horizontal",...a,ref:t})});H8.displayName=Tfe;var Nfe="MenuArrow",V8=w.forwardRef((e,t)=>{const{__scopeMenu:n,...a}=e,r=Hy(n);return f.jsx(zy,{...r,...a,ref:t})});V8.displayName=Nfe;var Cfe="MenuSub",[QTe,G8]=nc(Cfe),np="MenuSubTrigger",W8=w.forwardRef((e,t)=>{const n=rc(np,e.__scopeMenu),a=jm(np,e.__scopeMenu),r=G8(np,e.__scopeMenu),i=zN(np,e.__scopeMenu),s=w.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},m=w.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return w.useEffect(()=>m,[m]),w.useEffect(()=>{const h=c.current;return()=>{window.clearTimeout(h),u(null)}},[c,u]),f.jsx(PN,{asChild:!0,...d,children:f.jsx($8,{id:r.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":r.contentId,"data-state":Y8(n.open),...e,ref:Ki(t,r.onTriggerChange),onClick:h=>{e.onClick?.(h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ge(e.onPointerMove,Fp(h=>{i.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:Ge(e.onPointerLeave,Fp(h=>{m();const g=n.content?.getBoundingClientRect();if(g){const v=n.content?.dataset.side,x=v==="right",S=x?-5:5,y=g[x?"left":"right"],E=g[x?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+S,y:h.clientY},{x:y,y:g.top},{x:E,y:g.top},{x:E,y:g.bottom},{x:y,y:g.bottom}],side:v}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(h),h.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:Ge(e.onKeyDown,h=>{const g=i.searchRef.current!=="";e.disabled||g&&h.key===" "||lfe[a.dir].includes(h.key)&&(n.onOpenChange(!0),n.content?.focus(),h.preventDefault())})})})});W8.displayName=np;var K8="MenuSubContent",Z8=w.forwardRef((e,t)=>{const n=I8(Qa,e.__scopeMenu),{forceMount:a=n.forceMount,...r}=e,i=rc(Qa,e.__scopeMenu),s=jm(Qa,e.__scopeMenu),c=G8(K8,e.__scopeMenu),u=w.useRef(null),d=Jt(t,u);return f.jsx(zp.Provider,{scope:e.__scopeMenu,children:f.jsx(Ua,{present:a||i.open,children:f.jsx(zp.Slot,{scope:e.__scopeMenu,children:f.jsx(FN,{id:c.contentId,"aria-labelledby":c.triggerId,...r,ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{s.isUsingKeyboardRef.current&&u.current?.focus(),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:Ge(e.onFocusOutside,m=>{m.target!==c.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:Ge(e.onEscapeKeyDown,m=>{s.onClose(),m.preventDefault()}),onKeyDown:Ge(e.onKeyDown,m=>{const h=m.currentTarget.contains(m.target),g=cfe[s.dir].includes(m.key);h&&g&&(i.onOpenChange(!1),c.trigger?.focus(),m.preventDefault())})})})})})});Z8.displayName=K8;function Y8(e){return e?"open":"closed"}function Nv(e){return e==="indeterminate"}function VN(e){return Nv(e)?"indeterminate":e?"checked":"unchecked"}function Rfe(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Afe(e,t){return e.map((n,a)=>e[(t+a)%e.length])}function Ife(e,t,n){const r=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=Afe(e,Math.max(i,0));r.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(r.toLowerCase()));return u!==n?u:void 0}function Ofe(e,t){const{x:n,y:a}=e;let r=!1;for(let i=0,s=t.length-1;i<t.length;s=i++){const c=t[i],u=t[s],d=c.x,m=c.y,h=u.x,g=u.y;m>a!=g>a&&n<(h-d)*(a-m)/(g-m)+d&&(r=!r)}return r}function Dfe(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Ofe(n,t)}function Fp(e){return t=>t.pointerType==="mouse"?e(t):void 0}var jfe=A8,$fe=PN,Lfe=O8,Mfe=D8,Pfe=BN,Ufe=j8,zfe=Vy,Ffe=L8,Bfe=P8,Hfe=z8,Vfe=B8,Gfe=H8,Wfe=V8,Kfe=W8,Zfe=Z8,Gy="DropdownMenu",[Yfe]=Ii(Gy,[C8]),ia=C8(),[qfe,q8]=Yfe(Gy),X8=e=>{const{__scopeDropdownMenu:t,children:n,dir:a,open:r,defaultOpen:i,onOpenChange:s,modal:c=!0}=e,u=ia(t),d=w.useRef(null),[m,h]=Mo({prop:r,defaultProp:i??!1,onChange:s,caller:Gy});return f.jsx(qfe,{scope:t,triggerId:jr(),triggerRef:d,contentId:jr(),open:m,onOpenChange:h,onOpenToggle:w.useCallback(()=>h(g=>!g),[h]),modal:c,children:f.jsx(jfe,{...u,open:m,onOpenChange:h,dir:a,modal:c,children:n})})};X8.displayName=Gy;var J8="DropdownMenuTrigger",Q8=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:a=!1,...r}=e,i=q8(J8,n),s=ia(n);return f.jsx($fe,{asChild:!0,...s,children:f.jsx(_t.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":a?"":void 0,disabled:a,...r,ref:Ki(t,i.triggerRef),onPointerDown:Ge(e.onPointerDown,c=>{!a&&c.button===0&&c.ctrlKey===!1&&(i.onOpenToggle(),i.open||c.preventDefault())}),onKeyDown:Ge(e.onKeyDown,c=>{a||(["Enter"," "].includes(c.key)&&i.onOpenToggle(),c.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});Q8.displayName=J8;var Xfe="DropdownMenuPortal",eG=e=>{const{__scopeDropdownMenu:t,...n}=e,a=ia(t);return f.jsx(Lfe,{...a,...n})};eG.displayName=Xfe;var tG="DropdownMenuContent",nG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=q8(tG,n),i=ia(n),s=w.useRef(!1);return f.jsx(Mfe,{id:r.contentId,"aria-labelledby":r.triggerId,...i,...a,ref:t,onCloseAutoFocus:Ge(e.onCloseAutoFocus,c=>{s.current||r.triggerRef.current?.focus(),s.current=!1,c.preventDefault()}),onInteractOutside:Ge(e.onInteractOutside,c=>{const u=c.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,m=u.button===2||d;(!r.modal||m)&&(s.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});nG.displayName=tG;var Jfe="DropdownMenuGroup",Qfe=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Pfe,{...r,...a,ref:t})});Qfe.displayName=Jfe;var epe="DropdownMenuLabel",rG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Ufe,{...r,...a,ref:t})});rG.displayName=epe;var tpe="DropdownMenuItem",aG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(zfe,{...r,...a,ref:t})});aG.displayName=tpe;var npe="DropdownMenuCheckboxItem",iG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Ffe,{...r,...a,ref:t})});iG.displayName=npe;var rpe="DropdownMenuRadioGroup",ape=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Bfe,{...r,...a,ref:t})});ape.displayName=rpe;var ipe="DropdownMenuRadioItem",oG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Hfe,{...r,...a,ref:t})});oG.displayName=ipe;var ope="DropdownMenuItemIndicator",spe=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Vfe,{...r,...a,ref:t})});spe.displayName=ope;var lpe="DropdownMenuSeparator",sG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Gfe,{...r,...a,ref:t})});sG.displayName=lpe;var cpe="DropdownMenuArrow",upe=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Wfe,{...r,...a,ref:t})});upe.displayName=cpe;var dpe="DropdownMenuSubTrigger",lG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Kfe,{...r,...a,ref:t})});lG.displayName=dpe;var fpe="DropdownMenuSubContent",cG=w.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...a}=e,r=ia(n);return f.jsx(Zfe,{...r,...a,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});cG.displayName=fpe;var ppe=X8,mpe=Q8,hpe=eG,uG=nG,dG=rG,fG=aG,gpe=iG,bpe=oG,pG=sG,vpe=lG,ype=cG;const V_=ppe,G_=mpe;vpe.displayName;ype.displayName;function Cv({ref:e,className:t,sideOffset:n=4,...a}){return f.jsx(hpe,{children:f.jsx(uG,{ref:e,sideOffset:n,className:De("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t),...a})})}Cv.displayName=uG.displayName;function Ro({ref:e,className:t,inset:n,...a}){return f.jsx(fG,{ref:e,className:De("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n&&"pl-8",t),...a})}Ro.displayName=fG.displayName;gpe.displayName;bpe.displayName;function W_({ref:e,className:t,inset:n,...a}){return f.jsx(dG,{ref:e,className:De("px-2 py-1.5 text-sm font-semibold",n&&"pl-8",t),...a})}W_.displayName=dG.displayName;function rp({ref:e,className:t,...n}){return f.jsx(pG,{ref:e,className:De("-mx-1 my-1 h-px bg-muted",t),...n})}rp.displayName=pG.displayName;var wpe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Go=wpe.reduce((e,t)=>{const n=_9(`Primitive.${t}`),a=w.forwardRef((r,i)=>{const{asChild:s,...c}=r,u=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),f.jsx(u,{...c,ref:i})});return a.displayName=`Primitive.${t}`,{...e,[t]:a}},{}),Spe="Label",mG=w.forwardRef((e,t)=>f.jsx(Go.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));mG.displayName=Spe;var xpe=mG;function Kt({className:e,...t}){return f.jsx(xpe,{"data-slot":"label",className:De("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function Md({message:e,className:t="",vertical:n,noBorder:a}){return f.jsx("div",{className:De(`mt-2 rounded-md p-6 ${t}`,!a&&"border"),children:f.jsxs("p",{className:De("text-sm text-muted-foreground flex items-center gap-4",n&&"flex-col"),children:[f.jsx("svg",{width:"40",height:"40",viewBox:"0 0 273 273",version:"1.1",xmlns:"http://www.w3.org/2000/svg",className:"flex-shrink-0",children:f.jsx("g",{stroke:"none",strokeWidth:"1",fill:"none",fillRule:"evenodd",children:f.jsxs("g",{transform:"translate(5.320900, 5.320900)",fillRule:"nonzero",className:"stroke-black dark:stroke-white",strokeWidth:"4",children:[f.jsx("path",{d:"M49.953025,-2.10854389 C63.26892,-2.21867124 76.6185256,2.70621155 86.9019463,12.6653164 L86.9019463,12.6653164 L87.505627,13.2592944 C97.5154947,23.2654892 102.640454,36.3074513 102.880738,49.4222247 C103.08932,77.4533067 113.877287,105.391753 135.242867,126.757333 C156.613383,148.127849 184.559216,158.914875 212.568138,159.119313 L212.568138,159.119313 L213.212264,159.134159 C225.843948,159.517566 238.363557,164.434972 248.121998,173.886137 L248.121998,173.886137 L248.725621,174.480088 C258.982114,184.732164 264.11035,198.171134 264.11035,211.6101 C264.11035,225.04592 258.984514,238.481745 248.732867,248.732867 C238.592792,258.872942 225.336706,263.997882 212.046872,264.107794 C198.731075,264.21792 185.381569,259.293085 175.098248,249.334078 L175.098248,249.334078 L174.494602,248.740134 C163.75802,238.008189 158.640853,223.784027 159.143413,209.719372 C158.258245,182.640933 147.489786,155.83332 126.828333,135.171867 C106.351297,114.694831 79.8363505,103.934873 53.0237258,102.891841 L53.0237258,102.891841 L52.2811438,102.865674 C38.4791718,103.347421 24.5325234,98.4328111 13.8776628,88.1140866 L13.8776628,88.1140866 L13.2739843,87.5201168 C3.12895117,77.3789607 -1.9984796,64.1195994 -2.10841888,50.8264755 C-2.21854669,37.5105567 2.70635908,24.1609269 12.6655135,13.8774565 L12.6655135,13.8774565 L13.2594878,13.2737797 C23.4005926,3.12880025 36.659927,-1.99860507 49.953025,-2.10854389 Z"}),f.jsx("circle",{cx:"50",cy:"212.0001",r:"52.5"}),f.jsx("circle",{cx:"212.0001",cy:"50",r:"52.5"})]})})}),e]})})}function hG({className:e,color:t,children:n,grayscaled:a=!1}){const r=w.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[1]||"0")}return a?0:.2},[t,a]),i=w.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[0]||"0.5")}return a?.3:.4},[t,a]),s=w.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[2]||"0")}return Math.floor(Math.random()*360)},[t]),c=w.useMemo(()=>t||`oklch(${Math.min(i,1)} ${r} ${s})`,[s,r,i]),u=w.useMemo(()=>`oklch(${Math.min(i*2,1)} ${r} ${s})`,[s,r,i,t]),d=w.useMemo(()=>Math.floor(Math.random()*360),[s]),m=w.useMemo(()=>"1000%",[]);return f.jsx("section",{className:De("relative w-full h-full overflow-hidden",e),style:{background:`${u}`},children:f.jsxs("div",{className:"isolate relative w-full h-full",children:[f.jsx("div",{className:"noise w-full h-full",style:{background:`linear-gradient(${d}deg, ${c}, transparent), url(https://grainy-gradients.vercel.app/noise.svg)`,filter:`contrast(120%) brightness(${m})`}}),n&&f.jsx("div",{className:"relative z-10 w-full h-full",children:n})]})})}function GN(e){const t=w.useRef({value:e,previous:e});return w.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var Wy="Switch",[_pe]=Ii(Wy),[Epe,kpe]=_pe(Wy),gG=w.forwardRef((e,t)=>{const{__scopeSwitch:n,name:a,checked:r,defaultChecked:i,required:s,disabled:c,value:u="on",onCheckedChange:d,form:m,...h}=e,[g,v]=w.useState(null),x=Jt(t,k=>v(k)),S=w.useRef(!1),y=g?m||!!g.closest("form"):!0,[E,_]=Mo({prop:r,defaultProp:i??!1,onChange:d,caller:Wy});return f.jsxs(Epe,{scope:n,checked:E,disabled:c,children:[f.jsx(_t.button,{type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":wG(E),"data-disabled":c?"":void 0,disabled:c,value:u,...h,ref:x,onClick:Ge(e.onClick,k=>{_(C=>!C),y&&(S.current=k.isPropagationStopped(),S.current||k.stopPropagation())})}),y&&f.jsx(yG,{control:g,bubbles:!S.current,name:a,value:u,checked:E,required:s,disabled:c,form:m,style:{transform:"translateX(-100%)"}})]})});gG.displayName=Wy;var bG="SwitchThumb",vG=w.forwardRef((e,t)=>{const{__scopeSwitch:n,...a}=e,r=kpe(bG,n);return f.jsx(_t.span,{"data-state":wG(r.checked),"data-disabled":r.disabled?"":void 0,...a,ref:t})});vG.displayName=bG;var Tpe="SwitchBubbleInput",yG=w.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:a=!0,...r},i)=>{const s=w.useRef(null),c=Jt(s,i),u=GN(n),d=$N(t);return w.useEffect(()=>{const m=s.current;if(!m)return;const h=window.HTMLInputElement.prototype,v=Object.getOwnPropertyDescriptor(h,"checked").set;if(u!==n&&v){const x=new Event("click",{bubbles:a});v.call(m,n),m.dispatchEvent(x)}},[u,n,a]),f.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...r,tabIndex:-1,ref:c,style:{...r.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});yG.displayName=Tpe;function wG(e){return e?"checked":"unchecked"}var SG=gG,Npe=vG;function Ky({ref:e,className:t,...n}){return f.jsx(SG,{className:De("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",t),...n,ref:e,children:f.jsx(Npe,{className:De("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})})}Ky.displayName=SG.displayName;var xG=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Cpe="VisuallyHidden",_G=w.forwardRef((e,t)=>f.jsx(_t.span,{...e,ref:t,style:{...xG,...e.style}}));_G.displayName=Cpe;var Rpe=_G,[Zy]=Ii("Tooltip",[Zs]),Yy=Zs(),EG="TooltipProvider",Ape=700,K_="tooltip.open",[Ipe,WN]=Zy(EG),kG=e=>{const{__scopeTooltip:t,delayDuration:n=Ape,skipDelayDuration:a=300,disableHoverableContent:r=!1,children:i}=e,s=w.useRef(!0),c=w.useRef(!1),u=w.useRef(0);return w.useEffect(()=>{const d=u.current;return()=>window.clearTimeout(d)},[]),f.jsx(Ipe,{scope:t,isOpenDelayedRef:s,delayDuration:n,onOpen:w.useCallback(()=>{window.clearTimeout(u.current),s.current=!1},[]),onClose:w.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>s.current=!0,a)},[a]),isPointerInTransitRef:c,onPointerInTransitChange:w.useCallback(d=>{c.current=d},[]),disableHoverableContent:r,children:i})};kG.displayName=EG;var Bp="Tooltip",[Ope,$m]=Zy(Bp),TG=e=>{const{__scopeTooltip:t,children:n,open:a,defaultOpen:r,onOpenChange:i,disableHoverableContent:s,delayDuration:c}=e,u=WN(Bp,e.__scopeTooltip),d=Yy(t),[m,h]=w.useState(null),g=jr(),v=w.useRef(0),x=s??u.disableHoverableContent,S=c??u.delayDuration,y=w.useRef(!1),[E,_]=Mo({prop:a,defaultProp:r??!1,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(K_))):u.onClose(),i?.(A)},caller:Bp}),k=w.useMemo(()=>E?y.current?"delayed-open":"instant-open":"closed",[E]),C=w.useCallback(()=>{window.clearTimeout(v.current),v.current=0,y.current=!1,_(!0)},[_]),R=w.useCallback(()=>{window.clearTimeout(v.current),v.current=0,_(!1)},[_]),I=w.useCallback(()=>{window.clearTimeout(v.current),v.current=window.setTimeout(()=>{y.current=!0,_(!0),v.current=0},S)},[S,_]);return w.useEffect(()=>()=>{v.current&&(window.clearTimeout(v.current),v.current=0)},[]),f.jsx(Py,{...d,children:f.jsx(Ope,{scope:t,contentId:g,open:E,stateAttribute:k,trigger:m,onTriggerChange:h,onTriggerEnter:w.useCallback(()=>{u.isOpenDelayedRef.current?I():C()},[u.isOpenDelayedRef,I,C]),onTriggerLeave:w.useCallback(()=>{x?R():(window.clearTimeout(v.current),v.current=0)},[R,x]),onOpen:C,onClose:R,disableHoverableContent:x,children:n})})};TG.displayName=Bp;var Z_="TooltipTrigger",NG=w.forwardRef((e,t)=>{const{__scopeTooltip:n,...a}=e,r=$m(Z_,n),i=WN(Z_,n),s=Yy(n),c=w.useRef(null),u=Jt(t,c,r.onTriggerChange),d=w.useRef(!1),m=w.useRef(!1),h=w.useCallback(()=>d.current=!1,[]);return w.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),f.jsx(Am,{asChild:!0,...s,children:f.jsx(_t.button,{"aria-describedby":r.open?r.contentId:void 0,"data-state":r.stateAttribute,...a,ref:u,onPointerMove:Ge(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!i.isPointerInTransitRef.current&&(r.onTriggerEnter(),m.current=!0)}),onPointerLeave:Ge(e.onPointerLeave,()=>{r.onTriggerLeave(),m.current=!1}),onPointerDown:Ge(e.onPointerDown,()=>{r.open&&r.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:Ge(e.onFocus,()=>{d.current||r.onOpen()}),onBlur:Ge(e.onBlur,r.onClose),onClick:Ge(e.onClick,r.onClose)})})});NG.displayName=Z_;var KN="TooltipPortal",[Dpe,jpe]=Zy(KN,{forceMount:void 0}),CG=e=>{const{__scopeTooltip:t,forceMount:n,children:a,container:r}=e,i=$m(KN,t);return f.jsx(Dpe,{scope:t,forceMount:n,children:f.jsx(Ua,{present:n||i.open,children:f.jsx(Ld,{asChild:!0,container:r,children:a})})})};CG.displayName=KN;var dd="TooltipContent",RG=w.forwardRef((e,t)=>{const n=jpe(dd,e.__scopeTooltip),{forceMount:a=n.forceMount,side:r="top",...i}=e,s=$m(dd,e.__scopeTooltip);return f.jsx(Ua,{present:a||s.open,children:s.disableHoverableContent?f.jsx(AG,{side:r,...i,ref:t}):f.jsx($pe,{side:r,...i,ref:t})})}),$pe=w.forwardRef((e,t)=>{const n=$m(dd,e.__scopeTooltip),a=WN(dd,e.__scopeTooltip),r=w.useRef(null),i=Jt(t,r),[s,c]=w.useState(null),{trigger:u,onClose:d}=n,m=r.current,{onPointerInTransitChange:h}=a,g=w.useCallback(()=>{c(null),h(!1)},[h]),v=w.useCallback((x,S)=>{const y=x.currentTarget,E={x:x.clientX,y:x.clientY},_=Upe(E,y.getBoundingClientRect()),k=zpe(E,_),C=Fpe(S.getBoundingClientRect()),R=Hpe([...k,...C]);c(R),h(!0)},[h]);return w.useEffect(()=>()=>g(),[g]),w.useEffect(()=>{if(u&&m){const x=y=>v(y,m),S=y=>v(y,u);return u.addEventListener("pointerleave",x),m.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",x),m.removeEventListener("pointerleave",S)}}},[u,m,v,g]),w.useEffect(()=>{if(s){const x=S=>{const y=S.target,E={x:S.clientX,y:S.clientY},_=u?.contains(y)||m?.contains(y),k=!Bpe(E,s);_?g():k&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,m,s,d,g]),f.jsx(AG,{...e,ref:i})}),[Lpe,Mpe]=Zy(Bp,{isInside:!1}),Ppe=vce("TooltipContent"),AG=w.forwardRef((e,t)=>{const{__scopeTooltip:n,children:a,"aria-label":r,onEscapeKeyDown:i,onPointerDownOutside:s,...c}=e,u=$m(dd,n),d=Yy(n),{onClose:m}=u;return w.useEffect(()=>(document.addEventListener(K_,m),()=>document.removeEventListener(K_,m)),[m]),w.useEffect(()=>{if(u.trigger){const h=g=>{g.target?.contains(u.trigger)&&m()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[u.trigger,m]),f.jsx(Dd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:h=>h.preventDefault(),onDismiss:m,children:f.jsxs(Uy,{"data-state":u.stateAttribute,...d,...c,ref:t,style:{...c.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[f.jsx(Ppe,{children:a}),f.jsx(Lpe,{scope:n,isInside:!0,children:f.jsx(Rpe,{id:u.contentId,role:"tooltip",children:r||a})})]})})});RG.displayName=dd;var IG="TooltipArrow",OG=w.forwardRef((e,t)=>{const{__scopeTooltip:n,...a}=e,r=Yy(n);return Mpe(IG,n).isInside?null:f.jsx(zy,{...r,...a,ref:t})});OG.displayName=IG;function Upe(e,t){const n=Math.abs(t.top-e.y),a=Math.abs(t.bottom-e.y),r=Math.abs(t.right-e.x),i=Math.abs(t.left-e.x);switch(Math.min(n,a,r,i)){case i:return"left";case r:return"right";case n:return"top";case a:return"bottom";default:throw new Error("unreachable")}}function zpe(e,t,n=5){const a=[];switch(t){case"top":a.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":a.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":a.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":a.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return a}function Fpe(e){const{top:t,right:n,bottom:a,left:r}=e;return[{x:r,y:t},{x:n,y:t},{x:n,y:a},{x:r,y:a}]}function Bpe(e,t){const{x:n,y:a}=e;let r=!1;for(let i=0,s=t.length-1;i<t.length;s=i++){const c=t[i],u=t[s],d=c.x,m=c.y,h=u.x,g=u.y;m>a!=g>a&&n<(h-d)*(a-m)/(g-m)+d&&(r=!r)}return r}function Hpe(e){const t=e.slice();return t.sort((n,a)=>n.x<a.x?-1:n.x>a.x?1:n.y<a.y?-1:n.y>a.y?1:0),Vpe(t)}function Vpe(e){if(e.length<=1)return e.slice();const t=[];for(let a=0;a<e.length;a++){const r=e[a];for(;t.length>=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(r.y-s.y)>=(i.y-s.y)*(r.x-s.x))t.pop();else break}t.push(r)}t.pop();const n=[];for(let a=e.length-1;a>=0;a--){const r=e[a];for(;n.length>=2;){const i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(r.y-s.y)>=(i.y-s.y)*(r.x-s.x))n.pop();else break}n.push(r)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var Gpe=kG,Wpe=TG,Kpe=NG,Zpe=CG,Ype=RG,qpe=OG;function ZN({delayDuration:e=0,...t}){return f.jsx(Gpe,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Nt({...e}){return f.jsx(ZN,{children:f.jsx(Wpe,{"data-slot":"tooltip",...e})})}function Ct({...e}){return f.jsx(Kpe,{"data-slot":"tooltip-trigger",...e})}function Rt({className:e,sideOffset:t=0,children:n,...a}){return f.jsx(Zpe,{children:f.jsxs(Ype,{"data-slot":"tooltip-content",sideOffset:t,className:De("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...a,children:[n,f.jsx(qpe,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}class Xpe{name="mcp_inspector_open";properties;constructor(t){this.properties={server_url:t.serverUrl,connection_count:t.connectionCount}}}class qU{name="mcp_tool_execution";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId,success:t.success,duration:t.duration,error:t.error}}}class XU{name="mcp_resource_read";properties;constructor(t){this.properties={resource_uri:t.resourceUri,server_id:t.serverId,success:t.success,error:t.error}}}class JU{name="mcp_prompt_call";properties;constructor(t){this.properties={prompt_name:t.promptName,server_id:t.serverId,success:t.success,error:t.error}}}class QU{name="mcp_chat_message";properties;constructor(t){this.properties={server_id:t.serverId,provider:t.provider,model:t.model,message_count:t.messageCount,tool_calls_count:t.toolCallsCount,success:t.success,execution_mode:t.executionMode,duration:t.duration,error:t.error}}}class Jpe{name="mcp_server_added";properties;constructor(t){this.properties={server_id:t.serverId,server_url:t.serverUrl,connection_type:t.connectionType,via_proxy:t.viaProxy}}}class Qpe{name="mcp_server_removed";properties;constructor(t){this.properties={server_id:t.serverId}}}class eme{name="mcp_command_palette_open";properties;constructor(t){this.properties={trigger:t.trigger}}}class tme{name="mcp_tool_saved";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId}}}function wx(){try{return"0.13.0-canary.19"}catch{return"0.0.0"}}var nme={};function Sx(){try{return typeof window<"u"&&typeof document<"u"}catch{return!1}}class ez{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,a=setTimeout(()=>n.abort(),this.timeout),r=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(a),!r.ok)throw new Error(`HTTP error! status: ${r.status}`)}catch{}}}function ys(e){return`mcp_inspector_telemetry_${e}`}class vr{static instance=null;POSTHOG_PROXY_URL="/inspector/api/tel/posthog";SCARF_PROXY_URL="/inspector/api/tel/scarf";UNKNOWN_USER_ID="UNKNOWN_USER_ID";_currUserId=null;_posthogClient=null;_scarfClient=null;_source="inspector";constructor(){const t=Sx(),n=this.isTelemetryDisabled();if(this._source=this.getStoredSource()||"inspector",n)this._posthogClient=null,this._scarfClient=null;else if(!t)this._posthogClient=null,this._scarfClient=null;else{try{this._posthogClient=new ez(this.POSTHOG_PROXY_URL,3e3)}catch{this._posthogClient=null}try{this._scarfClient=new ez(this.SCARF_PROXY_URL,3e3)}catch{this._scarfClient=null}}}isTelemetryDisabled(){return typeof localStorage<"u"&&localStorage.getItem(ys("disabled"))==="true"||typeof process<"u"&&nme?.MCP_USE_ANONYMIZED_TELEMETRY==="false"}getStoredSource(){return typeof localStorage<"u"?localStorage.getItem(ys("source")):null}static getInstance(){return vr.instance||(vr.instance=new vr),vr.instance}setSource(t){this._source=t,typeof localStorage<"u"&&localStorage.setItem(ys("source"),t)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!Sx())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{const t=localStorage.getItem(ys("user_id"));if(t)this._currUserId=t;else{const n=this.generateUserId();localStorage.setItem(ys("user_id"),n),this._currUserId=n}this.trackPackageDownload({triggered_by:"user_id_property"}).catch(()=>{})}catch{this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}generateUserId(){const t=window.crypto;if(t){const n=new Uint8Array(16);t.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;const a=Array.from(n).map(r=>r.toString(16).padStart(2,"0")).join("");return a.slice(0,8)+"-"+a.slice(8,12)+"-"+a.slice(12,16)+"-"+a.slice(16,20)+"-"+a.slice(20,32)}else return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const a=Math.random()*16|0;return(n==="x"?a:a&3|8).toString(16)})}async capture(t){if(!(!this._posthogClient&&!this._scarfClient)){if(this._posthogClient)try{const n={event:t.name,user_id:this.userId,properties:{...t.properties,mcp_use_version:wx(),language:"typescript",source:this._source,package:"inspector"}};await this._posthogClient.logEvent(n)}catch{}if(this._scarfClient)try{const n={};n.mcp_use_version=wx(),n.user_id=this.userId,n.event=t.name,n.language="typescript",n.source=this._source,n.package="inspector",await this._scarfClient.logEvent(n)}catch{}}}async trackPackageDownload(t){if(this._scarfClient&&Sx())try{const n=wx();let a=!1,r=!1;const i=localStorage.getItem(ys("download_version"));if(i?n>i&&(a=!0,r=!1,localStorage.setItem(ys("download_version"),n)):(a=!0,r=!0,localStorage.setItem(ys("download_version"),n)),a){const s={...t||{}};s.mcp_use_version=n,s.user_id=this.userId,s.event="package_download",s.first_download=r,s.language="typescript",s.source=this._source,s.package="inspector",await this._scarfClient.logEvent(s)}}catch{}}async trackInspectorOpen(t){const n=new Xpe(t);await this.capture(n)}}const rme={model:"stub-model",stopReason:"endTurn",role:"assistant",content:{type:"text",text:"positive"}};function ame({requestId:e,serverName:t,onViewDetails:n,onApprove:a,onDeny:r}){return f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{children:[f.jsx("strong",{children:"Sampling Request Received"}),f.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["New request from ",t]})]}),f.jsxs("div",{className:"flex gap-2",children:[f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:i=>{i.stopPropagation(),n()},children:"View Details"}),f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:i=>{i.stopPropagation(),a(rme)},children:"Approve"}),f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:i=>{i.stopPropagation(),r()},children:"Deny"})]})]})}function ime({requestId:e,serverName:t,mode:n,message:a,url:r,onViewDetails:i,onOpenUrl:s,onCancel:c}){return f.jsxs("div",{className:"space-y-3",children:[f.jsxs("div",{children:[f.jsx("strong",{children:"Elicitation Request Received"}),f.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["From ",t,": ",a]}),n==="url"&&r&&f.jsx("p",{className:"text-xs text-muted-foreground mt-1 font-mono",children:r})]}),f.jsxs("div",{className:"flex gap-2 flex-wrap",children:[f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:u=>{u.stopPropagation(),i()},children:"View Details"}),n==="url"&&s&&f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:u=>{u.stopPropagation(),s()},children:"Open URL"}),f.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:u=>{u.stopPropagation(),c()},children:"Cancel"})]})]})}const cb=()=>{},ub=()=>{},db=()=>{},fb=()=>{},DG=w.createContext(null);function YN(){const e=w.use(DG);if(!e)throw new Error("useMcpContext must be used within a McpProvider");return e}function ome({url:e,name:t,proxyConfig:n,transportType:a,connectionId:r,onUpdate:i,onRemove:s}){const c=typeof window<"u"?new URL("/inspector/oauth/callback",window.location.origin).toString():"/inspector/oauth/callback";let u=e,d={};if(n?.proxyAddress){const $=new URL(n.proxyAddress),L=new URL(e);u=`${$.origin}${$.pathname}${L.pathname}${L.search}`,d["X-Target-URL"]=e}n?.customHeaders&&(d={...d,...n.customHeaders});const[m,h]=w.useState([]),g=w.useRef(0),[v,x]=w.useState([]),S=w.useRef(0),y=w.useMemo(()=>m.map($=>({id:$.id,request:$.request,timestamp:$.timestamp,serverName:$.serverName})),[m]),E=w.useMemo(()=>v.map($=>({id:$.id,request:$.request,timestamp:$.timestamp,serverName:$.serverName})),[v]),_=w.useRef(null),[k,C]=w.useState(!1),R=w.useRef(!1);w.useEffect(()=>{typeof window<"u"&&!R.current&&(R.current=!0,Jn(()=>import("./transport-wrapper-browser-BI4dDu3b.js"),[]).then($=>{_.current=$.wrapTransportForLogging,C(!0),console.log("[McpContext] Transport wrapper loaded")}).catch($=>{console.error("[McpContext] Failed to load transport wrapper:",$)}))},[]);const I=w.useMemo(()=>{if(!(!k||!_.current))return($,L)=>{const F=r;return console.log("[McpContext] Applying transport wrapper, serverId:",F,"from connector:",L),_.current($,F)}},[k,r]),A=`mcp-inspector-notifications-${r}`,O=500,[M,P]=w.useState([]);w.useEffect(()=>{try{const $=localStorage.getItem(A);if($){const L=JSON.parse($);Array.isArray(L)&&P(L)}}catch($){console.error("Failed to load notifications from localStorage:",$)}},[A]),w.useEffect(()=>{try{localStorage.setItem(A,JSON.stringify(M))}catch($){console.error("Failed to save notifications to localStorage:",$)}},[M,A]);const B=w.useCallback($=>{P(L=>L.map(F=>F.id===$?{...F,read:!0}:F))},[]),K=w.useCallback(()=>{P($=>$.map(L=>({...L,read:!0})))},[]),ee=w.useCallback(()=>{P([])},[]),te=w.useCallback($=>{P(L=>{const F=[$,...L];return F.length>O?F.slice(0,O):F})},[]),ae=w.useCallback(($,L)=>{h(F=>{const W=F.find(X=>X.id===$);return W?(W.resolve(L),F.filter(X=>X.id!==$)):F})},[]),H=w.useCallback(($,L)=>{h(F=>{const W=F.find(X=>X.id===$);return W?(W.reject(new Error(L||"User rejected sampling request")),F.filter(X=>X.id!==$)):F})},[]),Z=w.useCallback(($,L)=>{x(F=>{const W=F.find(X=>X.id===$);return W?(W.resolve(L),F.filter(X=>X.id!==$)):F})},[]),G=w.useCallback(($,L)=>{x(F=>{const W=F.find(X=>X.id===$);return W?(W.reject(new Error(L||"User rejected elicitation request")),F.filter(X=>X.id!==$)):F})},[]),re=w.useCallback(async $=>new Promise((L,F)=>{const W=`sampling-${g.current++}`,X={id:W,request:{params:$},timestamp:Date.now(),serverName:t,resolve:L,reject:F};h(ie=>[...ie,X]),typeof window<"u"&&Jn(async()=>{const{toast:ie}=await Promise.resolve().then(()=>sz);return{toast:ie}},void 0).then(({toast:ie})=>{const ce=ie(f.jsx(ame,{requestId:W,serverName:t,onViewDetails:()=>{const J=new globalThis.CustomEvent("navigate-to-sampling",{detail:{requestId:W}});window.dispatchEvent(J),ie.dismiss(ce)},onApprove:J=>{h(q=>{const le=q.find(he=>he.id===W);return le?(le.resolve(J),ie.success("Sampling request approved"),q.filter(he=>he.id!==W)):q}),ie.dismiss(ce)},onDeny:()=>{h(J=>{const q=J.find(le=>le.id===W);return q?(q.reject(new Error("User denied sampling request from toast")),ie.error("Sampling request denied"),J.filter(le=>le.id!==W)):J}),ie.dismiss(ce)}}),{duration:5e3})})}),[t]),ne=w.useCallback(async $=>new Promise((L,F)=>{const W=`elicitation-${S.current++}`,X={id:W,request:$,timestamp:Date.now(),serverName:t,resolve:L,reject:F};x(ie=>[...ie,X]),typeof window<"u"&&Jn(async()=>{const{toast:ie}=await Promise.resolve().then(()=>sz);return{toast:ie}},void 0).then(({toast:ie})=>{const ce=ie(f.jsx(ime,{requestId:W,serverName:t,mode:$.mode||"form",message:$.message,url:$.mode==="url"?$.url:void 0,onViewDetails:()=>{const J=new globalThis.CustomEvent("navigate-to-elicitation",{detail:{requestId:W}});window.dispatchEvent(J),ie.dismiss(ce)},onOpenUrl:$.mode==="url"?()=>{window.open($.url,"_blank"),ie.dismiss(ce)}:void 0,onCancel:()=>{x(J=>{const q=J.find(le=>le.id===W);return q?(q.reject(new Error("User cancelled elicitation request from toast")),ie.error("Elicitation request cancelled"),J.filter(le=>le.id!==W)):J}),ie.dismiss(ce)}}),{duration:5e3})})}),[t]),j=wN({url:u,callbackUrl:c,timeout:5e3,customHeaders:Object.keys(d).length>0?d:void 0,transportType:a||"http",preventAutoAuth:!0,useRedirectFlow:!0,enabled:k,wrapTransport:I,onNotification:$=>{te({id:globalThis.crypto.randomUUID(),method:$.method,params:$.params,timestamp:Date.now(),read:!1})},samplingCallback:re,onElicitation:ne}),V=w.useRef(i),z=w.useRef(null);return w.useEffect(()=>{V.current=i},[i]),w.useEffect(()=>{if(typeof queueMicrotask<"u")queueMicrotask(()=>{j.state==="ready"&&j.serverInfo&&console.log("[McpContext] Server info available:",j.serverInfo);const $=M.filter(W=>!W.read).length,L={id:r,url:e,name:j.serverInfo?.name||t,state:j.state,tools:j.tools,resources:j.resources,prompts:j.prompts,error:j.error??null,authUrl:j.authUrl??null,customHeaders:d,transportType:a,proxyConfig:n,serverInfo:j.serverInfo,capabilities:j.capabilities,notifications:M,unreadNotificationCount:$,markNotificationRead:B,markAllNotificationsRead:K,clearNotifications:ee,pendingSamplingRequests:y,approveSampling:ae,rejectSampling:H,pendingElicitationRequests:E,approveElicitation:Z,rejectElicitation:G,callTool:j.callTool,readResource:j.readResource,listPrompts:j.listPrompts,getPrompt:j.getPrompt,authenticate:j.authenticate,retry:j.retry,clearStorage:j.clearStorage,disconnect:j.disconnect,client:j.client},F=z.current;(!F||F.state!==L.state||F.error!==L.error||F.authUrl!==L.authUrl||F.name!==L.name||F.tools.length!==L.tools.length||F.resources.length!==L.resources.length||F.prompts.length!==L.prompts.length||F.serverInfo!==L.serverInfo||F.capabilities!==L.capabilities||F.notifications.length!==L.notifications.length||F.unreadNotificationCount!==L.unreadNotificationCount||F.pendingSamplingRequests.length!==L.pendingSamplingRequests.length||F.pendingElicitationRequests.length!==L.pendingElicitationRequests.length||!F.client)&&(z.current=L,V.current(L))});else{const $=M.filter(W=>!W.read).length,L={id:r,url:e,name:j.serverInfo?.name||t,state:j.state,tools:j.tools,resources:j.resources,prompts:j.prompts,error:j.error??null,authUrl:j.authUrl??null,customHeaders:d,transportType:a,proxyConfig:n,serverInfo:j.serverInfo,capabilities:j.capabilities,notifications:M,unreadNotificationCount:$,markNotificationRead:B,markAllNotificationsRead:K,clearNotifications:ee,pendingSamplingRequests:y,approveSampling:ae,rejectSampling:H,pendingElicitationRequests:E,approveElicitation:Z,rejectElicitation:G,callTool:j.callTool,readResource:j.readResource,listPrompts:j.listPrompts,getPrompt:j.getPrompt,authenticate:j.authenticate,retry:j.retry,clearStorage:j.clearStorage,disconnect:j.disconnect,client:j.client},F=z.current;(!F||F.state!==L.state||F.error!==L.error||F.authUrl!==L.authUrl||F.name!==L.name||F.tools.length!==L.tools.length||F.resources.length!==L.resources.length||F.prompts.length!==L.prompts.length||F.serverInfo!==L.serverInfo||F.capabilities!==L.capabilities||F.notifications.length!==L.notifications.length||F.unreadNotificationCount!==L.unreadNotificationCount||F.pendingSamplingRequests.length!==L.pendingSamplingRequests.length||F.pendingElicitationRequests.length!==L.pendingElicitationRequests.length||!F.client)&&(z.current=L,V.current(L))}},[e,t,a,n,d,r,j.state,j.tools,j.resources,j.prompts,j.error,j.authUrl,j.serverInfo,j.capabilities,j.client,M,B,K,ee,j.callTool,j.readResource,j.listPrompts,j.getPrompt,j.authenticate,j.retry,j.clearStorage,m,ae,H,E,Z,G]),null}function sme({children:e}){const[t,n]=w.useState([]),[a,r]=w.useState(!1),[i,s]=w.useState(!0),[c,u]=w.useState([]);w.useEffect(()=>{try{const y=localStorage.getItem("mcp-inspector-connections");if(y){const _=JSON.parse(y);Array.isArray(_)&&(u(_),n(_.map(k=>({id:k.id||k.url,url:k.url,name:k.name||"MCP Server",state:"discovering",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:k.proxyConfig?.customHeaders,transportType:k.transportType,proxyConfig:k.proxyConfig,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}))))}const E=localStorage.getItem("mcp-inspector-auto-connect");E!==null&&s(E==="true")}catch(y){console.error("Failed to load connections from localStorage:",y)}finally{r(!0)}},[]),w.useEffect(()=>{a&&localStorage.setItem("mcp-inspector-connections",JSON.stringify(c))},[c,a]),w.useEffect(()=>{a&&localStorage.setItem("mcp-inspector-auto-connect",String(i))},[i,a]);const d=w.useCallback((y,E,_,k)=>{const C=c.find(A=>A.url===y),R=t.find(A=>A.url===y);if(C&&R){if(JSON.stringify(C.proxyConfig)!==JSON.stringify(_)&&_){u(O=>O.filter(M=>M.url!==y)),n(O=>O.filter(M=>M.url!==y)),setTimeout(()=>{const O={id:y,url:y,name:E||C.name||"MCP Server",proxyConfig:_,transportType:k||C.transportType};u(M=>[...M,O]),n(M=>[...M,{id:y,url:y,name:E||C.name||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:_?.customHeaders,transportType:k||C.transportType,proxyConfig:_,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}])},10);return}return}if(C&&!R){(_||k)&&u(A=>A.map(O=>O.url===y?{...O,proxyConfig:_||O.proxyConfig,transportType:k||O.transportType,name:E||O.name}:O)),n(A=>[...A,{id:C.id||y,url:y,name:E||C.name||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:_?.customHeaders||C.proxyConfig?.customHeaders,transportType:k||C.transportType,proxyConfig:_||C.proxyConfig,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}]);return}const I={id:y,url:y,name:E||"MCP Server",proxyConfig:_,transportType:k};u(A=>[...A,I]),n(A=>[...A,{id:y,url:y,name:E||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:_?.customHeaders,transportType:k,proxyConfig:_,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:cb,rejectSampling:ub,pendingElicitationRequests:[],approveElicitation:db,rejectElicitation:fb,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}])},[c,t]),m=w.useCallback(y=>{const E=t.find(k=>k.id===y);E&&(console.log(`[McpContext] Cleaning up connection: ${y}`),E.disconnect&&(console.log(`[McpContext] Disconnecting from server: ${y}`),E.disconnect()),E.clearStorage&&(console.log(`[McpContext] Clearing OAuth storage for connection: ${y}`),E.clearStorage())),u(k=>k.filter(C=>C.id!==y)),n(k=>k.filter(C=>C.id!==y));const _=localStorage.getItem("mcp-inspector-connections");if(_)try{const C=JSON.parse(_).filter(R=>(R.id||R.url)!==y);localStorage.setItem("mcp-inspector-connections",JSON.stringify(C))}catch(k){console.error("Failed to update localStorage on remove:",k)}vr.getInstance().capture(new Qpe({serverId:y}))},[t]),h=w.useCallback((y,E)=>{u(_=>_.map(k=>k.id===y||k.url===y?{...k,...E}:k)),n(_=>_.map(k=>k.id===y?{...k,...E}:k))},[]),g=w.useCallback(y=>{n(E=>{const _=E.findIndex(R=>R.id===y.id);if(_===-1)return E;const k=E[_];if(k.state===y.state&&k.tools===y.tools&&k.resources===y.resources&&k.prompts===y.prompts&&k.error===y.error&&k.serverInfo===y.serverInfo&&k.client===y.client&&k.notifications===y.notifications&&k.unreadNotificationCount===y.unreadNotificationCount&&k.pendingSamplingRequests.length===y.pendingSamplingRequests.length&&k.pendingElicitationRequests.length===y.pendingElicitationRequests.length)return E;const C=[...E];return C[_]=y,C})},[]),v=w.useCallback(y=>{console.log("Connect requested for:",y)},[]),x=w.useCallback(y=>{console.log("Disconnect requested for:",y)},[]),S=w.useMemo(()=>({connections:t,addConnection:d,removeConnection:m,updateConnectionConfig:h,autoConnect:i,setAutoConnect:s,connectServer:v,disconnectServer:x,configLoaded:a}),[t,d,m,h,i,v,x,a]);return f.jsxs(DG.Provider,{value:S,children:[e,a&&i&&c.map(y=>{const E=`${y.id||y.url}-${y.proxyConfig?.proxyAddress?"proxy":"direct"}`;return console.warn("[McpContext] Rendering McpConnectionWrapper with key:",E,"proxyConfig:",y.proxyConfig),f.jsx(ome,{url:y.url,name:y.name,proxyConfig:y.proxyConfig,transportType:y.transportType,connectionId:y.id||y.url,onUpdate:g,onRemove:()=>m(y.id||y.url)},E)})]})}const lme=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),cme=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,a)=>a?a.toUpperCase():n.toLowerCase()),tz=e=>{const t=cme(e);return t.charAt(0).toUpperCase()+t.slice(1)},jG=(...e)=>e.filter((t,n,a)=>!!t&&t.trim()!==""&&a.indexOf(t)===n).join(" ").trim(),ume=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var dme={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const fme=w.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:a,className:r="",children:i,iconNode:s,...c},u)=>w.createElement("svg",{ref:u,...dme,width:t,height:t,stroke:e,strokeWidth:a?Number(n)*24/Number(t):n,className:jG("lucide",r),...!i&&!ume(c)&&{"aria-hidden":"true"},...c},[...s.map(([d,m])=>w.createElement(d,m)),...Array.isArray(i)?i:[i]]));const et=(e,t)=>{const n=w.forwardRef(({className:a,...r},i)=>w.createElement(fme,{ref:i,iconNode:t,className:jG(`lucide-${lme(tz(e))}`,`lucide-${e}`,a),...r}));return n.displayName=tz(e),n};const pme=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],mme=et("arrow-down-to-line",pme);const hme=[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]],gme=et("arrow-up-from-line",hme);const bme=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],vme=et("arrow-up",bme);const yme=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],qN=et("bell",yme);const wme=[["path",{d:"m11 10 3 3",key:"fzmg1i"}],["path",{d:"M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z",key:"p4q2r7"}],["path",{d:"M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031",key:"wy6l02"}]],$G=et("brush",wme);const Sme=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],xme=et("bug",Sme);const _me=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ra=et("check",_me);const Eme=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],ac=et("chevron-down",Eme);const kme=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],qy=et("chevron-left",kme);const Tme=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],LG=et("chevron-right",Tme);const Nme=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Cme=et("chevron-up",Nme);const Rme=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],Ame=et("chevrons-up-down",Rme);const Ime=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]],nz=et("circle-minus",Ime);const Ome=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],fd=et("clock",Ome);const Dme=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],XN=et("code",Dme);const jme=[["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}]],$me=et("cog",jme);const Lme=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],Mme=et("command",Lme);const Pme=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],$r=et("copy",Pme);const Ume=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],Xy=et("database",Ume);const zme=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],Lm=et("download",zme);const Fme=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],Bme=et("ellipsis-vertical",Fme);const Hme=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Y_=et("external-link",Hme);const Vme=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],MG=et("eye-off",Vme);const Gme=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],q_=et("eye",Gme);const Wme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Kme=et("file-code",Wme);const Zme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]],Yme=et("file-image",Zme);const qme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],JN=et("file-text",qme);const Xme=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],Jme=et("file",Xme);const Qme=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],ehe=et("folder-open",Qme);const the=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],nhe=et("globe",the);const rhe=[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]],ahe=et("grip-vertical",rhe);const ihe=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],PG=et("hash",ihe);const ohe=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Rv=et("history",ohe);const she=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],UG=et("key",she);const lhe=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],zs=et("loader-circle",lhe);const che=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]],QN=et("maximize-2",che);const uhe=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]],eC=et("maximize",uhe);const dhe=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],fhe=et("message-circle",dhe);const phe=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Hp=et("message-square",phe);const mhe=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]],hhe=et("minimize",mhe);const ghe=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],rz=et("monitor",ghe);const bhe=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],vhe=et("moon",bhe);const yhe=[["path",{d:"M2 10h6V4",key:"zwrco"}],["path",{d:"m2 4 6 6",key:"ug085t"}],["path",{d:"M21 10V7a2 2 0 0 0-2-2h-7",key:"git5jr"}],["path",{d:"M3 14v2a2 2 0 0 0 2 2h3",key:"1f7fh3"}],["rect",{x:"12",y:"14",width:"10",height:"7",rx:"1",key:"1wjs3o"}]],whe=et("picture-in-picture",yhe);const She=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],zG=et("play",She);const xhe=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],FG=et("plus",xhe);const _he=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],az=et("rotate-ccw",_he);const Ehe=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],tC=et("save",Ehe);const khe=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Pd=et("search",khe);const The=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Nhe=et("send",The);const Che=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],Rhe=et("server",Che);const Ahe=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Eu=et("settings",Ahe);const Ihe=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],Ohe=et("shield",Ihe);const Dhe=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],jhe=et("sparkles",Dhe);const $he=[["path",{d:"M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344",key:"2acyp4"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],BG=et("square-check-big",$he);const Lhe=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],Mhe=et("square-pen",Lhe);const Phe=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M20 12h.01",key:"1ykeid"}],["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M4 12h.01",key:"158zrr"}],["path",{d:"M17.657 6.343h.01",key:"31pqzk"}],["path",{d:"M17.657 17.657h.01",key:"jehnf4"}],["path",{d:"M6.343 17.657h.01",key:"gdk6ow"}],["path",{d:"M6.343 6.343h.01",key:"1uurf0"}]],Uhe=et("sun-dim",Phe);const zhe=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],xx=et("terminal",zhe);const Fhe=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Fs=et("trash-2",Fhe);const Bhe=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Hhe=et("trash",Bhe);const Vhe=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],Wl=et("wrench",Vhe);const Ghe=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ji=et("x",Ghe);const Whe=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],Vp=et("zap",Whe);function Khe(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const Zhe=e=>{switch(e){case"success":return Xhe;case"info":return Qhe;case"warning":return Jhe;case"error":return ege;default:return null}},Yhe=Array(12).fill(0),qhe=({visible:e,className:t})=>ue.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ue.createElement("div",{className:"sonner-spinner"},Yhe.map((n,a)=>ue.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${a}`})))),Xhe=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ue.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),Jhe=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ue.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),Qhe=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ue.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),ege=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ue.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),tge=ue.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ue.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ue.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),nge=()=>{const[e,t]=ue.useState(document.hidden);return ue.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let X_=1;class rge{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:a,...r}=t,i=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:X_++,s=this.toasts.find(u=>u.id===i),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),s?this.toasts=this.toasts.map(u=>u.id===i?(this.publish({...u,...t,id:i,title:a}),{...u,...t,id:i,dismissible:c,title:a}):u):this.addToast({title:a,...r,dismissible:c,id:i}),i},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(a=>a({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let a;n.loading!==void 0&&(a=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const r=Promise.resolve(t instanceof Function?t():t);let i=a!==void 0,s;const c=r.then(async d=>{if(s=["resolve",d],ue.isValidElement(d))i=!1,this.create({id:a,type:"default",message:d});else if(ige(d)&&!d.ok){i=!1;const h=typeof n.error=="function"?await n.error(`HTTP error! status: ${d.status}`):n.error,g=typeof n.description=="function"?await n.description(`HTTP error! status: ${d.status}`):n.description,x=typeof h=="object"&&!ue.isValidElement(h)?h:{message:h};this.create({id:a,type:"error",description:g,...x})}else if(d instanceof Error){i=!1;const h=typeof n.error=="function"?await n.error(d):n.error,g=typeof n.description=="function"?await n.description(d):n.description,x=typeof h=="object"&&!ue.isValidElement(h)?h:{message:h};this.create({id:a,type:"error",description:g,...x})}else if(n.success!==void 0){i=!1;const h=typeof n.success=="function"?await n.success(d):n.success,g=typeof n.description=="function"?await n.description(d):n.description,x=typeof h=="object"&&!ue.isValidElement(h)?h:{message:h};this.create({id:a,type:"success",description:g,...x})}}).catch(async d=>{if(s=["reject",d],n.error!==void 0){i=!1;const m=typeof n.error=="function"?await n.error(d):n.error,h=typeof n.description=="function"?await n.description(d):n.description,v=typeof m=="object"&&!ue.isValidElement(m)?m:{message:m};this.create({id:a,type:"error",description:h,...v})}}).finally(()=>{i&&(this.dismiss(a),a=void 0),n.finally==null||n.finally.call(n)}),u=()=>new Promise((d,m)=>c.then(()=>s[0]==="reject"?m(s[1]):d(s[1])).catch(m));return typeof a!="string"&&typeof a!="number"?{unwrap:u}:Object.assign(a,{unwrap:u})},this.custom=(t,n)=>{const a=n?.id||X_++;return this.create({jsx:t(a),id:a,...n}),a},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const ga=new rge,age=(e,t)=>{const n=t?.id||X_++;return ga.addToast({title:e,...t,id:n}),n},ige=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",oge=age,sge=()=>ga.toasts,lge=()=>ga.getActiveToasts(),Xt=Object.assign(oge,{success:ga.success,info:ga.info,warning:ga.warning,error:ga.error,custom:ga.custom,message:ga.message,promise:ga.promise,dismiss:ga.dismiss,loading:ga.loading},{getHistory:sge,getToasts:lge});Khe("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function pb(e){return e.label!==void 0}const cge=3,uge="24px",dge="16px",iz=4e3,fge=356,pge=14,mge=45,hge=200;function Ui(...e){return e.filter(Boolean).join(" ")}function gge(e){const[t,n]=e.split("-"),a=[];return t&&a.push(t),n&&a.push(n),a}const bge=e=>{var t,n,a,r,i,s,c,u,d;const{invert:m,toast:h,unstyled:g,interacting:v,setHeights:x,visibleToasts:S,heights:y,index:E,toasts:_,expanded:k,removeToast:C,defaultRichColors:R,closeButton:I,style:A,cancelButtonStyle:O,actionButtonStyle:M,className:P="",descriptionClassName:B="",duration:K,position:ee,gap:te,expandByDefault:ae,classNames:H,icons:Z,closeButtonAriaLabel:G="Close toast"}=e,[re,ne]=ue.useState(null),[j,V]=ue.useState(null),[z,$]=ue.useState(!1),[L,F]=ue.useState(!1),[W,X]=ue.useState(!1),[ie,ce]=ue.useState(!1),[J,q]=ue.useState(!1),[le,he]=ue.useState(0),[oe,Ne]=ue.useState(0),Ve=ue.useRef(h.duration||K||iz),_e=ue.useRef(null),ke=ue.useRef(null),Fe=E===0,pe=E+1<=S,Oe=h.type,He=h.dismissible!==!1,xe=h.className||"",at=h.descriptionClassName||"",nt=ue.useMemo(()=>y.findIndex(Ke=>Ke.toastId===h.id)||0,[y,h.id]),ft=ue.useMemo(()=>{var Ke;return(Ke=h.closeButton)!=null?Ke:I},[h.closeButton,I]),Et=ue.useMemo(()=>h.duration||K||iz,[h.duration,K]),pt=ue.useRef(0),mn=ue.useRef(0),Pr=ue.useRef(0),St=ue.useRef(null),[Be,Le]=ee.split("-"),Se=ue.useMemo(()=>y.reduce((Ke,Ze,dt)=>dt>=nt?Ke:Ke+Ze.height,0),[y,nt]),je=nge(),Ue=h.invert||m,We=Oe==="loading";mn.current=ue.useMemo(()=>nt*te+Se,[nt,Se]),ue.useEffect(()=>{Ve.current=Et},[Et]),ue.useEffect(()=>{$(!0)},[]),ue.useEffect(()=>{const Ke=ke.current;if(Ke){const Ze=Ke.getBoundingClientRect().height;return Ne(Ze),x(dt=>[{toastId:h.id,height:Ze,position:h.position},...dt]),()=>x(dt=>dt.filter(At=>At.toastId!==h.id))}},[x,h.id]),ue.useLayoutEffect(()=>{if(!z)return;const Ke=ke.current,Ze=Ke.style.height;Ke.style.height="auto";const dt=Ke.getBoundingClientRect().height;Ke.style.height=Ze,Ne(dt),x(At=>At.find(ln=>ln.toastId===h.id)?At.map(ln=>ln.toastId===h.id?{...ln,height:dt}:ln):[{toastId:h.id,height:dt,position:h.position},...At])},[z,h.title,h.description,x,h.id,h.jsx,h.action,h.cancel]);const Je=ue.useCallback(()=>{F(!0),he(mn.current),x(Ke=>Ke.filter(Ze=>Ze.toastId!==h.id)),setTimeout(()=>{C(h)},hge)},[h,C,x,mn]);ue.useEffect(()=>{if(h.promise&&Oe==="loading"||h.duration===1/0||h.type==="loading")return;let Ke;return k||v||je?(()=>{if(Pr.current<pt.current){const At=new Date().getTime()-pt.current;Ve.current=Ve.current-At}Pr.current=new Date().getTime()})():Ve.current!==1/0&&(pt.current=new Date().getTime(),Ke=setTimeout(()=>{h.onAutoClose==null||h.onAutoClose.call(h,h),Je()},Ve.current)),()=>clearTimeout(Ke)},[k,v,h,Oe,je,Je]),ue.useEffect(()=>{h.delete&&(Je(),h.onDismiss==null||h.onDismiss.call(h,h))},[Je,h.delete]);function yt(){var Ke;if(Z?.loading){var Ze;return ue.createElement("div",{className:Ui(H?.loader,h==null||(Ze=h.classNames)==null?void 0:Ze.loader,"sonner-loader"),"data-visible":Oe==="loading"},Z.loading)}return ue.createElement(qhe,{className:Ui(H?.loader,h==null||(Ke=h.classNames)==null?void 0:Ke.loader),visible:Oe==="loading"})}const mt=h.icon||Z?.[Oe]||Zhe(Oe);var Mt,nn;return ue.createElement("li",{tabIndex:0,ref:ke,className:Ui(P,xe,H?.toast,h==null||(t=h.classNames)==null?void 0:t.toast,H?.default,H?.[Oe],h==null||(n=h.classNames)==null?void 0:n[Oe]),"data-sonner-toast":"","data-rich-colors":(Mt=h.richColors)!=null?Mt:R,"data-styled":!(h.jsx||h.unstyled||g),"data-mounted":z,"data-promise":!!h.promise,"data-swiped":J,"data-removed":L,"data-visible":pe,"data-y-position":Be,"data-x-position":Le,"data-index":E,"data-front":Fe,"data-swiping":W,"data-dismissible":He,"data-type":Oe,"data-invert":Ue,"data-swipe-out":ie,"data-swipe-direction":j,"data-expanded":!!(k||ae&&z),"data-testid":h.testId,style:{"--index":E,"--toasts-before":E,"--z-index":_.length-E,"--offset":`${L?le:mn.current}px`,"--initial-height":ae?"auto":`${oe}px`,...A,...h.style},onDragEnd:()=>{X(!1),ne(null),St.current=null},onPointerDown:Ke=>{Ke.button!==2&&(We||!He||(_e.current=new Date,he(mn.current),Ke.target.setPointerCapture(Ke.pointerId),Ke.target.tagName!=="BUTTON"&&(X(!0),St.current={x:Ke.clientX,y:Ke.clientY})))},onPointerUp:()=>{var Ke,Ze,dt;if(ie||!He)return;St.current=null;const At=Number(((Ke=ke.current)==null?void 0:Ke.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Qn=Number(((Ze=ke.current)==null?void 0:Ze.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),ln=new Date().getTime()-((dt=_e.current)==null?void 0:dt.getTime()),Vn=re==="x"?At:Qn,$n=Math.abs(Vn)/ln;if(Math.abs(Vn)>=mge||$n>.11){he(mn.current),h.onDismiss==null||h.onDismiss.call(h,h),V(re==="x"?At>0?"right":"left":Qn>0?"down":"up"),Je(),ce(!0);return}else{var yn,fn;(yn=ke.current)==null||yn.style.setProperty("--swipe-amount-x","0px"),(fn=ke.current)==null||fn.style.setProperty("--swipe-amount-y","0px")}q(!1),X(!1),ne(null)},onPointerMove:Ke=>{var Ze,dt,At;if(!St.current||!He||((Ze=window.getSelection())==null?void 0:Ze.toString().length)>0)return;const ln=Ke.clientY-St.current.y,Vn=Ke.clientX-St.current.x;var $n;const yn=($n=e.swipeDirections)!=null?$n:gge(ee);!re&&(Math.abs(Vn)>1||Math.abs(ln)>1)&&ne(Math.abs(Vn)>Math.abs(ln)?"x":"y");let fn={x:0,y:0};const oa=Qt=>1/(1.5+Math.abs(Qt)/20);if(re==="y"){if(yn.includes("top")||yn.includes("bottom"))if(yn.includes("top")&&ln<0||yn.includes("bottom")&&ln>0)fn.y=ln;else{const Qt=ln*oa(ln);fn.y=Math.abs(Qt)<Math.abs(ln)?Qt:ln}}else if(re==="x"&&(yn.includes("left")||yn.includes("right")))if(yn.includes("left")&&Vn<0||yn.includes("right")&&Vn>0)fn.x=Vn;else{const Qt=Vn*oa(Vn);fn.x=Math.abs(Qt)<Math.abs(Vn)?Qt:Vn}(Math.abs(fn.x)>0||Math.abs(fn.y)>0)&&q(!0),(dt=ke.current)==null||dt.style.setProperty("--swipe-amount-x",`${fn.x}px`),(At=ke.current)==null||At.style.setProperty("--swipe-amount-y",`${fn.y}px`)}},ft&&!h.jsx&&Oe!=="loading"?ue.createElement("button",{"aria-label":G,"data-disabled":We,"data-close-button":!0,onClick:We||!He?()=>{}:()=>{Je(),h.onDismiss==null||h.onDismiss.call(h,h)},className:Ui(H?.closeButton,h==null||(a=h.classNames)==null?void 0:a.closeButton)},(nn=Z?.close)!=null?nn:tge):null,(Oe||h.icon||h.promise)&&h.icon!==null&&(Z?.[Oe]!==null||h.icon)?ue.createElement("div",{"data-icon":"",className:Ui(H?.icon,h==null||(r=h.classNames)==null?void 0:r.icon)},h.promise||h.type==="loading"&&!h.icon?h.icon||yt():null,h.type!=="loading"?mt:null):null,ue.createElement("div",{"data-content":"",className:Ui(H?.content,h==null||(i=h.classNames)==null?void 0:i.content)},ue.createElement("div",{"data-title":"",className:Ui(H?.title,h==null||(s=h.classNames)==null?void 0:s.title)},h.jsx?h.jsx:typeof h.title=="function"?h.title():h.title),h.description?ue.createElement("div",{"data-description":"",className:Ui(B,at,H?.description,h==null||(c=h.classNames)==null?void 0:c.description)},typeof h.description=="function"?h.description():h.description):null),ue.isValidElement(h.cancel)?h.cancel:h.cancel&&pb(h.cancel)?ue.createElement("button",{"data-button":!0,"data-cancel":!0,style:h.cancelButtonStyle||O,onClick:Ke=>{pb(h.cancel)&&He&&(h.cancel.onClick==null||h.cancel.onClick.call(h.cancel,Ke),Je())},className:Ui(H?.cancelButton,h==null||(u=h.classNames)==null?void 0:u.cancelButton)},h.cancel.label):null,ue.isValidElement(h.action)?h.action:h.action&&pb(h.action)?ue.createElement("button",{"data-button":!0,"data-action":!0,style:h.actionButtonStyle||M,onClick:Ke=>{pb(h.action)&&(h.action.onClick==null||h.action.onClick.call(h.action,Ke),!Ke.defaultPrevented&&Je())},className:Ui(H?.actionButton,h==null||(d=h.classNames)==null?void 0:d.actionButton)},h.action.label):null)};function oz(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function vge(e,t){const n={};return[e,t].forEach((a,r)=>{const i=r===1,s=i?"--mobile-offset":"--offset",c=i?dge:uge;function u(d){["top","right","bottom","left"].forEach(m=>{n[`${s}-${m}`]=typeof d=="number"?`${d}px`:d})}typeof a=="number"||typeof a=="string"?u(a):typeof a=="object"?["top","right","bottom","left"].forEach(d=>{a[d]===void 0?n[`${s}-${d}`]=c:n[`${s}-${d}`]=typeof a[d]=="number"?`${a[d]}px`:a[d]}):u(c)}),n}const HG=ue.forwardRef(function(t,n){const{id:a,invert:r,position:i="bottom-right",hotkey:s=["altKey","KeyT"],expand:c,closeButton:u,className:d,offset:m,mobileOffset:h,theme:g="light",richColors:v,duration:x,style:S,visibleToasts:y=cge,toastOptions:E,dir:_=oz(),gap:k=pge,icons:C,containerAriaLabel:R="Notifications"}=t,[I,A]=ue.useState([]),O=ue.useMemo(()=>a?I.filter(z=>z.toasterId===a):I.filter(z=>!z.toasterId),[I,a]),M=ue.useMemo(()=>Array.from(new Set([i].concat(O.filter(z=>z.position).map(z=>z.position)))),[O,i]),[P,B]=ue.useState([]),[K,ee]=ue.useState(!1),[te,ae]=ue.useState(!1),[H,Z]=ue.useState(g!=="system"?g:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),G=ue.useRef(null),re=s.join("+").replace(/Key/g,"").replace(/Digit/g,""),ne=ue.useRef(null),j=ue.useRef(!1),V=ue.useCallback(z=>{A($=>{var L;return(L=$.find(F=>F.id===z.id))!=null&&L.delete||ga.dismiss(z.id),$.filter(({id:F})=>F!==z.id)})},[]);return ue.useEffect(()=>ga.subscribe(z=>{if(z.dismiss){requestAnimationFrame(()=>{A($=>$.map(L=>L.id===z.id?{...L,delete:!0}:L))});return}setTimeout(()=>{z9.flushSync(()=>{A($=>{const L=$.findIndex(F=>F.id===z.id);return L!==-1?[...$.slice(0,L),{...$[L],...z},...$.slice(L+1)]:[z,...$]})})})}),[I]),ue.useEffect(()=>{if(g!=="system"){Z(g);return}if(g==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Z("dark"):Z("light")),typeof window>"u")return;const z=window.matchMedia("(prefers-color-scheme: dark)");try{z.addEventListener("change",({matches:$})=>{Z($?"dark":"light")})}catch{z.addListener(({matches:L})=>{try{Z(L?"dark":"light")}catch(F){console.error(F)}})}},[g]),ue.useEffect(()=>{I.length<=1&&ee(!1)},[I]),ue.useEffect(()=>{const z=$=>{var L;if(s.every(X=>$[X]||$.code===X)){var W;ee(!0),(W=G.current)==null||W.focus()}$.code==="Escape"&&(document.activeElement===G.current||(L=G.current)!=null&&L.contains(document.activeElement))&&ee(!1)};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[s]),ue.useEffect(()=>{if(G.current)return()=>{ne.current&&(ne.current.focus({preventScroll:!0}),ne.current=null,j.current=!1)}},[G.current]),ue.createElement("section",{ref:n,"aria-label":`${R} ${re}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},M.map((z,$)=>{var L;const[F,W]=z.split("-");return O.length?ue.createElement("ol",{key:z,dir:_==="auto"?oz():_,tabIndex:-1,ref:G,className:d,"data-sonner-toaster":!0,"data-sonner-theme":H,"data-y-position":F,"data-x-position":W,style:{"--front-toast-height":`${((L=P[0])==null?void 0:L.height)||0}px`,"--width":`${fge}px`,"--gap":`${k}px`,...S,...vge(m,h)},onBlur:X=>{j.current&&!X.currentTarget.contains(X.relatedTarget)&&(j.current=!1,ne.current&&(ne.current.focus({preventScroll:!0}),ne.current=null))},onFocus:X=>{X.target instanceof HTMLElement&&X.target.dataset.dismissible==="false"||j.current||(j.current=!0,ne.current=X.relatedTarget)},onMouseEnter:()=>ee(!0),onMouseMove:()=>ee(!0),onMouseLeave:()=>{te||ee(!1)},onDragEnd:()=>ee(!1),onPointerDown:X=>{X.target instanceof HTMLElement&&X.target.dataset.dismissible==="false"||ae(!0)},onPointerUp:()=>ae(!1)},O.filter(X=>!X.position&&$===0||X.position===z).map((X,ie)=>{var ce,J;return ue.createElement(bge,{key:X.id,icons:C,index:ie,toast:X,defaultRichColors:v,duration:(ce=E?.duration)!=null?ce:x,className:E?.className,descriptionClassName:E?.descriptionClassName,invert:r,visibleToasts:y,closeButton:(J=E?.closeButton)!=null?J:u,interacting:te,position:z,style:E?.style,unstyled:E?.unstyled,classNames:E?.classNames,cancelButtonStyle:E?.cancelButtonStyle,actionButtonStyle:E?.actionButtonStyle,closeButtonAriaLabel:E?.closeButtonAriaLabel,removeToast:V,toasts:O.filter(q=>q.position==X.position),heights:P.filter(q=>q.position==X.position),setHeights:B,expandByDefault:c,gap:k,expanded:K,swipeDirections:t.swipeDirections})})):null}))}),sz=Object.freeze(Object.defineProperty({__proto__:null,Toaster:HG,toast:Xt},Symbol.toStringTag,{value:"Module"}));var Jy="Dialog",[VG]=Ii(Jy),[yge,Oi]=VG(Jy),GG=e=>{const{__scopeDialog:t,children:n,open:a,defaultOpen:r,onOpenChange:i,modal:s=!0}=e,c=w.useRef(null),u=w.useRef(null),[d,m]=Mo({prop:a,defaultProp:r??!1,onChange:i,caller:Jy});return f.jsx(yge,{scope:t,triggerRef:c,contentRef:u,contentId:jr(),titleId:jr(),descriptionId:jr(),open:d,onOpenChange:m,onOpenToggle:w.useCallback(()=>m(h=>!h),[m]),modal:s,children:n})};GG.displayName=Jy;var WG="DialogTrigger",KG=w.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(WG,n),i=Jt(t,r.triggerRef);return f.jsx(_t.button,{type:"button","aria-haspopup":"dialog","aria-expanded":r.open,"aria-controls":r.contentId,"data-state":aC(r.open),...a,ref:i,onClick:Ge(e.onClick,r.onOpenToggle)})});KG.displayName=WG;var nC="DialogPortal",[wge,ZG]=VG(nC,{forceMount:void 0}),YG=e=>{const{__scopeDialog:t,forceMount:n,children:a,container:r}=e,i=Oi(nC,t);return f.jsx(wge,{scope:t,forceMount:n,children:w.Children.map(a,s=>f.jsx(Ua,{present:n||i.open,children:f.jsx(Ld,{asChild:!0,container:r,children:s})}))})};YG.displayName=nC;var Av="DialogOverlay",qG=w.forwardRef((e,t)=>{const n=ZG(Av,e.__scopeDialog),{forceMount:a=n.forceMount,...r}=e,i=Oi(Av,e.__scopeDialog);return i.modal?f.jsx(Ua,{present:a||i.open,children:f.jsx(xge,{...r,ref:t})}):null});qG.displayName=Av;var Sge=Vl("DialogOverlay.RemoveScroll"),xge=w.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(Av,n);return f.jsx(Om,{as:Sge,allowPinchZoom:!0,shards:[r.contentRef],children:f.jsx(_t.div,{"data-state":aC(r.open),...a,ref:t,style:{pointerEvents:"auto",...a.style}})})}),Kl="DialogContent",XG=w.forwardRef((e,t)=>{const n=ZG(Kl,e.__scopeDialog),{forceMount:a=n.forceMount,...r}=e,i=Oi(Kl,e.__scopeDialog);return f.jsx(Ua,{present:a||i.open,children:i.modal?f.jsx(_ge,{...r,ref:t}):f.jsx(Ege,{...r,ref:t})})});XG.displayName=Kl;var _ge=w.forwardRef((e,t)=>{const n=Oi(Kl,e.__scopeDialog),a=w.useRef(null),r=Jt(t,n.contentRef,a);return w.useEffect(()=>{const i=a.current;if(i)return Fy(i)},[]),f.jsx(JG,{...e,ref:r,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ge(e.onCloseAutoFocus,i=>{i.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ge(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,c=s.button===0&&s.ctrlKey===!0;(s.button===2||c)&&i.preventDefault()}),onFocusOutside:Ge(e.onFocusOutside,i=>i.preventDefault())})}),Ege=w.forwardRef((e,t)=>{const n=Oi(Kl,e.__scopeDialog),a=w.useRef(!1),r=w.useRef(!1);return f.jsx(JG,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{e.onCloseAutoFocus?.(i),i.defaultPrevented||(a.current||n.triggerRef.current?.focus(),i.preventDefault()),a.current=!1,r.current=!1},onInteractOutside:i=>{e.onInteractOutside?.(i),i.defaultPrevented||(a.current=!0,i.detail.originalEvent.type==="pointerdown"&&(r.current=!0));const s=i.target;n.triggerRef.current?.contains(s)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&r.current&&i.preventDefault()}})}),JG=w.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:a,onOpenAutoFocus:r,onCloseAutoFocus:i,...s}=e,c=Oi(Kl,n),u=w.useRef(null),d=Jt(t,u);return Dy(),f.jsxs(f.Fragment,{children:[f.jsx(Cm,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:r,onUnmountAutoFocus:i,children:f.jsx(Dd,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":aC(c.open),...s,ref:d,onDismiss:()=>c.onOpenChange(!1)})}),f.jsxs(f.Fragment,{children:[f.jsx(kge,{titleId:c.titleId}),f.jsx(Nge,{contentRef:u,descriptionId:c.descriptionId})]})]})}),rC="DialogTitle",QG=w.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(rC,n);return f.jsx(_t.h2,{id:r.titleId,...a,ref:t})});QG.displayName=rC;var e7="DialogDescription",t7=w.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(e7,n);return f.jsx(_t.p,{id:r.descriptionId,...a,ref:t})});t7.displayName=e7;var n7="DialogClose",r7=w.forwardRef((e,t)=>{const{__scopeDialog:n,...a}=e,r=Oi(n7,n);return f.jsx(_t.button,{type:"button",...a,ref:t,onClick:Ge(e.onClick,()=>r.onOpenChange(!1))})});r7.displayName=n7;function aC(e){return e?"open":"closed"}var a7="DialogTitleWarning",[eNe,i7]=fce(a7,{contentName:Kl,titleName:rC,docsSlug:"dialog"}),kge=({titleId:e})=>{const t=i7(a7),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
94
94
 
95
95
  If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
96
96
 
@@ -1657,8 +1657,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1657
1657
  <\/script>
1658
1658
  </body>
1659
1659
  </html>`,dY=1,g2=2,fY=3,b2=4,pY=5,v2=Symbol.for("quilt.threads.serialize"),hke=Symbol.for("quilt.threads.transferable");class gke extends AbortController{constructor(...t){super();const n=t.find(a=>a.aborted);if(n)this.abort(n.reason);else{const a=i=>this.abort(i.target.reason),r={signal:this.signal};for(const i of t)i.addEventListener("abort",a,r)}}}class y2 extends Error{constructor(){super("You attempted to call a function on a closed thread.")}}let bke="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";function mY(e=21){let t="",n=crypto.getRandomValues(new Uint8Array(e));for(let a=0;a<e;a++)t+=bke[63&n[a]];return t}var sp,iu,lp,Zb,QE,hY;class vke{constructor(){hi(this,QE),hi(this,sp,new Map),hi(this,iu,new Map),hi(this,lp,new Map),hi(this,Zb,new WeakMap)}get(t){return Pn(this,iu).get(t)}release(t){const n=Pn(this,iu).get(t);return n&&(Pn(this,iu).delete(t),Pn(this,sp).delete(n)),!!n}serialize(t){let n=Pn(this,sp).get(t);return n==null&&(n=mY(),Pn(this,sp).set(t,n),Pn(this,iu).set(n,t)),n}deserialize(t,n){var a,r;let i=(a=Pn(this,lp).get(t))==null?void 0:a.deref();return i||(i=(...s)=>{if(!Pn(this,lp).has(t))throw new Error("You attempted to call a function that was already revoked.");return n.call((c,u,d)=>{n.messages.send([fY,c,t,u],d)},s)},(r=Cr(this,QE,hY).call(this,n))==null||r.register(i,t),Pn(this,lp).set(t,new WeakRef(i)),i)}}sp=new WeakMap,iu=new WeakMap,lp=new WeakMap,Zb=new WeakMap,QE=new WeakSet,hY=function(e){let t=Pn(this,Zb).get(e);if(!(typeof FinalizationRegistry>"u"))return t||(t=new FinalizationRegistry(n=>{e.messages.send([pY,n])}),Pn(this,Zb).set(e,t)),t};function yke(e){return e!=null&&(Symbol.asyncIterator in e||Symbol.iterator in e)&&typeof e.next=="function"}function w2(e){if(e==null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t==null||t===Object.prototype}const qx="_@f",S2="_@i";var Np,Cp,Ya,Yb,_s;class wke{constructor(t){hi(this,Ya),hi(this,Np),hi(this,Cp),XE(this,Np,t?.serialize),XE(this,Cp,t?.deserialize)}serialize(t,n,a){return Cr(this,Ya,Yb).call(this,t,n,a)}deserialize(t,n){return Cr(this,Ya,_s).call(this,t,n)}}Np=new WeakMap,Cp=new WeakMap,Ya=new WeakSet,Yb=function(e,t,n,a=new Map,r=!1){if(e==null)return e;if(a.has(e))return a.get(e);if(a.set(e,void 0),typeof e=="object"){if(Pn(this,Np)&&!r){const c=Pn(this,Np).call(this,e,u=>Cr(this,Ya,Yb).call(this,u,t,n,a,!0),t,n);if(c!==void 0)return a.set(e,c),c}if(e[hke])return n?.push(e),a.set(e,e),e;const i=c=>Cr(this,Ya,Yb).call(this,c,t,n,a);if(typeof e[v2]=="function"){const c=e[v2]({serialize:i});return a.set(e,c),c}if(Array.isArray(e)){const c=e.map(u=>i(u));return a.set(e,c),c}if(e instanceof Map){const c=[...e.entries()].map(([d,m])=>[i(d),i(m)]),u=new Map(c);return a.set(e,u),u}if(e instanceof Set){const c=[...e].map(d=>i(d)),u=new Set(c);return a.set(e,u),u}const s=yke(e);if(w2(e)||s){const c={};for(const u of Object.keys(e))c[u]=i(e[u]);return s&&(c.next??(c.next=i(e.next.bind(e))),c.return??(c.return=i(e.return.bind(e))),c.throw??(c.throw=i(e.throw.bind(e))),c[S2]=!0),a.set(e,c),c}}if(typeof e=="function"){const i=t.functions.serialize(e,t,n),s={[qx]:i};return a.set(e,s),s}return a.set(e,e),e},_s=function(e,t,n=!1){if(e==null)return e;if(typeof e=="object"){if(Pn(this,Cp)&&!n){const r=Pn(this,Cp).call(this,e,i=>Cr(this,Ya,_s).call(this,i,t,!0),t);if(r!==void 0)return r}if(e==null)return e;if(Array.isArray(e))return e.map(r=>Cr(this,Ya,_s).call(this,r,t));if(e instanceof Map)return new Map([...e].map(([r,i])=>[Cr(this,Ya,_s).call(this,r,t),Cr(this,Ya,_s).call(this,i,t)]));if(e instanceof Set)return new Set([...e].map(r=>Cr(this,Ya,_s).call(this,r,t)));if(qx in e)return t.functions.deserialize(e[qx],t);if(!w2(e))return e;const a={};for(const r of Object.keys(e))r===S2?a[Symbol.asyncIterator]=()=>a:a[r]=Cr(this,Ya,_s).call(this,e[r],t);return a}return e};var ou,jl,Es,ek,gY,tk,bY;class Ske{constructor(t,{imports:n,exports:a,functions:r=new vke,serialization:i=new wke,signal:s}={}){hi(this,Es),hi(this,ou),hi(this,jl,new Map);var c,u,d,m;this.messages=t,XE(this,ou,s?new gke(s):new AbortController),this.exports=a??{},this.imports=xke(Cr(this,Es,gY).bind(this),n),this.functions=r,this.serialization=i,(u=(c=this.functions).start)==null||u.call(c,this),(m=(d=this.serialization).start)==null||m.call(d,this),this.signal.addEventListener("abort",()=>{for(const h of Pn(this,jl).keys())Cr(this,Es,tk).call(this,h,void 0,new y2);Pn(this,jl).clear()},{once:!0}),t.listen(async h=>{if(!(Array.isArray(h)&&typeof h[0]=="number"))return;const g=h;switch(g[0]){case dY:{const[,v,x,S]=g,y=this.exports[x]??(()=>{throw new Error(`No '${x}' method is exported from this thread`)});await Cr(this,Es,ek).call(this,y,S,(E,_,k)=>{this.messages.send([g2,v,E,_],k)});break}case fY:{const[,v,x,S]=g,y=this.functions.get(x,this)??_ke;await Cr(this,Es,ek).call(this,y,S,(E,_,k)=>{this.messages.send([b2,v,E,_],k)});break}case g2:case b2:{Cr(this,Es,tk).call(this,...g.slice(1));break}case pY:{const v=g[1];this.functions.release(v,this);break}}},{signal:this.signal})}get signal(){return Pn(this,ou).signal}get closed(){return Pn(this,ou).signal.aborted}close(){Pn(this,ou).abort()}call(t,n){if(this.closed)return Promise.reject(new y2);const a=[],r=this.serialization.serialize(n,this,a),i=mY(),s=Cr(this,Es,bY).call(this,i);return t(i,r,a),s}}ou=new WeakMap,jl=new WeakMap,Es=new WeakSet,ek=async function(e,t,n){try{const a=this.functions.call?await this.functions.call(e,t,this):await e(...this.serialization.deserialize(t,this)),r=[],i=this.serialization.serialize(a,this,r);n(i,void 0,r)}catch(a){n(void 0,this.serialization.serialize(a,this))}},gY=function(e){return(...t)=>{try{if(typeof e!="string"&&typeof e!="number")throw new Error(`Can’t call a symbol method on a thread: ${e.toString()}`);return this.call((n,a,r)=>{this.messages.send([dY,n,e,a],r)},t)}catch(n){return Promise.reject(n)}}},tk=function(...e){const t=e[0],n=Pn(this,jl).get(t);n&&(n(...e),Pn(this,jl).delete(t))},bY=function(e){const t=new Promise((n,a)=>{Pn(this,jl).set(e,(r,i,s)=>{s==null?n(this.serialization.deserialize(i,this)):a(this.serialization.deserialize(s,this))})});return Object.defineProperty(t,Symbol.asyncIterator,{async*value(){const n=await t;Object.defineProperty(n,Symbol.asyncIterator,{value:()=>n}),yield*n}}),t};function xke(e,t){let n;if(t==null){if(typeof Proxy!="function")throw new Error("You must pass an array of callable methods in environments without Proxies.");const a=new Map;n=new Proxy({},{get(r,i){if(a.has(i))return a.get(i);const s=e(i);return a.set(i,s),s}})}else{n={};for(const a of t)Object.defineProperty(n,a,{value:e(a),writable:!1,configurable:!0,enumerable:!0})}return n}function _ke(){throw new Error("You attempted to call a function that is not stored. It may have already been released.")}const Eke="quilt.threads.ping",x2="quilt.threads.pong";function kke(e,{targetOrigin:t="*"}={}){let n=!1;const a=function(i,s){e.postMessage(i,t,s)},r=new Promise(i=>{const s=new AbortController;globalThis.window.addEventListener("message",c=>{c.source===e&&c.data===x2&&(n=!0,s.abort(),i())},{signal:s.signal}),s.signal.addEventListener("abort",()=>i(),{once:!0}),a(Eke)});return{send(i,s){return n?a(i,s):r.then(()=>{if(n)return a(i,s)})},listen(i,{signal:s}){self.addEventListener("message",c=>{c.source===e&&c.data!==x2&&i(c.data)},{signal:s})}}}class Tke extends Ske{constructor(t,{targetOrigin:n="*",...a}={}){super(kke(t.contentWindow,{targetOrigin:n}),a),this.iframe=t}}const vY=ue.forwardRef(({content:e,children:t,...n},a)=>f.jsx("span",{ref:a,...n,children:e||t}));vY.displayName="UIText";const yY=ue.forwardRef(({label:e,onPress:t,onClick:n,children:a,...r},i)=>f.jsx("button",{ref:i,onClick:s=>{t&&t(),n&&n(s)},style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},...r,children:e||a}));yY.displayName="UIButton";const wY=ue.forwardRef(({direction:e="vertical",spacing:t="8",align:n="stretch",justify:a="flex-start",children:r,...i},s)=>f.jsx("div",{ref:s,style:{display:"flex",flexDirection:e==="horizontal"?"row":"column",gap:`${t}px`,alignItems:n,justifyContent:a},...i,children:r}));wY.displayName="UIStack";const SY=ue.forwardRef(({src:e,alt:t,width:n,height:a,children:r,...i},s)=>f.jsx("img",{ref:s,src:e,alt:t,width:n,height:a,style:{maxWidth:"100%",height:"auto",borderRadius:"8px",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.1)"},...i}));SY.displayName="UIImage";const yD={name:"basic",elements:[{tagName:"ui-text",component:vY,propMapping:{content:"content"},eventMapping:{}},{tagName:"ui-button",component:yY,propMapping:{label:"label"},eventMapping:{press:"onPress"}},{tagName:"ui-stack",component:wY,propMapping:{direction:"direction",spacing:"spacing",align:"align",justify:"justify"},eventMapping:{}},{tagName:"ui-image",component:SY,propMapping:{src:"src",alt:"alt",width:"width",height:"height"},eventMapping:{}}]},Nke=({receiver:e})=>{const t=w.useRef(null);return w.useEffect(()=>{if(t.current)return e.connect(t.current),()=>{e.disconnect()}},[e]),f.jsx("div",{ref:t,"data-testid":"standard-dom-renderer-container"})},Cke=({resource:e,library:t,remoteElements:n=[],onUIAction:a})=>{const r=w.useRef(null),i=w.useRef(null),[s,c]=w.useState(null),u=w.useMemo(()=>(e.mimeType||"").includes("framework=react")?"react":"webcomponents",[e.mimeType]),d=`${t?.name}-${u}`,{receiver:m,components:h}=w.useMemo(()=>{switch(u){case"react":{const v=new ike,x=t||yD,S=new Map;return x&&x.elements.forEach(y=>{const E=dke(y.component);S.set(y.tagName,E)}),{receiver:v,components:S}}case"webcomponents":default:return{receiver:new oke,components:null}}},[e,t,n]);w.useEffect(()=>{function v(x){var S;if(r.current&&x.source===r.current.contentWindow){const y=x.data;if(!y)return;(S=a?.(y))==null||S.catch(E=>{console.error("Error handling UI action result in RemoteDOMResourceRenderer:",E)})}}return window.addEventListener("message",v),()=>window.removeEventListener("message",v)},[a]),w.useEffect(()=>{const v=i.current;return i.current=null,()=>{v?.close()}},[d]);const g=()=>{const v=r.current;if(!v||i.current)return;const x=new Tke(v);i.current=x;const{code:S,error:y}=qEe(e);if(y){c(y);return}if(S&&m!=null&&m.connection){const E={code:S,remoteElements:n,useReactRenderer:u==="react",componentLibrary:t?.name};x.imports.render(E,m.connection).catch(_=>console.error("Error calling remote render:",_))}};return s?f.jsx("p",{className:"text-red-500",children:s}):f.jsxs(f.Fragment,{children:[f.jsx("iframe",{ref:r,srcDoc:mke,sandbox:"allow-scripts",style:{display:"none"},title:"Remote DOM Sandbox",onLoad:g},d),u==="react"&&h?f.jsx(pke,{receiver:m,components:h}):f.jsx(Nke,{receiver:m})]})};function Rke(e){var t;if(e.contentType)return e.contentType;if(e.mimeType==="text/html")return"rawHtml";if(e.mimeType==="text/uri-list")return"externalUrl";if((t=e.mimeType)!=null&&t.startsWith("application/vnd.mcp-ui.remote-dom"))return"remoteDom"}const wD=e=>{const{resource:t,onUIAction:n,supportedContentTypes:a,htmlProps:r,remoteDomProps:i}=e,s=Rke(t);if(a&&s&&!a.includes(s))return f.jsxs("p",{className:"text-red-500",children:["Unsupported content type: ",s,"."]});switch(s){case"rawHtml":case"externalUrl":return f.jsx(iY,{resource:t,onUIAction:n,...r});case"remoteDom":return f.jsx(Cke,{resource:t,onUIAction:n,library:i?.library||yD,...i});default:return f.jsx("p",{className:"text-red-500",children:"Unsupported resource type."})}};wD.displayName="UIResourceRenderer";const Ake={tagName:"ui-button",remoteAttributes:["label"],remoteEvents:["click","press"]},Ike={tagName:"ui-text",remoteAttributes:["content"]},Oke={tagName:"ui-stack",remoteAttributes:["direction","spacing","align","justify"]},Dke={tagName:"ui-image",remoteAttributes:["src","alt","width","height"]},jke=w.memo(({resource:e})=>{const t=async n=>(n.type==="tool"||n.type==="prompt"||(n.type==="link"?n.payload.url&&window.open(n.payload.url,"_blank"):n.type==="intent"||n.type),{status:"Action received"});return e.uri?.startsWith("ui://")?f.jsx("div",{className:"my-4 p-0 border h-[350px] rounded-2xl border-zinc-200 overflow-hidden bg-card",children:f.jsx(wD,{resource:e,onUIAction:t,htmlProps:{style:{maxWidth:"100%",height:"100%",overflow:"auto"},autoResizeIframe:!0,sandboxPermissions:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"}})}):null});function _2({toolName:e,toolArgs:t,result:n,serverId:a,readResource:r,toolMeta:i}){const[s,c]=w.useState(null);w.useEffect(()=>{console.log("[ToolResultRenderer] Rendering:",{toolName:e,hasToolMeta:!!i,outputTemplate:i?.["openai/outputTemplate"],hasResult:!!n,hasServerId:!!a,hasReadResource:!!r})},[e,i,n,a,r]);const u=w.useMemo(()=>{if(typeof n=="string")try{return JSON.parse(n)}catch(v){return console.error("[ToolResultRenderer] Failed to parse result:",v),n}return n},[n]),d=w.useMemo(()=>!!i?.["openai/outputTemplate"],[i]),m=w.useMemo(()=>!!(u?.content&&Array.isArray(u.content)&&u.content.some(v=>v.type==="resource"&&v.resource?.uri?.startsWith("ui://")&&v.resource?.mimeType==="text/html+skybridge")),[u]),h=w.useMemo(()=>m&&u.content.find(x=>x.type==="resource"&&x.resource?.uri?.startsWith("ui://")&&x.resource?.mimeType==="text/html+skybridge")?.resource||null,[m,u]);if(w.useEffect(()=>{if(h){c(h);return}if(d&&i&&r){const v=i["openai/outputTemplate"];console.log("[ToolResultRenderer] Fetching resource for Apps SDK tool:",v),r(v).then(x=>{console.log("[ToolResultRenderer] Resource fetched:",x),x?.contents&&Array.isArray(x.contents)&&x.contents.length>0?c(x.contents[0]):console.warn("[ToolResultRenderer] No contents in fetched resource:",x)}).catch(x=>{console.error("[ToolResultRenderer] Failed to fetch resource:",x)})}},[h,d,i,r]),(d||m)&&s&&a&&r)return f.jsx(mD,{componentUrl:s.uri,toolName:e,toolArgs:t,toolResult:u,serverId:a,readResource:r,noWrapper:!0,className:"my-4",showConsole:!1});if((d||m)&&!s)return f.jsx("div",{className:"flex items-center justify-center w-full h-[200px] rounded border",children:f.jsx(ki,{className:"size-5"})});if(d&&(!a||!r))return console.error("[ToolResultRenderer] Apps SDK tool but missing serverId or readResource:",{toolName:e,hasServerId:!!a,hasReadResource:!!r}),f.jsx("div",{className:"my-4 p-4 bg-red-50/30 dark:bg-red-950/20 border border-red-200/50 dark:border-red-800/50 rounded-lg",children:f.jsx("p",{className:"text-sm text-red-600 dark:text-red-400",children:"Cannot render widget: Missing required props (serverId or readResource)"})});const g=[];if(u?.content&&Array.isArray(u.content))for(const v of u.content)v.type==="resource"&&v.resource?.uri?.startsWith("ui://")&&v.resource?.mimeType!=="text/html+skybridge"&&g.push(v.resource);return g.length>0?f.jsx(f.Fragment,{children:g.map(v=>f.jsx(jke,{resource:v},`${e}-mcp-ui-${v.uri}`))}):(console.log("[ToolResultRenderer] Not rendering (no UI resources found):",{toolName:e,isAppsSdkTool:d,hasAppsSdkComponent:m,hasResourceData:!!s,contentLength:u?.content?.length}),null)}function $ke({content:e,timestamp:t}){return!e||e.length===0?null:f.jsx("div",{className:"flex items-start gap-3 justify-end group/user-message",children:f.jsxs("div",{className:"flex-1 min-w-0 flex flex-col items-end",children:[f.jsx("div",{className:"bg-zinc-200 dark:bg-zinc-800 text-primary rounded-3xl px-4 py-2 max-w-[80%] break-words",children:f.jsx("p",{className:"text-base leading-7 font-sans text-start break-words",children:e})}),t&&f.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:new Date(t).toLocaleTimeString()})]})})}const Lke=w.memo(({messages:e,isLoading:t,serverId:n,readResource:a,tools:r})=>{const i=w.useRef(null),s=d=>r?.find(h=>h.name===d)?._meta;w.useEffect(()=>{e.length>0&&i.current&&i.current.scrollIntoView({behavior:t?"auto":"smooth",block:"start"})},[e.length,t]);const c=t&&(()=>{if(e.length===0)return!0;const d=e[e.length-1];if(d.role==="user")return!0;if(d.role==="assistant"){const m=typeof d.content=="string"?d.content:Array.isArray(d.content)?d.content.map(g=>typeof g=="string"?g:g.text||JSON.stringify(g)).join(""):JSON.stringify(d.content);return!(m&&m.trim().length>0)}return!1})(),u=d=>{if(!t)return!1;const m=e[e.length-1];return d.id===m.id&&m.role==="assistant"};return f.jsxs("div",{className:"space-y-6 max-w-3xl mx-auto px-2",children:[e.map(d=>{const m=typeof d.content=="string"?d.content:Array.isArray(d.content)?d.content.map(h=>typeof h=="string"?h:h.text||JSON.stringify(h)).join(""):JSON.stringify(d.content);return d.role==="user"?f.jsx($ke,{content:m,timestamp:d.timestamp},d.id):d.role==="assistant"?f.jsx("div",{className:"space-y-4",children:d.parts&&d.parts.length>0?d.parts.map((h,g)=>{const v=h.type==="text"?`${d.id}-text-${g}-${h.text?.slice(0,20)}`:`${d.id}-tool-${h.toolInvocation?.toolName}-${g}`;return h.type==="text"?f.jsx(o2,{content:h.text||"",timestamp:g===d.parts.length-1?d.timestamp:void 0,_isStreaming:u(d)},v):h.type==="tool-invocation"&&h.toolInvocation?f.jsxs("div",{children:[f.jsx(s2,{toolName:h.toolInvocation.toolName,args:h.toolInvocation.args,result:h.toolInvocation.result,state:h.toolInvocation.result?"result":"call"}),h.toolInvocation.result&&f.jsx(_2,{toolName:h.toolInvocation.toolName,toolArgs:h.toolInvocation.args,result:h.toolInvocation.result,serverId:n,readResource:a,toolMeta:s(h.toolInvocation.toolName)})]},v):null}):f.jsxs(f.Fragment,{children:[f.jsx(o2,{content:m,timestamp:d.timestamp,_isStreaming:u(d)}),d.toolCalls&&d.toolCalls.length>0&&f.jsx("div",{className:"space-y-2",children:d.toolCalls.map(h=>{const g=`${d.id}-${h.toolName}-${JSON.stringify(h.args).slice(0,50)}`;return f.jsxs("div",{children:[f.jsx(s2,{toolName:h.toolName,args:h.args,result:h.result,state:h.result?"result":"call"}),h.result&&f.jsx(_2,{toolName:h.toolName,toolArgs:h.args,result:h.result,serverId:n,readResource:a,toolMeta:s(h.toolName)})]},g)})})]})},d.id):null}),c&&f.jsx("div",{className:"flex items-start gap-3",children:f.jsx("div",{className:"flex-1",children:f.jsx("div",{className:"rounded-lg p-4 max-w-fit",children:f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("span",{className:"text-sm",children:f.jsx(txe,{duration:2,spread:1,children:"Thinking..."})})})})})}),f.jsx("div",{ref:i})]})});function xY(e){let t=0;for(let n=0;n<e.length;n++){const a=e.charCodeAt(n);t=(t<<5)-t+a,t=t&t}return Math.abs(t).toString(16)}function Mke({mcpServerUrl:e,llmConfig:t,authConfig:n,isConnected:a}){const[r,i]=w.useState([]),[s,c]=w.useState(!1),u=w.useCallback(async m=>{if(!m.trim()||!t||!a)return;const h={id:`user-${Date.now()}`,role:"user",content:m.trim(),timestamp:Date.now()};i(g=>[...g,h]),c(!0);try{let g=n;if(n?.type==="oauth")try{const C="mcp:auth",R=xY(e),I=`${C}_${R}_tokens`,A=localStorage.getItem(I);if(A){const O=JSON.parse(A);g={...n,oauthTokens:O}}else console.warn("No OAuth tokens found in localStorage for key:",I)}catch(C){console.warn("Failed to retrieve OAuth tokens:",C)}const v=await fetch("/inspector/api/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mcpServerUrl:e,llmConfig:t,authConfig:g,messages:[...r,h].map(C=>({role:C.role,content:C.content}))})});if(!v.ok)throw new Error(`HTTP error! status: ${v.status}`);const x=`assistant-${Date.now()}`;let S="";const y=[];i(C=>[...C,{id:x,role:"assistant",content:"",timestamp:Date.now(),parts:[]}]);const E=v.body?.getReader(),_=new TextDecoder;if(!E)throw new Error("No response body");let k="";for(;;){const{done:C,value:R}=await E.read();if(C)break;k+=_.decode(R,{stream:!0});const I=k.split(`
1660
- `);k=I.pop()||"";for(const A of I)if(A.trim()&&A.startsWith("data: "))try{const O=JSON.parse(A.slice(6));if(console.log("[Client received event]",O.type,O.toolName||O.content?.slice?.(0,30)),O.type==="message")console.log("[Message started]",O.id);else if(O.type==="text"){S+=O.content;const M=y[y.length-1];M&&M.type==="text"?M.text=S:y.push({type:"text",text:S}),console.log("[Parts after text]",y.length,"parts, text length:",S.length),i(P=>P.map(B=>B.id===x?{...B,parts:[...y]}:B))}else if(O.type==="tool-call")S&&(S=""),y.push({type:"tool-invocation",toolInvocation:{toolName:O.toolName,args:O.args,state:"pending"}}),console.log("[Parts after tool-call]",y.length,"parts, tool:",O.toolName),i(M=>M.map(P=>P.id===x?{...P,parts:[...y]}:P));else if(O.type==="tool-result"){const M=y.find(P=>P.type==="tool-invocation"&&P.toolInvocation?.toolName===O.toolName&&!P.toolInvocation?.result);M&&M.toolInvocation?(M.toolInvocation.result=O.result,M.toolInvocation.state="result",console.log("[Parts after tool-result]",y.length,"parts, updated:",O.toolName),i(P=>P.map(B=>B.id===x?{...B,parts:[...y]}:B))):console.warn("[tool-result] Could not find matching tool part for",O.toolName)}else if(O.type==="done")console.log("[Done] Final parts:",y.length),i(M=>M.map(P=>P.id===x?{...P,parts:[...y],content:""}:P));else if(O.type==="error")throw new Error(O.message||"Streaming error")}catch(O){console.error("Failed to parse streaming event:",O,A)}}}catch(g){let v="Unknown error occurred";if(g instanceof Error){v=g.message;const S=g;S.status&&(v=`HTTP ${S.status}: ${v}`),(S.code===401||v.includes("401")||v.includes("Unauthorized"))&&(v="Authentication failed (401). Check your Authorization header in the connection settings.")}const x={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${v}`,timestamp:Date.now()};i(S=>[...S,x])}finally{c(!1)}},[t,a,e,r,n]),d=w.useCallback(()=>{i([])},[]);return{messages:r,isLoading:s,sendMessage:u,clearMessages:d}}function Pke({connection:e,llmConfig:t,isConnected:n,readResource:a}){const[r,i]=w.useState([]),[s,c]=w.useState(!1),u=w.useRef(null),d=w.useRef(null),m=w.useRef(null),h=w.useCallback(async v=>{if(!v.trim()||!t||!n)return;const x={id:`user-${Date.now()}`,role:"user",content:v.trim(),timestamp:Date.now()};i(E=>[...E,x]),c(!0),u.current=new AbortController;const S=Date.now();let y=0;try{const E=`assistant-${Date.now()}`;let _="";const k=[];if(i(C=>[...C,{id:E,role:"assistant",content:"",timestamp:Date.now(),parts:[]}]),!m.current||m.current.provider!==t.provider||m.current.model!==t.model||m.current.apiKey!==t.apiKey){let C;if(t.provider==="openai"){const{ChatOpenAI:R}=await Jn(async()=>{const{ChatOpenAI:I}=await import("./index-BWMAhNJO.js");return{ChatOpenAI:I}},__vite__mapDeps([6,7,8,2,9,10,11]));C=new R({model:t.model,apiKey:t.apiKey})}else if(t.provider==="anthropic"){const{ChatAnthropic:R}=await Jn(async()=>{const{ChatAnthropic:I}=await import("./index-CmdaC4jK.js");return{ChatAnthropic:I}},__vite__mapDeps([12,8,7,2,11]));C=new R({model:t.model,apiKey:t.apiKey})}else if(t.provider==="google"){const{ChatGoogleGenerativeAI:R}=await Jn(async()=>{const{ChatGoogleGenerativeAI:I}=await import("./index-BMVGFw1P.js");return{ChatGoogleGenerativeAI:I}},__vite__mapDeps([13,8,7,2,10]));C=new R({model:t.model,apiKey:t.apiKey})}else throw new Error(`Unsupported LLM provider: ${t.provider}`);m.current={instance:C,provider:t.provider,model:t.model,apiKey:t.apiKey}}if(!d.current||d.current.llm!==m.current.instance){const{MCPAgent:C}=await Jn(async()=>{const{MCPAgent:R}=await import("./browser-gXOjyGah.js");return{MCPAgent:R}},__vite__mapDeps([14,4,5,3,11,7,8,2,10,9]));d.current=new C({llm:m.current.instance,client:e.client,memoryEnabled:!0,systemPrompt:"You are a helpful assistant with access to MCP tools, prompts, and resources. Help users interact with the MCP server."}),await d.current.initialize()}else console.log("[useChatMessagesClientSide] Reusing existing agent. History length:",d.current.conversationHistory?.length);for await(const C of d.current.streamEvents(v,10,!1,void 0)){if(u.current?.signal.aborted)break;if(C.event==="on_chat_model_stream"&&C.data?.chunk?.text){const R=C.data.chunk.text;if(typeof R=="string"&&R.length>0){_+=R;const I=k[k.length-1];I&&I.type==="text"?I.text=_:k.push({type:"text",text:_}),i(A=>A.map(O=>O.id===E?{...O,parts:[...k]}:O))}}else if(C.event==="on_tool_start"){_&&(_="");let R={};C.data?.input?R=C.data.input:C.data?.tool_input?R=C.data.tool_input:C.data&&(R=C.data),console.log("[useChatMessagesClientSide] on_tool_start:",{toolName:C.name,eventData:C.data,extractedArgs:R}),y++,k.push({type:"tool-invocation",toolInvocation:{toolName:C.name||"unknown",args:R,state:"pending"}}),i(I=>I.map(A=>A.id===E?{...A,parts:[...k]}:A))}else if(C.event==="on_tool_end"){const R=k.find(I=>I.type==="tool-invocation"&&I.toolInvocation?.toolName===C.name&&!I.toolInvocation?.result);if(console.log("[useChatMessagesClientSide] on_tool_end event:",{toolName:C.name,hasToolPart:!!R,output:C.data?.output}),R&&R.toolInvocation){let I=C.data?.output;if(I?.kwargs?.content&&typeof I.kwargs.content=="string")try{I=JSON.parse(I.kwargs.content)}catch(O){console.warn("[useChatMessagesClientSide] Failed to parse kwargs.content:",O),I=I.kwargs.content}else if(I?.content&&typeof I.content=="string")try{I=JSON.parse(I.content)}catch{I=I.content}R.toolInvocation.result=I,R.toolInvocation.state="result";const A=I?._meta?.["openai/outputTemplate"];if(console.log("[useChatMessagesClientSide] Tool result:",{toolName:C.name,hasMeta:!!I?._meta,hasStructuredContent:!!I?.structuredContent,appsSdkUri:A}),A&&typeof A=="string"&&a){console.log("[useChatMessagesClientSide] Detected Apps SDK component, fetching resource:",A);try{const O=await a(A);console.log("[useChatMessagesClientSide] Resource fetched:",O);const M=I?.structuredContent||null;if(O?.contents&&Array.isArray(O.contents)){const P=O.contents.map(K=>({type:"resource",resource:K}));console.log("[useChatMessagesClientSide] Created MCP resources:",P);const B={...I,content:[...I.content||[],...P],structuredContent:M};R.toolInvocation.result=B,console.log("[useChatMessagesClientSide] Updated result with resources")}else console.warn("[useChatMessagesClientSide] No contents in resourceData:",O)}catch(O){console.error("Failed to fetch Apps SDK resource:",O)}}i(O=>O.map(M=>M.id===E?{...M,parts:[...k]}:M))}}}i(C=>C.map(R=>R.id===E?{...R,parts:[...k],content:""}:R)),t&&vr.getInstance().capture(new QU({serverId:e.url,provider:t.provider,model:t.model,messageCount:r.length+1,toolCallsCount:y,success:!0,executionMode:"client-side",duration:Date.now()-S})).catch(()=>{})}catch(E){console.error("Client-side agent error:",E);let _="Unknown error occurred";if(E instanceof Error){_=E.message;const C=E;C.status&&(_=`HTTP ${C.status}: ${_}`),(C.code===401||_.includes("401")||_.includes("Unauthorized"))&&(_="Authentication failed (401). Check your Authorization header in the connection settings.")}t&&vr.getInstance().capture(new QU({serverId:e.url,provider:t.provider,model:t.model,messageCount:r.length+1,toolCallsCount:y,success:!1,executionMode:"client-side",duration:Date.now()-S,error:_})).catch(()=>{});const k={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${_}`,timestamp:Date.now()};i(C=>[...C,k])}finally{c(!1),u.current=null}},[e,t,n,r,a]),g=w.useCallback(()=>{i([]),d.current&&d.current.clearConversationHistory()},[]);return{messages:r,isLoading:s,sendMessage:h,clearMessages:g}}const E2={openai:"gpt-4o",anthropic:"claude-haiku-4-5-20251001",google:"gemini-2.5-flash"};function _Y({mcpServerUrl:e}){const[t,n]=w.useState(null),[a,r]=w.useState(null),[i,s]=w.useState(!1),[c,u]=w.useState("openai"),[d,m]=w.useState(""),[h,g]=w.useState(E2.openai),v=w.useCallback(()=>{const M=localStorage.getItem("mcp-inspector-api-keys");if(M)try{return JSON.parse(M)}catch(P){return console.error("Failed to load API keys:",P),{}}return{}},[]),x=w.useCallback(M=>{localStorage.setItem("mcp-inspector-api-keys",JSON.stringify(M))},[]),[S,y]=w.useState("none"),[E,_]=w.useState(""),[k,C]=w.useState(""),[R,I]=w.useState("");w.useEffect(()=>{const M=localStorage.getItem("mcp-inspector-llm-config"),P=v();if(M)try{const B=JSON.parse(M);n(B),u(B.provider),m(P[B.provider]||B.apiKey||""),g(B.model)}catch(B){console.error("Failed to load LLM config:",B)}},[v]),w.useEffect(()=>{const M=localStorage.getItem("mcp-inspector-auth-config");if(M)try{const P=JSON.parse(M);r(P),y(P.type),P.username&&_(P.username),P.password&&C(P.password),P.token&&I(P.token)}catch(P){console.error("Failed to load auth config:",P)}else try{const P="mcp:auth",B=xY(e),K=`${P}_${B}_tokens`;localStorage.getItem(K)&&(r({type:"oauth"}),y("oauth"))}catch(P){console.error("Failed to check for OAuth tokens:",P)}},[e]),w.useEffect(()=>{g(E2[c]);const M=v();m(M[c]||"")},[c,v]);const A=w.useCallback(()=>{if(!d.trim())return;const M=v();M[c]=d,x(M);const P={provider:c,apiKey:d,model:h},B={type:S,...S==="basic"&&{username:E.trim(),password:k.trim()},...S==="bearer"&&{token:R.trim()}};n(P),r(B),localStorage.setItem("mcp-inspector-llm-config",JSON.stringify(P)),localStorage.setItem("mcp-inspector-auth-config",JSON.stringify(B)),s(!1)},[c,d,h,S,E,k,R,v,x]),O=w.useCallback(()=>{n(null),r(null);const M=v();delete M[c],x(M),m(""),_(""),C(""),I(""),y("none"),localStorage.removeItem("mcp-inspector-llm-config"),localStorage.removeItem("mcp-inspector-auth-config")},[c,v,x]);return{llmConfig:t,authConfig:a,configDialogOpen:i,setConfigDialogOpen:s,tempProvider:c,setTempProvider:u,tempApiKey:d,setTempApiKey:m,tempModel:h,setTempModel:g,tempAuthType:S,saveLLMConfig:A,clearConfig:O}}function Uke({connection:e,isConnected:t,useClientSide:n=!0,readResource:a}){const[r,i]=w.useState(""),s=w.useRef(null),{llmConfig:c,authConfig:u,configDialogOpen:d,setConfigDialogOpen:m,tempProvider:h,setTempProvider:g,tempApiKey:v,setTempApiKey:x,tempModel:S,setTempModel:y,saveLLMConfig:E,clearConfig:_}=_Y({mcpServerUrl:e.url}),k={connection:e,llmConfig:c,isConnected:t,readResource:a},C=Mke({mcpServerUrl:e.url,llmConfig:c,authConfig:u,isConnected:t}),R=Pke(k),{messages:I,isLoading:A,sendMessage:O,clearMessages:M}=n?R:C;SK({onNewChat:M}),w.useEffect(()=>{c&&I.length===0&&s.current&&s.current.focus()},[c,I.length]),w.useEffect(()=>{!A&&I.length>0&&s.current&&s.current.focus()},[A,I.length]);const P=w.useCallback(()=>{r.trim()&&(O(r),i(""))},[r,O]),B=w.useCallback(ee=>{ee.key==="Enter"&&!ee.shiftKey&&(ee.preventDefault(),P())},[P]),K=w.useCallback(()=>{_(),M()},[_,M]);return c&&I.length===0?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsx("div",{className:"absolute top-4 right-4 z-10",children:f.jsx(NE,{open:d,onOpenChange:m,tempProvider:h,tempModel:S,tempApiKey:v,onProviderChange:g,onModelChange:y,onApiKeyChange:x,onSave:E,onClear:K,showClearButton:!0,buttonLabel:"Change API Key"})}),f.jsx(QSe,{mcpServerUrl:e.url,inputValue:r,isConnected:t,isLoading:A,textareaRef:s,llmConfig:c,onInputChange:i,onKeyDown:B,onSubmit:ee=>{ee.preventDefault(),P()},onConfigDialogOpenChange:m})]}):f.jsxs("div",{className:"flex flex-col h-full relative",children:[f.jsx(qSe,{llmConfig:c,hasMessages:I.length>0,configDialogOpen:d,onConfigDialogOpenChange:m,onClearChat:M,tempProvider:h,tempModel:S,tempApiKey:v,onProviderChange:g,onModelChange:y,onApiKeyChange:x,onSaveConfig:E,onClearConfig:K}),f.jsx("div",{className:"flex-1 overflow-y-auto p-2 sm:p-4 pt-[80px] sm:pt-[100px]",children:c?f.jsx(Lke,{messages:I,isLoading:A,serverId:e.url,readResource:a,tools:e.tools}):f.jsx(exe,{onConfigureClick:()=>m(!0)})}),c&&f.jsx(XSe,{inputValue:r,isConnected:t,isLoading:A,textareaRef:s,onInputChange:i,onKeyDown:B,onSendMessage:P})]})}const Ew=w.createContext(null);Ew.displayName="PanelGroupContext";const Zn={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},SD=10,Ul=w.useLayoutEffect,k2=kd.useId,zke=typeof k2=="function"?k2:()=>null;let Fke=0;function xD(e=null){const t=zke(),n=w.useRef(e||t||null);return n.current===null&&(n.current=""+Fke++),e??n.current}function EY({children:e,className:t="",collapsedSize:n,collapsible:a,defaultSize:r,forwardedRef:i,id:s,maxSize:c,minSize:u,onCollapse:d,onExpand:m,onResize:h,order:g,style:v,tagName:x="div",...S}){const y=w.useContext(Ew);if(y===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:E,expandPanel:_,getPanelSize:k,getPanelStyle:C,groupId:R,isPanelCollapsed:I,reevaluatePanelConstraints:A,registerPanel:O,resizePanel:M,unregisterPanel:P}=y,B=xD(s),K=w.useRef({callbacks:{onCollapse:d,onExpand:m,onResize:h},constraints:{collapsedSize:n,collapsible:a,defaultSize:r,maxSize:c,minSize:u},id:B,idIsFromProps:s!==void 0,order:g});w.useRef({didLogMissingDefaultSizeWarning:!1}),Ul(()=>{const{callbacks:te,constraints:ae}=K.current,H={...ae};K.current.id=B,K.current.idIsFromProps=s!==void 0,K.current.order=g,te.onCollapse=d,te.onExpand=m,te.onResize=h,ae.collapsedSize=n,ae.collapsible=a,ae.defaultSize=r,ae.maxSize=c,ae.minSize=u,(H.collapsedSize!==ae.collapsedSize||H.collapsible!==ae.collapsible||H.maxSize!==ae.maxSize||H.minSize!==ae.minSize)&&A(K.current,H)}),Ul(()=>{const te=K.current;return O(te),()=>{P(te)}},[g,B,O,P]),w.useImperativeHandle(i,()=>({collapse:()=>{E(K.current)},expand:te=>{_(K.current,te)},getId(){return B},getSize(){return k(K.current)},isCollapsed(){return I(K.current)},isExpanded(){return!I(K.current)},resize:te=>{M(K.current,te)}}),[E,_,k,I,B,M]);const ee=C(K.current,r);return w.createElement(x,{...S,children:e,className:t,id:B,style:{...ee,...v},[Zn.groupId]:R,[Zn.panel]:"",[Zn.panelCollapsible]:a||void 0,[Zn.panelId]:B,[Zn.panelSize]:parseFloat(""+ee.flexGrow).toFixed(1)})}const kY=w.forwardRef((e,t)=>w.createElement(EY,{...e,forwardedRef:t}));EY.displayName="Panel";kY.displayName="forwardRef(Panel)";let nk=null,qb=-1,Rs=null;function Bke(e,t,n){const a=(t&AY)!==0,r=(t&IY)!==0,i=(t&OY)!==0,s=(t&DY)!==0;if(t){if(a)return i?"se-resize":s?"ne-resize":"e-resize";if(r)return i?"sw-resize":s?"nw-resize":"w-resize";if(i)return"s-resize";if(s)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function Hke(){Rs!==null&&(document.head.removeChild(Rs),nk=null,Rs=null,qb=-1)}function Xx(e,t,n){var a,r;const i=Bke(e,t);if(nk!==i){if(nk=i,Rs===null&&(Rs=document.createElement("style"),document.head.appendChild(Rs)),qb>=0){var s;(s=Rs.sheet)===null||s===void 0||s.removeRule(qb)}qb=(a=(r=Rs.sheet)===null||r===void 0?void 0:r.insertRule(`*{cursor: ${i} !important;}`))!==null&&a!==void 0?a:-1}}function TY(e){return e.type==="keydown"}function NY(e){return e.type.startsWith("pointer")}function CY(e){return e.type.startsWith("mouse")}function kw(e){if(NY(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(CY(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function Vke(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function Gke(e,t,n){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function Wke(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:C2(e),b:C2(t)};let a;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),a=e;It(a,"Stacking order can only be calculated for elements with a common ancestor");const r={a:N2(T2(n.a)),b:N2(T2(n.b))};if(r.a===r.b){const i=a.childNodes,s={a:n.a.at(-1),b:n.b.at(-1)};let c=i.length;for(;c--;){const u=i[c];if(u===s.a)return 1;if(u===s.b)return-1}}return Math.sign(r.a-r.b)}const Kke=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function Zke(e){var t;const n=getComputedStyle((t=RY(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function Yke(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||Zke(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||Kke.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function T2(e){let t=e.length;for(;t--;){const n=e[t];if(It(n,"Missing node"),Yke(n))return n}return null}function N2(e){return e&&Number(getComputedStyle(e).zIndex)||0}function C2(e){const t=[];for(;e;)t.push(e),e=RY(e);return t}function RY(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const AY=1,IY=2,OY=4,DY=8,qke=Vke()==="coarse";let wi=[],Cu=!1,As=new Map,Tw=new Map;const sm=new Set;function Xke(e,t,n,a,r){var i;const{ownerDocument:s}=t,c={direction:n,element:t,hitAreaMargins:a,setResizeHandlerState:r},u=(i=As.get(s))!==null&&i!==void 0?i:0;return As.set(s,u+1),sm.add(c),Qv(),function(){var m;Tw.delete(e),sm.delete(c);const h=(m=As.get(s))!==null&&m!==void 0?m:1;if(As.set(s,h-1),Qv(),h===1&&As.delete(s),wi.includes(c)){const g=wi.indexOf(c);g>=0&&wi.splice(g,1),Nw(),r("up",!0,null)}}}function Jke(e){const{target:t}=e,{x:n,y:a}=kw(e);Cu=!0,_D({target:t,x:n,y:a}),Qv(),wi.length>0&&(ey("down",e),Nw(),e.preventDefault(),jY(t)||e.stopImmediatePropagation())}function Jx(e){const{x:t,y:n}=kw(e);if(Cu&&e.type!=="pointerleave"&&e.buttons===0&&(Cu=!1,ey("up",e)),!Cu){const{target:a}=e;_D({target:a,x:t,y:n})}ey("move",e),Nw(),wi.length>0&&e.preventDefault()}function Qx(e){const{target:t}=e,{x:n,y:a}=kw(e);Tw.clear(),Cu=!1,wi.length>0&&(e.preventDefault(),jY(t)||e.stopImmediatePropagation()),ey("up",e),_D({target:t,x:n,y:a}),Nw(),Qv()}function jY(e){let t=e;for(;t;){if(t.hasAttribute(Zn.resizeHandle))return!0;t=t.parentElement}return!1}function _D({target:e,x:t,y:n}){wi.splice(0);let a=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(a=e),sm.forEach(r=>{const{element:i,hitAreaMargins:s}=r,c=i.getBoundingClientRect(),{bottom:u,left:d,right:m,top:h}=c,g=qke?s.coarse:s.fine;if(t>=d-g&&t<=m+g&&n>=h-g&&n<=u+g){if(a!==null&&document.contains(a)&&i!==a&&!i.contains(a)&&!a.contains(i)&&Wke(a,i)>0){let x=a,S=!1;for(;x&&!x.contains(i);){if(Gke(x.getBoundingClientRect(),c)){S=!0;break}x=x.parentElement}if(S)return}wi.push(r)}})}function e_(e,t){Tw.set(e,t)}function Nw(){let e=!1,t=!1;wi.forEach(a=>{const{direction:r}=a;r==="horizontal"?e=!0:t=!0});let n=0;Tw.forEach(a=>{n|=a}),e&&t?Xx("intersection",n):e?Xx("horizontal",n):t?Xx("vertical",n):Hke()}let t_;function Qv(){var e;(e=t_)===null||e===void 0||e.abort(),t_=new AbortController;const t={capture:!0,signal:t_.signal};sm.size&&(Cu?(wi.length>0&&As.forEach((n,a)=>{const{body:r}=a;n>0&&(r.addEventListener("contextmenu",Qx,t),r.addEventListener("pointerleave",Jx,t),r.addEventListener("pointermove",Jx,t))}),As.forEach((n,a)=>{const{body:r}=a;r.addEventListener("pointerup",Qx,t),r.addEventListener("pointercancel",Qx,t)})):As.forEach((n,a)=>{const{body:r}=a;n>0&&(r.addEventListener("pointerdown",Jke,t),r.addEventListener("pointermove",Jx,t))}))}function ey(e,t){sm.forEach(n=>{const{setResizeHandlerState:a}=n,r=wi.includes(n);a(e,r,t)})}function Qke(){const[e,t]=w.useState(0);return w.useCallback(()=>t(n=>n+1),[])}function It(e,t){if(!e)throw console.error(t),Error(t)}function Ql(e,t,n=SD){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function To(e,t,n=SD){return Ql(e,t,n)===0}function Da(e,t,n){return Ql(e,t,n)===0}function eTe(e,t,n){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a++){const r=e[a],i=t[a];if(!Da(r,i,n))return!1}return!0}function wu({panelConstraints:e,panelIndex:t,size:n}){const a=e[t];It(a!=null,`Panel constraints not found for index ${t}`);let{collapsedSize:r=0,collapsible:i,maxSize:s=100,minSize:c=0}=a;if(Ql(n,c)<0)if(i){const u=(r+c)/2;Ql(n,u)<0?n=r:n=c}else n=c;return n=Math.min(s,n),n=parseFloat(n.toFixed(SD)),n}function cp({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:a,prevLayout:r,trigger:i}){if(Da(e,0))return t;const s=[...t],[c,u]=a;It(c!=null,"Invalid first pivot index"),It(u!=null,"Invalid second pivot index");let d=0;if(i==="keyboard"){{const h=e<0?u:c,g=n[h];It(g,`Panel constraints not found for index ${h}`);const{collapsedSize:v=0,collapsible:x,minSize:S=0}=g;if(x){const y=t[h];if(It(y!=null,`Previous layout not found for panel index ${h}`),Da(y,v)){const E=S-y;Ql(E,Math.abs(e))>0&&(e=e<0?0-E:E)}}}{const h=e<0?c:u,g=n[h];It(g,`No panel constraints found for index ${h}`);const{collapsedSize:v=0,collapsible:x,minSize:S=0}=g;if(x){const y=t[h];if(It(y!=null,`Previous layout not found for panel index ${h}`),Da(y,S)){const E=y-v;Ql(E,Math.abs(e))>0&&(e=e<0?0-E:E)}}}}{const h=e<0?1:-1;let g=e<0?u:c,v=0;for(;;){const S=t[g];It(S!=null,`Previous layout not found for panel index ${g}`);const E=wu({panelConstraints:n,panelIndex:g,size:100})-S;if(v+=E,g+=h,g<0||g>=n.length)break}const x=Math.min(Math.abs(e),Math.abs(v));e=e<0?0-x:x}{let g=e<0?c:u;for(;g>=0&&g<n.length;){const v=Math.abs(e)-Math.abs(d),x=t[g];It(x!=null,`Previous layout not found for panel index ${g}`);const S=x-v,y=wu({panelConstraints:n,panelIndex:g,size:S});if(!Da(x,y)&&(d+=x-y,s[g]=y,d.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?g--:g++}}if(eTe(r,s))return r;{const h=e<0?u:c,g=t[h];It(g!=null,`Previous layout not found for panel index ${h}`);const v=g+d,x=wu({panelConstraints:n,panelIndex:h,size:v});if(s[h]=x,!Da(x,v)){let S=v-x,E=e<0?u:c;for(;E>=0&&E<n.length;){const _=s[E];It(_!=null,`Previous layout not found for panel index ${E}`);const k=_+S,C=wu({panelConstraints:n,panelIndex:E,size:k});if(Da(_,C)||(S-=C-_,s[E]=C),Da(S,0))break;e>0?E--:E++}}}const m=s.reduce((h,g)=>g+h,0);return Da(m,100)?s:r}function tTe({layout:e,panelsArray:t,pivotIndices:n}){let a=0,r=100,i=0,s=0;const c=n[0];It(c!=null,"No pivot index found"),t.forEach((h,g)=>{const{constraints:v}=h,{maxSize:x=100,minSize:S=0}=v;g===c?(a=S,r=x):(i+=S,s+=x)});const u=Math.min(r,100-i),d=Math.max(a,100-s),m=e[c];return{valueMax:u,valueMin:d,valueNow:m}}function lm(e,t=document){return Array.from(t.querySelectorAll(`[${Zn.resizeHandleId}][data-panel-group-id="${e}"]`))}function $Y(e,t,n=document){const r=lm(e,n).findIndex(i=>i.getAttribute(Zn.resizeHandleId)===t);return r??null}function LY(e,t,n){const a=$Y(e,t,n);return a!=null?[a,a+1]:[-1,-1]}function nTe(e){return e instanceof HTMLElement?!0:typeof e=="object"&&e!==null&&"tagName"in e&&"getAttribute"in e}function MY(e,t=document){if(nTe(t)&&t.dataset.panelGroupId==e)return t;const n=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return n||null}function Cw(e,t=document){const n=t.querySelector(`[${Zn.resizeHandleId}="${e}"]`);return n||null}function rTe(e,t,n,a=document){var r,i,s,c;const u=Cw(t,a),d=lm(e,a),m=u?d.indexOf(u):-1,h=(r=(i=n[m])===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:null,g=(s=(c=n[m+1])===null||c===void 0?void 0:c.id)!==null&&s!==void 0?s:null;return[h,g]}function aTe({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:a,panelDataArray:r,panelGroupElement:i,setLayout:s}){w.useRef({didWarnAboutMissingResizeHandle:!1}),Ul(()=>{if(!i)return;const c=lm(n,i);for(let u=0;u<r.length-1;u++){const{valueMax:d,valueMin:m,valueNow:h}=tTe({layout:a,panelsArray:r,pivotIndices:[u,u+1]}),g=c[u];if(g!=null){const v=r[u];It(v,`No panel data found for index "${u}"`),g.setAttribute("aria-controls",v.id),g.setAttribute("aria-valuemax",""+Math.round(d)),g.setAttribute("aria-valuemin",""+Math.round(m)),g.setAttribute("aria-valuenow",h!=null?""+Math.round(h):"")}}return()=>{c.forEach((u,d)=>{u.removeAttribute("aria-controls"),u.removeAttribute("aria-valuemax"),u.removeAttribute("aria-valuemin"),u.removeAttribute("aria-valuenow")})}},[n,a,r,i]),w.useEffect(()=>{if(!i)return;const c=t.current;It(c,"Eager values not found");const{panelDataArray:u}=c,d=MY(n,i);It(d!=null,`No group found for id "${n}"`);const m=lm(n,i);It(m,`No resize handles found for group id "${n}"`);const h=m.map(g=>{const v=g.getAttribute(Zn.resizeHandleId);It(v,"Resize handle element has no handle id attribute");const[x,S]=rTe(n,v,u,i);if(x==null||S==null)return()=>{};const y=E=>{if(!E.defaultPrevented)switch(E.key){case"Enter":{E.preventDefault();const _=u.findIndex(k=>k.id===x);if(_>=0){const k=u[_];It(k,`No panel data found for index ${_}`);const C=a[_],{collapsedSize:R=0,collapsible:I,minSize:A=0}=k.constraints;if(C!=null&&I){const O=cp({delta:Da(C,R)?A-R:R-C,initialLayout:a,panelConstraints:u.map(M=>M.constraints),pivotIndices:LY(n,v,i),prevLayout:a,trigger:"keyboard"});a!==O&&s(O)}}break}}};return g.addEventListener("keydown",y),()=>{g.removeEventListener("keydown",y)}});return()=>{h.forEach(g=>g())}},[i,e,t,n,a,r,s])}function R2(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function PY(e,t){const n=e==="horizontal",{x:a,y:r}=kw(t);return n?a:r}function iTe(e,t,n,a,r){const i=n==="horizontal",s=Cw(t,r);It(s,`No resize handle element found for id "${t}"`);const c=s.getAttribute(Zn.groupId);It(c,"Resize handle element has no group id attribute");let{initialCursorPosition:u}=a;const d=PY(n,e),m=MY(c,r);It(m,`No group element found for id "${c}"`);const h=m.getBoundingClientRect(),g=i?h.width:h.height;return(d-u)/g*100}function oTe(e,t,n,a,r,i){if(TY(e)){const s=n==="horizontal";let c=0;e.shiftKey?c=100:r!=null?c=r:c=10;let u=0;switch(e.key){case"ArrowDown":u=s?0:c;break;case"ArrowLeft":u=s?-c:0;break;case"ArrowRight":u=s?c:0;break;case"ArrowUp":u=s?0:-c;break;case"End":u=100;break;case"Home":u=-100;break}return u}else return a==null?0:iTe(e,t,n,a,i)}function sTe({panelDataArray:e}){const t=Array(e.length),n=e.map(i=>i.constraints);let a=0,r=100;for(let i=0;i<e.length;i++){const s=n[i];It(s,`Panel constraints not found for index ${i}`);const{defaultSize:c}=s;c!=null&&(a++,t[i]=c,r-=c)}for(let i=0;i<e.length;i++){const s=n[i];It(s,`Panel constraints not found for index ${i}`);const{defaultSize:c}=s;if(c!=null)continue;const u=e.length-a,d=r/u;a++,t[i]=d,r-=d}return t}function Xc(e,t,n){t.forEach((a,r)=>{const i=e[r];It(i,`Panel data not found for index ${r}`);const{callbacks:s,constraints:c,id:u}=i,{collapsedSize:d=0,collapsible:m}=c,h=n[u];if(h==null||a!==h){n[u]=a;const{onCollapse:g,onExpand:v,onResize:x}=s;x&&x(a,h),m&&(g||v)&&(v&&(h==null||To(h,d))&&!To(a,d)&&v(),g&&(h==null||!To(h,d))&&To(a,d)&&g())}})}function Eb(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function lTe({defaultSize:e,dragState:t,layout:n,panelData:a,panelIndex:r,precision:i=3}){const s=n[r];let c;return s==null?c=e!=null?e.toFixed(i):"1":a.length===1?c="1":c=s.toFixed(i),{flexBasis:0,flexGrow:c,flexShrink:1,overflow:"hidden",pointerEvents:t!==null?"none":void 0}}function cTe(e,t=10){let n=null;return(...r)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...r)},t)}}function A2(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function UY(e){return`react-resizable-panels:${e}`}function zY(e){return e.map(t=>{const{constraints:n,id:a,idIsFromProps:r,order:i}=t;return r?a:i?`${i}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function FY(e,t){try{const n=UY(e),a=t.getItem(n);if(a){const r=JSON.parse(a);if(typeof r=="object"&&r!=null)return r}}catch{}return null}function uTe(e,t,n){var a,r;const i=(a=FY(e,n))!==null&&a!==void 0?a:{},s=zY(t);return(r=i[s])!==null&&r!==void 0?r:null}function dTe(e,t,n,a,r){var i;const s=UY(e),c=zY(t),u=(i=FY(e,r))!==null&&i!==void 0?i:{};u[c]={expandToSizes:Object.fromEntries(n.entries()),layout:a};try{r.setItem(s,JSON.stringify(u))}catch(d){console.error(d)}}function I2({layout:e,panelConstraints:t}){const n=[...e],a=n.reduce((i,s)=>i+s,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(i=>`${i}%`).join(", ")}`);if(!Da(a,100)&&n.length>0)for(let i=0;i<t.length;i++){const s=n[i];It(s!=null,`No layout data found for index ${i}`);const c=100/a*s;n[i]=c}let r=0;for(let i=0;i<t.length;i++){const s=n[i];It(s!=null,`No layout data found for index ${i}`);const c=wu({panelConstraints:t,panelIndex:i,size:s});s!=c&&(r+=s-c,n[i]=c)}if(!Da(r,0))for(let i=0;i<t.length;i++){const s=n[i];It(s!=null,`No layout data found for index ${i}`);const c=s+r,u=wu({panelConstraints:t,panelIndex:i,size:c});if(s!==u&&(r-=u-s,n[i]=u,Da(r,0)))break}return n}const fTe=100,up={getItem:e=>(A2(up),up.getItem(e)),setItem:(e,t)=>{A2(up),up.setItem(e,t)}},O2={};function BY({autoSaveId:e=null,children:t,className:n="",direction:a,forwardedRef:r,id:i=null,onLayout:s=null,keyboardResizeBy:c=null,storage:u=up,style:d,tagName:m="div",...h}){const g=xD(i),v=w.useRef(null),[x,S]=w.useState(null),[y,E]=w.useState([]),_=Qke(),k=w.useRef({}),C=w.useRef(new Map),R=w.useRef(0),I=w.useRef({autoSaveId:e,direction:a,dragState:x,id:g,keyboardResizeBy:c,onLayout:s,storage:u}),A=w.useRef({layout:y,panelDataArray:[],panelDataArrayChanged:!1});w.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),w.useImperativeHandle(r,()=>({getId:()=>I.current.id,getLayout:()=>{const{layout:z}=A.current;return z},setLayout:z=>{const{onLayout:$}=I.current,{layout:L,panelDataArray:F}=A.current,W=I2({layout:z,panelConstraints:F.map(X=>X.constraints)});R2(L,W)||(E(W),A.current.layout=W,$&&$(W),Xc(F,W,k.current))}}),[]),Ul(()=>{I.current.autoSaveId=e,I.current.direction=a,I.current.dragState=x,I.current.id=g,I.current.onLayout=s,I.current.storage=u}),aTe({committedValuesRef:I,eagerValuesRef:A,groupId:g,layout:y,panelDataArray:A.current.panelDataArray,setLayout:E,panelGroupElement:v.current}),w.useEffect(()=>{const{panelDataArray:z}=A.current;if(e){if(y.length===0||y.length!==z.length)return;let $=O2[e];$==null&&($=cTe(dTe,fTe),O2[e]=$);const L=[...z],F=new Map(C.current);$(e,L,F,y,u)}},[e,y,u]),w.useEffect(()=>{});const O=w.useCallback(z=>{const{onLayout:$}=I.current,{layout:L,panelDataArray:F}=A.current;if(z.constraints.collapsible){const W=F.map(J=>J.constraints),{collapsedSize:X=0,panelSize:ie,pivotIndices:ce}=_l(F,z,L);if(It(ie!=null,`Panel size not found for panel "${z.id}"`),!To(ie,X)){C.current.set(z.id,ie);const q=su(F,z)===F.length-1?ie-X:X-ie,le=cp({delta:q,initialLayout:L,panelConstraints:W,pivotIndices:ce,prevLayout:L,trigger:"imperative-api"});Eb(L,le)||(E(le),A.current.layout=le,$&&$(le),Xc(F,le,k.current))}}},[]),M=w.useCallback((z,$)=>{const{onLayout:L}=I.current,{layout:F,panelDataArray:W}=A.current;if(z.constraints.collapsible){const X=W.map(he=>he.constraints),{collapsedSize:ie=0,panelSize:ce=0,minSize:J=0,pivotIndices:q}=_l(W,z,F),le=$??J;if(To(ce,ie)){const he=C.current.get(z.id),oe=he!=null&&he>=le?he:le,Ve=su(W,z)===W.length-1?ce-oe:oe-ce,_e=cp({delta:Ve,initialLayout:F,panelConstraints:X,pivotIndices:q,prevLayout:F,trigger:"imperative-api"});Eb(F,_e)||(E(_e),A.current.layout=_e,L&&L(_e),Xc(W,_e,k.current))}}},[]),P=w.useCallback(z=>{const{layout:$,panelDataArray:L}=A.current,{panelSize:F}=_l(L,z,$);return It(F!=null,`Panel size not found for panel "${z.id}"`),F},[]),B=w.useCallback((z,$)=>{const{panelDataArray:L}=A.current,F=su(L,z);return lTe({defaultSize:$,dragState:x,layout:y,panelData:L,panelIndex:F})},[x,y]),K=w.useCallback(z=>{const{layout:$,panelDataArray:L}=A.current,{collapsedSize:F=0,collapsible:W,panelSize:X}=_l(L,z,$);return It(X!=null,`Panel size not found for panel "${z.id}"`),W===!0&&To(X,F)},[]),ee=w.useCallback(z=>{const{layout:$,panelDataArray:L}=A.current,{collapsedSize:F=0,collapsible:W,panelSize:X}=_l(L,z,$);return It(X!=null,`Panel size not found for panel "${z.id}"`),!W||Ql(X,F)>0},[]),te=w.useCallback(z=>{const{panelDataArray:$}=A.current;$.push(z),$.sort((L,F)=>{const W=L.order,X=F.order;return W==null&&X==null?0:W==null?-1:X==null?1:W-X}),A.current.panelDataArrayChanged=!0,_()},[_]);Ul(()=>{if(A.current.panelDataArrayChanged){A.current.panelDataArrayChanged=!1;const{autoSaveId:z,onLayout:$,storage:L}=I.current,{layout:F,panelDataArray:W}=A.current;let X=null;if(z){const ce=uTe(z,W,L);ce&&(C.current=new Map(Object.entries(ce.expandToSizes)),X=ce.layout)}X==null&&(X=sTe({panelDataArray:W}));const ie=I2({layout:X,panelConstraints:W.map(ce=>ce.constraints)});R2(F,ie)||(E(ie),A.current.layout=ie,$&&$(ie),Xc(W,ie,k.current))}}),Ul(()=>{const z=A.current;return()=>{z.layout=[]}},[]);const ae=w.useCallback(z=>{let $=!1;const L=v.current;return L&&window.getComputedStyle(L,null).getPropertyValue("direction")==="rtl"&&($=!0),function(W){W.preventDefault();const X=v.current;if(!X)return()=>null;const{direction:ie,dragState:ce,id:J,keyboardResizeBy:q,onLayout:le}=I.current,{layout:he,panelDataArray:oe}=A.current,{initialLayout:Ne}=ce??{},Ve=LY(J,z,X);let _e=oTe(W,z,ie,ce,q,X);const ke=ie==="horizontal";ke&&$&&(_e=-_e);const Fe=oe.map(He=>He.constraints),pe=cp({delta:_e,initialLayout:Ne??he,panelConstraints:Fe,pivotIndices:Ve,prevLayout:he,trigger:TY(W)?"keyboard":"mouse-or-touch"}),Oe=!Eb(he,pe);(NY(W)||CY(W))&&R.current!=_e&&(R.current=_e,!Oe&&_e!==0?ke?e_(z,_e<0?AY:IY):e_(z,_e<0?OY:DY):e_(z,0)),Oe&&(E(pe),A.current.layout=pe,le&&le(pe),Xc(oe,pe,k.current))}},[]),H=w.useCallback((z,$)=>{const{onLayout:L}=I.current,{layout:F,panelDataArray:W}=A.current,X=W.map(he=>he.constraints),{panelSize:ie,pivotIndices:ce}=_l(W,z,F);It(ie!=null,`Panel size not found for panel "${z.id}"`);const q=su(W,z)===W.length-1?ie-$:$-ie,le=cp({delta:q,initialLayout:F,panelConstraints:X,pivotIndices:ce,prevLayout:F,trigger:"imperative-api"});Eb(F,le)||(E(le),A.current.layout=le,L&&L(le),Xc(W,le,k.current))},[]),Z=w.useCallback((z,$)=>{const{layout:L,panelDataArray:F}=A.current,{collapsedSize:W=0,collapsible:X}=$,{collapsedSize:ie=0,collapsible:ce,maxSize:J=100,minSize:q=0}=z.constraints,{panelSize:le}=_l(F,z,L);le!=null&&(X&&ce&&To(le,W)?To(W,ie)||H(z,ie):le<q?H(z,q):le>J&&H(z,J))},[H]),G=w.useCallback((z,$)=>{const{direction:L}=I.current,{layout:F}=A.current;if(!v.current)return;const W=Cw(z,v.current);It(W,`Drag handle element not found for id "${z}"`);const X=PY(L,$);S({dragHandleId:z,dragHandleRect:W.getBoundingClientRect(),initialCursorPosition:X,initialLayout:F})},[]),re=w.useCallback(()=>{S(null)},[]),ne=w.useCallback(z=>{const{panelDataArray:$}=A.current,L=su($,z);L>=0&&($.splice(L,1),delete k.current[z.id],A.current.panelDataArrayChanged=!0,_())},[_]),j=w.useMemo(()=>({collapsePanel:O,direction:a,dragState:x,expandPanel:M,getPanelSize:P,getPanelStyle:B,groupId:g,isPanelCollapsed:K,isPanelExpanded:ee,reevaluatePanelConstraints:Z,registerPanel:te,registerResizeHandle:ae,resizePanel:H,startDragging:G,stopDragging:re,unregisterPanel:ne,panelGroupElement:v.current}),[O,x,a,M,P,B,g,K,ee,Z,te,ae,H,G,re,ne]),V={display:"flex",flexDirection:a==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return w.createElement(Ew.Provider,{value:j},w.createElement(m,{...h,children:t,className:n,id:i,ref:v,style:{...V,...d},[Zn.group]:"",[Zn.groupDirection]:a,[Zn.groupId]:g}))}const HY=w.forwardRef((e,t)=>w.createElement(BY,{...e,forwardedRef:t}));BY.displayName="PanelGroup";HY.displayName="forwardRef(PanelGroup)";function su(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function _l(e,t,n){const a=su(e,t),i=a===e.length-1?[a-1,a]:[a,a+1],s=n[a];return{...t.constraints,panelSize:s,pivotIndices:i}}function pTe({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:a}){w.useEffect(()=>{if(e||n==null||a==null)return;const r=Cw(t,a);if(r==null)return;const i=s=>{if(!s.defaultPrevented)switch(s.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{s.preventDefault(),n(s);break}case"F6":{s.preventDefault();const c=r.getAttribute(Zn.groupId);It(c,`No group element found for id "${c}"`);const u=lm(c,a),d=$Y(c,t,a);It(d!==null,`No resize element found for id "${t}"`);const m=s.shiftKey?d>0?d-1:u.length-1:d+1<u.length?d+1:0;u[m].focus();break}}};return r.addEventListener("keydown",i),()=>{r.removeEventListener("keydown",i)}},[a,e,t,n])}function VY({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:a,id:r,onBlur:i,onClick:s,onDragging:c,onFocus:u,onPointerDown:d,onPointerUp:m,style:h={},tabIndex:g=0,tagName:v="div",...x}){var S,y;const E=w.useRef(null),_=w.useRef({onClick:s,onDragging:c,onPointerDown:d,onPointerUp:m});w.useEffect(()=>{_.current.onClick=s,_.current.onDragging=c,_.current.onPointerDown=d,_.current.onPointerUp=m});const k=w.useContext(Ew);if(k===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:C,groupId:R,registerResizeHandle:I,startDragging:A,stopDragging:O,panelGroupElement:M}=k,P=xD(r),[B,K]=w.useState("inactive"),[ee,te]=w.useState(!1),[ae,H]=w.useState(null),Z=w.useRef({state:B});Ul(()=>{Z.current.state=B}),w.useEffect(()=>{if(n)H(null);else{const j=I(P);H(()=>j)}},[n,P,I]);const G=(S=a?.coarse)!==null&&S!==void 0?S:15,re=(y=a?.fine)!==null&&y!==void 0?y:5;w.useEffect(()=>{if(n||ae==null)return;const j=E.current;It(j,"Element ref not attached");let V=!1;return Xke(P,j,C,{coarse:G,fine:re},($,L,F)=>{if(!L){K("inactive");return}switch($){case"down":{K("drag"),V=!1,It(F,'Expected event to be defined for "down" action'),A(P,F);const{onDragging:W,onPointerDown:X}=_.current;W?.(!0),X?.();break}case"move":{const{state:W}=Z.current;V=!0,W!=="drag"&&K("hover"),It(F,'Expected event to be defined for "move" action'),ae(F);break}case"up":{K("hover"),O();const{onClick:W,onDragging:X,onPointerUp:ie}=_.current;X?.(!1),ie?.(),V||W?.();break}}})},[G,C,n,re,I,P,ae,A,O]),pTe({disabled:n,handleId:P,resizeHandler:ae,panelGroupElement:M});const ne={touchAction:"none",userSelect:"none"};return w.createElement(v,{...x,children:e,className:t,id:r,onBlur:()=>{te(!1),i?.()},onFocus:()=>{te(!0),u?.()},ref:E,role:"separator",style:{...ne,...h},tabIndex:g,[Zn.groupDirection]:C,[Zn.groupId]:R,[Zn.resizeHandle]:"",[Zn.resizeHandleActive]:B==="drag"?"pointer":ee?"keyboard":void 0,[Zn.resizeHandleEnabled]:!n,[Zn.resizeHandleId]:P,[Zn.resizeHandleState]:B})}VY.displayName="PanelResizeHandle";function na({className:e,...t}){return f.jsx(HY,{"data-slot":"resizable-panel-group",className:De("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t})}function Rn({...e}){return f.jsx(kY,{"data-slot":"resizable-panel",...e})}function Si({withHandle:e,className:t,...n}){return f.jsx(VY,{"data-slot":"resizable-handle",className:De("bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&f.jsx("div",{className:"bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border",children:f.jsx(ahe,{className:"size-2.5"})})})}function eh({className:e,...t}){return f.jsx("kbd",{"data-slot":"kbd",className:De("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}function mTe({isSearchExpanded:e,searchQuery:t,filteredNotificationsCount:n,notificationsCount:a,onSearchExpand:r,onSearchChange:i,onSearchBlur:s,onClearAll:c,searchInputRef:u}){return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:u,placeholder:"Search notifications...",value:t,onChange:d=>i(d.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Notifications"}),f.jsx(wr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,disabled:a===0,className:"h-8 w-8 p-0",children:f.jsx(Fs,{className:"h-4 w-4"})})}),f.jsx(Rt,{side:"bottom",children:"Clear all"})]})})]})}function Qs({id:e,isSelected:t,isFocused:n,icon:a,title:r,description:i,metadata:s,onClick:c,className:u}){return f.jsx("button",{id:e,type:"button",onClick:c,className:De("w-full text-left cursor-pointer p-2 sm:p-4 border-b dark:border-zinc-700 hover:bg-gray-50 dark:hover:bg-zinc-800/50 transition-colors group",t&&"bg-zinc-50 dark:bg-zinc-800 border-l-4 border-l-zinc-500",n&&"ring-2 ring-zinc-500 dark:ring-zinc-400 ring-inset",u),children:f.jsxs("div",{className:"flex items-start gap-2 sm:gap-3",children:[a&&f.jsx("div",{className:"flex-shrink-0 mt-1",children:f.jsx("div",{className:De("p-2.5 rounded-full transition-colors",t?"bg-zinc-500 dark:bg-zinc-100/80 text-zinc-100 dark:text-zinc-900":"bg-gray-100 dark:bg-zinc-700 text-gray-600 dark:text-gray-400 group-hover:bg-gray-200 dark:group-hover:bg-zinc-600"),children:a})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsx("div",{className:"flex items-center gap-2 mb-1",children:f.jsx("h3",{className:De("font-medium truncate font-mono text-sm"),children:r})}),i&&f.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 line-clamp-2",children:i})]})]})})}function hTe({notifications:e,selectedNotification:t,onNotificationSelect:n,focusedIndex:a,formatRelativeTime:r,listRef:i}){return e.length===0?f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No notifications yet"})}):f.jsx("div",{ref:i,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((s,c)=>f.jsx(Qs,{id:`notification-${s.id}`,isSelected:t?.id===s.id,isFocused:a===c,title:f.jsxs("span",{className:"flex items-center gap-3",children:[s.method,!s.read&&f.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const u=r(s.timestamp),d=s.params&&Object.keys(s.params).length>0?Object.keys(s.params).length:0,m=d>0?` | ${d} param${d>1?"s":""}`:"";return u+m})(),onClick:()=>n(s)},s.id))})}function gTe({notification:e,previewMode:t,onTogglePreview:n,onCopy:a,onDownload:r,onFullscreen:i,isCopied:s=!1,onClose:c}){return e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex-shrink-0 px-4 py-3 border-b border-gray-200 dark:border-zinc-700 flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(fd,{className:"h-3 w-3 text-gray-400"}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleTimeString()})]}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:e.formatRelativeTime(e.timestamp)})]}),f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsxs($e,{variant:"ghost",size:"sm",onClick:n,className:t?"":"text-purple-600 dark:text-purple-400",children:[t?f.jsx(XN,{className:"h-4 w-4 mr-1"}):f.jsx($G,{className:"h-4 w-4 mr-1"}),t?"JSON":"Formatted"]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:a,children:s?f.jsx(ra,{className:"h-4 w-4"}):f.jsx($r,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:r,children:f.jsx(Lm,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:i,children:f.jsx(eC,{className:"h-4 w-4"})}),c&&f.jsx($e,{variant:"ghost",size:"sm",onClick:c,children:f.jsx(Ji,{className:"h-4 w-4"})})]})]}),f.jsx("div",{className:"flex-1 overflow-y-auto",children:f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:{method:e.method,timestamp:e.timestamp,read:e.read,params:e.params},filename:`notification-${e.method.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(qN,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a notification to view details"})]})}function ty(e){const n=Date.now()-e,a=Math.floor(n/1e3),r=Math.floor(a/60),i=Math.floor(r/60),s=Math.floor(i/24);return a<60?"just now":r<60?`${r}m ago`:i<24?`${i}h ago`:s<7?`${s}d ago`:new Date(e).toLocaleDateString()}function bTe({notifications:e,unreadCount:t,markNotificationRead:n,markAllNotificationsRead:a,clearNotifications:r,serverId:i,isConnected:s}){const[c,u]=w.useState(null),[d,m]=w.useState(""),[h,g]=w.useState(-1),[v,x]=w.useState(!0),[S,y]=w.useState(!1),[E,_]=w.useState(!0),[k,C]=w.useState(!1),R=w.useRef(null),I=w.useRef(null),A=w.useRef(null),O=w.useRef(!1);w.useEffect(()=>{v&&e.length>0&&R.current&&!O.current&&(R.current.scrollTop=0)},[e.length,v]),w.useEffect(()=>{const Z=R.current;if(!Z)return;const G=()=>{Z.scrollTop>0&&(O.current=!0,x(!1))};return Z.addEventListener("scroll",G),()=>Z.removeEventListener("scroll",G)},[]),w.useEffect(()=>{e.length===0&&(O.current=!1,x(!0))},[e.length]),w.useEffect(()=>{c&&!c.read&&n(c.id)},[c,n]),w.useEffect(()=>{S&&A.current&&A.current.focus()},[S]);const M=w.useCallback(()=>{d.trim()||y(!1)},[d]),P=w.useMemo(()=>{if(!d.trim())return e;const Z=d.toLowerCase();return e.filter(G=>G.method.toLowerCase().includes(Z)||JSON.stringify(G.params||{}).toLowerCase().includes(Z))},[e,d]);w.useEffect(()=>{g(-1)},[d]),w.useEffect(()=>{const Z=G=>{const re=G.target;if(re.tagName==="INPUT"||re.tagName==="TEXTAREA"||re.contentEditable==="true"||G.metaKey||G.ctrlKey||G.altKey)return;const j=P;if(G.key==="ArrowDown")G.preventDefault(),g(V=>{const z=V+1;return z>=j.length?0:z});else if(G.key==="ArrowUp")G.preventDefault(),g(V=>{const z=V-1;return z<0?j.length-1:z});else if(G.key==="Enter"&&h>=0){G.preventDefault();const V=P[h];V&&B(V)}};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[h,P]),w.useEffect(()=>{if(h>=0){const Z=`notification-${P[h]?.id}`,G=document.getElementById(Z);G&&G.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,P]);const B=w.useCallback(Z=>{u(Z)},[]),K=w.useCallback(()=>{window.confirm("Are you sure you want to clear all notifications? This cannot be undone.")&&(r(),u(null))},[r]),ee=w.useCallback(async()=>{if(c)try{await navigator.clipboard.writeText(JSON.stringify({method:c.method,timestamp:c.timestamp,read:c.read,params:c.params},null,2)),C(!0),setTimeout(()=>C(!1),2e3)}catch(Z){console.error("[NotificationsTab] Failed to copy notification:",Z)}},[c]),te=w.useCallback(()=>{if(c)try{const Z=new globalThis.Blob([JSON.stringify({method:c.method,timestamp:c.timestamp,read:c.read,params:c.params},null,2)],{type:"application/json"}),G=URL.createObjectURL(Z),re=document.createElement("a");re.href=G,re.download=`notification-${Date.now()}.json`,document.body.appendChild(re),re.click(),document.body.removeChild(re),URL.revokeObjectURL(G)}catch(Z){console.error("[NotificationsTab] Failed to download notification:",Z)}},[c]),ae=w.useCallback(async()=>{if(I.current)try{document.fullscreenElement?await document.exitFullscreen():await I.current.requestFullscreen()}catch(Z){console.error("[NotificationsTab] Failed to toggle fullscreen:",Z)}},[]),H=c?{method:c.method,params:c.params,timestamp:c.timestamp,read:c.read,formatRelativeTime:ty}:null;return s?f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:40,minSize:30,children:f.jsx(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:f.jsxs(Rn,{defaultSize:75,minSize:30,children:[f.jsx(mTe,{isSearchExpanded:S,searchQuery:d,filteredNotificationsCount:P.length,notificationsCount:e.length,onSearchExpand:()=>y(!0),onSearchChange:m,onSearchBlur:M,onClearAll:K,searchInputRef:A}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(hTe,{notifications:P,selectedNotification:c,onNotificationSelect:B,focusedIndex:h,formatRelativeTime:ty,listRef:R})})]})})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:60,minSize:40,children:f.jsx("div",{ref:I,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(gTe,{notification:H,previewMode:E,onTogglePreview:()=>_(!E),onCopy:ee,onDownload:te,onFullscreen:ae,onClose:()=>u(null),isCopied:k})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(qN,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function GY({activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabTitle:a,secondaryTabTitle:r,primaryCount:i,secondaryCount:s,secondaryIcon:c,primaryIcon:u,searchPlaceholder:d="Search...",onSearchExpand:m,onSearchChange:h,onSearchBlur:g,onTabSwitch:v,searchInputRef:x,primaryTabName:S}){const y=e===S;return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:t?f.jsx(En,{ref:x,placeholder:d,value:n,onChange:E=>h(E.target.value),onBlur:g,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:y?a:r}),y&&f.jsxs(f.Fragment,{children:[f.jsx(wr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:i}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:m,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})]})}),f.jsxs($e,{variant:"ghost",size:"sm",onClick:v,className:"gap-2 flex-shrink-0",children:[y?f.jsx(c,{}):f.jsx(u,{}),f.jsx("span",{className:"hidden sm:inline",children:y?r:a}),y&&s>0&&f.jsx(wr,{className:"bg-purple-500/20 text-purple-600 dark:text-purple-400 border-transparent",variant:"outline",children:s})]})]})}function D2({prompts:e,selectedPrompt:t,onPromptSelect:n,focusedIndex:a}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(Hp,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No prompts available"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((r,i)=>f.jsx(Qs,{id:`prompt-${r.name}`,isSelected:t?.name===r.name,isFocused:a===i,icon:f.jsx(Hp,{className:"h-4 w-4"}),title:r.name,description:r.description,metadata:r.arguments&&r.arguments.length>0&&f.jsxs(wr,{variant:"outline",className:"text-xs border-gray-300 dark:border-zinc-600 text-gray-600 dark:text-gray-400",children:[r.arguments.length," args"]}),onClick:()=>n(r)},r.name))})}function j2({activeTab:e,isSearchExpanded:t,searchQuery:n,filteredPromptsCount:a,savedPromptsCount:r,onSearchExpand:i,onSearchChange:s,onSearchBlur:c,onTabSwitch:u,searchInputRef:d}){return f.jsx(GY,{activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabName:"prompts",secondaryTabName:"saved",primaryTabTitle:"Prompts",secondaryTabTitle:"History",primaryCount:a,secondaryCount:r,primaryIcon:Hp,secondaryIcon:fd,searchPlaceholder:"Search prompts...",onSearchExpand:i,onSearchChange:s,onSearchBlur:c,onTabSwitch:u,searchInputRef:d})}function $2({savedPrompts:e,selectedPrompt:t,onLoadPrompt:n,onDeletePrompt:a,focusedIndex:r}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(fd,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No history"}),f.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500 mt-1",children:"Prompts you execute will appear here"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((i,s)=>f.jsx(Qs,{id:`saved-prompt-${i.id}`,isSelected:t?.id===i.id,isFocused:r===s,icon:f.jsx(fd,{className:"h-4 w-4"}),title:i.name,description:`${i.promptName} - ${new Date(i.savedAt).toLocaleString()}`,onClick:()=>n(i)},i.id))})}function vTe({selectedPrompt:e,promptArgs:t,onArgChange:n}){const a=e?.arguments||[];if(!(a.length>0))return f.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500 dark:text-gray-400 text-sm",children:"No arguments required"});const i=s=>{const c=s.name,u=t[c],d=typeof u=="string"?u:JSON.stringify(u);return s.type==="boolean"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsxs("div",{className:"flex items-center space-x-2",children:[f.jsx("input",{id:c,type:"checkbox",checked:!!u,onChange:m=>n(c,m.target.checked),className:"rounded","aria-label":`Toggle ${c}`}),f.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:s.description})]})]},c):s.type==="number"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(En,{id:c,type:"number",value:Number(u)||0,onChange:m=>n(c,Number(m.target.value)),placeholder:s.description||`Enter ${c}`}),s.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s.description})]},c):s.type==="array"||s.type==="object"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(Xl,{id:c,value:d,onChange:m=>{try{const h=JSON.parse(m.target.value);n(c,h)}catch{n(c,m.target.value)}},placeholder:s.description||`Enter ${c} as JSON`,className:"font-mono text-sm min-h-[100px]"}),s.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s.description})]},c):f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(En,{id:c,value:d,onChange:m=>n(c,m.target.value),placeholder:s.description||`Enter ${c}`}),s.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s.description})]},c)};return f.jsx("div",{className:"space-y-4",children:a.map(s=>i(s))})}function L2({selectedPrompt:e,promptArgs:t,isExecuting:n,isConnected:a,onArgChange:r,onExecute:i,onSave:s}){return w.useEffect(()=>{const c=u=>{(u.metaKey||u.ctrlKey)&&u.key==="Enter"&&e&&!n&&a&&(u.preventDefault(),i())};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[e,n,a,i]),e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsx("div",{className:"flex-shrink-0 p-3 sm:p-6 pt-3 pb-4 pr-3",children:f.jsxs("div",{children:[f.jsxs("div",{className:"flex flex-row items-center justify-between mb-0 gap-2",children:[f.jsx("h3",{className:"text-base sm:text-lg font-semibold",children:e.name}),f.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[f.jsx($e,{onClick:i,disabled:n||!a,size:"sm",className:"lg:size-default pr-1! gap-0",children:n?f.jsxs(f.Fragment,{children:[f.jsx(ki,{className:"mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]}):f.jsxs(f.Fragment,{children:[f.jsx(zG,{className:"h-4 w-4 sm:mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Execute"}),f.jsx("span",{className:"hidden sm:inline text-[12px] border text-zinc-300 p-1 rounded-full border-zinc-300 dark:text-zinc-600 dark:border-zinc-500 ml-2",children:"⌘↵"})]})}),f.jsxs($e,{variant:"outline",onClick:s,disabled:n,size:"sm",className:"lg:size-default gap-2",children:[f.jsx(tC,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Save"})]})]})]}),e.description&&f.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 leading-relaxed mt-2",children:e.description})]})}),f.jsx("div",{className:"flex-1 overflow-y-auto px-3 sm:px-6 pb-4 pr-3",children:f.jsx(vTe,{selectedPrompt:e,promptArgs:t,onArgChange:r})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a prompt to get started"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a prompt from the list to view its details and execute it"})]})}function yTe(e){return"isError"in e&&!e.isError?null:"error"in e&&e.error?e.error:"isError"in e&&e.isError?"An error occurred":null}function M2({results:e,copiedResult:t,onCopy:n}){return f.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:f.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:e.length>0?f.jsx("div",{className:"space-y-4 flex-1 h-full",children:e.map((a,r)=>{const i=a.error||yTe(a.result);return f.jsxs("div",{className:"space-y-0 flex-1 h-full flex flex-col",children:[f.jsxs("div",{className:"flex items-center gap-2 px-4 pt-2 border-b border-gray-200 dark:border-zinc-600 pb-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"Response"}),f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(fd,{className:"h-3 w-3 text-gray-400"}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(a.timestamp).toLocaleTimeString()})]}),a.duration!==void 0&&f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(Vp,{className:"h-3 w-3 text-gray-400"}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[a.duration,"ms"]})]}),f.jsx("div",{className:"flex gap-2 ml-auto",children:f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>n(r,a.result),className:"h-6 px-2",children:t===r?f.jsx(ra,{className:"h-4 w-4"}):f.jsx($r,{className:"h-4 w-4"})})})]}),i?f.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3 mx-4",children:[f.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),f.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:i})]}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:a.result,filename:`prompt-result-${a.promptName}-${Date.now()}.json`})})]},r)})}):f.jsx("div",{className:"flex items-center justify-center h-full",children:f.jsx("div",{className:"text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No Results yet"})})})})})}function ED({serverIds:e,onCountChange:t,onClearRef:n}={}){const[a,r]=w.useState([]),i=w.useRef(null),[s,c]=w.useState(new Set),[u]=w.useState(""),d=v=>{c(x=>{const S=new Set(x);return S.has(v)?S.delete(v):S.add(v),S})},m=async()=>{r([]),c(new Set),t?.(0);try{const v=new URLSearchParams;e&&e.length>0&&v.set("serverIds",e.join(","));const x=await fetch(`/inspector/api/rpc/log?${v.toString()}`,{method:"DELETE"});x.ok||console.warn("[RPC Logger] Failed to clear server buffer:",x.status)}catch(v){console.warn("[RPC Logger] Error clearing server buffer:",v)}},h=w.useMemo(()=>!e||e.length===0?"":[...e].sort().join(","),[e]);w.useEffect(()=>(n&&(n.current=m),()=>{n&&(n.current=null)}),[n,m]),w.useEffect(()=>{t?.(a.length)},[a.length,t]),w.useEffect(()=>{let v=null;try{const x=new URLSearchParams;x.set("replay","3"),x.set("_t",Date.now().toString()),e&&e.length>0&&x.set("serverIds",e.join(","));const S=`/inspector/api/rpc/stream?${x.toString()}`;console.log("[RPC Logger] Connecting to SSE stream:",S),v=new globalThis.EventSource(S),v.onopen=()=>{console.log("[RPC Logger] SSE connection opened")},v.onmessage=y=>{try{const E=JSON.parse(y.data);if(!E||E.type!=="rpc")return;const{serverId:_,direction:k,message:C,timestamp:R}=E,I=C,A=typeof I?.method=="string"?I.method:I?.result!==void 0?"result":I?.error!==void 0?"error":"unknown",O={id:`${R??Date.now()}-${Math.random().toString(36).slice(2)}`,serverId:typeof _=="string"?_:"unknown",direction:typeof k=="string"?k.toUpperCase():"",method:A,timestamp:R??new Date().toISOString(),payload:C};console.log("[RPC Logger] Received RPC event:",{method:A,direction:k,serverId:_}),r(M=>{const P=[O,...M].slice(0,1e3);return t?.(P.length),P})}catch(E){console.error("[RPC Logger] Error parsing SSE message:",E)}},v.onerror=y=>{console.error("[RPC Logger] SSE connection error:",y);try{v?.close()}catch{}}}catch(x){console.error("[RPC Logger] Failed to create SSE connection:",x)}return()=>{try{v?.close(),console.log("[RPC Logger] SSE connection closed")}catch{}}},[h]);const g=w.useMemo(()=>{let v=a;if(e&&e.length>0){const x=new Set(e);v=v.filter(S=>x.has(S.serverId))}if(u.trim()){const x=u.toLowerCase();v=v.filter(S=>S.serverId.toLowerCase().includes(x)||S.method.toLowerCase().includes(x)||S.direction.toLowerCase().includes(x)||JSON.stringify(S.payload).toLowerCase().includes(x))}return v},[a,u,e]);return f.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:f.jsx("div",{ref:i,className:"flex-1 min-h-0 overflow-y-auto",children:g.length===0?f.jsxs("div",{className:"text-center py-8",children:[f.jsx("div",{className:"text-xs text-muted-foreground",children:"No messages yet"}),f.jsx("div",{className:"text-[10px] text-muted-foreground mt-1",children:"JSON-RPC messages will appear here"})]}):g.map(v=>{const x=s.has(v.id);return f.jsxs("div",{className:"group hover:bg-muted/50 transition-all duration-200 overflow-hidden",children:[f.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>d(v.id),children:[f.jsx("div",{className:"flex-shrink-0",children:x?f.jsx(ac,{className:"h-3 w-3 text-muted-foreground transition-transform"}):f.jsx(LG,{className:"h-3 w-3 text-muted-foreground transition-transform"})}),f.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[f.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:new Date(v.timestamp).toLocaleTimeString()}),f.jsx("span",{className:`flex items-center justify-center px-1 py-0.5 rounded ${v.direction==="RECEIVE"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-green-500/10 text-green-600 dark:text-green-400"}`,title:v.direction==="RECEIVE"?"Incoming":"Outgoing",children:v.direction==="RECEIVE"?f.jsx(mme,{className:"h-3 w-3"}):f.jsx(gme,{className:"h-3 w-3"})}),f.jsx("span",{className:"text-xs font-mono text-foreground truncate",children:v.method})]})]}),x&&f.jsx("div",{className:"border-t bg-muted/20",children:f.jsx("div",{className:"p-3",children:f.jsx("div",{className:"max-h-[40vh] overflow-auto rounded-sm bg-background/60 p-2",children:f.jsx(Xn,{data:v.payload})})})})]},v.id)})})})}const P2="mcp-inspector-saved-prompts";function WY({ref:e,prompts:t,callPrompt:n,serverId:a,isConnected:r}){const[i,s]=w.useState(null),[c,u]=w.useState(null),{selectedPromptName:d,setSelectedPromptName:m}=ic(),[h,g]=w.useState({}),[v,x]=w.useState([]),[S,y]=w.useState(!1),[E,_]=w.useState(null),[k,C]=w.useState(""),[R,I]=w.useState("prompts"),[A,O]=w.useState([]),[M,P]=w.useState(!1),[B,K]=w.useState(""),[ee,te]=w.useState(!1),[ae,H]=w.useState(-1),Z=w.useRef(null),[G,re]=w.useState(!1),[ne,j]=w.useState("list"),[V,z]=w.useState(0),[$,L]=w.useState(!0),F=w.useRef(null),W=w.useRef(null);w.useEffect(()=>{const _e=()=>{re(window.innerWidth<1024)};return _e(),window.addEventListener("resize",_e),()=>window.removeEventListener("resize",_e)},[]),w.useEffect(()=>{j(i?"detail":"list")},[i]),w.useEffect(()=>{G&&v.length>0&&!S&&j("response")},[v,S,G]),w.useImperativeHandle(e,()=>({focusSearch:()=>{te(!0),setTimeout(()=>{Z.current&&Z.current.focus()},0)},blurSearch:()=>{C(""),te(!1),Z.current&&Z.current.blur()}})),w.useEffect(()=>{try{const _e=localStorage.getItem(P2);if(_e){const ke=JSON.parse(_e);O(ke)}}catch(_e){console.error("[PromptsTab] Failed to load saved prompts:",_e)}},[]);const X=w.useCallback(_e=>{try{localStorage.setItem(P2,JSON.stringify(_e))}catch(ke){console.error("[PromptsTab] Failed to save prompts:",ke)}},[]);w.useEffect(()=>{ee&&Z.current&&Z.current.focus()},[ee]);const ie=w.useCallback(()=>{k.trim()||te(!1)},[k]),ce=w.useMemo(()=>{if(!k.trim())return t;const _e=k.toLowerCase();return t.filter(ke=>ke.name.toLowerCase().includes(_e)||ke.description?.toLowerCase().includes(_e))},[t,k]),J=w.useCallback(_e=>{s(_e);const ke={};_e.arguments&&_e.arguments.forEach(Fe=>{Fe.default!==void 0?ke[Fe.name]=Fe.default:Fe.type==="string"?ke[Fe.name]="":Fe.type==="number"?ke[Fe.name]=0:Fe.type==="boolean"?ke[Fe.name]=!1:Fe.type==="array"?ke[Fe.name]=[]:Fe.type==="object"&&(ke[Fe.name]={})}),g(ke)},[]),q=w.useCallback(_e=>{const ke=t.find(Fe=>Fe.name===_e.promptName);ke&&(s(ke),g(_e.args),u(_e))},[t]);w.useEffect(()=>{H(-1)},[k,R]),w.useEffect(()=>{const _e=ke=>{const Fe=ke.target;if(Fe.tagName==="INPUT"||Fe.tagName==="TEXTAREA"||Fe.contentEditable==="true"||ke.metaKey||ke.ctrlKey||ke.altKey)return;const Oe=R==="prompts"?ce:A;if(ke.key==="ArrowDown")ke.preventDefault(),H(He=>{const xe=He+1;return xe>=Oe.length?0:xe});else if(ke.key==="ArrowUp")ke.preventDefault(),H(He=>{const xe=He-1;return xe<0?Oe.length-1:xe});else if(ke.key==="Enter"&&ae>=0)if(ke.preventDefault(),R==="prompts"){const He=ce[ae];He&&J(He)}else{const He=A[ae];He&&q(He)}};return document.addEventListener("keydown",_e),()=>document.removeEventListener("keydown",_e)},[ae,ce,A,R,J,q]),w.useEffect(()=>{if(ae>=0){const _e=R==="prompts"?`prompt-${ce[ae]?.name}`:`saved-prompt-${A[ae]?.id}`,ke=document.getElementById(_e);ke&&ke.scrollIntoView({behavior:"smooth",block:"nearest"})}},[ae,ce,A,R]),w.useEffect(()=>{if(console.warn("[PromptsTab] Auto-selection effect triggered:",{selectedPromptName:d,promptsCount:t.length,currentSelectedPrompt:i?.name}),d&&t.length>0){const _e=t.find(ke=>ke.name===d);if(console.warn("[PromptsTab] Prompt lookup result:",{selectedPromptName:d,promptFound:!!_e,promptName:_e?.name,shouldSelect:_e&&i?.name!==_e.name}),_e&&i?.name!==_e.name){console.warn("[PromptsTab] Selecting prompt:",_e.name),m(null);const ke=setTimeout(()=>{J(_e);const Fe=document.getElementById(`prompt-${_e.name}`);Fe&&(console.warn("[PromptsTab] Scrolling to prompt element"),Fe.scrollIntoView({behavior:"smooth",block:"nearest"}))},100);return()=>clearTimeout(ke)}}},[d,t,i,J,m]);const le=w.useCallback((_e,ke)=>{g(Fe=>({...Fe,[_e]:ke}))},[]),he=w.useCallback(async()=>{if(!i||S)return;y(!0);const _e=Date.now();try{const ke=await n(i.name,h),Fe=Date.now()-_e;vr.getInstance().capture(new JU({promptName:i.name,serverId:a,success:!0})).catch(()=>{}),x(Oe=>[{promptName:i.name,args:h,result:ke,timestamp:_e,duration:Fe},...Oe])}catch(ke){vr.getInstance().capture(new JU({promptName:i.name,serverId:a,success:!1,error:ke instanceof Error?ke.message:"Unknown error"})).catch(()=>{});const pe={promptName:i.name,args:h,result:null,error:ke instanceof Error?ke.message:String(ke),timestamp:_e,duration:Date.now()-_e};x(Oe=>[pe,...Oe])}finally{y(!1)}},[i,h,S,n,a]),oe=w.useCallback(async(_e,ke)=>{try{await navigator.clipboard.writeText(JSON.stringify(ke,null,2)),_(_e),setTimeout(()=>_(null),2e3)}catch(Fe){console.error("[PromptsTab] Failed to copy result:",Fe)}},[]),Ne=w.useCallback(()=>{i&&(K(""),P(!0))},[i]),Ve=w.useCallback(_e=>{X(A.filter(ke=>ke.id!==_e)),c?.id===_e&&u(null)},[A,X,c]);return G?f.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[ne!=="list"&&f.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{ne==="response"?j("detail"):(s(null),j("list"))},className:"p-0 h-8 w-8",children:f.jsx(qy,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center text-sm font-medium",children:[f.jsx("button",{onClick:()=>{s(null),j("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Prompts"}),ne!=="list"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("button",{onClick:()=>{ne==="response"&&j("detail")},className:ne==="detail"?"text-foreground hover:underline":ne==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),ne==="response"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),f.jsx("div",{className:"flex-1 relative overflow-hidden",children:f.jsxs(rw,{initial:!1,mode:"popLayout",children:[ne==="list"&&f.jsxs(ya.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[f.jsx(j2,{activeTab:R,isSearchExpanded:ee,searchQuery:k,filteredPromptsCount:ce.length,savedPromptsCount:A.length,onSearchExpand:()=>te(!0),onSearchChange:C,onSearchBlur:ie,onTabSwitch:()=>I(R==="prompts"?"saved":"prompts"),searchInputRef:Z}),R==="prompts"?f.jsx(D2,{prompts:ce,selectedPrompt:i,onPromptSelect:J,focusedIndex:ae}):f.jsx($2,{savedPrompts:A,selectedPrompt:c,onLoadPrompt:q,onDeletePrompt:Ve,focusedIndex:ae})]},"list"),ne==="detail"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-10",children:f.jsx(L2,{selectedPrompt:i,promptArgs:h,isExecuting:S,isConnected:r,onArgChange:le,onExecute:he,onSave:Ne})},"detail"),ne==="response"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-20",children:f.jsx(M2,{results:v,copiedResult:E,onCopy:oe})},"response")]})})]}):f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:33,className:"flex flex-col h-full relative",children:f.jsxs(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[f.jsx(Rn,{defaultSize:75,minSize:30,children:f.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[f.jsx(j2,{activeTab:R,isSearchExpanded:ee,searchQuery:k,filteredPromptsCount:ce.length,savedPromptsCount:A.length,onSearchExpand:()=>te(!0),onSearchChange:C,onSearchBlur:ie,onTabSwitch:()=>I(R==="prompts"?"saved":"prompts"),searchInputRef:Z}),R==="prompts"?f.jsx(D2,{prompts:ce,selectedPrompt:i,onPromptSelect:J,focusedIndex:ae}):f.jsx($2,{savedPrompts:A,selectedPrompt:c,onLoadPrompt:q,onDeletePrompt:Ve,focusedIndex:ae})]})}),f.jsx(Si,{withHandle:!0}),f.jsxs(Rn,{ref:F,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>L(!0),onExpand:()=>L(!1),className:"flex flex-col border-t dark:border-zinc-700",children:[f.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:_e=>{_e.preventDefault(),_e.stopPropagation(),$?(F.current?.resize(25),L(!1)):(F.current?.resize(5),L(!0))},children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),V>0&&f.jsx(wr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:V}),V>0&&!$&&f.jsx($e,{variant:"ghost",size:"sm",onClick:_e=>{_e.preventDefault(),_e.stopPropagation(),W.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:f.jsx(Fs,{className:"h-3.5 w-3.5"})})]}),f.jsx(ac,{className:`h-4 w-4 text-muted-foreground transition-transform ${$?"rotate-180":""}`})]}),!$&&f.jsx("div",{className:"flex-1 overflow-hidden min-h-0",children:f.jsx(ED,{serverIds:[a],onCountChange:z,onClearRef:W})})]})]})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{defaultSize:67,children:f.jsxs(na,{direction:"vertical",children:[f.jsx(Rn,{defaultSize:40,children:f.jsx(L2,{selectedPrompt:i,promptArgs:h,isExecuting:S,isConnected:r,onArgChange:le,onExecute:he,onSave:Ne})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{defaultSize:50,children:f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(M2,{results:v,copiedResult:E,onCopy:oe})})})]})})]})}WY.displayName="PromptsTab";function Ru(e){if(!e?.mimeType)return!1;const t=e.mimeType.toLowerCase();return t==="text/html"||t==="text/html+skybridge"||t==="text/uri-list"||t.startsWith("application/vnd.mcp-ui.remote-dom")}function wTe(e){return{uri:e.uri,mimeType:e.mimeType,text:e.text,blob:e.blob}}function KY({resource:e,onUIAction:t,className:n}){const a=async i=>t?.(i),r=wTe(e);return f.jsx("div",{className:n,children:f.jsx(wD,{resource:r,onUIAction:a,htmlProps:{autoResizeIframe:{width:!0,height:!0},style:{width:"100%",minHeight:"200px"},sandboxPermissions:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"},remoteDomProps:{remoteElements:[Ike,Ake,Oke,Dke],library:yD}})})}function STe(e){if("error"in e&&e.error)return e.error;if(!("isError"in e&&e.isError))return null;if("contents"in e&&Array.isArray(e.contents)){const t=e.contents.filter(n=>"text"in n).map(n=>n.text).filter(Boolean);if(t.length>0)return t.join(`
1661
- `)}return"An error occurred"}function U2({result:e,isLoading:t,previewMode:n,serverId:a,readResource:r,onTogglePreview:i,onCopy:s,onDownload:c,onFullscreen:u,isCopied:d=!1}){let m=[],h;if(e?.resourceAnnotations&&(m=Object.keys(e.resourceAnnotations).filter(y=>y.startsWith("openai/")),h=e.resourceAnnotations["openai/outputTemplate"]),e?.result?.contents?.[0]?._meta){const y=e.result.contents[0]._meta,E=Object.keys(y).filter(_=>_.startsWith("openai/"));E.length>0&&(m=[...m,...E]),!h&&y["openai/outputTemplate"]&&(h=y["openai/outputTemplate"]),!h&&e.uri&&e.uri.startsWith("ui://widget/")&&(h=e.uri)}const g=!!(m.length>0&&h&&typeof h=="string"&&a&&r);if(t)return f.jsx("div",{className:"flex absolute left-0 top-0 items-center justify-center w-full h-full",children:f.jsx(ki,{className:"size-5"})});if(!e)return f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a resource to view its contents"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a resource from the list to see its data"})]});const v=e.error||STe(e.result);if(v)return f.jsx("div",{className:"p-4",children:f.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3",children:[f.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),f.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:v})]})});const x=e?.result?.contents&&Array.isArray(e.result.contents)&&e.result.contents.some(y=>y.mimeType&&Ru(y)),S=x?e.result.contents.filter(y=>y.mimeType&&Ru(y)):[];return f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex-shrink-0 px-4 py-3 border-b border-gray-200 dark:border-zinc-700 flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(fd,{className:"h-3 w-3 text-gray-400"}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleTimeString()})]}),(()=>{const y=e?.duration??e.result?.duration??e.result?.metrics?.durationMs;return y!==void 0?f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(Vp,{className:"h-3 w-3 text-gray-400"}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[y,"ms"]})]}):null})(),x&&f.jsx(wr,{variant:"outline",className:"text-xs bg-purple-50 dark:bg-purple-900/20 border-none border-purple-200 dark:border-purple-800/50 text-purple-600 dark:text-purple-400",children:"MCP UI"}),g&&f.jsx(wr,{variant:"outline",className:"text-xs bg-blue-50 dark:bg-blue-900/20 border-none border-blue-200 dark:border-blue-800/50 text-blue-600 dark:text-blue-400",children:"OpenAI Widget"})]}),f.jsxs("div",{className:"flex items-center gap-1",children:[(x||g)&&f.jsxs($e,{variant:"ghost",size:"sm",onClick:i,className:n?"":"text-purple-600 dark:text-purple-400",children:[n?f.jsx(XN,{className:"h-4 w-4 mr-1"}):f.jsx($G,{className:"h-4 w-4 mr-1"}),n?"JSON":g?"Component":"Preview"]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:s,children:d?f.jsx(ra,{className:"h-4 w-4"}):f.jsx($r,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:c,children:f.jsx(Lm,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:u,children:f.jsx(eC,{className:"h-4 w-4"})})]})]}),f.jsx("div",{className:"flex-1 overflow-y-auto",children:g&&a&&r&&h?n?f.jsx("div",{className:"flex-1 h-full",children:f.jsx(mD,{componentUrl:h,toolName:e.uri,toolArgs:{},toolResult:e.result,serverId:a,readResource:r,className:"w-full h-full relative flex p-4"})}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:e.result,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})}):x?n?f.jsxs("div",{className:"space-y-0 h-full",children:[S.map((y,E)=>f.jsx("div",{className:"mx-0 size-full",children:f.jsx("div",{className:"w-full h-full",children:f.jsx(KY,{resource:y,className:"w-full h-full"})})},`mcp-ui-${y.uri||`resource-${Date.now()}-${Math.random()}`}`)),(()=>{if(e.result.contents&&Array.isArray(e.result.contents)){const y=e.result.contents.filter(E=>!(E.mimeType&&Ru(E)));if(y.length>0)return f.jsx("div",{className:"px-4",children:f.jsx(Xn,{data:y,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-non-ui-${Date.now()}.json`})})}return null})()]}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:e.result,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-mcp-ui-${Date.now()}.json`})}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:e.result,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})})})]})}function xTe(e,t){if(!e&&!t)return f.jsx(Jme,{className:"h-5 w-5"});const n=(e||t||"").toLowerCase();return n.includes("image")?f.jsx(Yme,{className:"h-5 w-5"}):n.includes("json")||n.includes("javascript")||n.includes("typescript")?f.jsx(Kme,{className:"h-5 w-5"}):n.includes("html")||n.includes("xml")?f.jsx(nhe,{className:"h-5 w-5"}):n.includes("database")||n.includes("sql")?f.jsx(Xy,{className:"h-5 w-5"}):f.jsx(JN,{className:"h-5 w-5"})}function z2({resources:e,selectedResource:t,onResourceSelect:n,focusedIndex:a}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(Xy,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No resources available"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((r,i)=>{const s=xTe(r.mimeType,r.uri),c=[r.description,r.mimeType&&f.jsx("span",{className:"font-mono",children:r.mimeType},"mime")].filter(Boolean);return f.jsx(Qs,{id:`resource-${r.uri}`,isSelected:t?.uri===r.uri,isFocused:a===i,icon:s,title:r.name,description:c.length>0?f.jsxs("span",{className:"flex flex-col gap-1",children:[r.description&&f.jsx("span",{children:r.description}),r.mimeType&&f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-500 font-mono",children:r.mimeType})]}):void 0,onClick:()=>n(r)},r.uri)})})}function F2({isSearchExpanded:e,searchQuery:t,filteredResourcesCount:n,onSearchExpand:a,onSearchChange:r,onSearchBlur:i,searchInputRef:s}){return f.jsx("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:s,placeholder:"Search resources...",value:t,onChange:c=>r(c.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Resources"}),f.jsx(wr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})})})}function ZY({ref:e,resources:t,readResource:n,serverId:a,isConnected:r}){const[i,s]=w.useState(null),{selectedResourceUri:c,setSelectedResourceUri:u}=ic(),[d,m]=w.useState(null),[h,g]=w.useState(!1),[v,x]=w.useState(""),[S]=w.useState("resources"),[y,E]=w.useState(!0),[_,k]=w.useState(!1),[C,R]=w.useState(-1),[I,A]=w.useState(!1),O=w.useRef(null),M=w.useRef(null),[P,B]=w.useState(!1),[K,ee]=w.useState("list"),[te,ae]=w.useState(0),[H,Z]=w.useState(!0),G=w.useRef(null),re=w.useRef(null);w.useEffect(()=>{const F=()=>{B(window.innerWidth<1024)};return F(),window.addEventListener("resize",F),()=>window.removeEventListener("resize",F)},[]),w.useEffect(()=>{ee(i?"detail":"list")},[i]),w.useImperativeHandle(e,()=>({focusSearch:()=>{k(!0),setTimeout(()=>{O.current&&O.current.focus()},0)},blurSearch:()=>{x(""),k(!1),O.current&&O.current.blur()}})),w.useEffect(()=>{_&&O.current&&O.current.focus()},[_]);const ne=w.useCallback(()=>{v.trim()||k(!1)},[v]),j=w.useMemo(()=>{if(!v)return t;const F=v.toLowerCase();return t.filter(W=>W.name.toLowerCase().includes(F)||W.description?.toLowerCase().includes(F)||W.uri.toLowerCase().includes(F))},[t,v]),V=w.useCallback(async F=>{if(s(F),r){g(!0);const W=Date.now();try{const X=await n(F.uri);vr.getInstance().capture(new XU({resourceUri:F.uri,serverId:a,success:!0})).catch(()=>{}),m({uri:F.uri,result:X,timestamp:W,resourceAnnotations:F.annotations})}catch(X){vr.getInstance().capture(new XU({resourceUri:F.uri,serverId:a,success:!1,error:X instanceof Error?X.message:"Unknown error"})).catch(()=>{}),m({uri:F.uri,result:null,error:X instanceof Error?X.message:"Unknown error",timestamp:W,resourceAnnotations:F.annotations})}finally{g(!1)}}},[n,a,r]);w.useEffect(()=>{R(-1)},[v,S]),w.useEffect(()=>{const F=W=>{const X=W.target;if(X.tagName==="INPUT"||X.tagName==="TEXTAREA"||X.contentEditable==="true"||W.metaKey||W.ctrlKey||W.altKey)return;const ce=j;if(W.key==="ArrowDown")W.preventDefault(),R(J=>{const q=J+1;return q>=ce.length?0:q});else if(W.key==="ArrowUp")W.preventDefault(),R(J=>{const q=J-1;return q<0?ce.length-1:q});else if(W.key==="Enter"&&C>=0){W.preventDefault();const J=j[C];J&&V(J)}};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[C,j,V]),w.useEffect(()=>{if(C>=0){const F=`resource-${j[C]?.uri}`,W=document.getElementById(F);W&&W.scrollIntoView({behavior:"smooth",block:"nearest"})}},[C,j]),w.useEffect(()=>{if(c&&t.length>0){const F=t.find(W=>W.uri===c);F&&i?.uri!==F.uri&&(u(null),setTimeout(()=>{V(F);const W=document.getElementById(`resource-${F.uri}`);W&&W.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[c,t,i,V,u]);const z=w.useCallback(async()=>{if(d)try{await navigator.clipboard.writeText(JSON.stringify(d.result,null,2)),A(!0),setTimeout(()=>A(!1),2e3)}catch(F){console.error("[ResourcesTab] Failed to copy result:",F)}},[d]),$=w.useCallback(()=>{if(d)try{const F=new globalThis.Blob([JSON.stringify(d.result,null,2)],{type:"application/json"}),W=URL.createObjectURL(F),X=document.createElement("a");X.href=W,X.download=`resource-${Date.now()}.json`,document.body.appendChild(X),X.click(),document.body.removeChild(X),URL.revokeObjectURL(W)}catch(F){console.error("[ResourcesTab] Failed to download result:",F)}},[d]),L=w.useCallback(async()=>{if(M.current)try{document.fullscreenElement?await document.exitFullscreen():await M.current.requestFullscreen()}catch(F){console.error("[ResourcesTab] Failed to toggle fullscreen:",F)}},[]);return P?f.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[K!=="list"&&f.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{s(null),ee("list")},className:"p-0 h-8 w-8",children:f.jsx(qy,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center text-sm font-medium",children:[f.jsx("button",{onClick:()=>{s(null),ee("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Resources"}),K==="detail"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("span",{className:"text-foreground",children:"Content"})]})]})]}),f.jsx("div",{className:"flex-1 relative overflow-hidden",children:f.jsxs(rw,{initial:!1,mode:"popLayout",children:[K==="list"&&f.jsxs(ya.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[f.jsx(F2,{activeTab:S,isSearchExpanded:_,searchQuery:v,filteredResourcesCount:j.length,onSearchExpand:()=>k(!0),onSearchChange:x,onSearchBlur:ne,onTabSwitch:()=>{},searchInputRef:O}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(z2,{resources:j,selectedResource:i,onResourceSelect:V,focusedIndex:C})})]},"list"),K==="detail"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-white dark:bg-zinc-900 z-10",children:f.jsx("div",{ref:M,className:"h-full",children:f.jsx(U2,{result:d,isLoading:h,previewMode:y,serverId:a,readResource:n,onTogglePreview:()=>E(!y),onCopy:z,onDownload:$,onFullscreen:L,isCopied:I})})},"detail")]})})]}):f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:25,children:f.jsxs(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[f.jsx(Rn,{defaultSize:75,minSize:30,children:f.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[f.jsx(F2,{activeTab:S,isSearchExpanded:_,searchQuery:v,filteredResourcesCount:j.length,onSearchExpand:()=>k(!0),onSearchChange:x,onSearchBlur:ne,onTabSwitch:()=>{},searchInputRef:O}),f.jsx(z2,{resources:j,selectedResource:i,onResourceSelect:V,focusedIndex:C})]})}),f.jsx(Si,{withHandle:!0}),f.jsxs(Rn,{ref:G,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>Z(!0),onExpand:()=>Z(!1),className:"flex flex-col border-t dark:border-zinc-700",children:[f.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:F=>{F.preventDefault(),F.stopPropagation(),H?(G.current?.resize(25),Z(!1)):(G.current?.resize(5),Z(!0))},children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),te>0&&f.jsx(wr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:te}),te>0&&!H&&f.jsx($e,{variant:"ghost",size:"sm",onClick:F=>{F.preventDefault(),F.stopPropagation(),re.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:f.jsx(Fs,{className:"h-3.5 w-3.5"})})]}),f.jsx(ac,{className:`h-4 w-4 text-muted-foreground transition-transform ${H?"":"rotate-180"}`})]}),!H&&f.jsx("div",{className:"flex-1 overflow-hidden min-h-0",children:f.jsx(ED,{serverIds:[a],onCountChange:ae,onClearRef:re})})]})]})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:50,children:f.jsx(na,{direction:"vertical",children:f.jsx(Rn,{defaultSize:70,children:f.jsx("div",{ref:M,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(U2,{result:d,isLoading:h,previewMode:y,serverId:a,readResource:n,onTogglePreview:()=>E(!y),onCopy:z,onDownload:$,onFullscreen:L,isCopied:I})})})})})]})}ZY.displayName="ResourcesTab";function B2({savedRequests:e,selectedRequest:t,onLoadRequest:n,onDeleteRequest:a,focusedIndex:r}){if(e.length===0)return f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(Xy,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"No saved requests yet"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Execute a tool and click Save to store requests"})]});const i=(s,c)=>{s.stopPropagation(),c()};return f.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((s,c)=>f.jsxs("div",{className:"relative group",children:[f.jsx(Qs,{id:`saved-${s.id}`,isSelected:t?.id===s.id,isFocused:r===c,icon:f.jsx(Rv,{className:"h-4 w-4"}),title:s.name,description:s.toolName,metadata:f.jsx("div",{className:"flex flex-col gap-1",children:f.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:new Date(s.savedAt).toLocaleString()})}),onClick:()=>n(s)}),f.jsx("div",{className:"absolute top-1/2 right-2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"secondary",size:"sm",onClick:u=>i(u,()=>a(s.id)),className:"h-8 w-8 p-0",children:f.jsx(Fs,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Delete saved request"})})]})})]},s.id))})}function H2({isOpen:e,requestName:t,defaultPlaceholder:n,onRequestNameChange:a,onSave:r,onCancel:i}){return e?f.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:i,children:f.jsxs("div",{className:"bg-white dark:bg-zinc-800 rounded-lg p-6 w-[400px] shadow-xl border border-gray-200 dark:border-zinc-700",onClick:s=>s.stopPropagation(),children:[f.jsx("h3",{className:"text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100",children:"Save Request"}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx(Kt,{htmlFor:"request-name",children:"Request Name (optional)"}),f.jsx(En,{id:"request-name",value:t,onChange:s=>a(s.target.value),placeholder:n,className:"mt-2",onKeyDown:s=>{s.key==="Enter"&&r()},autoFocus:!0})]}),f.jsxs("div",{className:"flex justify-end gap-2",children:[f.jsx($e,{variant:"outline",onClick:i,children:"Cancel"}),f.jsxs($e,{onClick:r,children:[f.jsx(tC,{className:"h-4 w-4 mr-2"}),"Save"]})]})]})]})}):null}function YY(e,t){if(!e?.$ref)return e;const n=e.$ref;if(n.startsWith("#/")){const a=n.substring(2).split("/");let r=t;for(const i of a)if(r&&typeof r=="object"&&i in r)r=r[i];else return console.warn(`Could not resolve $ref: ${n}`),e;return r}return e}function _Te(e,t){if(e.anyOf&&Array.isArray(e.anyOf)){const n=e.anyOf.find(a=>a.type!=="null");if(n)return{...YY(n,t),nullable:!0}}return e}function ETe(e){return Array.isArray(e.enum)?e.enum:null}function V2({selectedTool:e,toolArgs:t,onArgChange:n}){const a=e?.inputSchema?.properties||{},r=e?.inputSchema?.required||[];return Object.keys(a).length>0?f.jsx("div",{className:"space-y-4",children:Object.entries(a).map(([s,c])=>{const u=e?.inputSchema||{};let d=_Te(c,u);d=YY(d,u);const m=ETe(d),h=d.type==="string"&&m!==null,g=d;g.required=r.includes(s);const v=t[s];let x="";return v!=null&&(typeof v=="string"?x=v:typeof v=="object"&&v!==null?x=JSON.stringify(v,null,2):x=String(v)),g.type==="object"||g.type==="array"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:s,className:"text-sm font-medium",children:[s,g?.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(Xl,{id:s,value:x,onChange:y=>n(s,y.target.value),placeholder:g?.description||`Enter ${s}`,className:"min-h-[100px]"}),g?.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g.description})]},s):h&&m?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:s,className:"text-sm font-medium",children:[s,g.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsxs(Io,{value:String(t[s]||""),onValueChange:y=>n(s,y),children:[f.jsx(Do,{id:s,className:"w-full",children:f.jsx(Oo,{placeholder:g.description||"Select an option"})}),f.jsx(jo,{children:m.map((y,E)=>f.jsx(Ar,{value:y,children:g.enumNames?.[E]||y},y))})]}),g.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g.description})]},s):f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:s,className:"text-sm font-medium",children:[s,g?.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(En,{id:s,value:x,onChange:y=>n(s,y.target.value),placeholder:g?.description||`Enter ${s}`}),g?.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g.description})]},s)})}):f.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500 dark:text-gray-400 text-sm",children:"No parameters required"})}function G2({selectedTool:e,toolArgs:t,isExecuting:n,isConnected:a,onArgChange:r,onExecute:i,onSave:s,onCancel:c}){const[u,d]=w.useState(!1),[m,h]=w.useState(()=>{if(typeof window<"u"){const S=localStorage.getItem("mcp-inspector-show-tool-metadata");return S?JSON.parse(S):!1}return!1}),[g,v]=w.useState(!1);w.useEffect(()=>{typeof window<"u"&&localStorage.setItem("mcp-inspector-show-tool-metadata",JSON.stringify(m))},[m]);const x=()=>{if(!e)return;const S={name:e.name,description:e.description||"",_meta:e._meta};navigator.clipboard.writeText(JSON.stringify(S,null,2)),v(!0),setTimeout(()=>v(!1),2e3)};return w.useEffect(()=>{const S=y=>{(y.metaKey||y.ctrlKey)&&y.key==="Enter"&&e&&!n&&a&&(y.preventDefault(),i()),y.key==="Escape"&&n&&c&&(y.preventDefault(),c())};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[e,n,a,i,c]),e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsx("div",{className:"flex-shrink-0 p-3 sm:p-5 pt-3 sm:pt-4 pb-4 sm:pr-4",children:f.jsxs("div",{children:[f.jsxs("div",{className:"flex flex-row items-center justify-between mb-0 gap-2",children:[f.jsx("h3",{className:"text-base sm:text-lg font-semibold",children:e.name}),f.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsxs($e,{variant:m?"default":"outline",onClick:()=>h(!m),disabled:n,size:"sm",className:"lg:size-default gap-2",title:"Toggle tool metadata",children:[f.jsx(XN,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Metadata"})]})}),f.jsx(Rt,{children:f.jsx("p",{children:"Show tool definition metadata"})})]}),f.jsxs($e,{variant:"outline",onClick:s,disabled:n,size:"sm",className:"lg:size-default gap-2",children:[f.jsx(tC,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Save"})]}),n&&c?f.jsxs(Nt,{open:u?void 0:!1,children:[f.jsx(Ct,{asChild:!0,children:f.jsx("div",{onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),className:"relative",children:f.jsx($e,{onClick:c,variant:u?"destructive":"default",size:"sm",className:"lg:size-default gap-2 transition-all",children:u?f.jsxs(f.Fragment,{children:[f.jsx(Ji,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Cancel"}),f.jsx("span",{className:"hidden sm:inline text-[12px] border border-current p-1 rounded-full ml-2",children:"Esc"})]}):f.jsxs(f.Fragment,{children:[f.jsx(ki,{className:"mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]})})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Hover to cancel (or press Esc)"})})]}):f.jsx($e,{onClick:i,disabled:n||!a,size:"sm",className:"lg:size-default pr-1! gap-0",children:n?f.jsxs(f.Fragment,{children:[f.jsx(ki,{className:"mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]}):f.jsxs(f.Fragment,{children:[f.jsx(zG,{className:"h-4 w-4 sm:mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Execute"}),f.jsx("span",{className:"hidden sm:inline text-[12px] border text-zinc-300 p-1 rounded-full border-zinc-300 dark:text-zinc-600 dark:border-zinc-500 ml-2",children:"⌘↵"})]})})]})]}),e.description&&f.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 leading-relaxed mt-2",children:e.description})]})}),m?f.jsxs("div",{className:"flex-1 overflow-hidden flex gap-4 px-3 sm:px-6 pb-4",children:[f.jsx("div",{className:"flex-1 min-w-0 overflow-y-auto",children:f.jsx(V2,{selectedTool:e,toolArgs:t,onArgChange:r})}),f.jsxs("div",{className:"w-2/5 flex flex-col bg-zinc-50 dark:bg-zinc-900/50 rounded border border-zinc-200 dark:border-zinc-800 overflow-hidden",children:[f.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-zinc-200 dark:border-zinc-800 flex-shrink-0",children:[f.jsx("h4",{className:"text-sm font-medium",children:"Tool Definition"}),f.jsx($e,{variant:"ghost",size:"sm",onClick:x,className:"h-7 w-7 p-0",title:"Copy metadata",children:g?f.jsx(ra,{className:"h-3.5 w-3.5 text-green-600"}):f.jsx($r,{className:"h-3.5 w-3.5"})})]}),f.jsx("div",{className:"flex-1 overflow-y-auto p-3",children:f.jsx("pre",{className:"text-xs font-mono text-zinc-700 dark:text-zinc-300 whitespace-pre-wrap break-words",children:JSON.stringify({name:e.name,description:e.description||"(no description)",_meta:e._meta||null},null,2)})})]})]}):f.jsx("div",{className:"flex-1 overflow-y-auto px-3 sm:px-6 pb-4 pr-3",children:f.jsx(V2,{selectedTool:e,toolArgs:t,onArgChange:r})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a tool to get started"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a tool from the list to view its details and execute it"})]})}function W2(e){const n=Date.now()-e,a=Math.floor(n/1e3),r=Math.floor(a/60),i=Math.floor(r/60),s=Math.floor(i/24);return a<10?"now":a<60?`${a}s ago`:r<60?`${r}m ago`:i<24?`${i}h ago`:`${s}d ago`}function kTe(e){if(!e?.isError)return null;if(e.content&&Array.isArray(e.content)){const t=e.content.filter(n=>n.type==="text").map(n=>n.text).filter(Boolean);if(t.length>0)return t.join(`
1660
+ `);k=I.pop()||"";for(const A of I)if(A.trim()&&A.startsWith("data: "))try{const O=JSON.parse(A.slice(6));if(console.log("[Client received event]",O.type,O.toolName||O.content?.slice?.(0,30)),O.type==="message")console.log("[Message started]",O.id);else if(O.type==="text"){S+=O.content;const M=y[y.length-1];M&&M.type==="text"?M.text=S:y.push({type:"text",text:S}),console.log("[Parts after text]",y.length,"parts, text length:",S.length),i(P=>P.map(B=>B.id===x?{...B,parts:[...y]}:B))}else if(O.type==="tool-call")S&&(S=""),y.push({type:"tool-invocation",toolInvocation:{toolName:O.toolName,args:O.args,state:"pending"}}),console.log("[Parts after tool-call]",y.length,"parts, tool:",O.toolName),i(M=>M.map(P=>P.id===x?{...P,parts:[...y]}:P));else if(O.type==="tool-result"){const M=y.find(P=>P.type==="tool-invocation"&&P.toolInvocation?.toolName===O.toolName&&!P.toolInvocation?.result);M&&M.toolInvocation?(M.toolInvocation.result=O.result,M.toolInvocation.state="result",console.log("[Parts after tool-result]",y.length,"parts, updated:",O.toolName),i(P=>P.map(B=>B.id===x?{...B,parts:[...y]}:B))):console.warn("[tool-result] Could not find matching tool part for",O.toolName)}else if(O.type==="done")console.log("[Done] Final parts:",y.length),i(M=>M.map(P=>P.id===x?{...P,parts:[...y],content:""}:P));else if(O.type==="error")throw new Error(O.message||"Streaming error")}catch(O){console.error("Failed to parse streaming event:",O,A)}}}catch(g){let v="Unknown error occurred";if(g instanceof Error){v=g.message;const S=g;S.status&&(v=`HTTP ${S.status}: ${v}`),(S.code===401||v.includes("401")||v.includes("Unauthorized"))&&(v="Authentication failed (401). Check your Authorization header in the connection settings.")}const x={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${v}`,timestamp:Date.now()};i(S=>[...S,x])}finally{c(!1)}},[t,a,e,r,n]),d=w.useCallback(()=>{i([])},[]);return{messages:r,isLoading:s,sendMessage:u,clearMessages:d}}function Pke({connection:e,llmConfig:t,isConnected:n,readResource:a}){const[r,i]=w.useState([]),[s,c]=w.useState(!1),u=w.useRef(null),d=w.useRef(null),m=w.useRef(null),h=w.useCallback(async v=>{if(!v.trim()||!t||!n)return;const x={id:`user-${Date.now()}`,role:"user",content:v.trim(),timestamp:Date.now()};i(E=>[...E,x]),c(!0),u.current=new AbortController;const S=Date.now();let y=0;try{const E=`assistant-${Date.now()}`;let _="";const k=[];if(i(C=>[...C,{id:E,role:"assistant",content:"",timestamp:Date.now(),parts:[]}]),!m.current||m.current.provider!==t.provider||m.current.model!==t.model||m.current.apiKey!==t.apiKey){let C;if(t.provider==="openai"){const{ChatOpenAI:R}=await Jn(async()=>{const{ChatOpenAI:I}=await import("./index-BUXkns-K.js");return{ChatOpenAI:I}},__vite__mapDeps([6,7,8,2,9,10,11]));C=new R({model:t.model,apiKey:t.apiKey})}else if(t.provider==="anthropic"){const{ChatAnthropic:R}=await Jn(async()=>{const{ChatAnthropic:I}=await import("./index-9nm0CCqb.js");return{ChatAnthropic:I}},__vite__mapDeps([12,8,7,2,11]));C=new R({model:t.model,apiKey:t.apiKey})}else if(t.provider==="google"){const{ChatGoogleGenerativeAI:R}=await Jn(async()=>{const{ChatGoogleGenerativeAI:I}=await import("./index-CrVavwoh.js");return{ChatGoogleGenerativeAI:I}},__vite__mapDeps([13,8,7,2,10]));C=new R({model:t.model,apiKey:t.apiKey})}else throw new Error(`Unsupported LLM provider: ${t.provider}`);m.current={instance:C,provider:t.provider,model:t.model,apiKey:t.apiKey}}if(!d.current||d.current.llm!==m.current.instance){const{MCPAgent:C}=await Jn(async()=>{const{MCPAgent:R}=await import("./browser-BGOI9nSM.js");return{MCPAgent:R}},__vite__mapDeps([14,4,5,3,11,7,8,2,10,9]));d.current=new C({llm:m.current.instance,client:e.client,memoryEnabled:!0,systemPrompt:"You are a helpful assistant with access to MCP tools, prompts, and resources. Help users interact with the MCP server."}),await d.current.initialize()}else console.log("[useChatMessagesClientSide] Reusing existing agent. History length:",d.current.conversationHistory?.length);for await(const C of d.current.streamEvents(v,10,!1,void 0)){if(u.current?.signal.aborted)break;if(C.event==="on_chat_model_stream"&&C.data?.chunk?.text){const R=C.data.chunk.text;if(typeof R=="string"&&R.length>0){_+=R;const I=k[k.length-1];I&&I.type==="text"?I.text=_:k.push({type:"text",text:_}),i(A=>A.map(O=>O.id===E?{...O,parts:[...k]}:O))}}else if(C.event==="on_tool_start"){_&&(_="");let R={};C.data?.input?R=C.data.input:C.data?.tool_input?R=C.data.tool_input:C.data&&(R=C.data),console.log("[useChatMessagesClientSide] on_tool_start:",{toolName:C.name,eventData:C.data,extractedArgs:R}),y++,k.push({type:"tool-invocation",toolInvocation:{toolName:C.name||"unknown",args:R,state:"pending"}}),i(I=>I.map(A=>A.id===E?{...A,parts:[...k]}:A))}else if(C.event==="on_tool_end"){const R=k.find(I=>I.type==="tool-invocation"&&I.toolInvocation?.toolName===C.name&&!I.toolInvocation?.result);if(console.log("[useChatMessagesClientSide] on_tool_end event:",{toolName:C.name,hasToolPart:!!R,output:C.data?.output}),R&&R.toolInvocation){let I=C.data?.output;if(I?.kwargs?.content&&typeof I.kwargs.content=="string")try{I=JSON.parse(I.kwargs.content)}catch(O){console.warn("[useChatMessagesClientSide] Failed to parse kwargs.content:",O),I=I.kwargs.content}else if(I?.content&&typeof I.content=="string")try{I=JSON.parse(I.content)}catch{I=I.content}R.toolInvocation.result=I,R.toolInvocation.state="result";const A=I?._meta?.["openai/outputTemplate"];if(console.log("[useChatMessagesClientSide] Tool result:",{toolName:C.name,hasMeta:!!I?._meta,hasStructuredContent:!!I?.structuredContent,appsSdkUri:A}),A&&typeof A=="string"&&a){console.log("[useChatMessagesClientSide] Detected Apps SDK component, fetching resource:",A);try{const O=await a(A);console.log("[useChatMessagesClientSide] Resource fetched:",O);const M=I?.structuredContent||null;if(O?.contents&&Array.isArray(O.contents)){const P=O.contents.map(K=>({type:"resource",resource:K}));console.log("[useChatMessagesClientSide] Created MCP resources:",P);const B={...I,content:[...I.content||[],...P],structuredContent:M};R.toolInvocation.result=B,console.log("[useChatMessagesClientSide] Updated result with resources")}else console.warn("[useChatMessagesClientSide] No contents in resourceData:",O)}catch(O){console.error("Failed to fetch Apps SDK resource:",O)}}i(O=>O.map(M=>M.id===E?{...M,parts:[...k]}:M))}}}i(C=>C.map(R=>R.id===E?{...R,parts:[...k],content:""}:R)),t&&vr.getInstance().capture(new QU({serverId:e.url,provider:t.provider,model:t.model,messageCount:r.length+1,toolCallsCount:y,success:!0,executionMode:"client-side",duration:Date.now()-S})).catch(()=>{})}catch(E){console.error("Client-side agent error:",E);let _="Unknown error occurred";if(E instanceof Error){_=E.message;const C=E;C.status&&(_=`HTTP ${C.status}: ${_}`),(C.code===401||_.includes("401")||_.includes("Unauthorized"))&&(_="Authentication failed (401). Check your Authorization header in the connection settings.")}t&&vr.getInstance().capture(new QU({serverId:e.url,provider:t.provider,model:t.model,messageCount:r.length+1,toolCallsCount:y,success:!1,executionMode:"client-side",duration:Date.now()-S,error:_})).catch(()=>{});const k={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${_}`,timestamp:Date.now()};i(C=>[...C,k])}finally{c(!1),u.current=null}},[e,t,n,r,a]),g=w.useCallback(()=>{i([]),d.current&&d.current.clearConversationHistory()},[]);return{messages:r,isLoading:s,sendMessage:h,clearMessages:g}}const E2={openai:"gpt-4o",anthropic:"claude-haiku-4-5-20251001",google:"gemini-2.5-flash"};function _Y({mcpServerUrl:e}){const[t,n]=w.useState(null),[a,r]=w.useState(null),[i,s]=w.useState(!1),[c,u]=w.useState("openai"),[d,m]=w.useState(""),[h,g]=w.useState(E2.openai),v=w.useCallback(()=>{const M=localStorage.getItem("mcp-inspector-api-keys");if(M)try{return JSON.parse(M)}catch(P){return console.error("Failed to load API keys:",P),{}}return{}},[]),x=w.useCallback(M=>{localStorage.setItem("mcp-inspector-api-keys",JSON.stringify(M))},[]),[S,y]=w.useState("none"),[E,_]=w.useState(""),[k,C]=w.useState(""),[R,I]=w.useState("");w.useEffect(()=>{const M=localStorage.getItem("mcp-inspector-llm-config"),P=v();if(M)try{const B=JSON.parse(M);n(B),u(B.provider),m(P[B.provider]||B.apiKey||""),g(B.model)}catch(B){console.error("Failed to load LLM config:",B)}},[v]),w.useEffect(()=>{const M=localStorage.getItem("mcp-inspector-auth-config");if(M)try{const P=JSON.parse(M);r(P),y(P.type),P.username&&_(P.username),P.password&&C(P.password),P.token&&I(P.token)}catch(P){console.error("Failed to load auth config:",P)}else try{const P="mcp:auth",B=xY(e),K=`${P}_${B}_tokens`;localStorage.getItem(K)&&(r({type:"oauth"}),y("oauth"))}catch(P){console.error("Failed to check for OAuth tokens:",P)}},[e]),w.useEffect(()=>{g(E2[c]);const M=v();m(M[c]||"")},[c,v]);const A=w.useCallback(()=>{if(!d.trim())return;const M=v();M[c]=d,x(M);const P={provider:c,apiKey:d,model:h},B={type:S,...S==="basic"&&{username:E.trim(),password:k.trim()},...S==="bearer"&&{token:R.trim()}};n(P),r(B),localStorage.setItem("mcp-inspector-llm-config",JSON.stringify(P)),localStorage.setItem("mcp-inspector-auth-config",JSON.stringify(B)),s(!1)},[c,d,h,S,E,k,R,v,x]),O=w.useCallback(()=>{n(null),r(null);const M=v();delete M[c],x(M),m(""),_(""),C(""),I(""),y("none"),localStorage.removeItem("mcp-inspector-llm-config"),localStorage.removeItem("mcp-inspector-auth-config")},[c,v,x]);return{llmConfig:t,authConfig:a,configDialogOpen:i,setConfigDialogOpen:s,tempProvider:c,setTempProvider:u,tempApiKey:d,setTempApiKey:m,tempModel:h,setTempModel:g,tempAuthType:S,saveLLMConfig:A,clearConfig:O}}function Uke({connection:e,isConnected:t,useClientSide:n=!0,readResource:a}){const[r,i]=w.useState(""),s=w.useRef(null),{llmConfig:c,authConfig:u,configDialogOpen:d,setConfigDialogOpen:m,tempProvider:h,setTempProvider:g,tempApiKey:v,setTempApiKey:x,tempModel:S,setTempModel:y,saveLLMConfig:E,clearConfig:_}=_Y({mcpServerUrl:e.url}),k={connection:e,llmConfig:c,isConnected:t,readResource:a},C=Mke({mcpServerUrl:e.url,llmConfig:c,authConfig:u,isConnected:t}),R=Pke(k),{messages:I,isLoading:A,sendMessage:O,clearMessages:M}=n?R:C;SK({onNewChat:M}),w.useEffect(()=>{c&&I.length===0&&s.current&&s.current.focus()},[c,I.length]),w.useEffect(()=>{!A&&I.length>0&&s.current&&s.current.focus()},[A,I.length]);const P=w.useCallback(()=>{r.trim()&&(O(r),i(""))},[r,O]),B=w.useCallback(ee=>{ee.key==="Enter"&&!ee.shiftKey&&(ee.preventDefault(),P())},[P]),K=w.useCallback(()=>{_(),M()},[_,M]);return c&&I.length===0?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsx("div",{className:"absolute top-4 right-4 z-10",children:f.jsx(NE,{open:d,onOpenChange:m,tempProvider:h,tempModel:S,tempApiKey:v,onProviderChange:g,onModelChange:y,onApiKeyChange:x,onSave:E,onClear:K,showClearButton:!0,buttonLabel:"Change API Key"})}),f.jsx(QSe,{mcpServerUrl:e.url,inputValue:r,isConnected:t,isLoading:A,textareaRef:s,llmConfig:c,onInputChange:i,onKeyDown:B,onSubmit:ee=>{ee.preventDefault(),P()},onConfigDialogOpenChange:m})]}):f.jsxs("div",{className:"flex flex-col h-full relative",children:[f.jsx(qSe,{llmConfig:c,hasMessages:I.length>0,configDialogOpen:d,onConfigDialogOpenChange:m,onClearChat:M,tempProvider:h,tempModel:S,tempApiKey:v,onProviderChange:g,onModelChange:y,onApiKeyChange:x,onSaveConfig:E,onClearConfig:K}),f.jsx("div",{className:"flex-1 overflow-y-auto p-2 sm:p-4 pt-[80px] sm:pt-[100px]",children:c?f.jsx(Lke,{messages:I,isLoading:A,serverId:e.url,readResource:a,tools:e.tools}):f.jsx(exe,{onConfigureClick:()=>m(!0)})}),c&&f.jsx(XSe,{inputValue:r,isConnected:t,isLoading:A,textareaRef:s,onInputChange:i,onKeyDown:B,onSendMessage:P})]})}const Ew=w.createContext(null);Ew.displayName="PanelGroupContext";const Zn={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},SD=10,Ul=w.useLayoutEffect,k2=kd.useId,zke=typeof k2=="function"?k2:()=>null;let Fke=0;function xD(e=null){const t=zke(),n=w.useRef(e||t||null);return n.current===null&&(n.current=""+Fke++),e??n.current}function EY({children:e,className:t="",collapsedSize:n,collapsible:a,defaultSize:r,forwardedRef:i,id:s,maxSize:c,minSize:u,onCollapse:d,onExpand:m,onResize:h,order:g,style:v,tagName:x="div",...S}){const y=w.useContext(Ew);if(y===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:E,expandPanel:_,getPanelSize:k,getPanelStyle:C,groupId:R,isPanelCollapsed:I,reevaluatePanelConstraints:A,registerPanel:O,resizePanel:M,unregisterPanel:P}=y,B=xD(s),K=w.useRef({callbacks:{onCollapse:d,onExpand:m,onResize:h},constraints:{collapsedSize:n,collapsible:a,defaultSize:r,maxSize:c,minSize:u},id:B,idIsFromProps:s!==void 0,order:g});w.useRef({didLogMissingDefaultSizeWarning:!1}),Ul(()=>{const{callbacks:te,constraints:ae}=K.current,H={...ae};K.current.id=B,K.current.idIsFromProps=s!==void 0,K.current.order=g,te.onCollapse=d,te.onExpand=m,te.onResize=h,ae.collapsedSize=n,ae.collapsible=a,ae.defaultSize=r,ae.maxSize=c,ae.minSize=u,(H.collapsedSize!==ae.collapsedSize||H.collapsible!==ae.collapsible||H.maxSize!==ae.maxSize||H.minSize!==ae.minSize)&&A(K.current,H)}),Ul(()=>{const te=K.current;return O(te),()=>{P(te)}},[g,B,O,P]),w.useImperativeHandle(i,()=>({collapse:()=>{E(K.current)},expand:te=>{_(K.current,te)},getId(){return B},getSize(){return k(K.current)},isCollapsed(){return I(K.current)},isExpanded(){return!I(K.current)},resize:te=>{M(K.current,te)}}),[E,_,k,I,B,M]);const ee=C(K.current,r);return w.createElement(x,{...S,children:e,className:t,id:B,style:{...ee,...v},[Zn.groupId]:R,[Zn.panel]:"",[Zn.panelCollapsible]:a||void 0,[Zn.panelId]:B,[Zn.panelSize]:parseFloat(""+ee.flexGrow).toFixed(1)})}const kY=w.forwardRef((e,t)=>w.createElement(EY,{...e,forwardedRef:t}));EY.displayName="Panel";kY.displayName="forwardRef(Panel)";let nk=null,qb=-1,Rs=null;function Bke(e,t,n){const a=(t&AY)!==0,r=(t&IY)!==0,i=(t&OY)!==0,s=(t&DY)!==0;if(t){if(a)return i?"se-resize":s?"ne-resize":"e-resize";if(r)return i?"sw-resize":s?"nw-resize":"w-resize";if(i)return"s-resize";if(s)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function Hke(){Rs!==null&&(document.head.removeChild(Rs),nk=null,Rs=null,qb=-1)}function Xx(e,t,n){var a,r;const i=Bke(e,t);if(nk!==i){if(nk=i,Rs===null&&(Rs=document.createElement("style"),document.head.appendChild(Rs)),qb>=0){var s;(s=Rs.sheet)===null||s===void 0||s.removeRule(qb)}qb=(a=(r=Rs.sheet)===null||r===void 0?void 0:r.insertRule(`*{cursor: ${i} !important;}`))!==null&&a!==void 0?a:-1}}function TY(e){return e.type==="keydown"}function NY(e){return e.type.startsWith("pointer")}function CY(e){return e.type.startsWith("mouse")}function kw(e){if(NY(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(CY(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function Vke(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function Gke(e,t,n){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function Wke(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:C2(e),b:C2(t)};let a;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),a=e;It(a,"Stacking order can only be calculated for elements with a common ancestor");const r={a:N2(T2(n.a)),b:N2(T2(n.b))};if(r.a===r.b){const i=a.childNodes,s={a:n.a.at(-1),b:n.b.at(-1)};let c=i.length;for(;c--;){const u=i[c];if(u===s.a)return 1;if(u===s.b)return-1}}return Math.sign(r.a-r.b)}const Kke=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function Zke(e){var t;const n=getComputedStyle((t=RY(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function Yke(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||Zke(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||Kke.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function T2(e){let t=e.length;for(;t--;){const n=e[t];if(It(n,"Missing node"),Yke(n))return n}return null}function N2(e){return e&&Number(getComputedStyle(e).zIndex)||0}function C2(e){const t=[];for(;e;)t.push(e),e=RY(e);return t}function RY(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const AY=1,IY=2,OY=4,DY=8,qke=Vke()==="coarse";let wi=[],Cu=!1,As=new Map,Tw=new Map;const sm=new Set;function Xke(e,t,n,a,r){var i;const{ownerDocument:s}=t,c={direction:n,element:t,hitAreaMargins:a,setResizeHandlerState:r},u=(i=As.get(s))!==null&&i!==void 0?i:0;return As.set(s,u+1),sm.add(c),Qv(),function(){var m;Tw.delete(e),sm.delete(c);const h=(m=As.get(s))!==null&&m!==void 0?m:1;if(As.set(s,h-1),Qv(),h===1&&As.delete(s),wi.includes(c)){const g=wi.indexOf(c);g>=0&&wi.splice(g,1),Nw(),r("up",!0,null)}}}function Jke(e){const{target:t}=e,{x:n,y:a}=kw(e);Cu=!0,_D({target:t,x:n,y:a}),Qv(),wi.length>0&&(ey("down",e),Nw(),e.preventDefault(),jY(t)||e.stopImmediatePropagation())}function Jx(e){const{x:t,y:n}=kw(e);if(Cu&&e.type!=="pointerleave"&&e.buttons===0&&(Cu=!1,ey("up",e)),!Cu){const{target:a}=e;_D({target:a,x:t,y:n})}ey("move",e),Nw(),wi.length>0&&e.preventDefault()}function Qx(e){const{target:t}=e,{x:n,y:a}=kw(e);Tw.clear(),Cu=!1,wi.length>0&&(e.preventDefault(),jY(t)||e.stopImmediatePropagation()),ey("up",e),_D({target:t,x:n,y:a}),Nw(),Qv()}function jY(e){let t=e;for(;t;){if(t.hasAttribute(Zn.resizeHandle))return!0;t=t.parentElement}return!1}function _D({target:e,x:t,y:n}){wi.splice(0);let a=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(a=e),sm.forEach(r=>{const{element:i,hitAreaMargins:s}=r,c=i.getBoundingClientRect(),{bottom:u,left:d,right:m,top:h}=c,g=qke?s.coarse:s.fine;if(t>=d-g&&t<=m+g&&n>=h-g&&n<=u+g){if(a!==null&&document.contains(a)&&i!==a&&!i.contains(a)&&!a.contains(i)&&Wke(a,i)>0){let x=a,S=!1;for(;x&&!x.contains(i);){if(Gke(x.getBoundingClientRect(),c)){S=!0;break}x=x.parentElement}if(S)return}wi.push(r)}})}function e_(e,t){Tw.set(e,t)}function Nw(){let e=!1,t=!1;wi.forEach(a=>{const{direction:r}=a;r==="horizontal"?e=!0:t=!0});let n=0;Tw.forEach(a=>{n|=a}),e&&t?Xx("intersection",n):e?Xx("horizontal",n):t?Xx("vertical",n):Hke()}let t_;function Qv(){var e;(e=t_)===null||e===void 0||e.abort(),t_=new AbortController;const t={capture:!0,signal:t_.signal};sm.size&&(Cu?(wi.length>0&&As.forEach((n,a)=>{const{body:r}=a;n>0&&(r.addEventListener("contextmenu",Qx,t),r.addEventListener("pointerleave",Jx,t),r.addEventListener("pointermove",Jx,t))}),As.forEach((n,a)=>{const{body:r}=a;r.addEventListener("pointerup",Qx,t),r.addEventListener("pointercancel",Qx,t)})):As.forEach((n,a)=>{const{body:r}=a;n>0&&(r.addEventListener("pointerdown",Jke,t),r.addEventListener("pointermove",Jx,t))}))}function ey(e,t){sm.forEach(n=>{const{setResizeHandlerState:a}=n,r=wi.includes(n);a(e,r,t)})}function Qke(){const[e,t]=w.useState(0);return w.useCallback(()=>t(n=>n+1),[])}function It(e,t){if(!e)throw console.error(t),Error(t)}function Ql(e,t,n=SD){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function To(e,t,n=SD){return Ql(e,t,n)===0}function Da(e,t,n){return Ql(e,t,n)===0}function eTe(e,t,n){if(e.length!==t.length)return!1;for(let a=0;a<e.length;a++){const r=e[a],i=t[a];if(!Da(r,i,n))return!1}return!0}function wu({panelConstraints:e,panelIndex:t,size:n}){const a=e[t];It(a!=null,`Panel constraints not found for index ${t}`);let{collapsedSize:r=0,collapsible:i,maxSize:s=100,minSize:c=0}=a;if(Ql(n,c)<0)if(i){const u=(r+c)/2;Ql(n,u)<0?n=r:n=c}else n=c;return n=Math.min(s,n),n=parseFloat(n.toFixed(SD)),n}function cp({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:a,prevLayout:r,trigger:i}){if(Da(e,0))return t;const s=[...t],[c,u]=a;It(c!=null,"Invalid first pivot index"),It(u!=null,"Invalid second pivot index");let d=0;if(i==="keyboard"){{const h=e<0?u:c,g=n[h];It(g,`Panel constraints not found for index ${h}`);const{collapsedSize:v=0,collapsible:x,minSize:S=0}=g;if(x){const y=t[h];if(It(y!=null,`Previous layout not found for panel index ${h}`),Da(y,v)){const E=S-y;Ql(E,Math.abs(e))>0&&(e=e<0?0-E:E)}}}{const h=e<0?c:u,g=n[h];It(g,`No panel constraints found for index ${h}`);const{collapsedSize:v=0,collapsible:x,minSize:S=0}=g;if(x){const y=t[h];if(It(y!=null,`Previous layout not found for panel index ${h}`),Da(y,S)){const E=y-v;Ql(E,Math.abs(e))>0&&(e=e<0?0-E:E)}}}}{const h=e<0?1:-1;let g=e<0?u:c,v=0;for(;;){const S=t[g];It(S!=null,`Previous layout not found for panel index ${g}`);const E=wu({panelConstraints:n,panelIndex:g,size:100})-S;if(v+=E,g+=h,g<0||g>=n.length)break}const x=Math.min(Math.abs(e),Math.abs(v));e=e<0?0-x:x}{let g=e<0?c:u;for(;g>=0&&g<n.length;){const v=Math.abs(e)-Math.abs(d),x=t[g];It(x!=null,`Previous layout not found for panel index ${g}`);const S=x-v,y=wu({panelConstraints:n,panelIndex:g,size:S});if(!Da(x,y)&&(d+=x-y,s[g]=y,d.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?g--:g++}}if(eTe(r,s))return r;{const h=e<0?u:c,g=t[h];It(g!=null,`Previous layout not found for panel index ${h}`);const v=g+d,x=wu({panelConstraints:n,panelIndex:h,size:v});if(s[h]=x,!Da(x,v)){let S=v-x,E=e<0?u:c;for(;E>=0&&E<n.length;){const _=s[E];It(_!=null,`Previous layout not found for panel index ${E}`);const k=_+S,C=wu({panelConstraints:n,panelIndex:E,size:k});if(Da(_,C)||(S-=C-_,s[E]=C),Da(S,0))break;e>0?E--:E++}}}const m=s.reduce((h,g)=>g+h,0);return Da(m,100)?s:r}function tTe({layout:e,panelsArray:t,pivotIndices:n}){let a=0,r=100,i=0,s=0;const c=n[0];It(c!=null,"No pivot index found"),t.forEach((h,g)=>{const{constraints:v}=h,{maxSize:x=100,minSize:S=0}=v;g===c?(a=S,r=x):(i+=S,s+=x)});const u=Math.min(r,100-i),d=Math.max(a,100-s),m=e[c];return{valueMax:u,valueMin:d,valueNow:m}}function lm(e,t=document){return Array.from(t.querySelectorAll(`[${Zn.resizeHandleId}][data-panel-group-id="${e}"]`))}function $Y(e,t,n=document){const r=lm(e,n).findIndex(i=>i.getAttribute(Zn.resizeHandleId)===t);return r??null}function LY(e,t,n){const a=$Y(e,t,n);return a!=null?[a,a+1]:[-1,-1]}function nTe(e){return e instanceof HTMLElement?!0:typeof e=="object"&&e!==null&&"tagName"in e&&"getAttribute"in e}function MY(e,t=document){if(nTe(t)&&t.dataset.panelGroupId==e)return t;const n=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return n||null}function Cw(e,t=document){const n=t.querySelector(`[${Zn.resizeHandleId}="${e}"]`);return n||null}function rTe(e,t,n,a=document){var r,i,s,c;const u=Cw(t,a),d=lm(e,a),m=u?d.indexOf(u):-1,h=(r=(i=n[m])===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:null,g=(s=(c=n[m+1])===null||c===void 0?void 0:c.id)!==null&&s!==void 0?s:null;return[h,g]}function aTe({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:a,panelDataArray:r,panelGroupElement:i,setLayout:s}){w.useRef({didWarnAboutMissingResizeHandle:!1}),Ul(()=>{if(!i)return;const c=lm(n,i);for(let u=0;u<r.length-1;u++){const{valueMax:d,valueMin:m,valueNow:h}=tTe({layout:a,panelsArray:r,pivotIndices:[u,u+1]}),g=c[u];if(g!=null){const v=r[u];It(v,`No panel data found for index "${u}"`),g.setAttribute("aria-controls",v.id),g.setAttribute("aria-valuemax",""+Math.round(d)),g.setAttribute("aria-valuemin",""+Math.round(m)),g.setAttribute("aria-valuenow",h!=null?""+Math.round(h):"")}}return()=>{c.forEach((u,d)=>{u.removeAttribute("aria-controls"),u.removeAttribute("aria-valuemax"),u.removeAttribute("aria-valuemin"),u.removeAttribute("aria-valuenow")})}},[n,a,r,i]),w.useEffect(()=>{if(!i)return;const c=t.current;It(c,"Eager values not found");const{panelDataArray:u}=c,d=MY(n,i);It(d!=null,`No group found for id "${n}"`);const m=lm(n,i);It(m,`No resize handles found for group id "${n}"`);const h=m.map(g=>{const v=g.getAttribute(Zn.resizeHandleId);It(v,"Resize handle element has no handle id attribute");const[x,S]=rTe(n,v,u,i);if(x==null||S==null)return()=>{};const y=E=>{if(!E.defaultPrevented)switch(E.key){case"Enter":{E.preventDefault();const _=u.findIndex(k=>k.id===x);if(_>=0){const k=u[_];It(k,`No panel data found for index ${_}`);const C=a[_],{collapsedSize:R=0,collapsible:I,minSize:A=0}=k.constraints;if(C!=null&&I){const O=cp({delta:Da(C,R)?A-R:R-C,initialLayout:a,panelConstraints:u.map(M=>M.constraints),pivotIndices:LY(n,v,i),prevLayout:a,trigger:"keyboard"});a!==O&&s(O)}}break}}};return g.addEventListener("keydown",y),()=>{g.removeEventListener("keydown",y)}});return()=>{h.forEach(g=>g())}},[i,e,t,n,a,r,s])}function R2(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function PY(e,t){const n=e==="horizontal",{x:a,y:r}=kw(t);return n?a:r}function iTe(e,t,n,a,r){const i=n==="horizontal",s=Cw(t,r);It(s,`No resize handle element found for id "${t}"`);const c=s.getAttribute(Zn.groupId);It(c,"Resize handle element has no group id attribute");let{initialCursorPosition:u}=a;const d=PY(n,e),m=MY(c,r);It(m,`No group element found for id "${c}"`);const h=m.getBoundingClientRect(),g=i?h.width:h.height;return(d-u)/g*100}function oTe(e,t,n,a,r,i){if(TY(e)){const s=n==="horizontal";let c=0;e.shiftKey?c=100:r!=null?c=r:c=10;let u=0;switch(e.key){case"ArrowDown":u=s?0:c;break;case"ArrowLeft":u=s?-c:0;break;case"ArrowRight":u=s?c:0;break;case"ArrowUp":u=s?0:-c;break;case"End":u=100;break;case"Home":u=-100;break}return u}else return a==null?0:iTe(e,t,n,a,i)}function sTe({panelDataArray:e}){const t=Array(e.length),n=e.map(i=>i.constraints);let a=0,r=100;for(let i=0;i<e.length;i++){const s=n[i];It(s,`Panel constraints not found for index ${i}`);const{defaultSize:c}=s;c!=null&&(a++,t[i]=c,r-=c)}for(let i=0;i<e.length;i++){const s=n[i];It(s,`Panel constraints not found for index ${i}`);const{defaultSize:c}=s;if(c!=null)continue;const u=e.length-a,d=r/u;a++,t[i]=d,r-=d}return t}function Xc(e,t,n){t.forEach((a,r)=>{const i=e[r];It(i,`Panel data not found for index ${r}`);const{callbacks:s,constraints:c,id:u}=i,{collapsedSize:d=0,collapsible:m}=c,h=n[u];if(h==null||a!==h){n[u]=a;const{onCollapse:g,onExpand:v,onResize:x}=s;x&&x(a,h),m&&(g||v)&&(v&&(h==null||To(h,d))&&!To(a,d)&&v(),g&&(h==null||!To(h,d))&&To(a,d)&&g())}})}function Eb(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function lTe({defaultSize:e,dragState:t,layout:n,panelData:a,panelIndex:r,precision:i=3}){const s=n[r];let c;return s==null?c=e!=null?e.toFixed(i):"1":a.length===1?c="1":c=s.toFixed(i),{flexBasis:0,flexGrow:c,flexShrink:1,overflow:"hidden",pointerEvents:t!==null?"none":void 0}}function cTe(e,t=10){let n=null;return(...r)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...r)},t)}}function A2(e){try{if(typeof localStorage<"u")e.getItem=t=>localStorage.getItem(t),e.setItem=(t,n)=>{localStorage.setItem(t,n)};else throw new Error("localStorage not supported in this environment")}catch(t){console.error(t),e.getItem=()=>null,e.setItem=()=>{}}}function UY(e){return`react-resizable-panels:${e}`}function zY(e){return e.map(t=>{const{constraints:n,id:a,idIsFromProps:r,order:i}=t;return r?a:i?`${i}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function FY(e,t){try{const n=UY(e),a=t.getItem(n);if(a){const r=JSON.parse(a);if(typeof r=="object"&&r!=null)return r}}catch{}return null}function uTe(e,t,n){var a,r;const i=(a=FY(e,n))!==null&&a!==void 0?a:{},s=zY(t);return(r=i[s])!==null&&r!==void 0?r:null}function dTe(e,t,n,a,r){var i;const s=UY(e),c=zY(t),u=(i=FY(e,r))!==null&&i!==void 0?i:{};u[c]={expandToSizes:Object.fromEntries(n.entries()),layout:a};try{r.setItem(s,JSON.stringify(u))}catch(d){console.error(d)}}function I2({layout:e,panelConstraints:t}){const n=[...e],a=n.reduce((i,s)=>i+s,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(i=>`${i}%`).join(", ")}`);if(!Da(a,100)&&n.length>0)for(let i=0;i<t.length;i++){const s=n[i];It(s!=null,`No layout data found for index ${i}`);const c=100/a*s;n[i]=c}let r=0;for(let i=0;i<t.length;i++){const s=n[i];It(s!=null,`No layout data found for index ${i}`);const c=wu({panelConstraints:t,panelIndex:i,size:s});s!=c&&(r+=s-c,n[i]=c)}if(!Da(r,0))for(let i=0;i<t.length;i++){const s=n[i];It(s!=null,`No layout data found for index ${i}`);const c=s+r,u=wu({panelConstraints:t,panelIndex:i,size:c});if(s!==u&&(r-=u-s,n[i]=u,Da(r,0)))break}return n}const fTe=100,up={getItem:e=>(A2(up),up.getItem(e)),setItem:(e,t)=>{A2(up),up.setItem(e,t)}},O2={};function BY({autoSaveId:e=null,children:t,className:n="",direction:a,forwardedRef:r,id:i=null,onLayout:s=null,keyboardResizeBy:c=null,storage:u=up,style:d,tagName:m="div",...h}){const g=xD(i),v=w.useRef(null),[x,S]=w.useState(null),[y,E]=w.useState([]),_=Qke(),k=w.useRef({}),C=w.useRef(new Map),R=w.useRef(0),I=w.useRef({autoSaveId:e,direction:a,dragState:x,id:g,keyboardResizeBy:c,onLayout:s,storage:u}),A=w.useRef({layout:y,panelDataArray:[],panelDataArrayChanged:!1});w.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),w.useImperativeHandle(r,()=>({getId:()=>I.current.id,getLayout:()=>{const{layout:z}=A.current;return z},setLayout:z=>{const{onLayout:$}=I.current,{layout:L,panelDataArray:F}=A.current,W=I2({layout:z,panelConstraints:F.map(X=>X.constraints)});R2(L,W)||(E(W),A.current.layout=W,$&&$(W),Xc(F,W,k.current))}}),[]),Ul(()=>{I.current.autoSaveId=e,I.current.direction=a,I.current.dragState=x,I.current.id=g,I.current.onLayout=s,I.current.storage=u}),aTe({committedValuesRef:I,eagerValuesRef:A,groupId:g,layout:y,panelDataArray:A.current.panelDataArray,setLayout:E,panelGroupElement:v.current}),w.useEffect(()=>{const{panelDataArray:z}=A.current;if(e){if(y.length===0||y.length!==z.length)return;let $=O2[e];$==null&&($=cTe(dTe,fTe),O2[e]=$);const L=[...z],F=new Map(C.current);$(e,L,F,y,u)}},[e,y,u]),w.useEffect(()=>{});const O=w.useCallback(z=>{const{onLayout:$}=I.current,{layout:L,panelDataArray:F}=A.current;if(z.constraints.collapsible){const W=F.map(J=>J.constraints),{collapsedSize:X=0,panelSize:ie,pivotIndices:ce}=_l(F,z,L);if(It(ie!=null,`Panel size not found for panel "${z.id}"`),!To(ie,X)){C.current.set(z.id,ie);const q=su(F,z)===F.length-1?ie-X:X-ie,le=cp({delta:q,initialLayout:L,panelConstraints:W,pivotIndices:ce,prevLayout:L,trigger:"imperative-api"});Eb(L,le)||(E(le),A.current.layout=le,$&&$(le),Xc(F,le,k.current))}}},[]),M=w.useCallback((z,$)=>{const{onLayout:L}=I.current,{layout:F,panelDataArray:W}=A.current;if(z.constraints.collapsible){const X=W.map(he=>he.constraints),{collapsedSize:ie=0,panelSize:ce=0,minSize:J=0,pivotIndices:q}=_l(W,z,F),le=$??J;if(To(ce,ie)){const he=C.current.get(z.id),oe=he!=null&&he>=le?he:le,Ve=su(W,z)===W.length-1?ce-oe:oe-ce,_e=cp({delta:Ve,initialLayout:F,panelConstraints:X,pivotIndices:q,prevLayout:F,trigger:"imperative-api"});Eb(F,_e)||(E(_e),A.current.layout=_e,L&&L(_e),Xc(W,_e,k.current))}}},[]),P=w.useCallback(z=>{const{layout:$,panelDataArray:L}=A.current,{panelSize:F}=_l(L,z,$);return It(F!=null,`Panel size not found for panel "${z.id}"`),F},[]),B=w.useCallback((z,$)=>{const{panelDataArray:L}=A.current,F=su(L,z);return lTe({defaultSize:$,dragState:x,layout:y,panelData:L,panelIndex:F})},[x,y]),K=w.useCallback(z=>{const{layout:$,panelDataArray:L}=A.current,{collapsedSize:F=0,collapsible:W,panelSize:X}=_l(L,z,$);return It(X!=null,`Panel size not found for panel "${z.id}"`),W===!0&&To(X,F)},[]),ee=w.useCallback(z=>{const{layout:$,panelDataArray:L}=A.current,{collapsedSize:F=0,collapsible:W,panelSize:X}=_l(L,z,$);return It(X!=null,`Panel size not found for panel "${z.id}"`),!W||Ql(X,F)>0},[]),te=w.useCallback(z=>{const{panelDataArray:$}=A.current;$.push(z),$.sort((L,F)=>{const W=L.order,X=F.order;return W==null&&X==null?0:W==null?-1:X==null?1:W-X}),A.current.panelDataArrayChanged=!0,_()},[_]);Ul(()=>{if(A.current.panelDataArrayChanged){A.current.panelDataArrayChanged=!1;const{autoSaveId:z,onLayout:$,storage:L}=I.current,{layout:F,panelDataArray:W}=A.current;let X=null;if(z){const ce=uTe(z,W,L);ce&&(C.current=new Map(Object.entries(ce.expandToSizes)),X=ce.layout)}X==null&&(X=sTe({panelDataArray:W}));const ie=I2({layout:X,panelConstraints:W.map(ce=>ce.constraints)});R2(F,ie)||(E(ie),A.current.layout=ie,$&&$(ie),Xc(W,ie,k.current))}}),Ul(()=>{const z=A.current;return()=>{z.layout=[]}},[]);const ae=w.useCallback(z=>{let $=!1;const L=v.current;return L&&window.getComputedStyle(L,null).getPropertyValue("direction")==="rtl"&&($=!0),function(W){W.preventDefault();const X=v.current;if(!X)return()=>null;const{direction:ie,dragState:ce,id:J,keyboardResizeBy:q,onLayout:le}=I.current,{layout:he,panelDataArray:oe}=A.current,{initialLayout:Ne}=ce??{},Ve=LY(J,z,X);let _e=oTe(W,z,ie,ce,q,X);const ke=ie==="horizontal";ke&&$&&(_e=-_e);const Fe=oe.map(He=>He.constraints),pe=cp({delta:_e,initialLayout:Ne??he,panelConstraints:Fe,pivotIndices:Ve,prevLayout:he,trigger:TY(W)?"keyboard":"mouse-or-touch"}),Oe=!Eb(he,pe);(NY(W)||CY(W))&&R.current!=_e&&(R.current=_e,!Oe&&_e!==0?ke?e_(z,_e<0?AY:IY):e_(z,_e<0?OY:DY):e_(z,0)),Oe&&(E(pe),A.current.layout=pe,le&&le(pe),Xc(oe,pe,k.current))}},[]),H=w.useCallback((z,$)=>{const{onLayout:L}=I.current,{layout:F,panelDataArray:W}=A.current,X=W.map(he=>he.constraints),{panelSize:ie,pivotIndices:ce}=_l(W,z,F);It(ie!=null,`Panel size not found for panel "${z.id}"`);const q=su(W,z)===W.length-1?ie-$:$-ie,le=cp({delta:q,initialLayout:F,panelConstraints:X,pivotIndices:ce,prevLayout:F,trigger:"imperative-api"});Eb(F,le)||(E(le),A.current.layout=le,L&&L(le),Xc(W,le,k.current))},[]),Z=w.useCallback((z,$)=>{const{layout:L,panelDataArray:F}=A.current,{collapsedSize:W=0,collapsible:X}=$,{collapsedSize:ie=0,collapsible:ce,maxSize:J=100,minSize:q=0}=z.constraints,{panelSize:le}=_l(F,z,L);le!=null&&(X&&ce&&To(le,W)?To(W,ie)||H(z,ie):le<q?H(z,q):le>J&&H(z,J))},[H]),G=w.useCallback((z,$)=>{const{direction:L}=I.current,{layout:F}=A.current;if(!v.current)return;const W=Cw(z,v.current);It(W,`Drag handle element not found for id "${z}"`);const X=PY(L,$);S({dragHandleId:z,dragHandleRect:W.getBoundingClientRect(),initialCursorPosition:X,initialLayout:F})},[]),re=w.useCallback(()=>{S(null)},[]),ne=w.useCallback(z=>{const{panelDataArray:$}=A.current,L=su($,z);L>=0&&($.splice(L,1),delete k.current[z.id],A.current.panelDataArrayChanged=!0,_())},[_]),j=w.useMemo(()=>({collapsePanel:O,direction:a,dragState:x,expandPanel:M,getPanelSize:P,getPanelStyle:B,groupId:g,isPanelCollapsed:K,isPanelExpanded:ee,reevaluatePanelConstraints:Z,registerPanel:te,registerResizeHandle:ae,resizePanel:H,startDragging:G,stopDragging:re,unregisterPanel:ne,panelGroupElement:v.current}),[O,x,a,M,P,B,g,K,ee,Z,te,ae,H,G,re,ne]),V={display:"flex",flexDirection:a==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return w.createElement(Ew.Provider,{value:j},w.createElement(m,{...h,children:t,className:n,id:i,ref:v,style:{...V,...d},[Zn.group]:"",[Zn.groupDirection]:a,[Zn.groupId]:g}))}const HY=w.forwardRef((e,t)=>w.createElement(BY,{...e,forwardedRef:t}));BY.displayName="PanelGroup";HY.displayName="forwardRef(PanelGroup)";function su(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function _l(e,t,n){const a=su(e,t),i=a===e.length-1?[a-1,a]:[a,a+1],s=n[a];return{...t.constraints,panelSize:s,pivotIndices:i}}function pTe({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:a}){w.useEffect(()=>{if(e||n==null||a==null)return;const r=Cw(t,a);if(r==null)return;const i=s=>{if(!s.defaultPrevented)switch(s.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{s.preventDefault(),n(s);break}case"F6":{s.preventDefault();const c=r.getAttribute(Zn.groupId);It(c,`No group element found for id "${c}"`);const u=lm(c,a),d=$Y(c,t,a);It(d!==null,`No resize element found for id "${t}"`);const m=s.shiftKey?d>0?d-1:u.length-1:d+1<u.length?d+1:0;u[m].focus();break}}};return r.addEventListener("keydown",i),()=>{r.removeEventListener("keydown",i)}},[a,e,t,n])}function VY({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:a,id:r,onBlur:i,onClick:s,onDragging:c,onFocus:u,onPointerDown:d,onPointerUp:m,style:h={},tabIndex:g=0,tagName:v="div",...x}){var S,y;const E=w.useRef(null),_=w.useRef({onClick:s,onDragging:c,onPointerDown:d,onPointerUp:m});w.useEffect(()=>{_.current.onClick=s,_.current.onDragging=c,_.current.onPointerDown=d,_.current.onPointerUp=m});const k=w.useContext(Ew);if(k===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:C,groupId:R,registerResizeHandle:I,startDragging:A,stopDragging:O,panelGroupElement:M}=k,P=xD(r),[B,K]=w.useState("inactive"),[ee,te]=w.useState(!1),[ae,H]=w.useState(null),Z=w.useRef({state:B});Ul(()=>{Z.current.state=B}),w.useEffect(()=>{if(n)H(null);else{const j=I(P);H(()=>j)}},[n,P,I]);const G=(S=a?.coarse)!==null&&S!==void 0?S:15,re=(y=a?.fine)!==null&&y!==void 0?y:5;w.useEffect(()=>{if(n||ae==null)return;const j=E.current;It(j,"Element ref not attached");let V=!1;return Xke(P,j,C,{coarse:G,fine:re},($,L,F)=>{if(!L){K("inactive");return}switch($){case"down":{K("drag"),V=!1,It(F,'Expected event to be defined for "down" action'),A(P,F);const{onDragging:W,onPointerDown:X}=_.current;W?.(!0),X?.();break}case"move":{const{state:W}=Z.current;V=!0,W!=="drag"&&K("hover"),It(F,'Expected event to be defined for "move" action'),ae(F);break}case"up":{K("hover"),O();const{onClick:W,onDragging:X,onPointerUp:ie}=_.current;X?.(!1),ie?.(),V||W?.();break}}})},[G,C,n,re,I,P,ae,A,O]),pTe({disabled:n,handleId:P,resizeHandler:ae,panelGroupElement:M});const ne={touchAction:"none",userSelect:"none"};return w.createElement(v,{...x,children:e,className:t,id:r,onBlur:()=>{te(!1),i?.()},onFocus:()=>{te(!0),u?.()},ref:E,role:"separator",style:{...ne,...h},tabIndex:g,[Zn.groupDirection]:C,[Zn.groupId]:R,[Zn.resizeHandle]:"",[Zn.resizeHandleActive]:B==="drag"?"pointer":ee?"keyboard":void 0,[Zn.resizeHandleEnabled]:!n,[Zn.resizeHandleId]:P,[Zn.resizeHandleState]:B})}VY.displayName="PanelResizeHandle";function na({className:e,...t}){return f.jsx(HY,{"data-slot":"resizable-panel-group",className:De("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t})}function Rn({...e}){return f.jsx(kY,{"data-slot":"resizable-panel",...e})}function Si({withHandle:e,className:t,...n}){return f.jsx(VY,{"data-slot":"resizable-handle",className:De("bg-border focus-visible:ring-ring relative flex w-px items-center justify-center after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:ring-1 focus-visible:ring-offset-1 focus-visible:outline-hidden data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:translate-x-0 data-[panel-group-direction=vertical]:after:-translate-y-1/2 [&[data-panel-group-direction=vertical]>div]:rotate-90",t),...n,children:e&&f.jsx("div",{className:"bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border",children:f.jsx(ahe,{className:"size-2.5"})})})}function eh({className:e,...t}){return f.jsx("kbd",{"data-slot":"kbd",className:De("bg-muted text-muted-foreground pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm px-1 font-sans text-xs font-medium select-none","[&_svg:not([class*='size-'])]:size-3","[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",e),...t})}function mTe({isSearchExpanded:e,searchQuery:t,filteredNotificationsCount:n,notificationsCount:a,onSearchExpand:r,onSearchChange:i,onSearchBlur:s,onClearAll:c,searchInputRef:u}){return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:u,placeholder:"Search notifications...",value:t,onChange:d=>i(d.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Notifications"}),f.jsx(wr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,disabled:a===0,className:"h-8 w-8 p-0",children:f.jsx(Fs,{className:"h-4 w-4"})})}),f.jsx(Rt,{side:"bottom",children:"Clear all"})]})})]})}function Qs({id:e,isSelected:t,isFocused:n,icon:a,title:r,description:i,metadata:s,onClick:c,className:u}){return f.jsx("button",{id:e,type:"button",onClick:c,className:De("w-full text-left cursor-pointer p-2 sm:p-4 border-b dark:border-zinc-700 hover:bg-gray-50 dark:hover:bg-zinc-800/50 transition-colors group",t&&"bg-zinc-50 dark:bg-zinc-800 border-l-4 border-l-zinc-500",n&&"ring-2 ring-zinc-500 dark:ring-zinc-400 ring-inset",u),children:f.jsxs("div",{className:"flex items-start gap-2 sm:gap-3",children:[a&&f.jsx("div",{className:"flex-shrink-0 mt-1",children:f.jsx("div",{className:De("p-2.5 rounded-full transition-colors",t?"bg-zinc-500 dark:bg-zinc-100/80 text-zinc-100 dark:text-zinc-900":"bg-gray-100 dark:bg-zinc-700 text-gray-600 dark:text-gray-400 group-hover:bg-gray-200 dark:group-hover:bg-zinc-600"),children:a})}),f.jsxs("div",{className:"flex-1 min-w-0",children:[f.jsx("div",{className:"flex items-center gap-2 mb-1",children:f.jsx("h3",{className:De("font-medium truncate font-mono text-sm"),children:r})}),i&&f.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 line-clamp-2",children:i})]})]})})}function hTe({notifications:e,selectedNotification:t,onNotificationSelect:n,focusedIndex:a,formatRelativeTime:r,listRef:i}){return e.length===0?f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No notifications yet"})}):f.jsx("div",{ref:i,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((s,c)=>f.jsx(Qs,{id:`notification-${s.id}`,isSelected:t?.id===s.id,isFocused:a===c,title:f.jsxs("span",{className:"flex items-center gap-3",children:[s.method,!s.read&&f.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const u=r(s.timestamp),d=s.params&&Object.keys(s.params).length>0?Object.keys(s.params).length:0,m=d>0?` | ${d} param${d>1?"s":""}`:"";return u+m})(),onClick:()=>n(s)},s.id))})}function gTe({notification:e,previewMode:t,onTogglePreview:n,onCopy:a,onDownload:r,onFullscreen:i,isCopied:s=!1,onClose:c}){return e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex-shrink-0 px-4 py-3 border-b border-gray-200 dark:border-zinc-700 flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(fd,{className:"h-3 w-3 text-gray-400"}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleTimeString()})]}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:e.formatRelativeTime(e.timestamp)})]}),f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsxs($e,{variant:"ghost",size:"sm",onClick:n,className:t?"":"text-purple-600 dark:text-purple-400",children:[t?f.jsx(XN,{className:"h-4 w-4 mr-1"}):f.jsx($G,{className:"h-4 w-4 mr-1"}),t?"JSON":"Formatted"]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:a,children:s?f.jsx(ra,{className:"h-4 w-4"}):f.jsx($r,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:r,children:f.jsx(Lm,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:i,children:f.jsx(eC,{className:"h-4 w-4"})}),c&&f.jsx($e,{variant:"ghost",size:"sm",onClick:c,children:f.jsx(Ji,{className:"h-4 w-4"})})]})]}),f.jsx("div",{className:"flex-1 overflow-y-auto",children:f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:{method:e.method,timestamp:e.timestamp,read:e.read,params:e.params},filename:`notification-${e.method.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(qN,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a notification to view details"})]})}function ty(e){const n=Date.now()-e,a=Math.floor(n/1e3),r=Math.floor(a/60),i=Math.floor(r/60),s=Math.floor(i/24);return a<60?"just now":r<60?`${r}m ago`:i<24?`${i}h ago`:s<7?`${s}d ago`:new Date(e).toLocaleDateString()}function bTe({notifications:e,unreadCount:t,markNotificationRead:n,markAllNotificationsRead:a,clearNotifications:r,serverId:i,isConnected:s}){const[c,u]=w.useState(null),[d,m]=w.useState(""),[h,g]=w.useState(-1),[v,x]=w.useState(!0),[S,y]=w.useState(!1),[E,_]=w.useState(!0),[k,C]=w.useState(!1),R=w.useRef(null),I=w.useRef(null),A=w.useRef(null),O=w.useRef(!1);w.useEffect(()=>{v&&e.length>0&&R.current&&!O.current&&(R.current.scrollTop=0)},[e.length,v]),w.useEffect(()=>{const Z=R.current;if(!Z)return;const G=()=>{Z.scrollTop>0&&(O.current=!0,x(!1))};return Z.addEventListener("scroll",G),()=>Z.removeEventListener("scroll",G)},[]),w.useEffect(()=>{e.length===0&&(O.current=!1,x(!0))},[e.length]),w.useEffect(()=>{c&&!c.read&&n(c.id)},[c,n]),w.useEffect(()=>{S&&A.current&&A.current.focus()},[S]);const M=w.useCallback(()=>{d.trim()||y(!1)},[d]),P=w.useMemo(()=>{if(!d.trim())return e;const Z=d.toLowerCase();return e.filter(G=>G.method.toLowerCase().includes(Z)||JSON.stringify(G.params||{}).toLowerCase().includes(Z))},[e,d]);w.useEffect(()=>{g(-1)},[d]),w.useEffect(()=>{const Z=G=>{const re=G.target;if(re.tagName==="INPUT"||re.tagName==="TEXTAREA"||re.contentEditable==="true"||G.metaKey||G.ctrlKey||G.altKey)return;const j=P;if(G.key==="ArrowDown")G.preventDefault(),g(V=>{const z=V+1;return z>=j.length?0:z});else if(G.key==="ArrowUp")G.preventDefault(),g(V=>{const z=V-1;return z<0?j.length-1:z});else if(G.key==="Enter"&&h>=0){G.preventDefault();const V=P[h];V&&B(V)}};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[h,P]),w.useEffect(()=>{if(h>=0){const Z=`notification-${P[h]?.id}`,G=document.getElementById(Z);G&&G.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,P]);const B=w.useCallback(Z=>{u(Z)},[]),K=w.useCallback(()=>{window.confirm("Are you sure you want to clear all notifications? This cannot be undone.")&&(r(),u(null))},[r]),ee=w.useCallback(async()=>{if(c)try{await navigator.clipboard.writeText(JSON.stringify({method:c.method,timestamp:c.timestamp,read:c.read,params:c.params},null,2)),C(!0),setTimeout(()=>C(!1),2e3)}catch(Z){console.error("[NotificationsTab] Failed to copy notification:",Z)}},[c]),te=w.useCallback(()=>{if(c)try{const Z=new globalThis.Blob([JSON.stringify({method:c.method,timestamp:c.timestamp,read:c.read,params:c.params},null,2)],{type:"application/json"}),G=URL.createObjectURL(Z),re=document.createElement("a");re.href=G,re.download=`notification-${Date.now()}.json`,document.body.appendChild(re),re.click(),document.body.removeChild(re),URL.revokeObjectURL(G)}catch(Z){console.error("[NotificationsTab] Failed to download notification:",Z)}},[c]),ae=w.useCallback(async()=>{if(I.current)try{document.fullscreenElement?await document.exitFullscreen():await I.current.requestFullscreen()}catch(Z){console.error("[NotificationsTab] Failed to toggle fullscreen:",Z)}},[]),H=c?{method:c.method,params:c.params,timestamp:c.timestamp,read:c.read,formatRelativeTime:ty}:null;return s?f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:40,minSize:30,children:f.jsx(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:f.jsxs(Rn,{defaultSize:75,minSize:30,children:[f.jsx(mTe,{isSearchExpanded:S,searchQuery:d,filteredNotificationsCount:P.length,notificationsCount:e.length,onSearchExpand:()=>y(!0),onSearchChange:m,onSearchBlur:M,onClearAll:K,searchInputRef:A}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(hTe,{notifications:P,selectedNotification:c,onNotificationSelect:B,focusedIndex:h,formatRelativeTime:ty,listRef:R})})]})})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:60,minSize:40,children:f.jsx("div",{ref:I,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(gTe,{notification:H,previewMode:E,onTogglePreview:()=>_(!E),onCopy:ee,onDownload:te,onFullscreen:ae,onClose:()=>u(null),isCopied:k})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(qN,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function GY({activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabTitle:a,secondaryTabTitle:r,primaryCount:i,secondaryCount:s,secondaryIcon:c,primaryIcon:u,searchPlaceholder:d="Search...",onSearchExpand:m,onSearchChange:h,onSearchBlur:g,onTabSwitch:v,searchInputRef:x,primaryTabName:S}){const y=e===S;return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:t?f.jsx(En,{ref:x,placeholder:d,value:n,onChange:E=>h(E.target.value),onBlur:g,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:y?a:r}),y&&f.jsxs(f.Fragment,{children:[f.jsx(wr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:i}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:m,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})]})}),f.jsxs($e,{variant:"ghost",size:"sm",onClick:v,className:"gap-2 flex-shrink-0",children:[y?f.jsx(c,{}):f.jsx(u,{}),f.jsx("span",{className:"hidden sm:inline",children:y?r:a}),y&&s>0&&f.jsx(wr,{className:"bg-purple-500/20 text-purple-600 dark:text-purple-400 border-transparent",variant:"outline",children:s})]})]})}function D2({prompts:e,selectedPrompt:t,onPromptSelect:n,focusedIndex:a}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(Hp,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No prompts available"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((r,i)=>f.jsx(Qs,{id:`prompt-${r.name}`,isSelected:t?.name===r.name,isFocused:a===i,icon:f.jsx(Hp,{className:"h-4 w-4"}),title:r.name,description:r.description,metadata:r.arguments&&r.arguments.length>0&&f.jsxs(wr,{variant:"outline",className:"text-xs border-gray-300 dark:border-zinc-600 text-gray-600 dark:text-gray-400",children:[r.arguments.length," args"]}),onClick:()=>n(r)},r.name))})}function j2({activeTab:e,isSearchExpanded:t,searchQuery:n,filteredPromptsCount:a,savedPromptsCount:r,onSearchExpand:i,onSearchChange:s,onSearchBlur:c,onTabSwitch:u,searchInputRef:d}){return f.jsx(GY,{activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabName:"prompts",secondaryTabName:"saved",primaryTabTitle:"Prompts",secondaryTabTitle:"History",primaryCount:a,secondaryCount:r,primaryIcon:Hp,secondaryIcon:fd,searchPlaceholder:"Search prompts...",onSearchExpand:i,onSearchChange:s,onSearchBlur:c,onTabSwitch:u,searchInputRef:d})}function $2({savedPrompts:e,selectedPrompt:t,onLoadPrompt:n,onDeletePrompt:a,focusedIndex:r}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(fd,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No history"}),f.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500 mt-1",children:"Prompts you execute will appear here"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((i,s)=>f.jsx(Qs,{id:`saved-prompt-${i.id}`,isSelected:t?.id===i.id,isFocused:r===s,icon:f.jsx(fd,{className:"h-4 w-4"}),title:i.name,description:`${i.promptName} - ${new Date(i.savedAt).toLocaleString()}`,onClick:()=>n(i)},i.id))})}function vTe({selectedPrompt:e,promptArgs:t,onArgChange:n}){const a=e?.arguments||[];if(!(a.length>0))return f.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500 dark:text-gray-400 text-sm",children:"No arguments required"});const i=s=>{const c=s.name,u=t[c],d=typeof u=="string"?u:JSON.stringify(u);return s.type==="boolean"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsxs("div",{className:"flex items-center space-x-2",children:[f.jsx("input",{id:c,type:"checkbox",checked:!!u,onChange:m=>n(c,m.target.checked),className:"rounded","aria-label":`Toggle ${c}`}),f.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:s.description})]})]},c):s.type==="number"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(En,{id:c,type:"number",value:Number(u)||0,onChange:m=>n(c,Number(m.target.value)),placeholder:s.description||`Enter ${c}`}),s.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s.description})]},c):s.type==="array"||s.type==="object"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(Xl,{id:c,value:d,onChange:m=>{try{const h=JSON.parse(m.target.value);n(c,h)}catch{n(c,m.target.value)}},placeholder:s.description||`Enter ${c} as JSON`,className:"font-mono text-sm min-h-[100px]"}),s.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s.description})]},c):f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:c,className:"text-sm font-medium",children:[c,s.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(En,{id:c,value:d,onChange:m=>n(c,m.target.value),placeholder:s.description||`Enter ${c}`}),s.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:s.description})]},c)};return f.jsx("div",{className:"space-y-4",children:a.map(s=>i(s))})}function L2({selectedPrompt:e,promptArgs:t,isExecuting:n,isConnected:a,onArgChange:r,onExecute:i,onSave:s}){return w.useEffect(()=>{const c=u=>{(u.metaKey||u.ctrlKey)&&u.key==="Enter"&&e&&!n&&a&&(u.preventDefault(),i())};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[e,n,a,i]),e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsx("div",{className:"flex-shrink-0 p-3 sm:p-6 pt-3 pb-4 pr-3",children:f.jsxs("div",{children:[f.jsxs("div",{className:"flex flex-row items-center justify-between mb-0 gap-2",children:[f.jsx("h3",{className:"text-base sm:text-lg font-semibold",children:e.name}),f.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[f.jsx($e,{onClick:i,disabled:n||!a,size:"sm",className:"lg:size-default pr-1! gap-0",children:n?f.jsxs(f.Fragment,{children:[f.jsx(ki,{className:"mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]}):f.jsxs(f.Fragment,{children:[f.jsx(zG,{className:"h-4 w-4 sm:mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Execute"}),f.jsx("span",{className:"hidden sm:inline text-[12px] border text-zinc-300 p-1 rounded-full border-zinc-300 dark:text-zinc-600 dark:border-zinc-500 ml-2",children:"⌘↵"})]})}),f.jsxs($e,{variant:"outline",onClick:s,disabled:n,size:"sm",className:"lg:size-default gap-2",children:[f.jsx(tC,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Save"})]})]})]}),e.description&&f.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 leading-relaxed mt-2",children:e.description})]})}),f.jsx("div",{className:"flex-1 overflow-y-auto px-3 sm:px-6 pb-4 pr-3",children:f.jsx(vTe,{selectedPrompt:e,promptArgs:t,onArgChange:r})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a prompt to get started"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a prompt from the list to view its details and execute it"})]})}function yTe(e){return"isError"in e&&!e.isError?null:"error"in e&&e.error?e.error:"isError"in e&&e.isError?"An error occurred":null}function M2({results:e,copiedResult:t,onCopy:n}){return f.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:f.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:e.length>0?f.jsx("div",{className:"space-y-4 flex-1 h-full",children:e.map((a,r)=>{const i=a.error||yTe(a.result);return f.jsxs("div",{className:"space-y-0 flex-1 h-full flex flex-col",children:[f.jsxs("div",{className:"flex items-center gap-2 px-4 pt-2 border-b border-gray-200 dark:border-zinc-600 pb-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"Response"}),f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(fd,{className:"h-3 w-3 text-gray-400"}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(a.timestamp).toLocaleTimeString()})]}),a.duration!==void 0&&f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(Vp,{className:"h-3 w-3 text-gray-400"}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[a.duration,"ms"]})]}),f.jsx("div",{className:"flex gap-2 ml-auto",children:f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>n(r,a.result),className:"h-6 px-2",children:t===r?f.jsx(ra,{className:"h-4 w-4"}):f.jsx($r,{className:"h-4 w-4"})})})]}),i?f.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3 mx-4",children:[f.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),f.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:i})]}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:a.result,filename:`prompt-result-${a.promptName}-${Date.now()}.json`})})]},r)})}):f.jsx("div",{className:"flex items-center justify-center h-full",children:f.jsx("div",{className:"text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No Results yet"})})})})})}function ED({serverIds:e,onCountChange:t,onClearRef:n}={}){const[a,r]=w.useState([]),i=w.useRef(null),[s,c]=w.useState(new Set),[u]=w.useState(""),d=v=>{c(x=>{const S=new Set(x);return S.has(v)?S.delete(v):S.add(v),S})},m=async()=>{r([]),c(new Set),t?.(0);try{const v=new URLSearchParams;e&&e.length>0&&v.set("serverIds",e.join(","));const x=await fetch(`/inspector/api/rpc/log?${v.toString()}`,{method:"DELETE"});x.ok||console.warn("[RPC Logger] Failed to clear server buffer:",x.status)}catch(v){console.warn("[RPC Logger] Error clearing server buffer:",v)}},h=w.useMemo(()=>!e||e.length===0?"":[...e].sort().join(","),[e]);w.useEffect(()=>(n&&(n.current=m),()=>{n&&(n.current=null)}),[n,m]),w.useEffect(()=>{t?.(a.length)},[a.length,t]),w.useEffect(()=>{let v=null;try{const x=new URLSearchParams;x.set("replay","50"),x.set("_t",Date.now().toString()),e&&e.length>0&&x.set("serverIds",e.join(","));const S=`/inspector/api/rpc/stream?${x.toString()}`;console.log("[RPC Logger] Connecting to SSE stream:",S),v=new globalThis.EventSource(S),v.onopen=()=>{console.log("[RPC Logger] SSE connection opened")},v.onmessage=y=>{try{const E=JSON.parse(y.data);if(!E||E.type!=="rpc")return;const{serverId:_,direction:k,message:C,timestamp:R}=E,I=C,A=typeof I?.method=="string"?I.method:I?.result!==void 0?"result":I?.error!==void 0?"error":"unknown",O={id:`${R??Date.now()}-${Math.random().toString(36).slice(2)}`,serverId:typeof _=="string"?_:"unknown",direction:typeof k=="string"?k.toUpperCase():"",method:A,timestamp:R??new Date().toISOString(),payload:C};console.log("[RPC Logger] Received RPC event:",{method:A,direction:k,serverId:_}),r(M=>{const P=[O,...M].slice(0,1e3);return t?.(P.length),P})}catch(E){console.error("[RPC Logger] Error parsing SSE message:",E)}},v.onerror=y=>{console.error("[RPC Logger] SSE connection error:",y);try{v?.close()}catch{}}}catch(x){console.error("[RPC Logger] Failed to create SSE connection:",x)}return()=>{try{v?.close(),console.log("[RPC Logger] SSE connection closed")}catch{}}},[h]);const g=w.useMemo(()=>{let v=a;if(e&&e.length>0){const x=new Set(e);v=v.filter(S=>x.has(S.serverId))}if(u.trim()){const x=u.toLowerCase();v=v.filter(S=>S.serverId.toLowerCase().includes(x)||S.method.toLowerCase().includes(x)||S.direction.toLowerCase().includes(x)||JSON.stringify(S.payload).toLowerCase().includes(x))}return v=[...v].sort((x,S)=>new Date(S.timestamp).getTime()-new Date(x.timestamp).getTime()),v},[a,u,e]);return f.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:f.jsx("div",{ref:i,className:"flex-1 min-h-0 overflow-y-auto",children:g.length===0?f.jsxs("div",{className:"text-center py-8",children:[f.jsx("div",{className:"text-xs text-muted-foreground",children:"No messages yet"}),f.jsx("div",{className:"text-[10px] text-muted-foreground mt-1",children:"JSON-RPC messages will appear here"})]}):g.map(v=>{const x=s.has(v.id);return f.jsxs("div",{className:"group hover:bg-muted/50 transition-all duration-200 overflow-hidden",children:[f.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>d(v.id),children:[f.jsx("div",{className:"flex-shrink-0",children:x?f.jsx(ac,{className:"h-3 w-3 text-muted-foreground transition-transform"}):f.jsx(LG,{className:"h-3 w-3 text-muted-foreground transition-transform"})}),f.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[f.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:new Date(v.timestamp).toLocaleTimeString()}),f.jsx("span",{className:`flex items-center justify-center px-1 py-0.5 rounded ${v.direction==="RECEIVE"?"bg-blue-500/10 text-blue-600 dark:text-blue-400":"bg-green-500/10 text-green-600 dark:text-green-400"}`,title:v.direction==="RECEIVE"?"Incoming":"Outgoing",children:v.direction==="RECEIVE"?f.jsx(mme,{className:"h-3 w-3"}):f.jsx(gme,{className:"h-3 w-3"})}),f.jsx("span",{className:"text-xs font-mono text-foreground truncate",children:v.method})]})]}),x&&f.jsx("div",{className:"border-t bg-muted/20",children:f.jsx("div",{className:"p-3",children:f.jsx("div",{className:"max-h-[40vh] overflow-auto rounded-sm bg-background/60 p-2",children:f.jsx(Xn,{data:v.payload})})})})]},v.id)})})})}const P2="mcp-inspector-saved-prompts";function WY({ref:e,prompts:t,callPrompt:n,serverId:a,isConnected:r}){const[i,s]=w.useState(null),[c,u]=w.useState(null),{selectedPromptName:d,setSelectedPromptName:m}=ic(),[h,g]=w.useState({}),[v,x]=w.useState([]),[S,y]=w.useState(!1),[E,_]=w.useState(null),[k,C]=w.useState(""),[R,I]=w.useState("prompts"),[A,O]=w.useState([]),[M,P]=w.useState(!1),[B,K]=w.useState(""),[ee,te]=w.useState(!1),[ae,H]=w.useState(-1),Z=w.useRef(null),[G,re]=w.useState(!1),[ne,j]=w.useState("list"),[V,z]=w.useState(0),[$,L]=w.useState(!0),F=w.useRef(null),W=w.useRef(null);w.useEffect(()=>{const _e=()=>{re(window.innerWidth<1024)};return _e(),window.addEventListener("resize",_e),()=>window.removeEventListener("resize",_e)},[]),w.useEffect(()=>{j(i?"detail":"list")},[i]),w.useEffect(()=>{G&&v.length>0&&!S&&j("response")},[v,S,G]),w.useImperativeHandle(e,()=>({focusSearch:()=>{te(!0),setTimeout(()=>{Z.current&&Z.current.focus()},0)},blurSearch:()=>{C(""),te(!1),Z.current&&Z.current.blur()}})),w.useEffect(()=>{try{const _e=localStorage.getItem(P2);if(_e){const ke=JSON.parse(_e);O(ke)}}catch(_e){console.error("[PromptsTab] Failed to load saved prompts:",_e)}},[]);const X=w.useCallback(_e=>{try{localStorage.setItem(P2,JSON.stringify(_e))}catch(ke){console.error("[PromptsTab] Failed to save prompts:",ke)}},[]);w.useEffect(()=>{ee&&Z.current&&Z.current.focus()},[ee]);const ie=w.useCallback(()=>{k.trim()||te(!1)},[k]),ce=w.useMemo(()=>{if(!k.trim())return t;const _e=k.toLowerCase();return t.filter(ke=>ke.name.toLowerCase().includes(_e)||ke.description?.toLowerCase().includes(_e))},[t,k]),J=w.useCallback(_e=>{s(_e);const ke={};_e.arguments&&_e.arguments.forEach(Fe=>{Fe.default!==void 0?ke[Fe.name]=Fe.default:Fe.type==="string"?ke[Fe.name]="":Fe.type==="number"?ke[Fe.name]=0:Fe.type==="boolean"?ke[Fe.name]=!1:Fe.type==="array"?ke[Fe.name]=[]:Fe.type==="object"&&(ke[Fe.name]={})}),g(ke)},[]),q=w.useCallback(_e=>{const ke=t.find(Fe=>Fe.name===_e.promptName);ke&&(s(ke),g(_e.args),u(_e))},[t]);w.useEffect(()=>{H(-1)},[k,R]),w.useEffect(()=>{const _e=ke=>{const Fe=ke.target;if(Fe.tagName==="INPUT"||Fe.tagName==="TEXTAREA"||Fe.contentEditable==="true"||ke.metaKey||ke.ctrlKey||ke.altKey)return;const Oe=R==="prompts"?ce:A;if(ke.key==="ArrowDown")ke.preventDefault(),H(He=>{const xe=He+1;return xe>=Oe.length?0:xe});else if(ke.key==="ArrowUp")ke.preventDefault(),H(He=>{const xe=He-1;return xe<0?Oe.length-1:xe});else if(ke.key==="Enter"&&ae>=0)if(ke.preventDefault(),R==="prompts"){const He=ce[ae];He&&J(He)}else{const He=A[ae];He&&q(He)}};return document.addEventListener("keydown",_e),()=>document.removeEventListener("keydown",_e)},[ae,ce,A,R,J,q]),w.useEffect(()=>{if(ae>=0){const _e=R==="prompts"?`prompt-${ce[ae]?.name}`:`saved-prompt-${A[ae]?.id}`,ke=document.getElementById(_e);ke&&ke.scrollIntoView({behavior:"smooth",block:"nearest"})}},[ae,ce,A,R]),w.useEffect(()=>{if(console.warn("[PromptsTab] Auto-selection effect triggered:",{selectedPromptName:d,promptsCount:t.length,currentSelectedPrompt:i?.name}),d&&t.length>0){const _e=t.find(ke=>ke.name===d);if(console.warn("[PromptsTab] Prompt lookup result:",{selectedPromptName:d,promptFound:!!_e,promptName:_e?.name,shouldSelect:_e&&i?.name!==_e.name}),_e&&i?.name!==_e.name){console.warn("[PromptsTab] Selecting prompt:",_e.name),m(null);const ke=setTimeout(()=>{J(_e);const Fe=document.getElementById(`prompt-${_e.name}`);Fe&&(console.warn("[PromptsTab] Scrolling to prompt element"),Fe.scrollIntoView({behavior:"smooth",block:"nearest"}))},100);return()=>clearTimeout(ke)}}},[d,t,i,J,m]);const le=w.useCallback((_e,ke)=>{g(Fe=>({...Fe,[_e]:ke}))},[]),he=w.useCallback(async()=>{if(!i||S)return;y(!0);const _e=Date.now();try{const ke=await n(i.name,h),Fe=Date.now()-_e;vr.getInstance().capture(new JU({promptName:i.name,serverId:a,success:!0})).catch(()=>{}),x(Oe=>[{promptName:i.name,args:h,result:ke,timestamp:_e,duration:Fe},...Oe])}catch(ke){vr.getInstance().capture(new JU({promptName:i.name,serverId:a,success:!1,error:ke instanceof Error?ke.message:"Unknown error"})).catch(()=>{});const pe={promptName:i.name,args:h,result:null,error:ke instanceof Error?ke.message:String(ke),timestamp:_e,duration:Date.now()-_e};x(Oe=>[pe,...Oe])}finally{y(!1)}},[i,h,S,n,a]),oe=w.useCallback(async(_e,ke)=>{try{await navigator.clipboard.writeText(JSON.stringify(ke,null,2)),_(_e),setTimeout(()=>_(null),2e3)}catch(Fe){console.error("[PromptsTab] Failed to copy result:",Fe)}},[]),Ne=w.useCallback(()=>{i&&(K(""),P(!0))},[i]),Ve=w.useCallback(_e=>{X(A.filter(ke=>ke.id!==_e)),c?.id===_e&&u(null)},[A,X,c]);return G?f.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[ne!=="list"&&f.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{ne==="response"?j("detail"):(s(null),j("list"))},className:"p-0 h-8 w-8",children:f.jsx(qy,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center text-sm font-medium",children:[f.jsx("button",{onClick:()=>{s(null),j("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Prompts"}),ne!=="list"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("button",{onClick:()=>{ne==="response"&&j("detail")},className:ne==="detail"?"text-foreground hover:underline":ne==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),ne==="response"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),f.jsx("div",{className:"flex-1 relative overflow-hidden",children:f.jsxs(rw,{initial:!1,mode:"popLayout",children:[ne==="list"&&f.jsxs(ya.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[f.jsx(j2,{activeTab:R,isSearchExpanded:ee,searchQuery:k,filteredPromptsCount:ce.length,savedPromptsCount:A.length,onSearchExpand:()=>te(!0),onSearchChange:C,onSearchBlur:ie,onTabSwitch:()=>I(R==="prompts"?"saved":"prompts"),searchInputRef:Z}),R==="prompts"?f.jsx(D2,{prompts:ce,selectedPrompt:i,onPromptSelect:J,focusedIndex:ae}):f.jsx($2,{savedPrompts:A,selectedPrompt:c,onLoadPrompt:q,onDeletePrompt:Ve,focusedIndex:ae})]},"list"),ne==="detail"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-10",children:f.jsx(L2,{selectedPrompt:i,promptArgs:h,isExecuting:S,isConnected:r,onArgChange:le,onExecute:he,onSave:Ne})},"detail"),ne==="response"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-20",children:f.jsx(M2,{results:v,copiedResult:E,onCopy:oe})},"response")]})})]}):f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:33,className:"flex flex-col h-full relative",children:f.jsxs(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[f.jsx(Rn,{defaultSize:75,minSize:30,children:f.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[f.jsx(j2,{activeTab:R,isSearchExpanded:ee,searchQuery:k,filteredPromptsCount:ce.length,savedPromptsCount:A.length,onSearchExpand:()=>te(!0),onSearchChange:C,onSearchBlur:ie,onTabSwitch:()=>I(R==="prompts"?"saved":"prompts"),searchInputRef:Z}),R==="prompts"?f.jsx(D2,{prompts:ce,selectedPrompt:i,onPromptSelect:J,focusedIndex:ae}):f.jsx($2,{savedPrompts:A,selectedPrompt:c,onLoadPrompt:q,onDeletePrompt:Ve,focusedIndex:ae})]})}),f.jsx(Si,{withHandle:!0}),f.jsxs(Rn,{ref:F,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>L(!0),onExpand:()=>L(!1),className:"flex flex-col border-t dark:border-zinc-700",children:[f.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:_e=>{_e.preventDefault(),_e.stopPropagation(),$?(F.current?.resize(25),L(!1)):(F.current?.resize(5),L(!0))},children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),V>0&&f.jsx(wr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:V}),V>0&&!$&&f.jsx($e,{variant:"ghost",size:"sm",onClick:_e=>{_e.preventDefault(),_e.stopPropagation(),W.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:f.jsx(Fs,{className:"h-3.5 w-3.5"})})]}),f.jsx(ac,{className:`h-4 w-4 text-muted-foreground transition-transform ${$?"rotate-180":""}`})]}),f.jsx("div",{className:`flex-1 overflow-hidden min-h-0 ${$?"hidden":""}`,children:f.jsx(ED,{serverIds:[a],onCountChange:z,onClearRef:W})})]})]})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{defaultSize:67,children:f.jsxs(na,{direction:"vertical",children:[f.jsx(Rn,{defaultSize:40,children:f.jsx(L2,{selectedPrompt:i,promptArgs:h,isExecuting:S,isConnected:r,onArgChange:le,onExecute:he,onSave:Ne})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{defaultSize:50,children:f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(M2,{results:v,copiedResult:E,onCopy:oe})})})]})})]})}WY.displayName="PromptsTab";function Ru(e){if(!e?.mimeType)return!1;const t=e.mimeType.toLowerCase();return t==="text/html"||t==="text/html+skybridge"||t==="text/uri-list"||t.startsWith("application/vnd.mcp-ui.remote-dom")}function wTe(e){return{uri:e.uri,mimeType:e.mimeType,text:e.text,blob:e.blob}}function KY({resource:e,onUIAction:t,className:n}){const a=async i=>t?.(i),r=wTe(e);return f.jsx("div",{className:n,children:f.jsx(wD,{resource:r,onUIAction:a,htmlProps:{autoResizeIframe:{width:!0,height:!0},style:{width:"100%",minHeight:"200px"},sandboxPermissions:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox"},remoteDomProps:{remoteElements:[Ike,Ake,Oke,Dke],library:yD}})})}function STe(e){if("error"in e&&e.error)return e.error;if(!("isError"in e&&e.isError))return null;if("contents"in e&&Array.isArray(e.contents)){const t=e.contents.filter(n=>"text"in n).map(n=>n.text).filter(Boolean);if(t.length>0)return t.join(`
1661
+ `)}return"An error occurred"}function U2({result:e,isLoading:t,previewMode:n,serverId:a,readResource:r,onTogglePreview:i,onCopy:s,onDownload:c,onFullscreen:u,isCopied:d=!1}){let m=[],h;if(e?.resourceAnnotations&&(m=Object.keys(e.resourceAnnotations).filter(y=>y.startsWith("openai/")),h=e.resourceAnnotations["openai/outputTemplate"]),e?.result?.contents?.[0]?._meta){const y=e.result.contents[0]._meta,E=Object.keys(y).filter(_=>_.startsWith("openai/"));E.length>0&&(m=[...m,...E]),!h&&y["openai/outputTemplate"]&&(h=y["openai/outputTemplate"]),!h&&e.uri&&e.uri.startsWith("ui://widget/")&&(h=e.uri)}const g=!!(m.length>0&&h&&typeof h=="string"&&a&&r);if(t)return f.jsx("div",{className:"flex absolute left-0 top-0 items-center justify-center w-full h-full",children:f.jsx(ki,{className:"size-5"})});if(!e)return f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a resource to view its contents"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a resource from the list to see its data"})]});const v=e.error||STe(e.result);if(v)return f.jsx("div",{className:"p-4",children:f.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3",children:[f.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),f.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:v})]})});const x=e?.result?.contents&&Array.isArray(e.result.contents)&&e.result.contents.some(y=>y.mimeType&&Ru(y)),S=x?e.result.contents.filter(y=>y.mimeType&&Ru(y)):[];return f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex-shrink-0 px-4 py-3 border-b border-gray-200 dark:border-zinc-700 flex items-center justify-between",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(fd,{className:"h-3 w-3 text-gray-400"}),f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleTimeString()})]}),(()=>{const y=e?.duration??e.result?.duration??e.result?.metrics?.durationMs;return y!==void 0?f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(Vp,{className:"h-3 w-3 text-gray-400"}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[y,"ms"]})]}):null})(),x&&f.jsx(wr,{variant:"outline",className:"text-xs bg-purple-50 dark:bg-purple-900/20 border-none border-purple-200 dark:border-purple-800/50 text-purple-600 dark:text-purple-400",children:"MCP UI"}),g&&f.jsx(wr,{variant:"outline",className:"text-xs bg-blue-50 dark:bg-blue-900/20 border-none border-blue-200 dark:border-blue-800/50 text-blue-600 dark:text-blue-400",children:"OpenAI Widget"})]}),f.jsxs("div",{className:"flex items-center gap-1",children:[(x||g)&&f.jsxs($e,{variant:"ghost",size:"sm",onClick:i,className:n?"":"text-purple-600 dark:text-purple-400",children:[n?f.jsx(XN,{className:"h-4 w-4 mr-1"}):f.jsx($G,{className:"h-4 w-4 mr-1"}),n?"JSON":g?"Component":"Preview"]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:s,children:d?f.jsx(ra,{className:"h-4 w-4"}):f.jsx($r,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:c,children:f.jsx(Lm,{className:"h-4 w-4"})}),f.jsx($e,{variant:"ghost",size:"sm",onClick:u,children:f.jsx(eC,{className:"h-4 w-4"})})]})]}),f.jsx("div",{className:"flex-1 overflow-y-auto",children:g&&a&&r&&h?n?f.jsx("div",{className:"flex-1 h-full",children:f.jsx(mD,{componentUrl:h,toolName:e.uri,toolArgs:{},toolResult:e.result,serverId:a,readResource:r,className:"w-full h-full relative flex p-4"})}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:e.result,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})}):x?n?f.jsxs("div",{className:"space-y-0 h-full",children:[S.map((y,E)=>f.jsx("div",{className:"mx-0 size-full",children:f.jsx("div",{className:"w-full h-full",children:f.jsx(KY,{resource:y,className:"w-full h-full"})})},`mcp-ui-${y.uri||`resource-${Date.now()}-${Math.random()}`}`)),(()=>{if(e.result.contents&&Array.isArray(e.result.contents)){const y=e.result.contents.filter(E=>!(E.mimeType&&Ru(E)));if(y.length>0)return f.jsx("div",{className:"px-4",children:f.jsx(Xn,{data:y,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-non-ui-${Date.now()}.json`})})}return null})()]}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:e.result,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-mcp-ui-${Date.now()}.json`})}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:e.result,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})})})]})}function xTe(e,t){if(!e&&!t)return f.jsx(Jme,{className:"h-5 w-5"});const n=(e||t||"").toLowerCase();return n.includes("image")?f.jsx(Yme,{className:"h-5 w-5"}):n.includes("json")||n.includes("javascript")||n.includes("typescript")?f.jsx(Kme,{className:"h-5 w-5"}):n.includes("html")||n.includes("xml")?f.jsx(nhe,{className:"h-5 w-5"}):n.includes("database")||n.includes("sql")?f.jsx(Xy,{className:"h-5 w-5"}):f.jsx(JN,{className:"h-5 w-5"})}function z2({resources:e,selectedResource:t,onResourceSelect:n,focusedIndex:a}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(Xy,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No resources available"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((r,i)=>{const s=xTe(r.mimeType,r.uri),c=[r.description,r.mimeType&&f.jsx("span",{className:"font-mono",children:r.mimeType},"mime")].filter(Boolean);return f.jsx(Qs,{id:`resource-${r.uri}`,isSelected:t?.uri===r.uri,isFocused:a===i,icon:s,title:r.name,description:c.length>0?f.jsxs("span",{className:"flex flex-col gap-1",children:[r.description&&f.jsx("span",{children:r.description}),r.mimeType&&f.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-500 font-mono",children:r.mimeType})]}):void 0,onClick:()=>n(r)},r.uri)})})}function F2({isSearchExpanded:e,searchQuery:t,filteredResourcesCount:n,onSearchExpand:a,onSearchChange:r,onSearchBlur:i,searchInputRef:s}){return f.jsx("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:s,placeholder:"Search resources...",value:t,onChange:c=>r(c.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Resources"}),f.jsx(wr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})})})}function ZY({ref:e,resources:t,readResource:n,serverId:a,isConnected:r}){const[i,s]=w.useState(null),{selectedResourceUri:c,setSelectedResourceUri:u}=ic(),[d,m]=w.useState(null),[h,g]=w.useState(!1),[v,x]=w.useState(""),[S]=w.useState("resources"),[y,E]=w.useState(!0),[_,k]=w.useState(!1),[C,R]=w.useState(-1),[I,A]=w.useState(!1),O=w.useRef(null),M=w.useRef(null),[P,B]=w.useState(!1),[K,ee]=w.useState("list"),[te,ae]=w.useState(0),[H,Z]=w.useState(!0),G=w.useRef(null),re=w.useRef(null);w.useEffect(()=>{const F=()=>{B(window.innerWidth<1024)};return F(),window.addEventListener("resize",F),()=>window.removeEventListener("resize",F)},[]),w.useEffect(()=>{ee(i?"detail":"list")},[i]),w.useImperativeHandle(e,()=>({focusSearch:()=>{k(!0),setTimeout(()=>{O.current&&O.current.focus()},0)},blurSearch:()=>{x(""),k(!1),O.current&&O.current.blur()}})),w.useEffect(()=>{_&&O.current&&O.current.focus()},[_]);const ne=w.useCallback(()=>{v.trim()||k(!1)},[v]),j=w.useMemo(()=>{if(!v)return t;const F=v.toLowerCase();return t.filter(W=>W.name.toLowerCase().includes(F)||W.description?.toLowerCase().includes(F)||W.uri.toLowerCase().includes(F))},[t,v]),V=w.useCallback(async F=>{if(s(F),r){g(!0);const W=Date.now();try{const X=await n(F.uri);vr.getInstance().capture(new XU({resourceUri:F.uri,serverId:a,success:!0})).catch(()=>{}),m({uri:F.uri,result:X,timestamp:W,resourceAnnotations:F.annotations})}catch(X){vr.getInstance().capture(new XU({resourceUri:F.uri,serverId:a,success:!1,error:X instanceof Error?X.message:"Unknown error"})).catch(()=>{}),m({uri:F.uri,result:null,error:X instanceof Error?X.message:"Unknown error",timestamp:W,resourceAnnotations:F.annotations})}finally{g(!1)}}},[n,a,r]);w.useEffect(()=>{R(-1)},[v,S]),w.useEffect(()=>{const F=W=>{const X=W.target;if(X.tagName==="INPUT"||X.tagName==="TEXTAREA"||X.contentEditable==="true"||W.metaKey||W.ctrlKey||W.altKey)return;const ce=j;if(W.key==="ArrowDown")W.preventDefault(),R(J=>{const q=J+1;return q>=ce.length?0:q});else if(W.key==="ArrowUp")W.preventDefault(),R(J=>{const q=J-1;return q<0?ce.length-1:q});else if(W.key==="Enter"&&C>=0){W.preventDefault();const J=j[C];J&&V(J)}};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[C,j,V]),w.useEffect(()=>{if(C>=0){const F=`resource-${j[C]?.uri}`,W=document.getElementById(F);W&&W.scrollIntoView({behavior:"smooth",block:"nearest"})}},[C,j]),w.useEffect(()=>{if(c&&t.length>0){const F=t.find(W=>W.uri===c);F&&i?.uri!==F.uri&&(u(null),setTimeout(()=>{V(F);const W=document.getElementById(`resource-${F.uri}`);W&&W.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[c,t,i,V,u]);const z=w.useCallback(async()=>{if(d)try{await navigator.clipboard.writeText(JSON.stringify(d.result,null,2)),A(!0),setTimeout(()=>A(!1),2e3)}catch(F){console.error("[ResourcesTab] Failed to copy result:",F)}},[d]),$=w.useCallback(()=>{if(d)try{const F=new globalThis.Blob([JSON.stringify(d.result,null,2)],{type:"application/json"}),W=URL.createObjectURL(F),X=document.createElement("a");X.href=W,X.download=`resource-${Date.now()}.json`,document.body.appendChild(X),X.click(),document.body.removeChild(X),URL.revokeObjectURL(W)}catch(F){console.error("[ResourcesTab] Failed to download result:",F)}},[d]),L=w.useCallback(async()=>{if(M.current)try{document.fullscreenElement?await document.exitFullscreen():await M.current.requestFullscreen()}catch(F){console.error("[ResourcesTab] Failed to toggle fullscreen:",F)}},[]);return P?f.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[K!=="list"&&f.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{s(null),ee("list")},className:"p-0 h-8 w-8",children:f.jsx(qy,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center text-sm font-medium",children:[f.jsx("button",{onClick:()=>{s(null),ee("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Resources"}),K==="detail"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("span",{className:"text-foreground",children:"Content"})]})]})]}),f.jsx("div",{className:"flex-1 relative overflow-hidden",children:f.jsxs(rw,{initial:!1,mode:"popLayout",children:[K==="list"&&f.jsxs(ya.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[f.jsx(F2,{activeTab:S,isSearchExpanded:_,searchQuery:v,filteredResourcesCount:j.length,onSearchExpand:()=>k(!0),onSearchChange:x,onSearchBlur:ne,onTabSwitch:()=>{},searchInputRef:O}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(z2,{resources:j,selectedResource:i,onResourceSelect:V,focusedIndex:C})})]},"list"),K==="detail"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-white dark:bg-zinc-900 z-10",children:f.jsx("div",{ref:M,className:"h-full",children:f.jsx(U2,{result:d,isLoading:h,previewMode:y,serverId:a,readResource:n,onTogglePreview:()=>E(!y),onCopy:z,onDownload:$,onFullscreen:L,isCopied:I})})},"detail")]})})]}):f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:25,children:f.jsxs(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[f.jsx(Rn,{defaultSize:75,minSize:30,children:f.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[f.jsx(F2,{activeTab:S,isSearchExpanded:_,searchQuery:v,filteredResourcesCount:j.length,onSearchExpand:()=>k(!0),onSearchChange:x,onSearchBlur:ne,onTabSwitch:()=>{},searchInputRef:O}),f.jsx(z2,{resources:j,selectedResource:i,onResourceSelect:V,focusedIndex:C})]})}),f.jsx(Si,{withHandle:!0}),f.jsxs(Rn,{ref:G,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>Z(!0),onExpand:()=>Z(!1),className:"flex flex-col border-t dark:border-zinc-700",children:[f.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:F=>{F.preventDefault(),F.stopPropagation(),H?(G.current?.resize(25),Z(!1)):(G.current?.resize(5),Z(!0))},children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),te>0&&f.jsx(wr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:te}),te>0&&!H&&f.jsx($e,{variant:"ghost",size:"sm",onClick:F=>{F.preventDefault(),F.stopPropagation(),re.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:f.jsx(Fs,{className:"h-3.5 w-3.5"})})]}),f.jsx(ac,{className:`h-4 w-4 text-muted-foreground transition-transform ${H?"":"rotate-180"}`})]}),f.jsx("div",{className:`flex-1 overflow-hidden min-h-0 ${H?"hidden":""}`,children:f.jsx(ED,{serverIds:[a],onCountChange:ae,onClearRef:re})})]})]})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:50,children:f.jsx(na,{direction:"vertical",children:f.jsx(Rn,{defaultSize:70,children:f.jsx("div",{ref:M,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(U2,{result:d,isLoading:h,previewMode:y,serverId:a,readResource:n,onTogglePreview:()=>E(!y),onCopy:z,onDownload:$,onFullscreen:L,isCopied:I})})})})})]})}ZY.displayName="ResourcesTab";function B2({savedRequests:e,selectedRequest:t,onLoadRequest:n,onDeleteRequest:a,focusedIndex:r}){if(e.length===0)return f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(Xy,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"No saved requests yet"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Execute a tool and click Save to store requests"})]});const i=(s,c)=>{s.stopPropagation(),c()};return f.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((s,c)=>f.jsxs("div",{className:"relative group",children:[f.jsx(Qs,{id:`saved-${s.id}`,isSelected:t?.id===s.id,isFocused:r===c,icon:f.jsx(Rv,{className:"h-4 w-4"}),title:s.name,description:s.toolName,metadata:f.jsx("div",{className:"flex flex-col gap-1",children:f.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:new Date(s.savedAt).toLocaleString()})}),onClick:()=>n(s)}),f.jsx("div",{className:"absolute top-1/2 right-2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"secondary",size:"sm",onClick:u=>i(u,()=>a(s.id)),className:"h-8 w-8 p-0",children:f.jsx(Fs,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Delete saved request"})})]})})]},s.id))})}function H2({isOpen:e,requestName:t,defaultPlaceholder:n,onRequestNameChange:a,onSave:r,onCancel:i}){return e?f.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:i,children:f.jsxs("div",{className:"bg-white dark:bg-zinc-800 rounded-lg p-6 w-[400px] shadow-xl border border-gray-200 dark:border-zinc-700",onClick:s=>s.stopPropagation(),children:[f.jsx("h3",{className:"text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100",children:"Save Request"}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsx(Kt,{htmlFor:"request-name",children:"Request Name (optional)"}),f.jsx(En,{id:"request-name",value:t,onChange:s=>a(s.target.value),placeholder:n,className:"mt-2",onKeyDown:s=>{s.key==="Enter"&&r()},autoFocus:!0})]}),f.jsxs("div",{className:"flex justify-end gap-2",children:[f.jsx($e,{variant:"outline",onClick:i,children:"Cancel"}),f.jsxs($e,{onClick:r,children:[f.jsx(tC,{className:"h-4 w-4 mr-2"}),"Save"]})]})]})]})}):null}function YY(e,t){if(!e?.$ref)return e;const n=e.$ref;if(n.startsWith("#/")){const a=n.substring(2).split("/");let r=t;for(const i of a)if(r&&typeof r=="object"&&i in r)r=r[i];else return console.warn(`Could not resolve $ref: ${n}`),e;return r}return e}function _Te(e,t){if(e.anyOf&&Array.isArray(e.anyOf)){const n=e.anyOf.find(a=>a.type!=="null");if(n)return{...YY(n,t),nullable:!0}}return e}function ETe(e){return Array.isArray(e.enum)?e.enum:null}function V2({selectedTool:e,toolArgs:t,onArgChange:n}){const a=e?.inputSchema?.properties||{},r=e?.inputSchema?.required||[];return Object.keys(a).length>0?f.jsx("div",{className:"space-y-4",children:Object.entries(a).map(([s,c])=>{const u=e?.inputSchema||{};let d=_Te(c,u);d=YY(d,u);const m=ETe(d),h=d.type==="string"&&m!==null,g=d;g.required=r.includes(s);const v=t[s];let x="";return v!=null&&(typeof v=="string"?x=v:typeof v=="object"&&v!==null?x=JSON.stringify(v,null,2):x=String(v)),g.type==="object"||g.type==="array"?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:s,className:"text-sm font-medium",children:[s,g?.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(Xl,{id:s,value:x,onChange:y=>n(s,y.target.value),placeholder:g?.description||`Enter ${s}`,className:"min-h-[100px]"}),g?.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g.description})]},s):h&&m?f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:s,className:"text-sm font-medium",children:[s,g.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsxs(Io,{value:String(t[s]||""),onValueChange:y=>n(s,y),children:[f.jsx(Do,{id:s,className:"w-full",children:f.jsx(Oo,{placeholder:g.description||"Select an option"})}),f.jsx(jo,{children:m.map((y,E)=>f.jsx(Ar,{value:y,children:g.enumNames?.[E]||y},y))})]}),g.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g.description})]},s):f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:s,className:"text-sm font-medium",children:[s,g?.required&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),f.jsx(En,{id:s,value:x,onChange:y=>n(s,y.target.value),placeholder:g?.description||`Enter ${s}`}),g?.description&&f.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g.description})]},s)})}):f.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500 dark:text-gray-400 text-sm",children:"No parameters required"})}function G2({selectedTool:e,toolArgs:t,isExecuting:n,isConnected:a,onArgChange:r,onExecute:i,onSave:s,onCancel:c}){const[u,d]=w.useState(!1),[m,h]=w.useState(()=>{if(typeof window<"u"){const S=localStorage.getItem("mcp-inspector-show-tool-metadata");return S?JSON.parse(S):!1}return!1}),[g,v]=w.useState(!1);w.useEffect(()=>{typeof window<"u"&&localStorage.setItem("mcp-inspector-show-tool-metadata",JSON.stringify(m))},[m]);const x=()=>{if(!e)return;const S={name:e.name,description:e.description||"",_meta:e._meta};navigator.clipboard.writeText(JSON.stringify(S,null,2)),v(!0),setTimeout(()=>v(!1),2e3)};return w.useEffect(()=>{const S=y=>{(y.metaKey||y.ctrlKey)&&y.key==="Enter"&&e&&!n&&a&&(y.preventDefault(),i()),y.key==="Escape"&&n&&c&&(y.preventDefault(),c())};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[e,n,a,i,c]),e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsx("div",{className:"flex-shrink-0 p-3 sm:p-5 pt-3 sm:pt-4 pb-4 sm:pr-4",children:f.jsxs("div",{children:[f.jsxs("div",{className:"flex flex-row items-center justify-between mb-0 gap-2",children:[f.jsx("h3",{className:"text-base sm:text-lg font-semibold",children:e.name}),f.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsxs($e,{variant:m?"default":"outline",onClick:()=>h(!m),disabled:n,size:"sm",className:"lg:size-default gap-2",title:"Toggle tool metadata",children:[f.jsx(XN,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Metadata"})]})}),f.jsx(Rt,{children:f.jsx("p",{children:"Show tool definition metadata"})})]}),f.jsxs($e,{variant:"outline",onClick:s,disabled:n,size:"sm",className:"lg:size-default gap-2",children:[f.jsx(tC,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Save"})]}),n&&c?f.jsxs(Nt,{open:u?void 0:!1,children:[f.jsx(Ct,{asChild:!0,children:f.jsx("div",{onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),className:"relative",children:f.jsx($e,{onClick:c,variant:u?"destructive":"default",size:"sm",className:"lg:size-default gap-2 transition-all",children:u?f.jsxs(f.Fragment,{children:[f.jsx(Ji,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Cancel"}),f.jsx("span",{className:"hidden sm:inline text-[12px] border border-current p-1 rounded-full ml-2",children:"Esc"})]}):f.jsxs(f.Fragment,{children:[f.jsx(ki,{className:"mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]})})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Hover to cancel (or press Esc)"})})]}):f.jsx($e,{onClick:i,disabled:n||!a,size:"sm",className:"lg:size-default pr-1! gap-0",children:n?f.jsxs(f.Fragment,{children:[f.jsx(ki,{className:"mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]}):f.jsxs(f.Fragment,{children:[f.jsx(zG,{className:"h-4 w-4 sm:mr-2"}),f.jsx("span",{className:"hidden sm:inline",children:"Execute"}),f.jsx("span",{className:"hidden sm:inline text-[12px] border text-zinc-300 p-1 rounded-full border-zinc-300 dark:text-zinc-600 dark:border-zinc-500 ml-2",children:"⌘↵"})]})})]})]}),e.description&&f.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 leading-relaxed mt-2",children:e.description})]})}),m?f.jsxs("div",{className:"flex-1 overflow-hidden flex gap-4 px-3 sm:px-6 pb-4",children:[f.jsx("div",{className:"flex-1 min-w-0 overflow-y-auto",children:f.jsx(V2,{selectedTool:e,toolArgs:t,onArgChange:r})}),f.jsxs("div",{className:"w-2/5 flex flex-col bg-zinc-50 dark:bg-zinc-900/50 rounded border border-zinc-200 dark:border-zinc-800 overflow-hidden",children:[f.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-zinc-200 dark:border-zinc-800 flex-shrink-0",children:[f.jsx("h4",{className:"text-sm font-medium",children:"Tool Definition"}),f.jsx($e,{variant:"ghost",size:"sm",onClick:x,className:"h-7 w-7 p-0",title:"Copy metadata",children:g?f.jsx(ra,{className:"h-3.5 w-3.5 text-green-600"}):f.jsx($r,{className:"h-3.5 w-3.5"})})]}),f.jsx("div",{className:"flex-1 overflow-y-auto p-3",children:f.jsx("pre",{className:"text-xs font-mono text-zinc-700 dark:text-zinc-300 whitespace-pre-wrap break-words",children:JSON.stringify({name:e.name,description:e.description||"(no description)",_meta:e._meta||null},null,2)})})]})]}):f.jsx("div",{className:"flex-1 overflow-y-auto px-3 sm:px-6 pb-4 pr-3",children:f.jsx(V2,{selectedTool:e,toolArgs:t,onArgChange:r})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a tool to get started"}),f.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a tool from the list to view its details and execute it"})]})}function W2(e){const n=Date.now()-e,a=Math.floor(n/1e3),r=Math.floor(a/60),i=Math.floor(r/60),s=Math.floor(i/24);return a<10?"now":a<60?`${a}s ago`:r<60?`${r}m ago`:i<24?`${i}h ago`:`${s}d ago`}function kTe(e){if(!e?.isError)return null;if(e.content&&Array.isArray(e.content)){const t=e.content.filter(n=>n.type==="text").map(n=>n.text).filter(Boolean);if(t.length>0)return t.join(`
1662
1662
  `)}return"An error occurred"}function TTe(e){try{return JSON.parse(e),!0}catch{return!1}}function NTe({content:e}){return!Array.isArray(e)||e.length===0?f.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No content"}):f.jsx("div",{className:"space-y-4",children:e.map((t,n)=>{if(t.type==="text"){const a=t.text||"";if(TTe(a))try{const r=JSON.parse(a);return f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Text Content (JSON)"}),f.jsx(Xn,{data:r,filename:`content-${n}.json`})]},n)}catch{}return f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Text Content"}),f.jsx("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3 font-mono text-sm whitespace-pre-wrap break-words",children:a})]},n)}if(t.type==="image")return f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Image Content"}),f.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3",children:[f.jsx("img",{src:`data:${t.mimeType||"image/png"};base64,${t.data}`,alt:"Result",className:"max-w-full rounded"}),t.annotations&&f.jsx("div",{className:"mt-2 text-xs text-gray-500 dark:text-gray-400",children:f.jsx(Xn,{data:t.annotations,filename:`image-annotations-${n}.json`})})]})]},n);if(t.type==="audio")return f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Audio Content"}),f.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3",children:[f.jsx("audio",{controls:!0,src:`data:${t.mimeType||"audio/wav"};base64,${t.data}`,className:"w-full"}),t.annotations&&f.jsx("div",{className:"mt-2 text-xs text-gray-500 dark:text-gray-400",children:f.jsx(Xn,{data:t.annotations,filename:`audio-annotations-${n}.json`})})]})]},n);if(t.type==="resource_link")return f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Resource Link"}),f.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3 space-y-2",children:[f.jsxs("div",{className:"font-mono text-sm break-all",children:[f.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"URI:"})," ",t.uri]}),t.name&&f.jsxs("div",{className:"text-sm",children:[f.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"Name:"})," ",t.name]}),t.description&&f.jsxs("div",{className:"text-sm",children:[f.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"Description:"})," ",t.description]}),t.mimeType&&f.jsxs("div",{className:"text-sm",children:[f.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"MIME Type:"})," ",t.mimeType]}),t.annotations&&f.jsxs("div",{className:"mt-2",children:[f.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"Annotations:"}),f.jsx(Xn,{data:t.annotations,filename:`resource-link-annotations-${n}.json`})]})]})]},n);if(t.type==="resource"){const a=t.resource||{};return f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Embedded Resource"}),f.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3 space-y-2",children:[f.jsxs("div",{className:"font-mono text-sm break-all",children:[f.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"URI:"})," ",a.uri]}),a.mimeType&&f.jsxs("div",{className:"text-sm",children:[f.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"MIME Type:"})," ",a.mimeType]}),a.text&&f.jsxs("div",{children:[f.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"Content:"}),f.jsx("div",{className:"bg-white dark:bg-black rounded p-2 font-mono text-sm whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:a.text})]}),a.blob&&f.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:["[Binary content: ",a.blob.length||0," bytes]"]}),a.annotations&&f.jsxs("div",{className:"mt-2",children:[f.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"Annotations:"}),f.jsx(Xn,{data:a.annotations,filename:`resource-annotations-${n}.json`})]})]})]},n)}return f.jsxs("div",{className:"space-y-2",children:[f.jsxs("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:["Unknown Content Type: ",t.type||"N/A"]}),f.jsx(Xn,{data:t,filename:`content-${n}.json`})]},n)})})}function K2({results:e,copiedResult:t,previewMode:n,serverId:a,readResource:r,onCopy:i,onTogglePreview:s,onMaximize:c,isMaximized:u=!1}){const[d,m]=w.useState(0),[h,g]=w.useState(""),[v,x]=w.useState(!0),S=e[0],y=S?e.filter(te=>te.toolName===S.toolName):[],E=y[d]||y[0],_=e.findIndex(te=>te===E);w.useEffect(()=>{y.length>0&&d>=y.length&&m(0)},[y.length,d]),w.useEffect(()=>{const te=()=>{E&&g(W2(E.timestamp))};te();const ae=setInterval(te,1e3);return()=>clearInterval(ae)},[E]);const k=w.useMemo(()=>E?.args,[E?.timestamp,d]),C=w.useMemo(()=>E?.result,[E?.timestamp,d]),R=w.useCallback(te=>r(te),[r]);if(e.length===0)return f.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:f.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:f.jsx("div",{className:"flex items-center justify-center h-full",children:f.jsx("div",{className:"text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No Results yet"})})})})});const I=E.toolMeta?.["openai/outputTemplate"],A=!!(I&&typeof I=="string"&&E.appsSdkResource),O=I,M=E.result?.content||[],P=M.filter(te=>te.type==="resource"&&Ru(te.resource)),B=P.length>0,K=!!(M&&M.length>0||E.result?.structuredContent),ee=!B&&!A&&K;return f.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:f.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:f.jsxs("div",{className:"space-y-0 flex-1 h-full flex flex-col",children:[f.jsxs("div",{className:`flex items-center gap-2 px-4 pt-2 ${B||A||ee?"border-b border-gray-200 dark:border-zinc-600 pb-2":""}`,children:[f.jsx("h3",{className:"text-sm font-medium hidden sm:block",children:"Response"}),E.duration!==void 0&&f.jsxs("div",{className:"hidden sm:flex items-center gap-1",children:[f.jsx(Vp,{className:"h-3 w-3 text-gray-400"}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[E.duration,"ms"]})]}),A&&f.jsxs("div",{className:"flex items-center gap-4 sm:ml-4",children:[f.jsxs("span",{className:"hidden sm:inline text-xs text-gray-500 dark:text-gray-400",children:["URI: ",O||"No URI"]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:()=>s(),className:`text-xs font-medium ${n?"text-black dark:text-white":"text-zinc-500 dark:text-zinc-400"}`,children:"Component"}),f.jsx("span",{className:"text-xs text-zinc-400",children:"|"}),f.jsx("button",{onClick:()=>s(),className:`text-xs font-medium ${n?"text-zinc-500 dark:text-zinc-400":"text-black dark:text-white"}`,children:"Raw JSON"})]})]}),B&&!A&&f.jsxs("div",{className:"flex items-center gap-4 sm:ml-4",children:[f.jsxs("span",{className:"hidden sm:inline text-xs text-gray-500 dark:text-gray-400",children:["URI: ",P[0]?.resource?.uri||"No URI"]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("button",{onClick:()=>s(),className:`text-xs font-medium ${n?"text-black dark:text-white":"text-zinc-500 dark:text-zinc-400"}`,children:"Preview"}),f.jsx("span",{className:"text-xs text-zinc-400",children:"|"}),f.jsx("button",{onClick:()=>s(),className:`text-xs font-medium ${n?"text-zinc-500 dark:text-zinc-400":"text-black dark:text-white"}`,children:"JSON"})]})]}),ee&&f.jsxs("div",{className:"flex items-center gap-2 sm:ml-4",children:[f.jsx("button",{onClick:()=>x(!0),className:`text-xs font-medium ${v?"text-black dark:text-white":"text-zinc-500 dark:text-zinc-400"}`,children:"Formatted"}),f.jsx("span",{className:"text-xs text-zinc-400",children:"|"}),f.jsx("button",{onClick:()=>x(!1),className:`text-xs font-medium ${v?"text-zinc-500 dark:text-zinc-400":"text-black dark:text-white"}`,children:"Raw"})]}),f.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[(A||B)&&c&&f.jsx($e,{variant:"ghost",size:"sm",onClick:c,title:u?"Restore":"Maximize",children:u?f.jsx(hhe,{className:"h-4 w-4"}):f.jsx(eC,{className:"h-4 w-4"})}),y.length>1&&f.jsxs(Io,{value:d.toString(),onValueChange:te=>m(parseInt(te)),children:[f.jsx(Do,{size:"sm",className:"w-[140px] h-8 text-xs",children:f.jsx(Oo,{children:f.jsxs("div",{className:"flex items-center gap-1",children:[f.jsx(Rv,{className:"h-3 w-3"}),f.jsx("span",{children:h})]})})}),f.jsx(jo,{children:y.map((te,ae)=>f.jsx(Ar,{value:ae.toString(),children:f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Rv,{className:"h-3 w-3"}),f.jsx("span",{children:W2(te.timestamp)}),f.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",new Date(te.timestamp).toLocaleTimeString(),")"]})]})},ae))})]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>i(_,E.result),children:t===_?f.jsx(ra,{className:"h-4 w-4"}):f.jsx($r,{className:"h-4 w-4"})})]})]}),(()=>{const te=E.error||kTe(E.result);return te?f.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3 mx-4",children:[f.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),f.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:te})]}):(()=>{if(A){const ae=E.appsSdkResource;return ae.isLoading?f.jsx(f.Fragment,{}):ae.error?f.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3 mx-4",children:[f.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Resource Error:"}),f.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:ae.error})]}):n?f.jsx("div",{className:"flex-1",children:f.jsx(mD,{componentUrl:O,toolName:E.toolName,toolArgs:k,toolResult:C,serverId:a,readResource:R,className:"w-full h-full relative p-4"})}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:E.result,filename:`tool-result-${E.toolName}-${Date.now()}.json`})})}if(B)return n?f.jsxs("div",{className:"space-y-0 h-full",children:[P.map((ae,H)=>f.jsx("div",{className:"mx-0 size-full",children:f.jsx(KY,{resource:ae.resource,onUIAction:Z=>{},className:"w-full h-full relative"})},H)),M.filter(ae=>!(ae.type==="resource"&&Ru(ae.resource))).length>0&&f.jsx("div",{className:"px-4",children:f.jsx(Xn,{data:M.filter(ae=>!(ae.type==="resource"&&Ru(ae.resource))),filename:`tool-result-${E.toolName}-non-ui-${Date.now()}.json`})})]}):f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:E.result,filename:`tool-result-${E.toolName}-mcp-ui-${Date.now()}.json`})});if(ee&&v){const ae=E.result?.structuredContent;return f.jsxs("div",{className:"px-4 pt-4 space-y-4",children:[ae&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Structured Content"}),f.jsx(Xn,{data:ae,filename:`structured-content-${E.toolName}-${Date.now()}.json`})]}),M&&M.length>0&&f.jsx(NTe,{content:M}),!ae&&(!M||M.length===0)&&f.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No content to display"})]})}return f.jsx("div",{className:"px-4 pt-4",children:f.jsx(Xn,{data:E.result,filename:`tool-result-${E.toolName}-${Date.now()}.json`})})})()})()]})})})}function Z2({tools:e,selectedTool:t,onToolSelect:n,focusedIndex:a}){return e.length===0?f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(Wl,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No tools available"})]}):f.jsx("div",{className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((r,i)=>f.jsx(Qs,{id:`tool-${r.name}`,isSelected:t?.name===r.name,isFocused:a===i,icon:f.jsx(Wl,{className:"h-4 w-4"}),title:r.name,description:r.description,metadata:r.inputSchema?.properties&&f.jsxs(wr,{variant:"outline",className:"text-xs border-gray-300 dark:border-zinc-600 text-gray-600 dark:text-gray-400",children:[Object.keys(r.inputSchema.properties).length," params"]}),onClick:()=>n(r)},r.name))})}function Y2({activeTab:e,isSearchExpanded:t,searchQuery:n,filteredToolsCount:a,savedRequestsCount:r,onSearchExpand:i,onSearchChange:s,onSearchBlur:c,onTabSwitch:u,searchInputRef:d}){return f.jsx(GY,{activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabName:"tools",secondaryTabName:"saved",primaryTabTitle:"Tools",secondaryTabTitle:"Saved",primaryCount:a,secondaryCount:r,primaryIcon:Wl,secondaryIcon:Xy,searchPlaceholder:"Search tools...",onSearchExpand:i,onSearchChange:s,onSearchBlur:c,onTabSwitch:u,searchInputRef:d})}const q2="mcp-inspector-saved-requests";function qY({ref:e,tools:t,callTool:n,readResource:a,serverId:r,isConnected:i}){const[s,c]=w.useState(null),[u,d]=w.useState(null),{selectedToolName:m,setSelectedToolName:h}=ic(),[g,v]=w.useState({}),[x,S]=w.useState([]),[y,E]=w.useState(!1),[_,k]=w.useState(null),[C,R]=w.useState(null),[I,A]=w.useState(""),[O,M]=w.useState("tools"),[P,B]=w.useState([]),[K,ee]=w.useState(!1),[te,ae]=w.useState(""),[H,Z]=w.useState(!0),[G,re]=w.useState(!1),[ne,j]=w.useState(-1),V=w.useRef(null),[z,$]=w.useState(!1),[L,F]=w.useState("list"),[W,X]=w.useState(!1),[ie,ce]=w.useState(0),[J,q]=w.useState(!0),[le,he]=w.useState(void 0),oe=w.useRef(null),Ne=w.useRef(null),Ve=w.useRef(null),_e=w.useRef(null),ke=w.useRef(null);w.useEffect(()=>{const Se=()=>{$(window.innerWidth<1024)};return Se(),window.addEventListener("resize",Se),()=>window.removeEventListener("resize",Se)},[]),w.useEffect(()=>{F(s?"detail":"list")},[s]),w.useEffect(()=>{z&&x.length>0&&!y&&F("response")},[x,y,z]),w.useImperativeHandle(e,()=>({focusSearch:()=>{re(!0),setTimeout(()=>{V.current&&V.current.focus()},0)},blurSearch:()=>{A(""),re(!1),V.current&&V.current.blur()}})),w.useEffect(()=>{try{const Se=localStorage.getItem(q2);Se&&B(JSON.parse(Se))}catch(Se){console.error("[ToolsTab] Failed to load saved requests:",Se)}},[]);const Fe=w.useCallback(Se=>{try{localStorage.setItem(q2,JSON.stringify(Se)),B(Se)}catch(je){console.error("[ToolsTab] Failed to save requests:",je)}},[]),pe=w.useMemo(()=>{if(!I.trim())return t;const Se=I.toLowerCase();return t.filter(je=>je.name.toLowerCase().includes(Se)||je.description?.toLowerCase().includes(Se))},[t,I]),Oe=w.useCallback(Se=>{c(Se);const je={};Se.inputSchema?.properties&&Object.entries(Se.inputSchema.properties).forEach(([Ue,We])=>{const Je=We;Je.default!==void 0?je[Ue]=Je.default:Je.type==="string"?je[Ue]="":Je.type==="number"?je[Ue]=0:Je.type==="boolean"?je[Ue]=!1:Je.type==="array"?je[Ue]="[]":Je.type==="object"&&(je[Ue]="{}")}),v(je)},[]),He=w.useCallback(Se=>{const je=t.find(Ue=>Ue.name===Se.toolName);je&&(c(je),v(Se.args),d(Se))},[t]);w.useEffect(()=>{G&&V.current&&V.current.focus()},[G]);const xe=w.useCallback(()=>{I.trim()||re(!1)},[I]);w.useEffect(()=>{O!=="tools"&&re(!1)},[O]),w.useEffect(()=>{j(-1)},[I,O]),w.useEffect(()=>{const Se=je=>{const Ue=je.target;if(Ue.tagName==="INPUT"||Ue.tagName==="TEXTAREA"||Ue.contentEditable==="true"||je.metaKey||je.ctrlKey||je.altKey)return;const Je=O==="tools"?pe:P;if(je.key==="ArrowDown")je.preventDefault(),j(yt=>{const mt=yt+1;return mt>=Je.length?0:mt});else if(je.key==="ArrowUp")je.preventDefault(),j(yt=>{const mt=yt-1;return mt<0?Je.length-1:mt});else if(je.key==="Enter"&&ne>=0)if(je.preventDefault(),O==="tools"){const yt=pe[ne];yt&&Oe(yt)}else{const yt=P[ne];yt&&He(yt)}};return document.addEventListener("keydown",Se),()=>document.removeEventListener("keydown",Se)},[ne,pe,P,O,Oe,He]),w.useEffect(()=>{if(ne>=0){const Se=O==="tools"?`tool-${pe[ne]?.name}`:`saved-${P[ne]?.id}`,je=document.getElementById(Se);je&&je.scrollIntoView({behavior:"smooth",block:"nearest"})}},[ne,pe,P,O]),w.useEffect(()=>{if(m&&t.length>0){const Se=t.find(je=>je.name===m);if(Se&&s?.name!==Se.name){h(null);const je=setTimeout(()=>{Oe(Se);const Ue=document.getElementById(`tool-${Se.name}`);Ue&&Ue.scrollIntoView({behavior:"smooth",block:"nearest"})},100);return()=>clearTimeout(je)}}},[m,t,s,Oe,h]);const at=w.useCallback((Se,je)=>{v(Ue=>{const We={...Ue};if(s?.inputSchema?.properties?.[Se]){const yt=s.inputSchema.properties[Se].type;if(yt==="object"||yt==="array")We[Se]=je;else if(yt==="string")We[Se]=je;else try{We[Se]=JSON.parse(je)}catch{We[Se]=je}}else We[Se]=je;return We})},[s]),nt=w.useCallback(async()=>{if(!s||y)return;const Se=new AbortController;R(Se),E(!0);const je=Date.now();try{const Ue={...g};s.inputSchema?.properties&&Object.entries(s.inputSchema.properties).forEach(([Ke,Ze])=>{const At=Ze.type,Qn=Ue[Ke];if((At==="object"||At==="array")&&typeof Qn=="string")try{Ue[Ke]=JSON.parse(Qn)}catch{}});const We=await n(s.name,Ue,{timeout:6e5,resetTimeoutOnProgress:!0,signal:Se.signal}),Je=Date.now()-je;vr.getInstance().capture(new qU({toolName:s.name,serverId:r,success:!0,duration:Je})).catch(()=>{});const mt=s?._meta||s?.metadata,Mt=mt?.["openai/outputTemplate"];let nn;if(Mt&&typeof Mt=="string"){const Ke={toolName:s.name,args:g,result:We,timestamp:je,duration:Je,toolMeta:mt,appsSdkResource:{uri:Mt,resourceData:null,isLoading:!0}};S([Ke]);try{const Ze=await a(Mt);let dt=null;if(We?.structuredContent)dt=We.structuredContent;else if(Array.isArray(We)&&We[0]){const At=We[0];At.output?.value?.structuredContent?dt=At.output.value.structuredContent:At.structuredContent?dt=At.structuredContent:At.output?.value&&(dt=At.output.value)}dt||(dt=We),nn={uri:Mt,resourceData:{...Ze,structuredContent:dt},isLoading:!1}}catch(Ze){nn={uri:Mt,resourceData:null,isLoading:!1,error:Ze instanceof Error?Ze.message:String(Ze)}}S(Ze=>Ze.map((dt,At)=>At===0?{...dt,appsSdkResource:nn}:dt))}else S(Ke=>[{toolName:s.name,args:g,result:We,timestamp:je,duration:Je,toolMeta:mt},...Ke])}catch(Ue){const We=Date.now()-je;vr.getInstance().capture(new qU({toolName:s.name,serverId:r,success:!1,duration:We,error:Ue instanceof Error?Ue.message:String(Ue)})).catch(()=>{});const yt=s?._meta||s?.metadata,mt={toolName:s.name,args:g,result:null,error:Ue instanceof Error?Ue.message:String(Ue),timestamp:je,duration:We,toolMeta:yt},Mt=yt?.["openai/outputTemplate"];S(Mt?[mt]:nn=>[mt,...nn])}finally{E(!1)}},[s,g,y,n,a,r]),ft=w.useCallback(async(Se,je)=>{try{await navigator.clipboard.writeText(JSON.stringify(je,null,2)),k(Se),setTimeout(()=>k(null),2e3)}catch(Ue){console.error("[ToolsTab] Failed to copy result:",Ue)}},[]),Et=w.useCallback(Se=>{S(je=>je.filter((Ue,We)=>We!==Se))},[]),pt=w.useMemo(()=>s?x.filter(Se=>Se.toolName===s.name):[],[x,s]),mn=w.useCallback(Se=>{const je=pt[Se];if(je){const Ue=window.open("","_blank","width=800,height=600");Ue&&(Ue.document.write(`
1663
1663
  <html>
1664
1664
  <head>
@@ -1673,4 +1673,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1673
1673
  <pre>${JSON.stringify(je.result,null,2)}</pre>
1674
1674
  </body>
1675
1675
  </html>
1676
- `),Ue.document.close())}},[x]),Pr=w.useCallback(()=>{W?(oe.current&&oe.current.expand(),Ne.current&&Ne.current.expand(),X(!1)):(oe.current&&oe.current.collapse(),Ne.current&&Ne.current.collapse(),X(!0))},[W]),St=w.useCallback(()=>{s&&(ae(""),ee(!0))},[s]),Be=w.useCallback(()=>{if(!s)return;const Se={id:`${Date.now()}-${Math.random()}`,name:te.trim()||`${s.name} - ${new Date().toLocaleString()}`,toolName:s.name,args:g,savedAt:Date.now(),serverId:s._serverId,serverName:s._serverName};Fe([...P,Se]),vr.getInstance().capture(new tme({toolName:s.name,serverId:r})).catch(()=>{}),ee(!1),ae("")},[s,te,g,P,Fe,r]),Le=w.useCallback(Se=>{Fe(P.filter(je=>je.id!==Se)),u?.id===Se&&d(null)},[P,Fe,u]);return z?f.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[L!=="list"&&f.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{L==="response"?F("detail"):(c(null),F("list"))},className:"p-0 h-8 w-8",children:f.jsx(qy,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center text-sm font-medium",children:[f.jsx("button",{onClick:()=>{c(null),F("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Tools"}),L==="detail"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("button",{onClick:()=>{F("response")},className:L==="detail"?"text-foreground hover:underline":L==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),L==="response"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),f.jsx("div",{className:"flex-1 relative overflow-hidden",children:f.jsxs(rw,{initial:!1,mode:"popLayout",children:[L==="list"&&f.jsxs(ya.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[f.jsx(Y2,{activeTab:O,isSearchExpanded:G,searchQuery:I,filteredToolsCount:pe.length,savedRequestsCount:P.length,onSearchExpand:()=>re(!0),onSearchChange:A,onSearchBlur:xe,onTabSwitch:()=>M(O==="tools"?"saved":"tools"),searchInputRef:V}),O==="tools"?f.jsx(Z2,{tools:pe,selectedTool:s,onToolSelect:Oe,focusedIndex:ne}):f.jsx(B2,{savedRequests:P,selectedRequest:u,onLoadRequest:He,onDeleteRequest:Le,focusedIndex:ne})]},"list"),L==="detail"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-10",children:f.jsx(G2,{selectedTool:s,toolArgs:g,isExecuting:y,isConnected:i,onArgChange:at,onExecute:nt,onSave:St})},"detail"),L==="response"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-20",children:f.jsx(K2,{results:pt,copiedResult:_,previewMode:H,serverId:r,readResource:a,onCopy:ft,onDelete:Et,onFullscreen:mn,onTogglePreview:()=>Z(!H)})},"response")]})}),f.jsx(H2,{isOpen:K,requestName:te,defaultPlaceholder:`${s?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:ae,onSave:Be,onCancel:()=>ee(!1)})]}):f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{ref:oe,defaultSize:33,collapsible:!0,className:"flex flex-col h-full relative",children:f.jsxs(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[f.jsx(Rn,{defaultSize:75,minSize:30,children:f.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[f.jsx(Y2,{activeTab:O,isSearchExpanded:G,searchQuery:I,filteredToolsCount:pe.length,savedRequestsCount:P.length,onSearchExpand:()=>re(!0),onSearchChange:A,onSearchBlur:xe,onTabSwitch:()=>M(O==="tools"?"saved":"tools"),searchInputRef:V}),O==="tools"?f.jsx(Z2,{tools:pe,selectedTool:s,onToolSelect:Oe,focusedIndex:ne}):f.jsx(B2,{savedRequests:P,selectedRequest:u,onLoadRequest:He,onDeleteRequest:Le,focusedIndex:ne})]})}),f.jsx(Si,{withHandle:!0}),f.jsxs(Rn,{ref:_e,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>{q(!0)},onExpand:()=>{q(!1)},className:"flex flex-col border-t dark:border-zinc-700",children:[f.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:Se=>{Se.preventDefault(),Se.stopPropagation(),J?(_e.current?.resize(25),q(!1)):(_e.current?.resize(5),q(!0))},children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),ie>0&&f.jsx(wr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:ie}),ie>0&&!J&&f.jsx($e,{variant:"ghost",size:"sm",onClick:Se=>{Se.preventDefault(),Se.stopPropagation(),ke.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:f.jsx(Fs,{className:"h-3.5 w-3.5"})})]}),f.jsx(ac,{className:`h-4 w-4 text-muted-foreground transition-transform ${J?"":"rotate-180"}`})]}),!J&&f.jsx("div",{className:"flex-1 overflow-hidden min-h-0",children:f.jsx(ED,{serverIds:[r],onCountChange:ce,onClearRef:ke})})]})]})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{defaultSize:67,children:f.jsxs(na,{direction:"vertical",children:[f.jsx(Rn,{ref:Ne,defaultSize:40,collapsible:!0,children:f.jsx(G2,{selectedTool:s,toolArgs:g,isExecuting:y,isConnected:i,onArgChange:at,onExecute:nt,onSave:St,onCancel:()=>{C&&C.abort()}})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{ref:Ve,defaultSize:60,children:f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(K2,{results:pt,copiedResult:_,previewMode:H,serverId:r,readResource:a,onCopy:ft,onDelete:Et,onFullscreen:mn,onTogglePreview:()=>Z(!H),onMaximize:Pr,isMaximized:W})})})]})}),f.jsx(H2,{isOpen:K,requestName:te,defaultPlaceholder:`${s?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:ae,onSave:Be,onCancel:()=>ee(!1)})]})}qY.displayName="ToolsTab";function CTe({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:a,onSearchExpand:r,onSearchChange:i,onSearchBlur:s,onRejectAll:c,searchInputRef:u}){return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:u,placeholder:"Search requests...",value:t,onChange:d=>i(d.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Sampling"}),f.jsx(wr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,disabled:a===0,className:"h-8 w-8 p-0",children:f.jsx(Fs,{className:"h-4 w-4"})})}),f.jsx(Rt,{side:"bottom",children:"Reject all"})]})})]})}function RTe({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:a,formatRelativeTime:r,listRef:i}){return e.length===0?f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No sampling requests"})}):f.jsx("div",{ref:i,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((s,c)=>{const u=s.request.params?.messages?.length||0,d=s.request.params?.maxTokens;return f.jsx(Qs,{id:`sampling-request-${s.id}`,isSelected:t?.id===s.id,isFocused:a===c,title:f.jsxs("span",{className:"flex items-center gap-3",children:[s.serverName,f.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const m=r(s.timestamp),h=[];u>0&&h.push(`${u} message${u>1?"s":""}`),d&&h.push(`max ${d} tokens`);const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(s)},s.id)})})}function ATe({llmConfig:e}){const t=w.useRef(null);return{generateResponse:w.useCallback(async({request:a})=>{if(!e)throw new Error("LLM config is not available");const r=a.params||{},i=r.maxTokens,s=r.temperature;r.modelPreferences;const c=r.messages||[];if(console.log("[useSamplingLLM] Request structure:",{hasParams:!!r,messagesCount:c.length,messages:c,params:r}),c.length===0)throw new Error("No messages found in sampling request");const u=[],{HumanMessage:d,AIMessage:m}=await Jn(async()=>{const{HumanMessage:x,AIMessage:S}=await import("./index-DDtG6uBj.js").then(y=>y.bI);return{HumanMessage:x,AIMessage:S}},[]);for(const x of c){if(!x||!x.role){console.warn("Skipping invalid message:",x);continue}const S=Array.isArray(x.content)?x.content[0]:x.content;if(!S){console.warn("Skipping message with no content:",x);continue}S.type==="text"&&S.text?x.role==="user"?u.push(new d(S.text)):x.role==="assistant"&&u.push(new m(S.text)):console.warn("Skipping message with unsupported content type:",S)}if(u.length===0)throw new Error("No valid messages could be converted. Please ensure messages have 'text' content type.");if(!t.current||t.current.provider!==e.provider||t.current.model!==e.model||t.current.apiKey!==e.apiKey){let x;const S={model:e.model,apiKey:e.apiKey};if(i!==void 0&&(S.maxTokens=i),s!==void 0?S.temperature=s:e.temperature!==void 0&&(S.temperature=e.temperature),e.provider==="openai"){const{ChatOpenAI:y}=await Jn(async()=>{const{ChatOpenAI:E}=await import("./index-BWMAhNJO.js");return{ChatOpenAI:E}},__vite__mapDeps([6,7,8,2,9,10,11]));x=new y(S)}else if(e.provider==="anthropic"){const{ChatAnthropic:y}=await Jn(async()=>{const{ChatAnthropic:E}=await import("./index-CmdaC4jK.js");return{ChatAnthropic:E}},__vite__mapDeps([12,8,7,2,11]));x=new y(S)}else if(e.provider==="google"){const{ChatGoogleGenerativeAI:y}=await Jn(async()=>{const{ChatGoogleGenerativeAI:E}=await import("./index-BMVGFw1P.js");return{ChatGoogleGenerativeAI:E}},__vite__mapDeps([13,8,7,2,10]));x=new y(S)}else throw new Error(`Unsupported LLM provider: ${e.provider}`);t.current={instance:x,provider:e.provider,model:e.model,apiKey:e.apiKey}}const h=await t.current.instance.invoke(u);return{role:"assistant",content:{type:"text",text:h.content||h.text||""},model:e.model,stopReason:"endTurn"}},[e]),isAvailable:e!==null}}function ITe({request:e,onApprove:t,onReject:n,onClose:a,previewMode:r,onTogglePreview:i,isCopied:s,onCopy:c,onDownload:u,onFullscreen:d,llmConfig:m}){const[h,g]=w.useState("manual"),[v,x]=w.useState("stub-model"),[S,y]=w.useState("endTurn"),[E,_]=w.useState("assistant"),[k,C]=w.useState("text"),[R,I]=w.useState("positive"),[A,O]=w.useState(""),[M,P]=w.useState("image/png"),[B,K]=w.useState(!1),[ee,te]=w.useState(null),{generateResponse:ae,isAvailable:H}=ATe({llmConfig:m});w.useEffect(()=>{e&&(x("stub-model"),y("endTurn"),_("assistant"),C("text"),I("positive"),O(""),P("image/png"),te(null))},[e?.id]);const Z=async()=>{if(!(!e||!H)){K(!0),te(null);try{const j=await ae({request:e.request});x(j.model||m?.model||"stub-model"),y(j.stopReason||"endTurn"),_(j.role||"assistant");const V=Array.isArray(j.content)?j.content[0]:j.content;V.type==="text"?(C("text"),I(V.text||"")):V.type==="image"&&(C("image"),O(V.data||""),P(V.mimeType||"image/png"))}catch(j){const V=j instanceof Error?j.message:"Failed to generate response";te(V),Xt.error("LLM Generation Failed",{description:V})}finally{K(!1)}}},G=w.useMemo(()=>{const j={model:v,stopReason:S,role:E,content:{type:k}};return k==="text"?j.content.text=R:k==="image"&&(j.content.data=A,j.content.mimeType=M),j},[v,S,E,k,R,A,M]),re=()=>{if(!e)return;const j=cN.safeParse(G);if(!j.success){Xt.error("Invalid response",{description:`Validation failed: ${j.error.message}`});return}t(e.id,j.data),a(),Jn(()=>Promise.resolve().then(()=>kd),void 0).then(V=>{const z=Xt(V.createElement("div",{className:"space-y-3"},V.createElement("div",null,V.createElement("strong",null,"Sampling Response Sent"),V.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),V.createElement("div",{className:"flex gap-2"},V.createElement("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>{const $=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:e.toolName}});window.dispatchEvent($),Xt.dismiss(z)}},"View Tool Result"))),{duration:5e3})})},ne=()=>{e&&(n(e.id,"User rejected sampling request"),a())};return e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),f.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,className:"h-8 w-8 p-0",children:s?f.jsx(ra,{className:"h-4 w-4 text-green-600"}):f.jsx($r,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Copy request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:f.jsx(Lm,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Download request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:d,className:"h-8 w-8 p-0",children:f.jsx(QN,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Fullscreen"})]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:f.jsx(Ji,{className:"h-4 w-4"})})]})]}),f.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Request"}),f.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:f.jsx(Xn,{data:e.request})})]}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Response"}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Kt,{htmlFor:`responseMode-${e.id}`,className:"text-xs text-gray-500 dark:text-gray-400",children:"Mode:"}),f.jsxs(Io,{value:h,onValueChange:j=>g(j),children:[f.jsx(Do,{id:`responseMode-${e.id}`,className:"w-32 h-8 text-xs",children:f.jsx(Oo,{})}),f.jsxs(jo,{children:[f.jsx(Ar,{value:"manual",children:"Manual"}),f.jsx(Ar,{value:"llm",children:"LLM"})]})]})]})]}),h==="llm"&&f.jsxs("div",{className:"space-y-2 p-3 bg-muted rounded-lg",children:[H?f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx($e,{onClick:Z,disabled:B,size:"sm",className:"flex items-center gap-2",children:B?f.jsxs(f.Fragment,{children:[f.jsx(zs,{className:"h-4 w-4 animate-spin"}),"Generating..."]}):f.jsxs(f.Fragment,{children:[f.jsx(jhe,{className:"h-4 w-4"}),"Generate with LLM"]})}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["Using ",m?.provider," (",m?.model,")"]})]}):f.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:"LLM not configured. Please configure LLM in the Chat tab."}),ee&&f.jsx("div",{className:"text-xs text-red-600 dark:text-red-400",children:ee})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`model-${e.id}`,children:"Model"}),f.jsx(En,{id:`model-${e.id}`,value:v,onChange:j=>x(j.target.value),placeholder:"stub-model",disabled:h==="llm"&&B})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`stopReason-${e.id}`,children:"Stop Reason"}),f.jsx(En,{id:`stopReason-${e.id}`,value:S,onChange:j=>y(j.target.value),placeholder:"endTurn",disabled:h==="llm"&&B})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`role-${e.id}`,children:"Role"}),f.jsxs(Io,{value:E,onValueChange:j=>_(j),disabled:h==="llm"&&B,children:[f.jsx(Do,{id:`role-${e.id}`,children:f.jsx(Oo,{})}),f.jsxs(jo,{children:[f.jsx(Ar,{value:"assistant",children:"assistant"}),f.jsx(Ar,{value:"user",children:"user"})]})]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`contentType-${e.id}`,children:"Content Type"}),f.jsxs(Io,{value:k,onValueChange:j=>C(j),disabled:h==="llm"&&B,children:[f.jsx(Do,{id:`contentType-${e.id}`,children:f.jsx(Oo,{})}),f.jsxs(jo,{children:[f.jsx(Ar,{value:"text",children:"text"}),f.jsx(Ar,{value:"image",children:"image"})]})]})]}),k==="text"&&f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`text-${e.id}`,children:"Text Content"}),f.jsx(Xl,{id:`text-${e.id}`,value:R,onChange:j=>I(j.target.value),placeholder:"Enter response text...",rows:6,disabled:h==="llm"&&B})]}),k==="image"&&f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`imageData-${e.id}`,children:"Base64 Image Data"}),f.jsx(Xl,{id:`imageData-${e.id}`,value:A,onChange:j=>O(j.target.value),placeholder:"Base64 encoded image data...",rows:4,disabled:h==="llm"&&B})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`mimeType-${e.id}`,children:"MIME Type"}),f.jsx(En,{id:`mimeType-${e.id}`,value:M,onChange:j=>P(j.target.value),placeholder:"image/png",disabled:h==="llm"&&B})]})]})]})]}),f.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[f.jsx($e,{onClick:re,className:"flex-1",disabled:h==="llm"&&B,children:"Approve"}),f.jsx($e,{onClick:ne,variant:"outline",className:"flex-1",disabled:h==="llm"&&B,children:"Reject"})]})]}):f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a sampling request to view details"})})}function OTe({pendingRequests:e,onApprove:t,onReject:n,serverId:a,isConnected:r,mcpServerUrl:i}){const{selectedSamplingRequestId:s,setSelectedSamplingRequestId:c}=ic(),{llmConfig:u}=_Y({mcpServerUrl:i}),[d,m]=w.useState(null),[h,g]=w.useState(""),[v,x]=w.useState(-1),[S,y]=w.useState(!0),[E,_]=w.useState(!1),[k,C]=w.useState(!0),[R,I]=w.useState(!1),A=w.useRef(null),O=w.useRef(null),M=w.useRef(null),P=w.useRef(!1);w.useEffect(()=>{if(console.log("[SamplingTab] Auto-selection check:",{selectedSamplingRequestId:s,pendingRequestsCount:e.length,currentSelectedId:d?.id}),s&&e.length>0){const G=e.find(re=>re.id===s);console.log("[SamplingTab] Found request for auto-selection:",!!G,G?.id),G&&(console.log("[SamplingTab] Auto-selecting request:",G.id),c(null),m(G),setTimeout(()=>{const re=document.getElementById(`sampling-request-${G.id}`);console.log("[SamplingTab] Scrolling to element:",!!re),re&&re.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[s,e,c]),w.useEffect(()=>{const G=re=>{const j=re.detail.requestId;console.log("[SamplingTab] Custom navigate event received:",j);const V=e.find(z=>z.id===j);V&&(console.log("[SamplingTab] Selecting request from event:",j),m(V),setTimeout(()=>{const z=document.getElementById(`sampling-request-${j}`);z&&z.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-sampling",G),()=>window.removeEventListener("navigate-to-sampling",G)},[e]),w.useEffect(()=>{S&&e.length>0&&A.current&&!P.current&&(A.current.scrollTop=0)},[e.length,S]),w.useEffect(()=>{const G=A.current;if(!G)return;const re=()=>{G.scrollTop>0&&(P.current=!0,y(!1))};return G.addEventListener("scroll",re),()=>G.removeEventListener("scroll",re)},[]),w.useEffect(()=>{e.length===0&&(P.current=!1,y(!0))},[e.length]),w.useEffect(()=>{E&&M.current&&M.current.focus()},[E]);const B=w.useCallback(()=>{h.trim()||_(!1)},[h]),K=w.useMemo(()=>{if(!h.trim())return e;const G=h.toLowerCase();return e.filter(re=>re.serverName.toLowerCase().includes(G)||JSON.stringify(re.request||{}).toLowerCase().includes(G))},[e,h]);w.useEffect(()=>{x(-1)},[h]),w.useEffect(()=>{const G=re=>{const ne=re.target;if(ne.tagName==="INPUT"||ne.tagName==="TEXTAREA"||ne.contentEditable==="true"||re.metaKey||re.ctrlKey||re.altKey)return;const V=K;if(re.key==="ArrowDown")re.preventDefault(),x(z=>{const $=z+1;return $>=V.length?0:$});else if(re.key==="ArrowUp")re.preventDefault(),x(z=>{const $=z-1;return $<0?V.length-1:$});else if(re.key==="Enter"&&v>=0){re.preventDefault();const z=K[v];z&&ee(z)}};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[v,K]),w.useEffect(()=>{if(v>=0){const G=`sampling-request-${K[v]?.id}`,re=document.getElementById(G);re&&re.scrollIntoView({behavior:"smooth",block:"nearest"})}},[v,K]);const ee=w.useCallback(G=>{m(G)},[]),te=w.useCallback(()=>{window.confirm("Are you sure you want to reject all sampling requests? This cannot be undone.")&&(e.forEach(G=>{n(G.id,"User rejected all requests")}),m(null))},[e,n]),ae=w.useCallback(async()=>{if(d)try{await navigator.clipboard.writeText(JSON.stringify({id:d.id,serverName:d.serverName,timestamp:d.timestamp,request:d.request},null,2)),I(!0),setTimeout(()=>I(!1),2e3)}catch(G){console.error("[SamplingTab] Failed to copy request:",G)}},[d]),H=w.useCallback(()=>{if(d)try{const G=new globalThis.Blob([JSON.stringify({id:d.id,serverName:d.serverName,timestamp:d.timestamp,request:d.request},null,2)],{type:"application/json"}),re=URL.createObjectURL(G),ne=document.createElement("a");ne.href=re,ne.download=`sampling-request-${Date.now()}.json`,document.body.appendChild(ne),ne.click(),document.body.removeChild(ne),URL.revokeObjectURL(re)}catch(G){console.error("[SamplingTab] Failed to download request:",G)}},[d]),Z=w.useCallback(async()=>{if(O.current)try{document.fullscreenElement?await document.exitFullscreen():await O.current.requestFullscreen()}catch(G){console.error("[SamplingTab] Failed to toggle fullscreen:",G)}},[]);return r?f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:40,minSize:30,children:f.jsx(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:f.jsxs(Rn,{defaultSize:75,minSize:30,children:[f.jsx(CTe,{isSearchExpanded:E,searchQuery:h,filteredRequestsCount:K.length,requestsCount:e.length,onSearchExpand:()=>_(!0),onSearchChange:g,onSearchBlur:B,onRejectAll:te,searchInputRef:M}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(RTe,{requests:K,selectedRequest:d,onRequestSelect:ee,focusedIndex:v,formatRelativeTime:ty,listRef:A})})]})})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:60,minSize:40,children:f.jsx("div",{ref:O,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(ITe,{request:d,onApprove:t,onReject:n,onClose:()=>m(null),previewMode:k,onTogglePreview:()=>C(!k),isCopied:R,onCopy:ae,onDownload:H,onFullscreen:Z,llmConfig:u})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(PG,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function DTe({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:a,onSearchExpand:r,onSearchChange:i,onSearchBlur:s,onCancelAll:c,searchInputRef:u}){return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:u,placeholder:"Search requests...",value:t,onChange:d=>i(d.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Elicitation"}),f.jsx(wr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,disabled:a===0,className:"h-8 w-8 p-0",children:f.jsx(Ji,{className:"h-4 w-4"})})}),f.jsx(Rt,{side:"bottom",children:"Cancel all"})]})})]})}function jTe({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:a,formatRelativeTime:r,listRef:i}){return e.length===0?f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No elicitation requests"})}):f.jsx("div",{ref:i,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((s,c)=>{const u=s.request.mode||"form",d=u==="form"&&"requestedSchema"in s.request&&s.request.requestedSchema;return f.jsx(Qs,{id:`elicitation-request-${s.id}`,isSelected:t?.id===s.id,isFocused:a===c,title:f.jsxs("span",{className:"flex items-center gap-3",children:[s.serverName,f.jsx(wr,{variant:"outline",className:u==="url"?"bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/50":"bg-green-500/20 text-green-600 dark:text-green-400 border-green-500/50",children:u})]}),description:(()=>{const m=r(s.timestamp),h=[];d&&h.push("with schema"),u==="url"&&h.push("external action");const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(s)},s.id)})})}function $Te({request:e,onApprove:t,onReject:n,onClose:a,previewMode:r,onTogglePreview:i,isCopied:s,onCopy:c,onDownload:u,onFullscreen:d}){const[m,h]=w.useState({}),[g,v]=w.useState(!1),x=e?.request.mode||"form",S=x==="form",y=x==="url";w.useEffect(()=>{if(e&&S&&"requestedSchema"in e.request){const A=e.request.requestedSchema,O={};if(A?.type==="object"&&A.properties)for(const[M,P]of Object.entries(A.properties)){const B=P;B.default!==void 0?O[M]=B.default:B.type==="boolean"?O[M]=!1:B.type==="number"||B.type==="integer"?O[M]=0:O[M]=""}h(O)}v(!1)},[e?.id,S]);const E=(A,O)=>{h(M=>({...M,[A]:O}))},_=()=>{if(e){if(S){if("requestedSchema"in e.request){const A=e.request.requestedSchema;if(A?.required){const O=A.required.filter(M=>m[M]===void 0||m[M]===""||m[M]===null);if(O.length>0){Xt.error("Missing required fields",{description:`Please fill in: ${O.join(", ")}`});return}}}t(e.id,{action:"accept",data:m})}else y&&t(e.id,{action:"accept"});a(),Jn(()=>Promise.resolve().then(()=>kd),void 0).then(A=>{const O=Xt(A.createElement("div",{className:"space-y-3"},A.createElement("div",null,A.createElement("strong",null,"Elicitation Response Sent"),A.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),A.createElement("div",{className:"flex gap-2"},A.createElement("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>{const M=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:null}});window.dispatchEvent(M),Xt.dismiss(O)}},"View Tool Result"))),{duration:5e3})})}},k=()=>{e&&(t(e.id,{action:"decline"}),a())},C=()=>{e&&(n(e.id,"User cancelled elicitation request"),a())},R=()=>{e&&y&&"url"in e.request&&(window.open(e.request.url,"_blank"),v(!0))},I=w.useMemo(()=>{if(!e||!S||!("requestedSchema"in e.request))return null;const A=e.request.requestedSchema;if(!A||A.type!=="object"||!A.properties)return f.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No form schema available"});const O=A.properties,M=A.required||[];return f.jsx("div",{className:"space-y-4",children:Object.entries(O).map(([P,B])=>{const K=B,ee=M.includes(P),te=K.type||"string",ae=K.title||P,H=K.description;return f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:`field-${P}`,children:[ae,ee&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),H&&f.jsx("p",{className:"text-xs text-muted-foreground",children:H}),te==="boolean"?f.jsxs("div",{className:"flex items-center space-x-2",children:[f.jsx(im,{id:`field-${P}`,checked:m[P]||!1,onCheckedChange:Z=>E(P,Z)}),f.jsx(Kt,{htmlFor:`field-${P}`,className:"text-sm font-normal cursor-pointer",children:K.title||P})]}):te==="number"||te==="integer"?f.jsx(En,{id:`field-${P}`,type:"number",value:m[P]||"",onChange:Z=>E(P,te==="integer"?parseInt(Z.target.value,10):parseFloat(Z.target.value)),placeholder:K.default?.toString()||""}):K.enum?f.jsxs("select",{id:`field-${P}`,value:m[P]||"",onChange:Z=>E(P,Z.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:[f.jsx("option",{value:"",children:"Select..."}),K.enum.map(Z=>f.jsx("option",{value:Z,children:Z},Z))]}):te==="string"&&(K.format==="textarea"||K.maxLength>100)?f.jsx(Xl,{id:`field-${P}`,value:m[P]||"",onChange:Z=>E(P,Z.target.value),placeholder:K.default||"",rows:4}):f.jsx(En,{id:`field-${P}`,type:"text",value:m[P]||"",onChange:Z=>E(P,Z.target.value),placeholder:K.default||""})]},P)})})},[e,m,S]);return e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),f.jsx(wr,{variant:"outline",className:y?"bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/50":"bg-green-500/20 text-green-600 dark:text-green-400 border-green-500/50",children:x}),f.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,className:"h-8 w-8 p-0",children:s?f.jsx(ra,{className:"h-4 w-4 text-green-600"}):f.jsx($r,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Copy request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:f.jsx(Lm,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Download request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:d,className:"h-8 w-8 p-0",children:f.jsx(QN,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Fullscreen"})]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:f.jsx(Ji,{className:"h-4 w-4"})})]})]}),f.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Message"}),f.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:e.request.message})]}),y&&"url"in e.request&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"External Action Required"}),f.jsxs("div",{className:"bg-muted rounded-lg p-4 space-y-3",children:[f.jsx("p",{className:"text-sm text-muted-foreground",children:"This request requires you to complete an action at an external URL:"}),f.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background rounded border",children:[f.jsx("code",{className:"flex-1 text-xs font-mono break-all",children:e.request.url}),f.jsxs($e,{size:"sm",variant:"outline",onClick:R,className:"flex items-center gap-2",children:[f.jsx(Y_,{className:"h-4 w-4"}),"Open URL"]})]}),f.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[f.jsx(im,{id:"url-completed",checked:g,onCheckedChange:A=>v(!!A)}),f.jsx(Kt,{htmlFor:"url-completed",className:"text-sm font-normal cursor-pointer",children:"I have completed the required action"})]})]})]}),S&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Form Data"}),I]}),S&&"requestedSchema"in e.request&&e.request.requestedSchema&&f.jsxs("details",{className:"space-y-2",children:[f.jsx("summary",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 cursor-pointer",children:"Schema (for reference)"}),f.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:f.jsx(Xn,{data:e.request.requestedSchema})})]})]}),f.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[f.jsx($e,{onClick:_,className:"flex-1",children:"Accept"}),f.jsx($e,{onClick:k,variant:"outline",className:"flex-1",children:"Decline"}),f.jsx($e,{onClick:C,variant:"outline",className:"flex-1",children:"Cancel"})]})]}):f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select an elicitation request to view details"})})}function LTe({pendingRequests:e=[],onApprove:t,onReject:n,serverId:a,isConnected:r}){const{selectedElicitationRequestId:i,setSelectedElicitationRequestId:s}=ic(),[c,u]=w.useState(null),[d,m]=w.useState(""),[h,g]=w.useState(-1),[v,x]=w.useState(!0),[S,y]=w.useState(!1),[E,_]=w.useState(!0),[k,C]=w.useState(!1),R=w.useRef(null),I=w.useRef(null),A=w.useRef(null),O=w.useRef(!1);w.useEffect(()=>{if(console.log("[ElicitationTab] Auto-selection check:",{selectedElicitationRequestId:i,pendingRequestsCount:e.length,currentSelectedId:c?.id}),i&&e.length>0){const H=e.find(Z=>Z.id===i);console.log("[ElicitationTab] Found request for auto-selection:",!!H,H?.id),H&&(console.log("[ElicitationTab] Auto-selecting request:",H.id),s(null),u(H),setTimeout(()=>{const Z=document.getElementById(`elicitation-request-${H.id}`);console.log("[ElicitationTab] Scrolling to element:",!!Z),Z&&Z.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[i,e,s]),w.useEffect(()=>{const H=Z=>{const re=Z.detail.requestId;console.log("[ElicitationTab] Custom navigate event received:",re);const ne=e.find(j=>j.id===re);ne&&(console.log("[ElicitationTab] Selecting request from event:",re),u(ne),setTimeout(()=>{const j=document.getElementById(`elicitation-request-${re}`);j&&j.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-elicitation",H),()=>window.removeEventListener("navigate-to-elicitation",H)},[e]),w.useEffect(()=>{v&&e.length>0&&R.current&&!O.current&&(R.current.scrollTop=0)},[e.length,v]),w.useEffect(()=>{const H=R.current;if(!H)return;const Z=()=>{H.scrollTop>0&&(O.current=!0,x(!1))};return H.addEventListener("scroll",Z),()=>H.removeEventListener("scroll",Z)},[]),w.useEffect(()=>{e.length===0&&(O.current=!1,x(!0))},[e.length]),w.useEffect(()=>{S&&A.current&&A.current.focus()},[S]);const M=w.useCallback(()=>{d.trim()||y(!1)},[d]),P=w.useMemo(()=>{if(!d.trim())return e;const H=d.toLowerCase();return e.filter(Z=>Z.serverName.toLowerCase().includes(H)||Z.request.message.toLowerCase().includes(H)||JSON.stringify(Z.request||{}).toLowerCase().includes(H))},[e,d]);w.useEffect(()=>{g(-1)},[d]),w.useEffect(()=>{const H=Z=>{const G=Z.target;if(G.tagName==="INPUT"||G.tagName==="TEXTAREA"||G.contentEditable==="true"||Z.metaKey||Z.ctrlKey||Z.altKey)return;const ne=P;if(Z.key==="ArrowDown")Z.preventDefault(),g(j=>{const V=j+1;return V>=ne.length?0:V});else if(Z.key==="ArrowUp")Z.preventDefault(),g(j=>{const V=j-1;return V<0?ne.length-1:V});else if(Z.key==="Enter"&&h>=0){Z.preventDefault();const j=P[h];j&&B(j)}};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[h,P]),w.useEffect(()=>{if(h>=0){const H=`elicitation-request-${P[h]?.id}`,Z=document.getElementById(H);Z&&Z.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,P]);const B=w.useCallback(H=>{u(H)},[]),K=w.useCallback(()=>{window.confirm("Are you sure you want to cancel all elicitation requests? This cannot be undone.")&&(e.forEach(H=>{n(H.id,"User cancelled all requests")}),u(null))},[e,n]),ee=w.useCallback(async()=>{if(c)try{await navigator.clipboard.writeText(JSON.stringify({id:c.id,serverName:c.serverName,timestamp:c.timestamp,request:c.request},null,2)),C(!0),setTimeout(()=>C(!1),2e3)}catch(H){console.error("[ElicitationTab] Failed to copy request:",H)}},[c]),te=w.useCallback(()=>{if(c)try{const H=new globalThis.Blob([JSON.stringify({id:c.id,serverName:c.serverName,timestamp:c.timestamp,request:c.request},null,2)],{type:"application/json"}),Z=URL.createObjectURL(H),G=document.createElement("a");G.href=Z,G.download=`elicitation-request-${Date.now()}.json`,document.body.appendChild(G),G.click(),document.body.removeChild(G),URL.revokeObjectURL(Z)}catch(H){console.error("[ElicitationTab] Failed to download request:",H)}},[c]),ae=w.useCallback(async()=>{if(I.current)try{document.fullscreenElement?await document.exitFullscreen():await I.current.requestFullscreen()}catch(H){console.error("[ElicitationTab] Failed to toggle fullscreen:",H)}},[]);return r?f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:40,minSize:30,children:f.jsx(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:f.jsxs(Rn,{defaultSize:75,minSize:30,children:[f.jsx(DTe,{isSearchExpanded:S,searchQuery:d,filteredRequestsCount:P.length,requestsCount:e.length,onSearchExpand:()=>y(!0),onSearchChange:m,onSearchBlur:M,onCancelAll:K,searchInputRef:A}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(jTe,{requests:P,selectedRequest:c,onRequestSelect:B,focusedIndex:h,formatRelativeTime:ty,listRef:R})})]})})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:60,minSize:40,children:f.jsx("div",{ref:I,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx($Te,{request:c,onApprove:t,onReject:n,onClose:()=>u(null),previewMode:E,onTogglePreview:()=>_(!E),isCopied:k,onCopy:ee,onDownload:te,onFullscreen:ae})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(BG,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function MTe({selectedServer:e,activeTab:t,toolsSearchRef:n,promptsSearchRef:a,resourcesSearchRef:r,children:i}){return e?f.jsxs(f.Fragment,{children:[f.jsx("div",{style:{display:t==="tools"?"block":"none"},className:"h-full",children:f.jsx(qY,{ref:n,tools:e.tools,callTool:e.callTool,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="prompts"?"block":"none"},className:"h-full",children:f.jsx(WY,{ref:a,prompts:e.prompts,callPrompt:e.getPrompt,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="resources"?"block":"none"},className:"h-full",children:f.jsx(ZY,{ref:r,resources:e.resources,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="chat"?"block":"none"},className:"h-full",children:f.jsx(Uke,{connection:e,isConnected:e.state==="ready",readResource:e.readResource},e.id)}),f.jsx("div",{style:{display:t==="sampling"?"block":"none"},className:"h-full",children:f.jsx(OTe,{pendingRequests:e.pendingSamplingRequests,onApprove:e.approveSampling,onReject:e.rejectSampling,serverId:e.id,isConnected:e.state==="ready",mcpServerUrl:e.url})}),f.jsx("div",{style:{display:t==="elicitation"?"block":"none"},className:"h-full",children:f.jsx(LTe,{pendingRequests:e.pendingElicitationRequests,onApprove:e.approveElicitation,onReject:e.rejectElicitation,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="notifications"?"block":"none"},className:"h-full",children:f.jsx(bTe,{notifications:e.notifications,unreadCount:e.unreadNotificationCount,markNotificationRead:e.markNotificationRead,markAllNotificationsRead:e.markAllNotificationsRead,clearNotifications:e.clearNotifications,serverId:e.id,isConnected:e.state==="ready"})}),t!=="tools"&&t!=="prompts"&&t!=="resources"&&t!=="chat"&&t!=="sampling"&&t!=="elicitation"&&t!=="notifications"&&f.jsx(f.Fragment,{children:i})]}):f.jsx(f.Fragment,{children:i})}function X2({className:e}){return f.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentcolor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[f.jsx("path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"}),f.jsx("path",{d:"M9 18c-4.51 2-5-2-7-2"})]})}const XY=w.createContext(void 0);function JY(){const e=w.use(XY);if(!e)throw new Error("useTabs must be used within a TabsProvider");return e}const QY=w.createContext(void 0);function PTe(){return w.use(QY)}function rk({ref:e,children:t,defaultValue:n,value:a,onValueChange:r,className:i,collapsed:s,onCollapsedChange:c,...u}){const[d,m]=w.useState(n||""),h=a!==void 0,g=s!==void 0,[v,x]=w.useState(!1),S=w.useCallback(k=>{h||m(k),r?.(k)},[h,r]),y=h?a:d,E=g?s:v,_=w.useCallback(k=>{g||x(k),c?.(k)},[g,c]);return f.jsx(XY,{value:{activeValue:y,handleValueChange:S,collapsed:E,handleCollapsedChange:_},children:f.jsx("div",{ref:e,className:De("flex flex-col gap-2",i),...u,children:t})})}rk.displayName="Tabs";function ak({ref:e,children:t,className:n,variant:a="default",collapsible:r=!1,...i}){const{activeValue:s,collapsed:c,handleCollapsedChange:u}=JY(),[d,m]=w.useState({width:0,left:0}),h=w.useRef(null),g=w.useRef(null),v=w.useRef(null),x=w.useCallback(()=>{const E=h.current;if(!E)return;const _=E.querySelector("div:first-child");if(!_)return;const k=_.querySelector(`button[data-tab-value="${s}"]`);if(k&&s){const C=_.getBoundingClientRect(),R=k.getBoundingClientRect();m({width:R.width,left:R.left-C.left})}else m({width:0,left:0})},[s]),S=w.useCallback(()=>{v.current&&clearTimeout(v.current),v.current=setTimeout(x,16)},[x]);w.useEffect(()=>{const E=setTimeout(x,10);return()=>clearTimeout(E)},[x,c]),w.useEffect(()=>{const E=h.current;if(!E)return;g.current=new ResizeObserver(()=>{S()}),g.current.observe(E);const _=E.querySelector("div:first-child");return _&&_.querySelectorAll("button[data-tab-value]").forEach(C=>{g.current&&g.current.observe(C)}),()=>{g.current&&g.current.disconnect(),v.current&&clearTimeout(v.current)}},[S]),w.useEffect(()=>{const E=()=>{S()};return window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[S]);const y=w.useRef(null);return w.useEffect(()=>{y.current&&(y.current.style.width=`${d.width}px`,y.current.style.left=`${d.left}px`)},[d]),f.jsx(QY,{value:{variant:a,collapsed:c,handleCollapsedChange:u},children:f.jsx("div",{ref:h,className:De("relative flex items-center bg-none gap-1",a==="default"&&"p-1 rounded-full border border-zinc-300 dark:border-zinc-600",a==="underline"&&"border-b border-zinc-200 dark:border-zinc-700",n),...i,children:f.jsxs("div",{role:"tablist",className:"flex-1 flex items-center relative",children:[t,f.jsx("span",{ref:y,className:De("absolute transition-all duration-500 ease-in-out z-0",a==="default"&&"bg-white dark:bg-zinc-700 rounded-full h-[calc(100%)] top-0 border border-zinc-300 dark:border-zinc-600",a==="underline"&&"bottom-0 h-0.5 bg-black dark:bg-white")})]})})})}ak.displayName="TabsList";const UTe=({children:e,title:t,collapsed:n})=>!t||!n?e:f.jsx(ZN,{children:f.jsxs(Nt,{children:[f.jsx(Ct,{children:e}),f.jsx(Rt,{children:t})]})}),ik=w.forwardRef(({children:e,value:t,className:n,disabled:a,icon:r,title:i,...s},c)=>{const{activeValue:u,handleValueChange:d,collapsed:m}=JY(),g=PTe()?.variant||"default",v=u===t,x=m&&i?i:void 0;return f.jsx(UTe,{title:i,collapsed:m,children:f.jsxs("button",{ref:c,disabled:a,onClick:()=>d(t),"data-tab-value":t,"data-tab-active":v,role:"tab","aria-selected":v?"true":"false",title:x,className:De("relative z-10 flex-1 inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-500 ease-in-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 cursor-pointer",g==="default"&&"py-2.5",g==="default"&&"rounded-md px-4",g==="underline"&&"px-6 py-3 border-b-2 border-transparent",v&&"text-foreground",!v&&"text-muted-foreground hover:text-foreground",n),...s,children:[r&&f.jsx(r,{className:De("h-4 w-4 transition-all duration-500 ease-in-out",!m&&"mr-2",m&&"mr-0!")}),f.jsx("span",{className:De("transition-all duration-500 ease-in-out overflow-hidden",m?"w-0 opacity-0":"w-auto opacity-100"),children:e})]})})});ik.displayName="TabsTrigger";function J2({className:e}){const{theme:t,setTheme:n}=xw(),a=w.useRef(null),[r,i]=w.useState(!1);w.useEffect(()=>{i(!0)},[]);const s=()=>t==="system"?"light":t==="light"?"dark":"system",c=()=>t==="system"?f.jsx(rz,{className:"size-4"}):t==="light"?f.jsx(Uhe,{className:"size-5"}):f.jsx(vhe,{className:"size-4"}),u=()=>t==="system"?"Switch to light mode":t==="light"?"Switch to dark mode":"Switch to system mode",d=async()=>{if(!a.current)return;const m=s();if(typeof document<"u"&&"startViewTransition"in document){await document.startViewTransition(()=>{Od.flushSync(()=>{n(m)})}).ready;const{top:h,left:g,width:v,height:x}=a.current.getBoundingClientRect(),S=h+x/2,y=g+v/2,E=window.innerWidth-g,_=window.innerHeight-h,k=Math.hypot(Math.max(g,E),Math.max(h,_));document.documentElement.animate({clipPath:[`circle(0px at ${y}px ${S}px)`,`circle(${k}px at ${y}px ${S}px)`]},{duration:700,easing:"ease-in-out",pseudoElement:"::view-transition-new(root)"})}else n(m)};return r?f.jsx("button",{ref:a,onClick:d,className:De(e),"aria-label":u(),title:`Current: ${t==="system"?"Auto":t==="light"?"Light":"Dark"}`,children:c()}):f.jsx("button",{ref:a,className:De(e),"aria-label":"Toggle theme",children:f.jsx(rz,{className:"size-4"})})}function Q2({className:e,state:t="collapsed",href:n="https://mcp-use.com"}){const[a,r]=w.useState(!1),i=.2,s=.7,c=.6,u=4,d=i+s+c,m=0,h=i/d,g=(i+s)/d,v=1;return f.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:De("flex items-center transition-opacity -my-3",t==="expanded"?"space-x-2":"",e),onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:[f.jsx("div",{className:"relative",children:f.jsxs(ya.svg,{viewBox:"0 0 303 303",initial:"rest",animate:a?"hover":"rest",className:De("text-foreground",t==="expanded"?"size-[40px]":"size-[20px]"),children:[f.jsxs(ya.g,{variants:{rest:{opacity:1},hover:{opacity:[1,0,0,1],transition:{duration:d,times:[m,h,g,v],ease:"easeInOut"}}},fill:"currentColor",fillRule:"nonzero",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"m105.5 34.8.6.6c9.5 9.5 14.4 21.9 14.6 34.4a112.6 112.6 0 0 0 112.2 112.1h.6c12 .4 24 5.1 33.2 14.1l.6.6a50 50 0 0 1-70.1 71.3l-.6-.6A49.9 49.9 0 0 1 182 230 112.6 112.6 0 0 0 73.4 120.7h-.8a49.9 49.9 0 0 1-36.7-14l-.5-.6a50 50 0 0 1-.6-70.2l.6-.5a50 50 0 0 1 69.5-1.2l.6.6Z"}),f.jsx("circle",{cx:"70.3",cy:"232.3",r:"50"}),f.jsx("circle",{cx:"232.3",cy:"70.3",r:"50"})]}),f.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx(zTe,{d:"m105.5 34.8.6.6c9.5 9.5 14.4 21.9 14.6 34.4a112.6 112.6 0 0 0 112.2 112.1h.6c12 .4 24 5.1 33.2 14.1l.6.6a50 50 0 0 1-70.1 71.3l-.6-.6A49.9 49.9 0 0 1 182 230 112.6 112.6 0 0 0 73.4 120.7h-.8a49.9 49.9 0 0 1-36.7-14l-.5-.6a50 50 0 0 1-.6-70.2l.6-.5a50 50 0 0 1 69.5-1.2l.6.6Z",times:{T0:m,T1:h,T2:g,T3:v},total:d}),f.jsx(eF,{cx:70.3,cy:232.3,r:50,times:{T0:m,T1:h,T2:g,T3:v},total:d}),f.jsx(eF,{cx:232.3,cy:70.3,r:50,times:{T0:m,T1:h,T2:g,T3:v},total:d})]})]})}),t==="expanded"&&f.jsxs("div",{className:"font-ubuntu flex flex-col items-start -space-y-1 mr-3",children:[f.jsx("h1",{className:"text-xl font-medium",children:"mcp-use"}),f.jsx("span",{className:"text-lg text-muted-foreground tracking-wide font-sans font-light",children:"Inspector"})]})]})}function zTe({d:e,times:t,total:n}){const{T0:a,T1:r,T2:i,T3:s}=t;return f.jsx(ya.path,{d:e,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:n,times:[a,r,i,s],ease:"easeInOut"}}}})}function eF({cx:e,cy:t,r:n,times:a,total:r}){const{T0:i,T1:s,T2:c,T3:u}=a;return f.jsx(ya.circle,{cx:e,cy:t,r:n,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:r,times:[i,s,c,u],ease:"easeInOut"}}}})}function eq({ref:e,shimmerColor:t,shimmerSize:n="0.05em",shimmerDuration:a="3s",borderRadius:r="100px",background:i,className:s,children:c,...u}){const{resolvedTheme:d}=xw(),m=d==="dark"?"#000000":"#ffffff",h=d==="dark"?"rgba(255, 255, 255, 1)":"rgba(0, 0, 0, 1)",g=t||m,v=i||h;return f.jsxs("button",{style:{"--spread":"90deg","--shimmer-color":g,"--radius":r,"--speed":a,"--cut":n,"--bg":v},className:De("group relative z-0 flex cursor-pointer items-center justify-center overflow-hidden [border-radius:var(--radius)] border px-6 py-3 whitespace-nowrap [background:var(--bg)]","transform-gpu transition-transform duration-300 ease-in-out active:translate-y-px",d==="dark"?"border-black/10 text-black":"border-white/10 text-white",s),ref:e,...u,children:[f.jsx("div",{className:De("-z-30 blur-[2px]","[container-type:size] absolute inset-0 overflow-visible"),children:f.jsx("div",{className:"animate-shimmer-slide absolute inset-0 [aspect-ratio:1] h-[100cqh] [border-radius:0] [mask:none]",children:f.jsx("div",{className:"animate-spin-around absolute -inset-full w-auto [translate:0_0] rotate-0 [background:conic-gradient(from_calc(270deg-(var(--spread)*0.5)),transparent_0,var(--shimmer-color)_var(--spread),transparent_var(--spread))]"})})}),c,f.jsx("div",{className:De("absolute inset-0 size-full","rounded-2xl px-4 py-1.5 text-sm font-medium","transform-gpu transition-all duration-300 ease-in-out",d==="dark"?"shadow-[inset_0_-8px_10px_#0000001f] group-hover:shadow-[inset_0_-6px_10px_#0000003f] group-active:shadow-[inset_0_-10px_10px_#0000003f]":"shadow-[inset_0_-8px_10px_#ffffff1f] group-hover:shadow-[inset_0_-6px_10px_#ffffff3f] group-active:shadow-[inset_0_-10px_10px_#ffffff3f]")}),f.jsx("div",{className:De("absolute [inset:var(--cut)] -z-20 [border-radius:var(--radius)] [background:var(--bg)]")})]})}eq.displayName="ShimmerButton";function tF({status:e}){const t=i=>{switch(i){case"ready":return{color:"bg-emerald-500",ringColor:"ring-emerald-500",tooltip:"Connected"};case"failed":return{color:"bg-red-500",ringColor:"ring-red-500",tooltip:"Failed"};default:return{color:"bg-yellow-500",ringColor:"ring-yellow-500",tooltip:i}}},{color:n,ringColor:a,tooltip:r}=t(e);return f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:`absolute w-2 h-2 rounded-full ${a} animate-ping`}),f.jsx("div",{className:`relative w-2 h-2 rounded-full ${n}`})]})}),f.jsx(Rt,{children:f.jsx("p",{children:r})})]})}function nF({connections:e,selectedServer:t,onServerSelect:n,onOpenConnectionOptions:a,mobileMode:r=!1}){const i=Rd(),s=c=>{const u=e.find(d=>d.id===c);if(!u||u.state!=="ready"){Xt.error("Server is not connected and cannot be inspected");return}n(c)};return r?f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("div",{className:"relative",children:f.jsxs(V_,{children:[f.jsx(G_,{asChild:!0,children:f.jsxs($e,{variant:"ghost",className:"h-11 px-2 bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200 flex items-center gap-1.5",children:[t?f.jsx(Ol,{serverUrl:t.url,serverName:t.name,size:"md"}):f.jsx(Rhe,{className:"h-5 w-5"}),f.jsx(ac,{className:"h-4 w-4"})]})}),f.jsxs(Cv,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[f.jsx(W_,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>i("/"),children:"MCP Servers"}),f.jsx(rp,{}),e.length===0?f.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center",children:"No servers connected. Go to the dashboard to add one."}):e.map(c=>f.jsxs(Ro,{onClick:()=>s(c.id),className:"flex items-center gap-3",children:[f.jsx(Ol,{serverUrl:c.url,serverName:c.name,size:"sm"}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx("div",{className:"font-medium",children:c.name}),f.jsx(tF,{status:c.state})]}),f.jsx($e,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:u=>{u.stopPropagation(),a(c.id)},children:f.jsx(Eu,{className:"h-3 w-3"})})]},c.id)),f.jsx(rp,{}),f.jsx(Ro,{onClick:()=>i("/"),children:f.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})})}):f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("div",{className:"relative",children:f.jsxs(V_,{children:[f.jsx(G_,{asChild:!0,children:f.jsxs(eq,{className:De("min-w-0 sm:min-w-[200px] p-0 px-1 text-sm h-11 justify-start bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200",!t&&"pl-4",t&&"pr-10"),children:[t&&f.jsx(Ol,{serverUrl:t.url,serverName:t.name,size:"md",className:"mr-2"}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx("span",{className:"truncate",children:t?t.name:"Select server to inspect"}),t&&f.jsx("div",{className:"flex items-center gap-2",children:t.error&&t.state!=="ready"?f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx("button",{onClick:c=>{c.stopPropagation()},className:"w-2 h-2 rounded-full bg-rose-500 animate-status-pulse-red hover:bg-rose-600 transition-colors",title:"Click to copy error message","aria-label":"Copy error message to clipboard"})}),f.jsx(Rt,{children:f.jsx("p",{className:"max-w-xs",children:t.error})})]}):f.jsx("div",{className:`w-2 h-2 rounded-full ${t.state==="ready"?"bg-emerald-600 animate-status-pulse":t.state==="failed"?"bg-rose-600 animate-status-pulse-red":"bg-yellow-500 animate-status-pulse-yellow"}`})})]})]})}),t&&f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx("button",{type:"button",onClick:()=>{a(t.id)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1.5 hover:bg-white/10 dark:hover:bg-black/10 rounded-full transition-colors text-white dark:text-black","aria-label":"Edit connection settings",children:f.jsx(Eu,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Edit connection settings"})})]}),f.jsxs(Cv,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[f.jsx(W_,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>i("/"),children:"MCP Servers"}),f.jsx(rp,{}),e.length===0?f.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center",children:"No servers connected. Go to the dashboard to add one."}):e.map(c=>f.jsxs(Ro,{onClick:()=>s(c.id),className:"flex items-center gap-3",children:[f.jsx(Ol,{serverUrl:c.url,serverName:c.name,size:"sm"}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx("div",{className:"font-medium",children:c.name}),f.jsx(tF,{status:c.state})]}),f.jsx($e,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:u=>{u.stopPropagation(),a(c.id)},children:f.jsx(Eu,{className:"h-3 w-3"})})]},c.id)),f.jsx(rp,{}),f.jsx(Ro,{onClick:()=>i("/"),children:f.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})})})}const rF=[{id:"tools",label:"Tools",icon:Wl},{id:"prompts",label:"Prompts",icon:Hp},{id:"resources",label:"Resources",icon:ehe},{id:"sampling",label:"Sampling",icon:PG},{id:"elicitation",label:"Elicitation",icon:BG},{id:"notifications",label:"Notifications",icon:qN},{id:"chat",label:"Chat",icon:fhe}];function aF(e,t){return e==="tools"?t.tools.length:e==="prompts"?t.prompts.length:e==="resources"?t.resources.length:e==="sampling"?t.pendingSamplingRequests?.length||0:e==="elicitation"?t.pendingElicitationRequests?.length||0:e==="notifications"?t.unreadNotificationCount:0}function FTe({collapsed:e,onToggle:t}){return f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx("button",{onClick:t,className:De("shrink-0 p-1.5 rounded-md transition-all duration-500 ease-in-out cursor-pointer","text-muted-foreground hover:text-foreground","hover:bg-zinc-100 dark:hover:bg-zinc-800","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"),"aria-label":e?"Expand tabs":"Collapse tabs",type:"button",children:e?f.jsx(LG,{className:"h-4 w-4 transition-transform duration-500 ease-in-out"}):f.jsx(qy,{className:"h-4 w-4 transition-transform duration-500 ease-in-out"})})}),f.jsx(Rt,{children:f.jsx("p",{children:e?"Expand tabs":"Collapse tabs"})})]})}function BTe({connections:e,selectedServer:t,activeTab:n,onServerSelect:a,onTabChange:r,onCommandPaletteOpen:i,onOpenConnectionOptions:s}){const{tunnelUrl:c}=ic(),u=t&&c,[d,m]=w.useState(!1),[h,g]=w.useState(!1),v=async()=>{if(c)try{await navigator.clipboard.writeText(`${c}/mcp`),m(!0),Xt.success("Tunnel URL copied to clipboard"),setTimeout(()=>m(!1),2e3)}catch{Xt.error("Failed to copy URL")}};return f.jsxs("header",{className:"w-full mx-auto",children:[f.jsxs("div",{className:"flex lg:hidden flex-col gap-3",children:[f.jsxs("div",{className:"flex items-center justify-between w-full",children:[f.jsx("div",{className:"flex-1 flex justify-start",children:f.jsx(nF,{connections:e,selectedServer:t,onServerSelect:a,onOpenConnectionOptions:s,mobileMode:!0})}),f.jsx("div",{className:"flex-shrink-0 flex justify-center",children:f.jsx("div",{className:"scale-150",children:f.jsx(Q2,{state:"collapsed"})})}),f.jsxs("div",{className:"flex-1 flex justify-end items-center gap-2",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",asChild:!0,children:f.jsx("a",{href:"https://github.com/mcp-use/mcp-use",target:"_blank",rel:"noopener noreferrer",className:"p-2","aria-label":"GitHub",children:f.jsx(X2,{className:"h-4 w-4"})})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Give us a star ⭐"})})]}),f.jsx(J2,{className:"p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors cursor-pointer"})]})]}),t&&f.jsx("div",{className:"w-full",children:f.jsx(rk,{value:n,onValueChange:x=>r(x),collapsed:h,onCollapsedChange:g,children:f.jsx(ak,{className:"w-full justify-center",children:rF.map(x=>{const S=aF(x.id,t);return f.jsxs(ik,{value:x.id,icon:x.icon,className:De("[&>svg]:mr-0 flex-1 flex-row gap-2 relative",h&&"pl-2"),children:[S>0&&f.jsx("span",{className:De(n===x.id?"dark:bg-black":"dark:bg-zinc-700","bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-[10px] px-1.5 py-0.5 rounded-full font-medium"),children:S}),f.jsx("span",{className:"sr-only",children:x.label})]},x.id)})})})})]}),f.jsxs("div",{className:"hidden lg:flex items-center justify-between gap-3",children:[f.jsxs("div",{className:"flex items-center flex-wrap gap-2 md:space-x-6 space-x-2",children:[f.jsx(nF,{connections:e,selectedServer:t,onServerSelect:a,onOpenConnectionOptions:s}),t&&f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(rk,{value:n,onValueChange:x=>r(x),collapsed:h,onCollapsedChange:g,children:f.jsx(ak,{className:"overflow-x-auto",collapsible:!0,children:rF.map(x=>{const S=aF(x.id,t),y=S>0?`${x.label} (${S})`:x.label;return f.jsx(ik,{value:x.id,icon:x.icon,className:De("[&>svg]:mr-0 lg:[&>svg]:mr-2 relative",h&&"pl-4"),title:y,children:f.jsxs("div",{className:"items-center gap-2 hidden lg:flex",children:[x.label,S>0&&f.jsx("span",{className:De(n===x.id?" dark:bg-black ":"dark:bg-zinc-700","bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-xs px-2 py-0.5 rounded-full font-medium"),children:S})]})})})})}),f.jsx(FTe,{collapsed:h,onToggle:()=>g(!h)})]}),u&&f.jsxs(KK,{children:[f.jsx(ZK,{asChild:!0,children:f.jsxs("button",{className:"flex items-center gap-2 px-3 py-1.5 bg-gradient-to-r from-purple-500/10 to-pink-500/10 dark:from-purple-500/20 dark:to-pink-500/20 border border-purple-500/30 dark:border-purple-500/40 rounded-full hover:from-purple-500/20 hover:to-pink-500/20 dark:hover:from-purple-500/30 dark:hover:to-pink-500/30 transition-colors cursor-pointer",children:[f.jsx(Vp,{className:"size-4 text-purple-600 dark:text-purple-400 animate-pulse"}),f.jsx("span",{className:"text-xs font-medium text-purple-700 dark:text-purple-300 hidden lg:inline",children:"Tunnel"})]})}),f.jsx(WC,{className:"w-[calc(100vw-2rem)] sm:w-96",align:"start",children:f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsxs("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:[f.jsx(Vp,{className:"size-4 text-purple-600 dark:text-purple-400"}),"Tunnel URL"]}),f.jsxs("div",{className:"flex items-center gap-2 p-2 py-0 bg-muted rounded-full",children:[f.jsxs("code",{className:"flex-1 text-[10px] font-mono",children:[c,"/mcp"]}),f.jsx($e,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:v,children:d?f.jsx(ra,{className:"size-3.5 text-green-600"}):f.jsx($r,{className:"size-3.5"})})]})]}),f.jsxs("div",{children:[f.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Use in ChatGPT"}),f.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[f.jsxs("li",{className:"flex gap-2",children:[f.jsx("span",{className:"font-semibold text-foreground",children:"1."}),f.jsxs("span",{children:["Enable"," ",f.jsx("span",{className:"font-medium text-foreground",children:"dev mode"})," ","from settings"]})]}),f.jsxs("li",{className:"flex gap-2",children:[f.jsx("span",{className:"font-semibold text-foreground",children:"2."}),f.jsxs("span",{children:["In"," ",f.jsx("span",{className:"font-medium text-foreground",children:"App & Connectors"})," ","click on"," ",f.jsx("span",{className:"font-medium text-foreground",children:"create"})]})]}),f.jsxs("li",{className:"flex gap-2",children:[f.jsx("span",{className:"font-semibold text-foreground",children:"3."}),f.jsx("span",{children:"Use the tunnel URL in the input"})]})]})]})]})})]})]}),f.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-shrink-0",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{children:f.jsx(J2,{className:"p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors cursor-pointer"})}),f.jsx(Rt,{children:f.jsx("p",{children:"Toggle theme"})})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsxs($e,{variant:"ghost",className:"hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full px-1 -mx-3 flex gap-1",onClick:i,children:[f.jsx(Mme,{className:"size-4"}),f.jsx("span",{className:"text-base font-mono hidden sm:inline",children:"K"})]})}),f.jsx(Rt,{children:f.jsx("p",{children:"Command Palette"})})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",asChild:!0,children:f.jsxs("a",{href:"https://github.com/mcp-use/mcp-use",className:"flex items-center gap-2",target:"_blank",rel:"noopener noreferrer",children:[f.jsx(X2,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Github"})]})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Give us a star ⭐"})})]}),f.jsx(Q2,{state:"expanded"})]})]})]})}function HTe({children:e}){const t=Rd(),n=Vo(),{connections:a,addConnection:r,removeConnection:i,updateConnectionConfig:s,configLoaded:c}=YN(),{selectedServerId:u,setSelectedServerId:d,activeTab:m,setActiveTab:h,navigateToItem:g,setTunnelUrl:v}=ic(),[x,S]=w.useState(!1),[y,E]=w.useState(null),_=rSe();w.useEffect(()=>{const Z=new URLSearchParams(n.search).get("tunnelUrl");v(Z)},[n.search,v]),w.useEffect(()=>{const H=re=>{const j=re.detail.requestId;u&&g(u,"sampling",j)},Z=re=>{const j=re.detail.requestId;u&&g(u,"elicitation",j)},G=re=>{const j=re.detail.toolName;u&&j?g(u,"tools",j):u&&h("tools")};return window.addEventListener("navigate-to-sampling",H),window.addEventListener("navigate-to-elicitation",Z),window.addEventListener("navigate-to-tool-result",G),()=>{window.removeEventListener("navigate-to-sampling",H),window.removeEventListener("navigate-to-elicitation",Z),window.removeEventListener("navigate-to-tool-result",G)}},[u,h,g]);const k=w.useRef(null),C=w.useRef(null),R=w.useRef(null),{isAutoConnecting:I}=nSe({connections:a,addConnection:r,removeConnection:i,configLoaded:c}),A=w.useCallback(H=>{vr.getInstance().capture(new eme({trigger:H})).catch(()=>{}),S(!0)},[]),O=H=>{const Z=a.find(j=>j.id===H);if(!Z||Z.state!=="ready"){Xt.error("Server is not connected and cannot be inspected");return}d(H);const re=new URLSearchParams(n.search).get("tunnelUrl"),ne=re?`/?server=${encodeURIComponent(H)}&tunnelUrl=${encodeURIComponent(re)}`:`/?server=${encodeURIComponent(H)}`;t(ne)},M=w.useCallback(H=>{E(H)},[]),P=w.useCallback(H=>{y&&(H.url!==y?(i(y),r(H.url,H.name,H.proxyConfig,H.transportType)):s(y,{name:H.name,proxyConfig:H.proxyConfig,transportType:H.transportType}),E(null),Xt.success("Connection settings updated"))},[y,i,r,s]),B=(H,Z,G)=>{if(console.warn("[Layout] handleCommandPaletteNavigate called:",{tab:H,itemName:Z,serverId:G}),G){const re=a.find(z=>z.id===G);if(console.warn("[Layout] Server lookup:",{serverId:G,serverFound:!!re,serverState:re?.state}),!re||re.state!=="ready"){console.warn("[Layout] Server not ready, showing error"),Xt.error("Server is not connected and cannot be inspected");return}console.warn("[Layout] Calling navigateToItem:",{serverId:G,tab:H,itemName:Z}),g(G,H,Z);const j=new URLSearchParams(n.search).get("tunnelUrl"),V=j?`/?server=${encodeURIComponent(G)}&tunnelUrl=${encodeURIComponent(j)}`:`/?server=${encodeURIComponent(G)}`;console.warn("[Layout] Navigating to:",V),t(V)}else console.warn("[Layout] No serverId, just updating tab to:",H),h(H)},K=a.find(H=>H.id===u),ee=K?K.tools.map(H=>({...H,_serverId:K.id})):a.flatMap(H=>H.state==="ready"?H.tools.map(Z=>({...Z,_serverId:H.id,_serverName:H.name})):[]),te=K?K.prompts.map(H=>({...H,_serverId:K.id})):a.flatMap(H=>H.state==="ready"?H.prompts.map(Z=>({...Z,_serverId:H.id,_serverName:H.name})):[]),ae=K?K.resources.map(H=>({...H,_serverId:K.id})):a.flatMap(H=>H.state==="ready"?H.resources.map(Z=>({...Z,_serverId:H.id,_serverName:H.name})):[]);return w.useEffect(()=>{const Z=new URLSearchParams(n.search).get("server"),G=Z?decodeURIComponent(Z):null;G!==u&&d(G)},[n.search,u,d]),w.useEffect(()=>{const Z=new URLSearchParams(n.search).get("server");if(!Z)return;const G=decodeURIComponent(Z),re=a.find(ne=>ne.id===G);if(!re){const ne=setTimeout(()=>t("/"),3e3);return()=>clearTimeout(ne)}if(re.state==="failed"){const ne=setTimeout(()=>t("/"),2e3);return()=>clearTimeout(ne)}},[n.search,t,a]),SK({onCommandPalette:()=>A("keyboard"),onToolsTab:()=>{K&&h("tools")},onPromptsTab:()=>{K&&h("prompts")},onResourcesTab:()=>{K&&h("resources")},onChatTab:()=>{K&&h("chat")},onHome:()=>{t("/")},onFocusSearch:()=>{m==="tools"&&k.current?k.current.focusSearch():m==="prompts"&&C.current?C.current.focusSearch():m==="resources"&&R.current&&R.current.focusSearch()},onBlurSearch:()=>{m==="tools"&&k.current?k.current.blurSearch():m==="prompts"&&C.current?C.current.blurSearch():m==="resources"&&R.current&&R.current.blurSearch()}}),I?f.jsx("div",{className:"h-screen bg-white dark:bg-zinc-900 flex items-center justify-center",children:f.jsxs("div",{className:"flex flex-col items-center gap-4",children:[f.jsx(ki,{className:"h-8 w-8 text-zinc-600 dark:text-zinc-400"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Connecting to MCP server..."})]})}):f.jsx(ZN,{children:f.jsxs("div",{className:"h-screen bg-[#f3f3f3] dark:bg-black flex flex-col px-2 py-2 sm:px-4 sm:py-4 gap-2 sm:gap-4",children:[f.jsx(BTe,{connections:a,selectedServer:K,activeTab:m,onServerSelect:O,onTabChange:h,onCommandPaletteOpen:()=>A("button"),onOpenConnectionOptions:M}),f.jsx("main",{className:"flex-1 w-full mx-auto bg-white dark:bg-black rounded-2xl border border-zinc-200 dark:border-zinc-700 p-0 overflow-auto",children:f.jsx(MTe,{selectedServer:K,activeTab:m,toolsSearchRef:k,promptsSearchRef:C,resourcesSearchRef:R,children:e})}),f.jsx(ASe,{isOpen:x,onOpenChange:S,tools:ee,prompts:te,resources:ae,savedRequests:_,connections:a,onNavigate:B,onServerSelect:O}),f.jsx(M7,{connection:y&&a.find(H=>H.id===y)||null,open:y!==null,onOpenChange:H=>{H||E(null)},onConnect:P})]})})}function VTe(){const[e,t]=w.useState("processing"),[n,a]=w.useState("");return w.useEffect(()=>{console.log("[OAuthCallback] Component mounted, handling authorization..."),console.log("[OAuthCallback] Current URL:",window.location.href),vN().then(()=>{console.log("[OAuthCallback] Authorization successful"),t("success")}).catch(r=>{console.error("[OAuthCallback] Authorization failed:",r),t("error"),a(r instanceof Error?r.message:String(r))})},[]),e==="processing"?f.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:f.jsxs("div",{className:"flex flex-col items-center gap-4",children:[f.jsx(zs,{className:"h-8 w-8 animate-spin text-zinc-600 dark:text-zinc-400"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Completing authentication..."})]})}):e==="error"?f.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:f.jsxs("div",{className:"max-w-md p-6",children:[f.jsx("h1",{className:"text-xl font-semibold text-red-600 dark:text-red-400 mb-2",children:"Authentication Error"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400 mb-4",children:n}),f.jsx("p",{className:"text-xs text-zinc-500 dark:text-zinc-500",children:"You can close this window and try again."})]})}):f.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:f.jsxs("div",{className:"max-w-md p-6",children:[f.jsx("h1",{className:"text-xl font-semibold text-green-600 dark:text-green-400 mb-2",children:"Authentication Successful!"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Redirecting you back..."})]})})}var GTe=(e,t,n,a,r,i,s,c)=>{let u=document.documentElement,d=["light","dark"];function m(v){(Array.isArray(e)?e:[e]).forEach(x=>{let S=x==="class",y=S&&i?r.map(E=>i[E]||E):r;S?(u.classList.remove(...y),u.classList.add(i&&i[v]?i[v]:v)):u.setAttribute(x,v)}),h(v)}function h(v){c&&d.includes(v)&&(u.style.colorScheme=v)}function g(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(a)m(a);else try{let v=localStorage.getItem(t)||n,x=s&&v==="system"?g():v;m(x)}catch{}},WTe=w.createContext(void 0),KTe={setTheme:e=>{},themes:[]},ZTe=()=>{var e;return(e=w.useContext(WTe))!=null?e:KTe};w.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:a,enableColorScheme:r,defaultTheme:i,value:s,themes:c,nonce:u,scriptProps:d})=>{let m=JSON.stringify([n,t,i,e,c,s,a,r]).slice(1,-1);return w.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?u:"",dangerouslySetInnerHTML:{__html:`(${GTe.toString()})(${m})`}})});function YTe({...e}){const{theme:t="system"}=ZTe();return f.jsx(HG,{theme:t,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...e})}function qTe(){return f.jsx(vEe,{children:f.jsx(sme,{children:f.jsxs(tSe,{children:[f.jsx(ile,{basename:"/inspector",children:f.jsxs(Lse,{children:[f.jsx(j_,{path:"/oauth/callback",element:f.jsx(VTe,{})}),f.jsx(j_,{path:"/",element:f.jsx(HTe,{children:f.jsx(eSe,{})})})]})}),f.jsx(YTe,{position:"top-center"})]})})})}const iF=new URLSearchParams(window.location.search);if(iF.has("code")||iF.has("error"))try{vN()}catch(e){console.error("[inspector] OAuth callback error:",e)}const oF=document.getElementById("root");oF?Voe.createRoot(oF).render(f.jsx(qTe,{})):console.error("[inspector] Root element not found");export{kB as $,AF as A,DF as B,L6 as C,EB as D,_oe as E,Jb as F,Ce as G,Noe as H,Eoe as I,Cb as J,ZP as K,ks as L,xoe as M,koe as N,Ll as O,ov as P,Ot as Q,ue as R,u6 as S,zi as T,vF as U,RJ as V,Ob as W,uF as X,Coe as Y,$ne as Z,ze as _,Jn as a,bJ as a0,vN as a1,IJ as a2,kd as b,ny as c,od as d,LT as e,Cne as f,JTe as g,hne as h,wy as i,sd as j,F5 as k,Nb as l,a_ as m,iv as n,Jf as o,FF as p,UT as q,w as r,Op as s,lu as t,id as u,vi as v,i_ as w,ni as x,M6 as y,HB as z};
1676
+ `),Ue.document.close())}},[x]),Pr=w.useCallback(()=>{W?(oe.current&&oe.current.expand(),Ne.current&&Ne.current.expand(),X(!1)):(oe.current&&oe.current.collapse(),Ne.current&&Ne.current.collapse(),X(!0))},[W]),St=w.useCallback(()=>{s&&(ae(""),ee(!0))},[s]),Be=w.useCallback(()=>{if(!s)return;const Se={id:`${Date.now()}-${Math.random()}`,name:te.trim()||`${s.name} - ${new Date().toLocaleString()}`,toolName:s.name,args:g,savedAt:Date.now(),serverId:s._serverId,serverName:s._serverName};Fe([...P,Se]),vr.getInstance().capture(new tme({toolName:s.name,serverId:r})).catch(()=>{}),ee(!1),ae("")},[s,te,g,P,Fe,r]),Le=w.useCallback(Se=>{Fe(P.filter(je=>je.id!==Se)),u?.id===Se&&d(null)},[P,Fe,u]);return z?f.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[L!=="list"&&f.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[f.jsx($e,{variant:"ghost",size:"sm",onClick:()=>{L==="response"?F("detail"):(c(null),F("list"))},className:"p-0 h-8 w-8",children:f.jsx(qy,{className:"h-4 w-4"})}),f.jsxs("div",{className:"flex items-center text-sm font-medium",children:[f.jsx("button",{onClick:()=>{c(null),F("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Tools"}),L==="detail"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("button",{onClick:()=>{F("response")},className:L==="detail"?"text-foreground hover:underline":L==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),L==="response"&&f.jsxs(f.Fragment,{children:[f.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),f.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),f.jsx("div",{className:"flex-1 relative overflow-hidden",children:f.jsxs(rw,{initial:!1,mode:"popLayout",children:[L==="list"&&f.jsxs(ya.div,{initial:{x:"-100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 flex flex-col bg-background z-0",children:[f.jsx(Y2,{activeTab:O,isSearchExpanded:G,searchQuery:I,filteredToolsCount:pe.length,savedRequestsCount:P.length,onSearchExpand:()=>re(!0),onSearchChange:A,onSearchBlur:xe,onTabSwitch:()=>M(O==="tools"?"saved":"tools"),searchInputRef:V}),O==="tools"?f.jsx(Z2,{tools:pe,selectedTool:s,onToolSelect:Oe,focusedIndex:ne}):f.jsx(B2,{savedRequests:P,selectedRequest:u,onLoadRequest:He,onDeleteRequest:Le,focusedIndex:ne})]},"list"),L==="detail"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"-100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-10",children:f.jsx(G2,{selectedTool:s,toolArgs:g,isExecuting:y,isConnected:i,onArgChange:at,onExecute:nt,onSave:St})},"detail"),L==="response"&&f.jsx(ya.div,{initial:{x:"100%"},animate:{x:0},exit:{x:"100%"},transition:{type:"spring",stiffness:300,damping:30},className:"absolute inset-0 bg-background z-20",children:f.jsx(K2,{results:pt,copiedResult:_,previewMode:H,serverId:r,readResource:a,onCopy:ft,onDelete:Et,onFullscreen:mn,onTogglePreview:()=>Z(!H)})},"response")]})}),f.jsx(H2,{isOpen:K,requestName:te,defaultPlaceholder:`${s?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:ae,onSave:Be,onCancel:()=>ee(!1)})]}):f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{ref:oe,defaultSize:33,collapsible:!0,className:"flex flex-col h-full relative",children:f.jsxs(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[f.jsx(Rn,{defaultSize:75,minSize:30,children:f.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[f.jsx(Y2,{activeTab:O,isSearchExpanded:G,searchQuery:I,filteredToolsCount:pe.length,savedRequestsCount:P.length,onSearchExpand:()=>re(!0),onSearchChange:A,onSearchBlur:xe,onTabSwitch:()=>M(O==="tools"?"saved":"tools"),searchInputRef:V}),O==="tools"?f.jsx(Z2,{tools:pe,selectedTool:s,onToolSelect:Oe,focusedIndex:ne}):f.jsx(B2,{savedRequests:P,selectedRequest:u,onLoadRequest:He,onDeleteRequest:Le,focusedIndex:ne})]})}),f.jsx(Si,{withHandle:!0}),f.jsxs(Rn,{ref:_e,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>{q(!0)},onExpand:()=>{q(!1)},className:"flex flex-col border-t dark:border-zinc-700",children:[f.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:Se=>{Se.preventDefault(),Se.stopPropagation(),J?(_e.current?.resize(25),q(!1)):(_e.current?.resize(5),q(!0))},children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),ie>0&&f.jsx(wr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:ie}),ie>0&&!J&&f.jsx($e,{variant:"ghost",size:"sm",onClick:Se=>{Se.preventDefault(),Se.stopPropagation(),ke.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:f.jsx(Fs,{className:"h-3.5 w-3.5"})})]}),f.jsx(ac,{className:`h-4 w-4 text-muted-foreground transition-transform ${J?"":"rotate-180"}`})]}),f.jsx("div",{className:`flex-1 overflow-hidden min-h-0 ${J?"hidden":""}`,children:f.jsx(ED,{serverIds:[r],onCountChange:ce,onClearRef:ke})})]})]})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{defaultSize:67,children:f.jsxs(na,{direction:"vertical",children:[f.jsx(Rn,{ref:Ne,defaultSize:40,collapsible:!0,children:f.jsx(G2,{selectedTool:s,toolArgs:g,isExecuting:y,isConnected:i,onArgChange:at,onExecute:nt,onSave:St,onCancel:()=>{C&&C.abort()}})}),f.jsx(Si,{withHandle:!0}),f.jsx(Rn,{ref:Ve,defaultSize:60,children:f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(K2,{results:pt,copiedResult:_,previewMode:H,serverId:r,readResource:a,onCopy:ft,onDelete:Et,onFullscreen:mn,onTogglePreview:()=>Z(!H),onMaximize:Pr,isMaximized:W})})})]})}),f.jsx(H2,{isOpen:K,requestName:te,defaultPlaceholder:`${s?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:ae,onSave:Be,onCancel:()=>ee(!1)})]})}qY.displayName="ToolsTab";function CTe({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:a,onSearchExpand:r,onSearchChange:i,onSearchBlur:s,onRejectAll:c,searchInputRef:u}){return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:u,placeholder:"Search requests...",value:t,onChange:d=>i(d.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Sampling"}),f.jsx(wr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,disabled:a===0,className:"h-8 w-8 p-0",children:f.jsx(Fs,{className:"h-4 w-4"})})}),f.jsx(Rt,{side:"bottom",children:"Reject all"})]})})]})}function RTe({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:a,formatRelativeTime:r,listRef:i}){return e.length===0?f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No sampling requests"})}):f.jsx("div",{ref:i,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((s,c)=>{const u=s.request.params?.messages?.length||0,d=s.request.params?.maxTokens;return f.jsx(Qs,{id:`sampling-request-${s.id}`,isSelected:t?.id===s.id,isFocused:a===c,title:f.jsxs("span",{className:"flex items-center gap-3",children:[s.serverName,f.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const m=r(s.timestamp),h=[];u>0&&h.push(`${u} message${u>1?"s":""}`),d&&h.push(`max ${d} tokens`);const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(s)},s.id)})})}function ATe({llmConfig:e}){const t=w.useRef(null);return{generateResponse:w.useCallback(async({request:a})=>{if(!e)throw new Error("LLM config is not available");const r=a.params||{},i=r.maxTokens,s=r.temperature;r.modelPreferences;const c=r.messages||[];if(console.log("[useSamplingLLM] Request structure:",{hasParams:!!r,messagesCount:c.length,messages:c,params:r}),c.length===0)throw new Error("No messages found in sampling request");const u=[],{HumanMessage:d,AIMessage:m}=await Jn(async()=>{const{HumanMessage:x,AIMessage:S}=await import("./index-kPmN3fDk.js").then(y=>y.bI);return{HumanMessage:x,AIMessage:S}},[]);for(const x of c){if(!x||!x.role){console.warn("Skipping invalid message:",x);continue}const S=Array.isArray(x.content)?x.content[0]:x.content;if(!S){console.warn("Skipping message with no content:",x);continue}S.type==="text"&&S.text?x.role==="user"?u.push(new d(S.text)):x.role==="assistant"&&u.push(new m(S.text)):console.warn("Skipping message with unsupported content type:",S)}if(u.length===0)throw new Error("No valid messages could be converted. Please ensure messages have 'text' content type.");if(!t.current||t.current.provider!==e.provider||t.current.model!==e.model||t.current.apiKey!==e.apiKey){let x;const S={model:e.model,apiKey:e.apiKey};if(i!==void 0&&(S.maxTokens=i),s!==void 0?S.temperature=s:e.temperature!==void 0&&(S.temperature=e.temperature),e.provider==="openai"){const{ChatOpenAI:y}=await Jn(async()=>{const{ChatOpenAI:E}=await import("./index-BUXkns-K.js");return{ChatOpenAI:E}},__vite__mapDeps([6,7,8,2,9,10,11]));x=new y(S)}else if(e.provider==="anthropic"){const{ChatAnthropic:y}=await Jn(async()=>{const{ChatAnthropic:E}=await import("./index-9nm0CCqb.js");return{ChatAnthropic:E}},__vite__mapDeps([12,8,7,2,11]));x=new y(S)}else if(e.provider==="google"){const{ChatGoogleGenerativeAI:y}=await Jn(async()=>{const{ChatGoogleGenerativeAI:E}=await import("./index-CrVavwoh.js");return{ChatGoogleGenerativeAI:E}},__vite__mapDeps([13,8,7,2,10]));x=new y(S)}else throw new Error(`Unsupported LLM provider: ${e.provider}`);t.current={instance:x,provider:e.provider,model:e.model,apiKey:e.apiKey}}const h=await t.current.instance.invoke(u);return{role:"assistant",content:{type:"text",text:h.content||h.text||""},model:e.model,stopReason:"endTurn"}},[e]),isAvailable:e!==null}}function ITe({request:e,onApprove:t,onReject:n,onClose:a,previewMode:r,onTogglePreview:i,isCopied:s,onCopy:c,onDownload:u,onFullscreen:d,llmConfig:m}){const[h,g]=w.useState("manual"),[v,x]=w.useState("stub-model"),[S,y]=w.useState("endTurn"),[E,_]=w.useState("assistant"),[k,C]=w.useState("text"),[R,I]=w.useState("positive"),[A,O]=w.useState(""),[M,P]=w.useState("image/png"),[B,K]=w.useState(!1),[ee,te]=w.useState(null),{generateResponse:ae,isAvailable:H}=ATe({llmConfig:m});w.useEffect(()=>{e&&(x("stub-model"),y("endTurn"),_("assistant"),C("text"),I("positive"),O(""),P("image/png"),te(null))},[e?.id]);const Z=async()=>{if(!(!e||!H)){K(!0),te(null);try{const j=await ae({request:e.request});x(j.model||m?.model||"stub-model"),y(j.stopReason||"endTurn"),_(j.role||"assistant");const V=Array.isArray(j.content)?j.content[0]:j.content;V.type==="text"?(C("text"),I(V.text||"")):V.type==="image"&&(C("image"),O(V.data||""),P(V.mimeType||"image/png"))}catch(j){const V=j instanceof Error?j.message:"Failed to generate response";te(V),Xt.error("LLM Generation Failed",{description:V})}finally{K(!1)}}},G=w.useMemo(()=>{const j={model:v,stopReason:S,role:E,content:{type:k}};return k==="text"?j.content.text=R:k==="image"&&(j.content.data=A,j.content.mimeType=M),j},[v,S,E,k,R,A,M]),re=()=>{if(!e)return;const j=cN.safeParse(G);if(!j.success){Xt.error("Invalid response",{description:`Validation failed: ${j.error.message}`});return}t(e.id,j.data),a(),Jn(()=>Promise.resolve().then(()=>kd),void 0).then(V=>{const z=Xt(V.createElement("div",{className:"space-y-3"},V.createElement("div",null,V.createElement("strong",null,"Sampling Response Sent"),V.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),V.createElement("div",{className:"flex gap-2"},V.createElement("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>{const $=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:e.toolName}});window.dispatchEvent($),Xt.dismiss(z)}},"View Tool Result"))),{duration:5e3})})},ne=()=>{e&&(n(e.id,"User rejected sampling request"),a())};return e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),f.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,className:"h-8 w-8 p-0",children:s?f.jsx(ra,{className:"h-4 w-4 text-green-600"}):f.jsx($r,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Copy request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:f.jsx(Lm,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Download request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:d,className:"h-8 w-8 p-0",children:f.jsx(QN,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Fullscreen"})]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:f.jsx(Ji,{className:"h-4 w-4"})})]})]}),f.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Request"}),f.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:f.jsx(Xn,{data:e.request})})]}),f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{className:"flex items-center justify-between",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Response"}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(Kt,{htmlFor:`responseMode-${e.id}`,className:"text-xs text-gray-500 dark:text-gray-400",children:"Mode:"}),f.jsxs(Io,{value:h,onValueChange:j=>g(j),children:[f.jsx(Do,{id:`responseMode-${e.id}`,className:"w-32 h-8 text-xs",children:f.jsx(Oo,{})}),f.jsxs(jo,{children:[f.jsx(Ar,{value:"manual",children:"Manual"}),f.jsx(Ar,{value:"llm",children:"LLM"})]})]})]})]}),h==="llm"&&f.jsxs("div",{className:"space-y-2 p-3 bg-muted rounded-lg",children:[H?f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx($e,{onClick:Z,disabled:B,size:"sm",className:"flex items-center gap-2",children:B?f.jsxs(f.Fragment,{children:[f.jsx(zs,{className:"h-4 w-4 animate-spin"}),"Generating..."]}):f.jsxs(f.Fragment,{children:[f.jsx(jhe,{className:"h-4 w-4"}),"Generate with LLM"]})}),f.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["Using ",m?.provider," (",m?.model,")"]})]}):f.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:"LLM not configured. Please configure LLM in the Chat tab."}),ee&&f.jsx("div",{className:"text-xs text-red-600 dark:text-red-400",children:ee})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`model-${e.id}`,children:"Model"}),f.jsx(En,{id:`model-${e.id}`,value:v,onChange:j=>x(j.target.value),placeholder:"stub-model",disabled:h==="llm"&&B})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`stopReason-${e.id}`,children:"Stop Reason"}),f.jsx(En,{id:`stopReason-${e.id}`,value:S,onChange:j=>y(j.target.value),placeholder:"endTurn",disabled:h==="llm"&&B})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`role-${e.id}`,children:"Role"}),f.jsxs(Io,{value:E,onValueChange:j=>_(j),disabled:h==="llm"&&B,children:[f.jsx(Do,{id:`role-${e.id}`,children:f.jsx(Oo,{})}),f.jsxs(jo,{children:[f.jsx(Ar,{value:"assistant",children:"assistant"}),f.jsx(Ar,{value:"user",children:"user"})]})]})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`contentType-${e.id}`,children:"Content Type"}),f.jsxs(Io,{value:k,onValueChange:j=>C(j),disabled:h==="llm"&&B,children:[f.jsx(Do,{id:`contentType-${e.id}`,children:f.jsx(Oo,{})}),f.jsxs(jo,{children:[f.jsx(Ar,{value:"text",children:"text"}),f.jsx(Ar,{value:"image",children:"image"})]})]})]}),k==="text"&&f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`text-${e.id}`,children:"Text Content"}),f.jsx(Xl,{id:`text-${e.id}`,value:R,onChange:j=>I(j.target.value),placeholder:"Enter response text...",rows:6,disabled:h==="llm"&&B})]}),k==="image"&&f.jsxs(f.Fragment,{children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`imageData-${e.id}`,children:"Base64 Image Data"}),f.jsx(Xl,{id:`imageData-${e.id}`,value:A,onChange:j=>O(j.target.value),placeholder:"Base64 encoded image data...",rows:4,disabled:h==="llm"&&B})]}),f.jsxs("div",{className:"space-y-2",children:[f.jsx(Kt,{htmlFor:`mimeType-${e.id}`,children:"MIME Type"}),f.jsx(En,{id:`mimeType-${e.id}`,value:M,onChange:j=>P(j.target.value),placeholder:"image/png",disabled:h==="llm"&&B})]})]})]})]}),f.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[f.jsx($e,{onClick:re,className:"flex-1",disabled:h==="llm"&&B,children:"Approve"}),f.jsx($e,{onClick:ne,variant:"outline",className:"flex-1",disabled:h==="llm"&&B,children:"Reject"})]})]}):f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a sampling request to view details"})})}function OTe({pendingRequests:e,onApprove:t,onReject:n,serverId:a,isConnected:r,mcpServerUrl:i}){const{selectedSamplingRequestId:s,setSelectedSamplingRequestId:c}=ic(),{llmConfig:u}=_Y({mcpServerUrl:i}),[d,m]=w.useState(null),[h,g]=w.useState(""),[v,x]=w.useState(-1),[S,y]=w.useState(!0),[E,_]=w.useState(!1),[k,C]=w.useState(!0),[R,I]=w.useState(!1),A=w.useRef(null),O=w.useRef(null),M=w.useRef(null),P=w.useRef(!1);w.useEffect(()=>{if(console.log("[SamplingTab] Auto-selection check:",{selectedSamplingRequestId:s,pendingRequestsCount:e.length,currentSelectedId:d?.id}),s&&e.length>0){const G=e.find(re=>re.id===s);console.log("[SamplingTab] Found request for auto-selection:",!!G,G?.id),G&&(console.log("[SamplingTab] Auto-selecting request:",G.id),c(null),m(G),setTimeout(()=>{const re=document.getElementById(`sampling-request-${G.id}`);console.log("[SamplingTab] Scrolling to element:",!!re),re&&re.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[s,e,c]),w.useEffect(()=>{const G=re=>{const j=re.detail.requestId;console.log("[SamplingTab] Custom navigate event received:",j);const V=e.find(z=>z.id===j);V&&(console.log("[SamplingTab] Selecting request from event:",j),m(V),setTimeout(()=>{const z=document.getElementById(`sampling-request-${j}`);z&&z.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-sampling",G),()=>window.removeEventListener("navigate-to-sampling",G)},[e]),w.useEffect(()=>{S&&e.length>0&&A.current&&!P.current&&(A.current.scrollTop=0)},[e.length,S]),w.useEffect(()=>{const G=A.current;if(!G)return;const re=()=>{G.scrollTop>0&&(P.current=!0,y(!1))};return G.addEventListener("scroll",re),()=>G.removeEventListener("scroll",re)},[]),w.useEffect(()=>{e.length===0&&(P.current=!1,y(!0))},[e.length]),w.useEffect(()=>{E&&M.current&&M.current.focus()},[E]);const B=w.useCallback(()=>{h.trim()||_(!1)},[h]),K=w.useMemo(()=>{if(!h.trim())return e;const G=h.toLowerCase();return e.filter(re=>re.serverName.toLowerCase().includes(G)||JSON.stringify(re.request||{}).toLowerCase().includes(G))},[e,h]);w.useEffect(()=>{x(-1)},[h]),w.useEffect(()=>{const G=re=>{const ne=re.target;if(ne.tagName==="INPUT"||ne.tagName==="TEXTAREA"||ne.contentEditable==="true"||re.metaKey||re.ctrlKey||re.altKey)return;const V=K;if(re.key==="ArrowDown")re.preventDefault(),x(z=>{const $=z+1;return $>=V.length?0:$});else if(re.key==="ArrowUp")re.preventDefault(),x(z=>{const $=z-1;return $<0?V.length-1:$});else if(re.key==="Enter"&&v>=0){re.preventDefault();const z=K[v];z&&ee(z)}};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[v,K]),w.useEffect(()=>{if(v>=0){const G=`sampling-request-${K[v]?.id}`,re=document.getElementById(G);re&&re.scrollIntoView({behavior:"smooth",block:"nearest"})}},[v,K]);const ee=w.useCallback(G=>{m(G)},[]),te=w.useCallback(()=>{window.confirm("Are you sure you want to reject all sampling requests? This cannot be undone.")&&(e.forEach(G=>{n(G.id,"User rejected all requests")}),m(null))},[e,n]),ae=w.useCallback(async()=>{if(d)try{await navigator.clipboard.writeText(JSON.stringify({id:d.id,serverName:d.serverName,timestamp:d.timestamp,request:d.request},null,2)),I(!0),setTimeout(()=>I(!1),2e3)}catch(G){console.error("[SamplingTab] Failed to copy request:",G)}},[d]),H=w.useCallback(()=>{if(d)try{const G=new globalThis.Blob([JSON.stringify({id:d.id,serverName:d.serverName,timestamp:d.timestamp,request:d.request},null,2)],{type:"application/json"}),re=URL.createObjectURL(G),ne=document.createElement("a");ne.href=re,ne.download=`sampling-request-${Date.now()}.json`,document.body.appendChild(ne),ne.click(),document.body.removeChild(ne),URL.revokeObjectURL(re)}catch(G){console.error("[SamplingTab] Failed to download request:",G)}},[d]),Z=w.useCallback(async()=>{if(O.current)try{document.fullscreenElement?await document.exitFullscreen():await O.current.requestFullscreen()}catch(G){console.error("[SamplingTab] Failed to toggle fullscreen:",G)}},[]);return r?f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:40,minSize:30,children:f.jsx(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:f.jsxs(Rn,{defaultSize:75,minSize:30,children:[f.jsx(CTe,{isSearchExpanded:E,searchQuery:h,filteredRequestsCount:K.length,requestsCount:e.length,onSearchExpand:()=>_(!0),onSearchChange:g,onSearchBlur:B,onRejectAll:te,searchInputRef:M}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(RTe,{requests:K,selectedRequest:d,onRequestSelect:ee,focusedIndex:v,formatRelativeTime:ty,listRef:A})})]})})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:60,minSize:40,children:f.jsx("div",{ref:O,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx(ITe,{request:d,onApprove:t,onReject:n,onClose:()=>m(null),previewMode:k,onTogglePreview:()=>C(!k),isCopied:R,onCopy:ae,onDownload:H,onFullscreen:Z,llmConfig:u})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(PG,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function DTe({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:a,onSearchExpand:r,onSearchChange:i,onSearchBlur:s,onCancelAll:c,searchInputRef:u}){return f.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[f.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?f.jsx(En,{ref:u,placeholder:"Search requests...",value:t,onChange:d=>i(d.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):f.jsxs(f.Fragment,{children:[f.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Elicitation"}),f.jsx(wr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:f.jsx(Pd,{className:"h-4 w-4"})})}),f.jsxs(Rt,{side:"bottom",className:"flex gap-2",children:["Search",f.jsx(eh,{children:"F"})]})]})]})}),f.jsx("div",{className:"flex items-center gap-2",children:f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,disabled:a===0,className:"h-8 w-8 p-0",children:f.jsx(Ji,{className:"h-4 w-4"})})}),f.jsx(Rt,{side:"bottom",children:"Cancel all"})]})})]})}function jTe({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:a,formatRelativeTime:r,listRef:i}){return e.length===0?f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx(Md,{vertical:!0,noBorder:!0,message:"No elicitation requests"})}):f.jsx("div",{ref:i,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((s,c)=>{const u=s.request.mode||"form",d=u==="form"&&"requestedSchema"in s.request&&s.request.requestedSchema;return f.jsx(Qs,{id:`elicitation-request-${s.id}`,isSelected:t?.id===s.id,isFocused:a===c,title:f.jsxs("span",{className:"flex items-center gap-3",children:[s.serverName,f.jsx(wr,{variant:"outline",className:u==="url"?"bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/50":"bg-green-500/20 text-green-600 dark:text-green-400 border-green-500/50",children:u})]}),description:(()=>{const m=r(s.timestamp),h=[];d&&h.push("with schema"),u==="url"&&h.push("external action");const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(s)},s.id)})})}function $Te({request:e,onApprove:t,onReject:n,onClose:a,previewMode:r,onTogglePreview:i,isCopied:s,onCopy:c,onDownload:u,onFullscreen:d}){const[m,h]=w.useState({}),[g,v]=w.useState(!1),x=e?.request.mode||"form",S=x==="form",y=x==="url";w.useEffect(()=>{if(e&&S&&"requestedSchema"in e.request){const A=e.request.requestedSchema,O={};if(A?.type==="object"&&A.properties)for(const[M,P]of Object.entries(A.properties)){const B=P;B.default!==void 0?O[M]=B.default:B.type==="boolean"?O[M]=!1:B.type==="number"||B.type==="integer"?O[M]=0:O[M]=""}h(O)}v(!1)},[e?.id,S]);const E=(A,O)=>{h(M=>({...M,[A]:O}))},_=()=>{if(e){if(S){if("requestedSchema"in e.request){const A=e.request.requestedSchema;if(A?.required){const O=A.required.filter(M=>m[M]===void 0||m[M]===""||m[M]===null);if(O.length>0){Xt.error("Missing required fields",{description:`Please fill in: ${O.join(", ")}`});return}}}t(e.id,{action:"accept",data:m})}else y&&t(e.id,{action:"accept"});a(),Jn(()=>Promise.resolve().then(()=>kd),void 0).then(A=>{const O=Xt(A.createElement("div",{className:"space-y-3"},A.createElement("div",null,A.createElement("strong",null,"Elicitation Response Sent"),A.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),A.createElement("div",{className:"flex gap-2"},A.createElement("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>{const M=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:null}});window.dispatchEvent(M),Xt.dismiss(O)}},"View Tool Result"))),{duration:5e3})})}},k=()=>{e&&(t(e.id,{action:"decline"}),a())},C=()=>{e&&(n(e.id,"User cancelled elicitation request"),a())},R=()=>{e&&y&&"url"in e.request&&(window.open(e.request.url,"_blank"),v(!0))},I=w.useMemo(()=>{if(!e||!S||!("requestedSchema"in e.request))return null;const A=e.request.requestedSchema;if(!A||A.type!=="object"||!A.properties)return f.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No form schema available"});const O=A.properties,M=A.required||[];return f.jsx("div",{className:"space-y-4",children:Object.entries(O).map(([P,B])=>{const K=B,ee=M.includes(P),te=K.type||"string",ae=K.title||P,H=K.description;return f.jsxs("div",{className:"space-y-2",children:[f.jsxs(Kt,{htmlFor:`field-${P}`,children:[ae,ee&&f.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),H&&f.jsx("p",{className:"text-xs text-muted-foreground",children:H}),te==="boolean"?f.jsxs("div",{className:"flex items-center space-x-2",children:[f.jsx(im,{id:`field-${P}`,checked:m[P]||!1,onCheckedChange:Z=>E(P,Z)}),f.jsx(Kt,{htmlFor:`field-${P}`,className:"text-sm font-normal cursor-pointer",children:K.title||P})]}):te==="number"||te==="integer"?f.jsx(En,{id:`field-${P}`,type:"number",value:m[P]||"",onChange:Z=>E(P,te==="integer"?parseInt(Z.target.value,10):parseFloat(Z.target.value)),placeholder:K.default?.toString()||""}):K.enum?f.jsxs("select",{id:`field-${P}`,value:m[P]||"",onChange:Z=>E(P,Z.target.value),className:"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:[f.jsx("option",{value:"",children:"Select..."}),K.enum.map(Z=>f.jsx("option",{value:Z,children:Z},Z))]}):te==="string"&&(K.format==="textarea"||K.maxLength>100)?f.jsx(Xl,{id:`field-${P}`,value:m[P]||"",onChange:Z=>E(P,Z.target.value),placeholder:K.default||"",rows:4}):f.jsx(En,{id:`field-${P}`,type:"text",value:m[P]||"",onChange:Z=>E(P,Z.target.value),placeholder:K.default||""})]},P)})})},[e,m,S]);return e?f.jsxs("div",{className:"flex flex-col h-full",children:[f.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),f.jsx(wr,{variant:"outline",className:y?"bg-blue-500/20 text-blue-600 dark:text-blue-400 border-blue-500/50":"bg-green-500/20 text-green-600 dark:text-green-400 border-green-500/50",children:x}),f.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:c,className:"h-8 w-8 p-0",children:s?f.jsx(ra,{className:"h-4 w-4 text-green-600"}):f.jsx($r,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Copy request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:f.jsx(Lm,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Download request"})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",onClick:d,className:"h-8 w-8 p-0",children:f.jsx(QN,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:"Fullscreen"})]}),f.jsx($e,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:f.jsx(Ji,{className:"h-4 w-4"})})]})]}),f.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Message"}),f.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:e.request.message})]}),y&&"url"in e.request&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"External Action Required"}),f.jsxs("div",{className:"bg-muted rounded-lg p-4 space-y-3",children:[f.jsx("p",{className:"text-sm text-muted-foreground",children:"This request requires you to complete an action at an external URL:"}),f.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background rounded border",children:[f.jsx("code",{className:"flex-1 text-xs font-mono break-all",children:e.request.url}),f.jsxs($e,{size:"sm",variant:"outline",onClick:R,className:"flex items-center gap-2",children:[f.jsx(Y_,{className:"h-4 w-4"}),"Open URL"]})]}),f.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[f.jsx(im,{id:"url-completed",checked:g,onCheckedChange:A=>v(!!A)}),f.jsx(Kt,{htmlFor:"url-completed",className:"text-sm font-normal cursor-pointer",children:"I have completed the required action"})]})]})]}),S&&f.jsxs("div",{className:"space-y-2",children:[f.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Form Data"}),I]}),S&&"requestedSchema"in e.request&&e.request.requestedSchema&&f.jsxs("details",{className:"space-y-2",children:[f.jsx("summary",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 cursor-pointer",children:"Schema (for reference)"}),f.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:f.jsx(Xn,{data:e.request.requestedSchema})})]})]}),f.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[f.jsx($e,{onClick:_,className:"flex-1",children:"Accept"}),f.jsx($e,{onClick:k,variant:"outline",className:"flex-1",children:"Decline"}),f.jsx($e,{onClick:C,variant:"outline",className:"flex-1",children:"Cancel"})]})]}):f.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select an elicitation request to view details"})})}function LTe({pendingRequests:e=[],onApprove:t,onReject:n,serverId:a,isConnected:r}){const{selectedElicitationRequestId:i,setSelectedElicitationRequestId:s}=ic(),[c,u]=w.useState(null),[d,m]=w.useState(""),[h,g]=w.useState(-1),[v,x]=w.useState(!0),[S,y]=w.useState(!1),[E,_]=w.useState(!0),[k,C]=w.useState(!1),R=w.useRef(null),I=w.useRef(null),A=w.useRef(null),O=w.useRef(!1);w.useEffect(()=>{if(console.log("[ElicitationTab] Auto-selection check:",{selectedElicitationRequestId:i,pendingRequestsCount:e.length,currentSelectedId:c?.id}),i&&e.length>0){const H=e.find(Z=>Z.id===i);console.log("[ElicitationTab] Found request for auto-selection:",!!H,H?.id),H&&(console.log("[ElicitationTab] Auto-selecting request:",H.id),s(null),u(H),setTimeout(()=>{const Z=document.getElementById(`elicitation-request-${H.id}`);console.log("[ElicitationTab] Scrolling to element:",!!Z),Z&&Z.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[i,e,s]),w.useEffect(()=>{const H=Z=>{const re=Z.detail.requestId;console.log("[ElicitationTab] Custom navigate event received:",re);const ne=e.find(j=>j.id===re);ne&&(console.log("[ElicitationTab] Selecting request from event:",re),u(ne),setTimeout(()=>{const j=document.getElementById(`elicitation-request-${re}`);j&&j.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-elicitation",H),()=>window.removeEventListener("navigate-to-elicitation",H)},[e]),w.useEffect(()=>{v&&e.length>0&&R.current&&!O.current&&(R.current.scrollTop=0)},[e.length,v]),w.useEffect(()=>{const H=R.current;if(!H)return;const Z=()=>{H.scrollTop>0&&(O.current=!0,x(!1))};return H.addEventListener("scroll",Z),()=>H.removeEventListener("scroll",Z)},[]),w.useEffect(()=>{e.length===0&&(O.current=!1,x(!0))},[e.length]),w.useEffect(()=>{S&&A.current&&A.current.focus()},[S]);const M=w.useCallback(()=>{d.trim()||y(!1)},[d]),P=w.useMemo(()=>{if(!d.trim())return e;const H=d.toLowerCase();return e.filter(Z=>Z.serverName.toLowerCase().includes(H)||Z.request.message.toLowerCase().includes(H)||JSON.stringify(Z.request||{}).toLowerCase().includes(H))},[e,d]);w.useEffect(()=>{g(-1)},[d]),w.useEffect(()=>{const H=Z=>{const G=Z.target;if(G.tagName==="INPUT"||G.tagName==="TEXTAREA"||G.contentEditable==="true"||Z.metaKey||Z.ctrlKey||Z.altKey)return;const ne=P;if(Z.key==="ArrowDown")Z.preventDefault(),g(j=>{const V=j+1;return V>=ne.length?0:V});else if(Z.key==="ArrowUp")Z.preventDefault(),g(j=>{const V=j-1;return V<0?ne.length-1:V});else if(Z.key==="Enter"&&h>=0){Z.preventDefault();const j=P[h];j&&B(j)}};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[h,P]),w.useEffect(()=>{if(h>=0){const H=`elicitation-request-${P[h]?.id}`,Z=document.getElementById(H);Z&&Z.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,P]);const B=w.useCallback(H=>{u(H)},[]),K=w.useCallback(()=>{window.confirm("Are you sure you want to cancel all elicitation requests? This cannot be undone.")&&(e.forEach(H=>{n(H.id,"User cancelled all requests")}),u(null))},[e,n]),ee=w.useCallback(async()=>{if(c)try{await navigator.clipboard.writeText(JSON.stringify({id:c.id,serverName:c.serverName,timestamp:c.timestamp,request:c.request},null,2)),C(!0),setTimeout(()=>C(!1),2e3)}catch(H){console.error("[ElicitationTab] Failed to copy request:",H)}},[c]),te=w.useCallback(()=>{if(c)try{const H=new globalThis.Blob([JSON.stringify({id:c.id,serverName:c.serverName,timestamp:c.timestamp,request:c.request},null,2)],{type:"application/json"}),Z=URL.createObjectURL(H),G=document.createElement("a");G.href=Z,G.download=`elicitation-request-${Date.now()}.json`,document.body.appendChild(G),G.click(),document.body.removeChild(G),URL.revokeObjectURL(Z)}catch(H){console.error("[ElicitationTab] Failed to download request:",H)}},[c]),ae=w.useCallback(async()=>{if(I.current)try{document.fullscreenElement?await document.exitFullscreen():await I.current.requestFullscreen()}catch(H){console.error("[ElicitationTab] Failed to toggle fullscreen:",H)}},[]);return r?f.jsxs(na,{direction:"horizontal",className:"h-full",children:[f.jsx(Rn,{defaultSize:40,minSize:30,children:f.jsx(na,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:f.jsxs(Rn,{defaultSize:75,minSize:30,children:[f.jsx(DTe,{isSearchExpanded:S,searchQuery:d,filteredRequestsCount:P.length,requestsCount:e.length,onSearchExpand:()=>y(!0),onSearchChange:m,onSearchBlur:M,onCancelAll:K,searchInputRef:A}),f.jsx("div",{className:"flex flex-col h-full",children:f.jsx(jTe,{requests:P,selectedRequest:c,onRequestSelect:B,focusedIndex:h,formatRelativeTime:ty,listRef:R})})]})})}),f.jsx(Si,{}),f.jsx(Rn,{defaultSize:60,minSize:40,children:f.jsx("div",{ref:I,className:"h-full bg-white dark:bg-zinc-900",children:f.jsx($Te,{request:c,onApprove:t,onReject:n,onClose:()=>u(null),previewMode:E,onTogglePreview:()=>_(!E),isCopied:k,onCopy:ee,onDownload:te,onFullscreen:ae})})})]}):f.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[f.jsx(BG,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),f.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function MTe({selectedServer:e,activeTab:t,toolsSearchRef:n,promptsSearchRef:a,resourcesSearchRef:r,children:i}){return e?f.jsxs(f.Fragment,{children:[f.jsx("div",{style:{display:t==="tools"?"block":"none"},className:"h-full",children:f.jsx(qY,{ref:n,tools:e.tools,callTool:e.callTool,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="prompts"?"block":"none"},className:"h-full",children:f.jsx(WY,{ref:a,prompts:e.prompts,callPrompt:e.getPrompt,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="resources"?"block":"none"},className:"h-full",children:f.jsx(ZY,{ref:r,resources:e.resources,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="chat"?"block":"none"},className:"h-full",children:f.jsx(Uke,{connection:e,isConnected:e.state==="ready",readResource:e.readResource},e.id)}),f.jsx("div",{style:{display:t==="sampling"?"block":"none"},className:"h-full",children:f.jsx(OTe,{pendingRequests:e.pendingSamplingRequests,onApprove:e.approveSampling,onReject:e.rejectSampling,serverId:e.id,isConnected:e.state==="ready",mcpServerUrl:e.url})}),f.jsx("div",{style:{display:t==="elicitation"?"block":"none"},className:"h-full",children:f.jsx(LTe,{pendingRequests:e.pendingElicitationRequests,onApprove:e.approveElicitation,onReject:e.rejectElicitation,serverId:e.id,isConnected:e.state==="ready"})}),f.jsx("div",{style:{display:t==="notifications"?"block":"none"},className:"h-full",children:f.jsx(bTe,{notifications:e.notifications,unreadCount:e.unreadNotificationCount,markNotificationRead:e.markNotificationRead,markAllNotificationsRead:e.markAllNotificationsRead,clearNotifications:e.clearNotifications,serverId:e.id,isConnected:e.state==="ready"})}),t!=="tools"&&t!=="prompts"&&t!=="resources"&&t!=="chat"&&t!=="sampling"&&t!=="elicitation"&&t!=="notifications"&&f.jsx(f.Fragment,{children:i})]}):f.jsx(f.Fragment,{children:i})}function X2({className:e}){return f.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentcolor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[f.jsx("path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"}),f.jsx("path",{d:"M9 18c-4.51 2-5-2-7-2"})]})}const XY=w.createContext(void 0);function JY(){const e=w.use(XY);if(!e)throw new Error("useTabs must be used within a TabsProvider");return e}const QY=w.createContext(void 0);function PTe(){return w.use(QY)}function rk({ref:e,children:t,defaultValue:n,value:a,onValueChange:r,className:i,collapsed:s,onCollapsedChange:c,...u}){const[d,m]=w.useState(n||""),h=a!==void 0,g=s!==void 0,[v,x]=w.useState(!1),S=w.useCallback(k=>{h||m(k),r?.(k)},[h,r]),y=h?a:d,E=g?s:v,_=w.useCallback(k=>{g||x(k),c?.(k)},[g,c]);return f.jsx(XY,{value:{activeValue:y,handleValueChange:S,collapsed:E,handleCollapsedChange:_},children:f.jsx("div",{ref:e,className:De("flex flex-col gap-2",i),...u,children:t})})}rk.displayName="Tabs";function ak({ref:e,children:t,className:n,variant:a="default",collapsible:r=!1,...i}){const{activeValue:s,collapsed:c,handleCollapsedChange:u}=JY(),[d,m]=w.useState({width:0,left:0}),h=w.useRef(null),g=w.useRef(null),v=w.useRef(null),x=w.useCallback(()=>{const E=h.current;if(!E)return;const _=E.querySelector("div:first-child");if(!_)return;const k=_.querySelector(`button[data-tab-value="${s}"]`);if(k&&s){const C=_.getBoundingClientRect(),R=k.getBoundingClientRect();m({width:R.width,left:R.left-C.left})}else m({width:0,left:0})},[s]),S=w.useCallback(()=>{v.current&&clearTimeout(v.current),v.current=setTimeout(x,16)},[x]);w.useEffect(()=>{const E=setTimeout(x,10);return()=>clearTimeout(E)},[x,c]),w.useEffect(()=>{const E=h.current;if(!E)return;g.current=new ResizeObserver(()=>{S()}),g.current.observe(E);const _=E.querySelector("div:first-child");return _&&_.querySelectorAll("button[data-tab-value]").forEach(C=>{g.current&&g.current.observe(C)}),()=>{g.current&&g.current.disconnect(),v.current&&clearTimeout(v.current)}},[S]),w.useEffect(()=>{const E=()=>{S()};return window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[S]);const y=w.useRef(null);return w.useEffect(()=>{y.current&&(y.current.style.width=`${d.width}px`,y.current.style.left=`${d.left}px`)},[d]),f.jsx(QY,{value:{variant:a,collapsed:c,handleCollapsedChange:u},children:f.jsx("div",{ref:h,className:De("relative flex items-center bg-none gap-1",a==="default"&&"p-1 rounded-full border border-zinc-300 dark:border-zinc-600",a==="underline"&&"border-b border-zinc-200 dark:border-zinc-700",n),...i,children:f.jsxs("div",{role:"tablist",className:"flex-1 flex items-center relative",children:[t,f.jsx("span",{ref:y,className:De("absolute transition-all duration-500 ease-in-out z-0",a==="default"&&"bg-white dark:bg-zinc-700 rounded-full h-[calc(100%)] top-0 border border-zinc-300 dark:border-zinc-600",a==="underline"&&"bottom-0 h-0.5 bg-black dark:bg-white")})]})})})}ak.displayName="TabsList";const UTe=({children:e,title:t,collapsed:n})=>!t||!n?e:f.jsx(ZN,{children:f.jsxs(Nt,{children:[f.jsx(Ct,{children:e}),f.jsx(Rt,{children:t})]})}),ik=w.forwardRef(({children:e,value:t,className:n,disabled:a,icon:r,title:i,...s},c)=>{const{activeValue:u,handleValueChange:d,collapsed:m}=JY(),g=PTe()?.variant||"default",v=u===t,x=m&&i?i:void 0;return f.jsx(UTe,{title:i,collapsed:m,children:f.jsxs("button",{ref:c,disabled:a,onClick:()=>d(t),"data-tab-value":t,"data-tab-active":v,role:"tab","aria-selected":v?"true":"false",title:x,className:De("relative z-10 flex-1 inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-500 ease-in-out focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 cursor-pointer",g==="default"&&"py-2.5",g==="default"&&"rounded-md px-4",g==="underline"&&"px-6 py-3 border-b-2 border-transparent",v&&"text-foreground",!v&&"text-muted-foreground hover:text-foreground",n),...s,children:[r&&f.jsx(r,{className:De("h-4 w-4 transition-all duration-500 ease-in-out",!m&&"mr-2",m&&"mr-0!")}),f.jsx("span",{className:De("transition-all duration-500 ease-in-out overflow-hidden",m?"w-0 opacity-0":"w-auto opacity-100"),children:e})]})})});ik.displayName="TabsTrigger";function J2({className:e}){const{theme:t,setTheme:n}=xw(),a=w.useRef(null),[r,i]=w.useState(!1);w.useEffect(()=>{i(!0)},[]);const s=()=>t==="system"?"light":t==="light"?"dark":"system",c=()=>t==="system"?f.jsx(rz,{className:"size-4"}):t==="light"?f.jsx(Uhe,{className:"size-5"}):f.jsx(vhe,{className:"size-4"}),u=()=>t==="system"?"Switch to light mode":t==="light"?"Switch to dark mode":"Switch to system mode",d=async()=>{if(!a.current)return;const m=s();if(typeof document<"u"&&"startViewTransition"in document){await document.startViewTransition(()=>{Od.flushSync(()=>{n(m)})}).ready;const{top:h,left:g,width:v,height:x}=a.current.getBoundingClientRect(),S=h+x/2,y=g+v/2,E=window.innerWidth-g,_=window.innerHeight-h,k=Math.hypot(Math.max(g,E),Math.max(h,_));document.documentElement.animate({clipPath:[`circle(0px at ${y}px ${S}px)`,`circle(${k}px at ${y}px ${S}px)`]},{duration:700,easing:"ease-in-out",pseudoElement:"::view-transition-new(root)"})}else n(m)};return r?f.jsx("button",{ref:a,onClick:d,className:De(e),"aria-label":u(),title:`Current: ${t==="system"?"Auto":t==="light"?"Light":"Dark"}`,children:c()}):f.jsx("button",{ref:a,className:De(e),"aria-label":"Toggle theme",children:f.jsx(rz,{className:"size-4"})})}function Q2({className:e,state:t="collapsed",href:n="https://mcp-use.com"}){const[a,r]=w.useState(!1),i=.2,s=.7,c=.6,u=4,d=i+s+c,m=0,h=i/d,g=(i+s)/d,v=1;return f.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:De("flex items-center transition-opacity -my-3",t==="expanded"?"space-x-2":"",e),onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:[f.jsx("div",{className:"relative",children:f.jsxs(ya.svg,{viewBox:"0 0 303 303",initial:"rest",animate:a?"hover":"rest",className:De("text-foreground",t==="expanded"?"size-[40px]":"size-[20px]"),children:[f.jsxs(ya.g,{variants:{rest:{opacity:1},hover:{opacity:[1,0,0,1],transition:{duration:d,times:[m,h,g,v],ease:"easeInOut"}}},fill:"currentColor",fillRule:"nonzero",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx("path",{d:"m105.5 34.8.6.6c9.5 9.5 14.4 21.9 14.6 34.4a112.6 112.6 0 0 0 112.2 112.1h.6c12 .4 24 5.1 33.2 14.1l.6.6a50 50 0 0 1-70.1 71.3l-.6-.6A49.9 49.9 0 0 1 182 230 112.6 112.6 0 0 0 73.4 120.7h-.8a49.9 49.9 0 0 1-36.7-14l-.5-.6a50 50 0 0 1-.6-70.2l.6-.5a50 50 0 0 1 69.5-1.2l.6.6Z"}),f.jsx("circle",{cx:"70.3",cy:"232.3",r:"50"}),f.jsx("circle",{cx:"232.3",cy:"70.3",r:"50"})]}),f.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[f.jsx(zTe,{d:"m105.5 34.8.6.6c9.5 9.5 14.4 21.9 14.6 34.4a112.6 112.6 0 0 0 112.2 112.1h.6c12 .4 24 5.1 33.2 14.1l.6.6a50 50 0 0 1-70.1 71.3l-.6-.6A49.9 49.9 0 0 1 182 230 112.6 112.6 0 0 0 73.4 120.7h-.8a49.9 49.9 0 0 1-36.7-14l-.5-.6a50 50 0 0 1-.6-70.2l.6-.5a50 50 0 0 1 69.5-1.2l.6.6Z",times:{T0:m,T1:h,T2:g,T3:v},total:d}),f.jsx(eF,{cx:70.3,cy:232.3,r:50,times:{T0:m,T1:h,T2:g,T3:v},total:d}),f.jsx(eF,{cx:232.3,cy:70.3,r:50,times:{T0:m,T1:h,T2:g,T3:v},total:d})]})]})}),t==="expanded"&&f.jsxs("div",{className:"font-ubuntu flex flex-col items-start -space-y-1 mr-3",children:[f.jsx("h1",{className:"text-xl font-medium",children:"mcp-use"}),f.jsx("span",{className:"text-lg text-muted-foreground tracking-wide font-sans font-light",children:"Inspector"})]})]})}function zTe({d:e,times:t,total:n}){const{T0:a,T1:r,T2:i,T3:s}=t;return f.jsx(ya.path,{d:e,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:n,times:[a,r,i,s],ease:"easeInOut"}}}})}function eF({cx:e,cy:t,r:n,times:a,total:r}){const{T0:i,T1:s,T2:c,T3:u}=a;return f.jsx(ya.circle,{cx:e,cy:t,r:n,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:r,times:[i,s,c,u],ease:"easeInOut"}}}})}function eq({ref:e,shimmerColor:t,shimmerSize:n="0.05em",shimmerDuration:a="3s",borderRadius:r="100px",background:i,className:s,children:c,...u}){const{resolvedTheme:d}=xw(),m=d==="dark"?"#000000":"#ffffff",h=d==="dark"?"rgba(255, 255, 255, 1)":"rgba(0, 0, 0, 1)",g=t||m,v=i||h;return f.jsxs("button",{style:{"--spread":"90deg","--shimmer-color":g,"--radius":r,"--speed":a,"--cut":n,"--bg":v},className:De("group relative z-0 flex cursor-pointer items-center justify-center overflow-hidden [border-radius:var(--radius)] border px-6 py-3 whitespace-nowrap [background:var(--bg)]","transform-gpu transition-transform duration-300 ease-in-out active:translate-y-px",d==="dark"?"border-black/10 text-black":"border-white/10 text-white",s),ref:e,...u,children:[f.jsx("div",{className:De("-z-30 blur-[2px]","[container-type:size] absolute inset-0 overflow-visible"),children:f.jsx("div",{className:"animate-shimmer-slide absolute inset-0 [aspect-ratio:1] h-[100cqh] [border-radius:0] [mask:none]",children:f.jsx("div",{className:"animate-spin-around absolute -inset-full w-auto [translate:0_0] rotate-0 [background:conic-gradient(from_calc(270deg-(var(--spread)*0.5)),transparent_0,var(--shimmer-color)_var(--spread),transparent_var(--spread))]"})})}),c,f.jsx("div",{className:De("absolute inset-0 size-full","rounded-2xl px-4 py-1.5 text-sm font-medium","transform-gpu transition-all duration-300 ease-in-out",d==="dark"?"shadow-[inset_0_-8px_10px_#0000001f] group-hover:shadow-[inset_0_-6px_10px_#0000003f] group-active:shadow-[inset_0_-10px_10px_#0000003f]":"shadow-[inset_0_-8px_10px_#ffffff1f] group-hover:shadow-[inset_0_-6px_10px_#ffffff3f] group-active:shadow-[inset_0_-10px_10px_#ffffff3f]")}),f.jsx("div",{className:De("absolute [inset:var(--cut)] -z-20 [border-radius:var(--radius)] [background:var(--bg)]")})]})}eq.displayName="ShimmerButton";function tF({status:e}){const t=i=>{switch(i){case"ready":return{color:"bg-emerald-500",ringColor:"ring-emerald-500",tooltip:"Connected"};case"failed":return{color:"bg-red-500",ringColor:"ring-red-500",tooltip:"Failed"};default:return{color:"bg-yellow-500",ringColor:"ring-yellow-500",tooltip:i}}},{color:n,ringColor:a,tooltip:r}=t(e);return f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsxs("div",{className:"relative",children:[f.jsx("div",{className:`absolute w-2 h-2 rounded-full ${a} animate-ping`}),f.jsx("div",{className:`relative w-2 h-2 rounded-full ${n}`})]})}),f.jsx(Rt,{children:f.jsx("p",{children:r})})]})}function nF({connections:e,selectedServer:t,onServerSelect:n,onOpenConnectionOptions:a,mobileMode:r=!1}){const i=Rd(),s=c=>{const u=e.find(d=>d.id===c);if(!u||u.state!=="ready"){Xt.error("Server is not connected and cannot be inspected");return}n(c)};return r?f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("div",{className:"relative",children:f.jsxs(V_,{children:[f.jsx(G_,{asChild:!0,children:f.jsxs($e,{variant:"ghost",className:"h-11 px-2 bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200 flex items-center gap-1.5",children:[t?f.jsx(Ol,{serverUrl:t.url,serverName:t.name,size:"md"}):f.jsx(Rhe,{className:"h-5 w-5"}),f.jsx(ac,{className:"h-4 w-4"})]})}),f.jsxs(Cv,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[f.jsx(W_,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>i("/"),children:"MCP Servers"}),f.jsx(rp,{}),e.length===0?f.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center",children:"No servers connected. Go to the dashboard to add one."}):e.map(c=>f.jsxs(Ro,{onClick:()=>s(c.id),className:"flex items-center gap-3",children:[f.jsx(Ol,{serverUrl:c.url,serverName:c.name,size:"sm"}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx("div",{className:"font-medium",children:c.name}),f.jsx(tF,{status:c.state})]}),f.jsx($e,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:u=>{u.stopPropagation(),a(c.id)},children:f.jsx(Eu,{className:"h-3 w-3"})})]},c.id)),f.jsx(rp,{}),f.jsx(Ro,{onClick:()=>i("/"),children:f.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})})}):f.jsx("div",{className:"flex items-center gap-2",children:f.jsx("div",{className:"relative",children:f.jsxs(V_,{children:[f.jsx(G_,{asChild:!0,children:f.jsxs(eq,{className:De("min-w-0 sm:min-w-[200px] p-0 px-1 text-sm h-11 justify-start bg-black dark:bg-white text-white dark:text-black border-black dark:border-white hover:bg-gray-800 dark:hover:bg-zinc-100 hover:border-gray-800 dark:hover:border-zinc-200",!t&&"pl-4",t&&"pr-10"),children:[t&&f.jsx(Ol,{serverUrl:t.url,serverName:t.name,size:"md",className:"mr-2"}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx("span",{className:"truncate",children:t?t.name:"Select server to inspect"}),t&&f.jsx("div",{className:"flex items-center gap-2",children:t.error&&t.state!=="ready"?f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx("button",{onClick:c=>{c.stopPropagation()},className:"w-2 h-2 rounded-full bg-rose-500 animate-status-pulse-red hover:bg-rose-600 transition-colors",title:"Click to copy error message","aria-label":"Copy error message to clipboard"})}),f.jsx(Rt,{children:f.jsx("p",{className:"max-w-xs",children:t.error})})]}):f.jsx("div",{className:`w-2 h-2 rounded-full ${t.state==="ready"?"bg-emerald-600 animate-status-pulse":t.state==="failed"?"bg-rose-600 animate-status-pulse-red":"bg-yellow-500 animate-status-pulse-yellow"}`})})]})]})}),t&&f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx("button",{type:"button",onClick:()=>{a(t.id)},className:"absolute right-2 top-1/2 -translate-y-1/2 p-1.5 hover:bg-white/10 dark:hover:bg-black/10 rounded-full transition-colors text-white dark:text-black","aria-label":"Edit connection settings",children:f.jsx(Eu,{className:"h-4 w-4"})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Edit connection settings"})})]}),f.jsxs(Cv,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[f.jsx(W_,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>i("/"),children:"MCP Servers"}),f.jsx(rp,{}),e.length===0?f.jsx("div",{className:"px-2 py-4 text-sm text-muted-foreground dark:text-zinc-400 text-center",children:"No servers connected. Go to the dashboard to add one."}):e.map(c=>f.jsxs(Ro,{onClick:()=>s(c.id),className:"flex items-center gap-3",children:[f.jsx(Ol,{serverUrl:c.url,serverName:c.name,size:"sm"}),f.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[f.jsx("div",{className:"font-medium",children:c.name}),f.jsx(tF,{status:c.state})]}),f.jsx($e,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:u=>{u.stopPropagation(),a(c.id)},children:f.jsx(Eu,{className:"h-3 w-3"})})]},c.id)),f.jsx(rp,{}),f.jsx(Ro,{onClick:()=>i("/"),children:f.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})})})}const rF=[{id:"tools",label:"Tools",icon:Wl},{id:"prompts",label:"Prompts",icon:Hp},{id:"resources",label:"Resources",icon:ehe},{id:"sampling",label:"Sampling",icon:PG},{id:"elicitation",label:"Elicitation",icon:BG},{id:"notifications",label:"Notifications",icon:qN},{id:"chat",label:"Chat",icon:fhe}];function aF(e,t){return e==="tools"?t.tools.length:e==="prompts"?t.prompts.length:e==="resources"?t.resources.length:e==="sampling"?t.pendingSamplingRequests?.length||0:e==="elicitation"?t.pendingElicitationRequests?.length||0:e==="notifications"?t.unreadNotificationCount:0}function FTe({collapsed:e,onToggle:t}){return f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx("button",{onClick:t,className:De("shrink-0 p-1.5 rounded-md transition-all duration-500 ease-in-out cursor-pointer","text-muted-foreground hover:text-foreground","hover:bg-zinc-100 dark:hover:bg-zinc-800","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"),"aria-label":e?"Expand tabs":"Collapse tabs",type:"button",children:e?f.jsx(LG,{className:"h-4 w-4 transition-transform duration-500 ease-in-out"}):f.jsx(qy,{className:"h-4 w-4 transition-transform duration-500 ease-in-out"})})}),f.jsx(Rt,{children:f.jsx("p",{children:e?"Expand tabs":"Collapse tabs"})})]})}function BTe({connections:e,selectedServer:t,activeTab:n,onServerSelect:a,onTabChange:r,onCommandPaletteOpen:i,onOpenConnectionOptions:s}){const{tunnelUrl:c}=ic(),u=t&&c,[d,m]=w.useState(!1),[h,g]=w.useState(!1),v=async()=>{if(c)try{await navigator.clipboard.writeText(`${c}/mcp`),m(!0),Xt.success("Tunnel URL copied to clipboard"),setTimeout(()=>m(!1),2e3)}catch{Xt.error("Failed to copy URL")}};return f.jsxs("header",{className:"w-full mx-auto",children:[f.jsxs("div",{className:"flex lg:hidden flex-col gap-3",children:[f.jsxs("div",{className:"flex items-center justify-between w-full",children:[f.jsx("div",{className:"flex-1 flex justify-start",children:f.jsx(nF,{connections:e,selectedServer:t,onServerSelect:a,onOpenConnectionOptions:s,mobileMode:!0})}),f.jsx("div",{className:"flex-shrink-0 flex justify-center",children:f.jsx("div",{className:"scale-150",children:f.jsx(Q2,{state:"collapsed"})})}),f.jsxs("div",{className:"flex-1 flex justify-end items-center gap-2",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",asChild:!0,children:f.jsx("a",{href:"https://github.com/mcp-use/mcp-use",target:"_blank",rel:"noopener noreferrer",className:"p-2","aria-label":"GitHub",children:f.jsx(X2,{className:"h-4 w-4"})})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Give us a star ⭐"})})]}),f.jsx(J2,{className:"p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors cursor-pointer"})]})]}),t&&f.jsx("div",{className:"w-full",children:f.jsx(rk,{value:n,onValueChange:x=>r(x),collapsed:h,onCollapsedChange:g,children:f.jsx(ak,{className:"w-full justify-center",children:rF.map(x=>{const S=aF(x.id,t);return f.jsxs(ik,{value:x.id,icon:x.icon,className:De("[&>svg]:mr-0 flex-1 flex-row gap-2 relative",h&&"pl-2"),children:[S>0&&f.jsx("span",{className:De(n===x.id?"dark:bg-black":"dark:bg-zinc-700","bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-[10px] px-1.5 py-0.5 rounded-full font-medium"),children:S}),f.jsx("span",{className:"sr-only",children:x.label})]},x.id)})})})})]}),f.jsxs("div",{className:"hidden lg:flex items-center justify-between gap-3",children:[f.jsxs("div",{className:"flex items-center flex-wrap gap-2 md:space-x-6 space-x-2",children:[f.jsx(nF,{connections:e,selectedServer:t,onServerSelect:a,onOpenConnectionOptions:s}),t&&f.jsxs("div",{className:"flex items-center gap-2",children:[f.jsx(rk,{value:n,onValueChange:x=>r(x),collapsed:h,onCollapsedChange:g,children:f.jsx(ak,{className:"overflow-x-auto",collapsible:!0,children:rF.map(x=>{const S=aF(x.id,t),y=S>0?`${x.label} (${S})`:x.label;return f.jsx(ik,{value:x.id,icon:x.icon,className:De("[&>svg]:mr-0 lg:[&>svg]:mr-2 relative",h&&"pl-4"),title:y,children:f.jsxs("div",{className:"items-center gap-2 hidden lg:flex",children:[x.label,S>0&&f.jsx("span",{className:De(n===x.id?" dark:bg-black ":"dark:bg-zinc-700","bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-xs px-2 py-0.5 rounded-full font-medium"),children:S})]})})})})}),f.jsx(FTe,{collapsed:h,onToggle:()=>g(!h)})]}),u&&f.jsxs(KK,{children:[f.jsx(ZK,{asChild:!0,children:f.jsxs("button",{className:"flex items-center gap-2 px-3 py-1.5 bg-gradient-to-r from-purple-500/10 to-pink-500/10 dark:from-purple-500/20 dark:to-pink-500/20 border border-purple-500/30 dark:border-purple-500/40 rounded-full hover:from-purple-500/20 hover:to-pink-500/20 dark:hover:from-purple-500/30 dark:hover:to-pink-500/30 transition-colors cursor-pointer",children:[f.jsx(Vp,{className:"size-4 text-purple-600 dark:text-purple-400 animate-pulse"}),f.jsx("span",{className:"text-xs font-medium text-purple-700 dark:text-purple-300 hidden lg:inline",children:"Tunnel"})]})}),f.jsx(WC,{className:"w-[calc(100vw-2rem)] sm:w-96",align:"start",children:f.jsxs("div",{className:"space-y-4",children:[f.jsxs("div",{children:[f.jsxs("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:[f.jsx(Vp,{className:"size-4 text-purple-600 dark:text-purple-400"}),"Tunnel URL"]}),f.jsxs("div",{className:"flex items-center gap-2 p-2 py-0 bg-muted rounded-full",children:[f.jsxs("code",{className:"flex-1 text-[10px] font-mono",children:[c,"/mcp"]}),f.jsx($e,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:v,children:d?f.jsx(ra,{className:"size-3.5 text-green-600"}):f.jsx($r,{className:"size-3.5"})})]})]}),f.jsxs("div",{children:[f.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Use in ChatGPT"}),f.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[f.jsxs("li",{className:"flex gap-2",children:[f.jsx("span",{className:"font-semibold text-foreground",children:"1."}),f.jsxs("span",{children:["Enable"," ",f.jsx("span",{className:"font-medium text-foreground",children:"dev mode"})," ","from settings"]})]}),f.jsxs("li",{className:"flex gap-2",children:[f.jsx("span",{className:"font-semibold text-foreground",children:"2."}),f.jsxs("span",{children:["In"," ",f.jsx("span",{className:"font-medium text-foreground",children:"App & Connectors"})," ","click on"," ",f.jsx("span",{className:"font-medium text-foreground",children:"create"})]})]}),f.jsxs("li",{className:"flex gap-2",children:[f.jsx("span",{className:"font-semibold text-foreground",children:"3."}),f.jsx("span",{children:"Use the tunnel URL in the input"})]})]})]})]})})]})]}),f.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-shrink-0",children:[f.jsxs(Nt,{children:[f.jsx(Ct,{children:f.jsx(J2,{className:"p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors cursor-pointer"})}),f.jsx(Rt,{children:f.jsx("p",{children:"Toggle theme"})})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsxs($e,{variant:"ghost",className:"hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full px-1 -mx-3 flex gap-1",onClick:i,children:[f.jsx(Mme,{className:"size-4"}),f.jsx("span",{className:"text-base font-mono hidden sm:inline",children:"K"})]})}),f.jsx(Rt,{children:f.jsx("p",{children:"Command Palette"})})]}),f.jsxs(Nt,{children:[f.jsx(Ct,{asChild:!0,children:f.jsx($e,{variant:"ghost",size:"sm",asChild:!0,children:f.jsxs("a",{href:"https://github.com/mcp-use/mcp-use",className:"flex items-center gap-2",target:"_blank",rel:"noopener noreferrer",children:[f.jsx(X2,{className:"h-4 w-4"}),f.jsx("span",{className:"hidden sm:inline",children:"Github"})]})})}),f.jsx(Rt,{children:f.jsx("p",{children:"Give us a star ⭐"})})]}),f.jsx(Q2,{state:"expanded"})]})]})]})}function HTe({children:e}){const t=Rd(),n=Vo(),{connections:a,addConnection:r,removeConnection:i,updateConnectionConfig:s,configLoaded:c}=YN(),{selectedServerId:u,setSelectedServerId:d,activeTab:m,setActiveTab:h,navigateToItem:g,setTunnelUrl:v}=ic(),[x,S]=w.useState(!1),[y,E]=w.useState(null),_=rSe();w.useEffect(()=>{const Z=new URLSearchParams(n.search).get("tunnelUrl");v(Z)},[n.search,v]),w.useEffect(()=>{const H=re=>{const j=re.detail.requestId;u&&g(u,"sampling",j)},Z=re=>{const j=re.detail.requestId;u&&g(u,"elicitation",j)},G=re=>{const j=re.detail.toolName;u&&j?g(u,"tools",j):u&&h("tools")};return window.addEventListener("navigate-to-sampling",H),window.addEventListener("navigate-to-elicitation",Z),window.addEventListener("navigate-to-tool-result",G),()=>{window.removeEventListener("navigate-to-sampling",H),window.removeEventListener("navigate-to-elicitation",Z),window.removeEventListener("navigate-to-tool-result",G)}},[u,h,g]);const k=w.useRef(null),C=w.useRef(null),R=w.useRef(null),{isAutoConnecting:I}=nSe({connections:a,addConnection:r,removeConnection:i,configLoaded:c}),A=w.useCallback(H=>{vr.getInstance().capture(new eme({trigger:H})).catch(()=>{}),S(!0)},[]),O=H=>{const Z=a.find(j=>j.id===H);if(!Z||Z.state!=="ready"){Xt.error("Server is not connected and cannot be inspected");return}d(H);const re=new URLSearchParams(n.search).get("tunnelUrl"),ne=re?`/?server=${encodeURIComponent(H)}&tunnelUrl=${encodeURIComponent(re)}`:`/?server=${encodeURIComponent(H)}`;t(ne)},M=w.useCallback(H=>{E(H)},[]),P=w.useCallback(H=>{y&&(H.url!==y?(i(y),r(H.url,H.name,H.proxyConfig,H.transportType)):s(y,{name:H.name,proxyConfig:H.proxyConfig,transportType:H.transportType}),E(null),Xt.success("Connection settings updated"))},[y,i,r,s]),B=(H,Z,G)=>{if(console.warn("[Layout] handleCommandPaletteNavigate called:",{tab:H,itemName:Z,serverId:G}),G){const re=a.find(z=>z.id===G);if(console.warn("[Layout] Server lookup:",{serverId:G,serverFound:!!re,serverState:re?.state}),!re||re.state!=="ready"){console.warn("[Layout] Server not ready, showing error"),Xt.error("Server is not connected and cannot be inspected");return}console.warn("[Layout] Calling navigateToItem:",{serverId:G,tab:H,itemName:Z}),g(G,H,Z);const j=new URLSearchParams(n.search).get("tunnelUrl"),V=j?`/?server=${encodeURIComponent(G)}&tunnelUrl=${encodeURIComponent(j)}`:`/?server=${encodeURIComponent(G)}`;console.warn("[Layout] Navigating to:",V),t(V)}else console.warn("[Layout] No serverId, just updating tab to:",H),h(H)},K=a.find(H=>H.id===u),ee=K?K.tools.map(H=>({...H,_serverId:K.id})):a.flatMap(H=>H.state==="ready"?H.tools.map(Z=>({...Z,_serverId:H.id,_serverName:H.name})):[]),te=K?K.prompts.map(H=>({...H,_serverId:K.id})):a.flatMap(H=>H.state==="ready"?H.prompts.map(Z=>({...Z,_serverId:H.id,_serverName:H.name})):[]),ae=K?K.resources.map(H=>({...H,_serverId:K.id})):a.flatMap(H=>H.state==="ready"?H.resources.map(Z=>({...Z,_serverId:H.id,_serverName:H.name})):[]);return w.useEffect(()=>{const Z=new URLSearchParams(n.search).get("server"),G=Z?decodeURIComponent(Z):null;G!==u&&d(G)},[n.search,u,d]),w.useEffect(()=>{const Z=new URLSearchParams(n.search).get("server");if(!Z)return;const G=decodeURIComponent(Z),re=a.find(ne=>ne.id===G);if(!re){const ne=setTimeout(()=>t("/"),3e3);return()=>clearTimeout(ne)}if(re.state==="failed"){const ne=setTimeout(()=>t("/"),2e3);return()=>clearTimeout(ne)}},[n.search,t,a]),SK({onCommandPalette:()=>A("keyboard"),onToolsTab:()=>{K&&h("tools")},onPromptsTab:()=>{K&&h("prompts")},onResourcesTab:()=>{K&&h("resources")},onChatTab:()=>{K&&h("chat")},onHome:()=>{t("/")},onFocusSearch:()=>{m==="tools"&&k.current?k.current.focusSearch():m==="prompts"&&C.current?C.current.focusSearch():m==="resources"&&R.current&&R.current.focusSearch()},onBlurSearch:()=>{m==="tools"&&k.current?k.current.blurSearch():m==="prompts"&&C.current?C.current.blurSearch():m==="resources"&&R.current&&R.current.blurSearch()}}),I?f.jsx("div",{className:"h-screen bg-white dark:bg-zinc-900 flex items-center justify-center",children:f.jsxs("div",{className:"flex flex-col items-center gap-4",children:[f.jsx(ki,{className:"h-8 w-8 text-zinc-600 dark:text-zinc-400"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Connecting to MCP server..."})]})}):f.jsx(ZN,{children:f.jsxs("div",{className:"h-screen bg-[#f3f3f3] dark:bg-black flex flex-col px-2 py-2 sm:px-4 sm:py-4 gap-2 sm:gap-4",children:[f.jsx(BTe,{connections:a,selectedServer:K,activeTab:m,onServerSelect:O,onTabChange:h,onCommandPaletteOpen:()=>A("button"),onOpenConnectionOptions:M}),f.jsx("main",{className:"flex-1 w-full mx-auto bg-white dark:bg-black rounded-2xl border border-zinc-200 dark:border-zinc-700 p-0 overflow-auto",children:f.jsx(MTe,{selectedServer:K,activeTab:m,toolsSearchRef:k,promptsSearchRef:C,resourcesSearchRef:R,children:e})}),f.jsx(ASe,{isOpen:x,onOpenChange:S,tools:ee,prompts:te,resources:ae,savedRequests:_,connections:a,onNavigate:B,onServerSelect:O}),f.jsx(M7,{connection:y&&a.find(H=>H.id===y)||null,open:y!==null,onOpenChange:H=>{H||E(null)},onConnect:P})]})})}function VTe(){const[e,t]=w.useState("processing"),[n,a]=w.useState("");return w.useEffect(()=>{console.log("[OAuthCallback] Component mounted, handling authorization..."),console.log("[OAuthCallback] Current URL:",window.location.href),vN().then(()=>{console.log("[OAuthCallback] Authorization successful"),t("success")}).catch(r=>{console.error("[OAuthCallback] Authorization failed:",r),t("error"),a(r instanceof Error?r.message:String(r))})},[]),e==="processing"?f.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:f.jsxs("div",{className:"flex flex-col items-center gap-4",children:[f.jsx(zs,{className:"h-8 w-8 animate-spin text-zinc-600 dark:text-zinc-400"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Completing authentication..."})]})}):e==="error"?f.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:f.jsxs("div",{className:"max-w-md p-6",children:[f.jsx("h1",{className:"text-xl font-semibold text-red-600 dark:text-red-400 mb-2",children:"Authentication Error"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400 mb-4",children:n}),f.jsx("p",{className:"text-xs text-zinc-500 dark:text-zinc-500",children:"You can close this window and try again."})]})}):f.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:f.jsxs("div",{className:"max-w-md p-6",children:[f.jsx("h1",{className:"text-xl font-semibold text-green-600 dark:text-green-400 mb-2",children:"Authentication Successful!"}),f.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Redirecting you back..."})]})})}var GTe=(e,t,n,a,r,i,s,c)=>{let u=document.documentElement,d=["light","dark"];function m(v){(Array.isArray(e)?e:[e]).forEach(x=>{let S=x==="class",y=S&&i?r.map(E=>i[E]||E):r;S?(u.classList.remove(...y),u.classList.add(i&&i[v]?i[v]:v)):u.setAttribute(x,v)}),h(v)}function h(v){c&&d.includes(v)&&(u.style.colorScheme=v)}function g(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(a)m(a);else try{let v=localStorage.getItem(t)||n,x=s&&v==="system"?g():v;m(x)}catch{}},WTe=w.createContext(void 0),KTe={setTheme:e=>{},themes:[]},ZTe=()=>{var e;return(e=w.useContext(WTe))!=null?e:KTe};w.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:a,enableColorScheme:r,defaultTheme:i,value:s,themes:c,nonce:u,scriptProps:d})=>{let m=JSON.stringify([n,t,i,e,c,s,a,r]).slice(1,-1);return w.createElement("script",{...d,suppressHydrationWarning:!0,nonce:typeof window>"u"?u:"",dangerouslySetInnerHTML:{__html:`(${GTe.toString()})(${m})`}})});function YTe({...e}){const{theme:t="system"}=ZTe();return f.jsx(HG,{theme:t,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...e})}function qTe(){return f.jsx(vEe,{children:f.jsx(sme,{children:f.jsxs(tSe,{children:[f.jsx(ile,{basename:"/inspector",children:f.jsxs(Lse,{children:[f.jsx(j_,{path:"/oauth/callback",element:f.jsx(VTe,{})}),f.jsx(j_,{path:"/",element:f.jsx(HTe,{children:f.jsx(eSe,{})})})]})}),f.jsx(YTe,{position:"top-center"})]})})})}const iF=new URLSearchParams(window.location.search);if(iF.has("code")||iF.has("error"))try{vN()}catch(e){console.error("[inspector] OAuth callback error:",e)}const oF=document.getElementById("root");oF?Voe.createRoot(oF).render(f.jsx(qTe,{})):console.error("[inspector] Root element not found");export{kB as $,AF as A,DF as B,L6 as C,EB as D,_oe as E,Jb as F,Ce as G,Noe as H,Eoe as I,Cb as J,ZP as K,ks as L,xoe as M,koe as N,Ll as O,ov as P,Ot as Q,ue as R,u6 as S,zi as T,vF as U,RJ as V,Ob as W,uF as X,Coe as Y,$ne as Z,ze as _,Jn as a,bJ as a0,vN as a1,IJ as a2,kd as b,ny as c,od as d,LT as e,Cne as f,JTe as g,hne as h,wy as i,sd as j,F5 as k,Nb as l,a_ as m,iv as n,Jf as o,FF as p,UT as q,w as r,Op as s,lu as t,id as u,vi as v,i_ as w,ni as x,M6 as y,HB as z};