@mcp-use/inspector 0.12.0 → 0.12.1-canary.0

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-C9XdstMd.js","assets/util-t-trnxQI.js","assets/__vite-browser-external-D7Ct-6yo.js","assets/index-DRz5BQNA.js","assets/path-C2bN6h38.js","assets/index-D3h9OtLD.js","assets/index-D4BJ-4dv.js","assets/index-CNOfsJmB.js","assets/index-C1PULc-j.js","assets/embeddings-DN38A_vZ.js","assets/index-B-y3tpvd.js","assets/index-DVE3PVDT.js","assets/browser-Cx0JHZqb.js"])))=>i.map(i=>d[i]);
2
- var vG=Object.defineProperty;var wG=(e,t,n)=>t in e?vG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ef=(e,t,n)=>wG(e,typeof t!="symbol"?t+"":t,n);function EG(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const a in r)if(a!=="default"&&!(a in e)){const s=Object.getOwnPropertyDescriptor(r,a);s&&Object.defineProperty(e,a,s.get?s:{enumerable:!0,get:()=>r[a]})}}}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 a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const s of a)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(a){const s={};return a.integrity&&(s.integrity=a.integrity),a.referrerPolicy&&(s.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?s.credentials="include":a.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(a){if(a.ep)return;a.ep=!0;const s=n(a);fetch(a.href,s)}})();function jp(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function w0e(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var a=!1;try{a=this instanceof r}catch{}return a?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(r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}),n}var Ow={exports:{}},xf={};var SL;function xG(){if(SL)return xf;SL=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,a,s){var i=null;if(s!==void 0&&(i=""+s),a.key!==void 0&&(i=""+a.key),"key"in a){s={};for(var c in a)c!=="key"&&(s[c]=a[c])}else s=a;return a=s.ref,{$$typeof:e,type:r,key:i,ref:a!==void 0?a:null,props:s}}return xf.Fragment=t,xf.jsx=n,xf.jsxs=n,xf}var _L;function SG(){return _L||(_L=1,Ow.exports=xG()),Ow.exports}var d=SG();const _G="modulepreload",TG=function(e){return"/inspector/"+e},TL={},rr=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){let u=function(f){return Promise.all(f.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=i?.nonce||i?.getAttribute("nonce");a=u(n.map(f=>{if(f=TG(f),f in TL)return;TL[f]=!0;const m=f.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":_G,m||(g.as="script"),g.crossOrigin="",g.href=f,c&&g.setAttribute("nonce",c),document.head.appendChild(g),m)return new Promise((y,x)=>{g.addEventListener("load",y),g.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${f}`)))})}))}function s(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&s(c.reason);return t().catch(s)})};var NG=Object.defineProperty,Pe=(e,t)=>NG(e,"name",{value:t,configurable:!0}),wi=(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')}),$c={};async function Tz(){if(typeof process<"u")try{const e=await rr(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(n=>n._),[]),t=await rr(()=>import("./path-C2bN6h38.js").then(n=>n.p),[]);return{fs:e.default,path:t.default}}catch{return{fs:null,path:null}}return{fs:null,path:null}}Pe(Tz,"getNodeModules");var ja=null;function Nz(){if(typeof wi<"u")try{ja=wi("winston")}catch{}}Pe(Nz,"loadWinstonSync");async function kz(){return ja||(ja=await rr(()=>import("./winston-C9XdstMd.js").then(e=>e.w),__vite__mapDeps([0,1,2,3,4]))),ja}Pe(kz,"getWinston");var nx="mcp-use";function db(){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}}Pe(db,"isNodeJSEnvironment");var wu,kG=(wu=class{_level;name;constructor(t=nx,n="info"){this.name=t,this._level=n}shouldLog(t){const n=["error","warn","info","http","verbose","debug","silly"],r=n.indexOf(this._level);return n.indexOf(t)<=r}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}},Pe(wu,"SimpleConsoleLogger"),wu);function zg(e){switch((typeof process<"u"&&$c?e:void 0)?.trim()){case"2":return"debug";case"1":return"info";default:return"info"}}Pe(zg,"resolveLevel");var xs,Cz=(xs=class{static get(t=nx){if(!db()){if(!this.simpleInstances[t]){const n=typeof process<"u"&&$c?.DEBUG||void 0;this.simpleInstances[t]=new kG(t,zg(n))}return this.simpleInstances[t]}if(!this.instances[t]){if(!ja)throw new Error("Winston not loaded - call Logger.configure() first");const{createLogger:n,format:r}=ja,{combine:a,timestamp:s,label:i,colorize:c,splat:u}=r;this.instances[t]=n({level:zg($c.DEBUG),format:a(c(),u(),i({label:t}),s({format:"HH:mm:ss"}),this.getFormatter()),transports:[]})}return this.instances[t]}static getFormatter(){if(!ja)throw new Error("Winston not loaded");const{format:t}=ja,{printf:n}=t,r=n(({level:i,message:c,label:u,timestamp:f})=>`${f} [${u}] ${i}: ${c}`),a=n(({level:i,message:c,label:u,timestamp:f})=>`${f} [${u}] ${i.toUpperCase()}: ${c}`),s=n(({level:i,message:c,label:u,timestamp:f})=>`${f} [${u}] ${i.toUpperCase()}: ${c}`);switch(this.currentFormat){case"minimal":return r;case"detailed":return a;case"emoji":return s;default:return r}}static async configure(t={}){const{level:n,console:r=!0,file:a,format:s="minimal"}=t,i=typeof process<"u"&&$c?.DEBUG||void 0,c=n??zg(i);if(this.currentFormat=s,!db()){Object.values(this.simpleInstances).forEach(w=>{w.level=c});return}if(await kz(),!ja)throw new Error("Failed to load winston");const u=this.get();u.level=c;const f=u;if(f.clear(),r&&f.add(new ja.transports.Console),a){const{fs:w,path:_}=await Tz();if(w&&_){const S=_.dirname(_.resolve(a));w.existsSync(S)||w.mkdirSync(S,{recursive:!0}),f.add(new ja.transports.File({filename:a}))}}const{format:m}=ja,{combine:h,timestamp:g,label:y,colorize:x,splat:E}=m;Object.values(this.instances).forEach(w=>{w&&"format"in w&&(w.level=c,w.format=h(x(),E(),y({label:nx}),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(r=>{r.level=n}),Object.values(this.instances).forEach(r=>{r&&(r.level=n)}),typeof process<"u"&&$c&&($c.DEBUG=t?t===!0?"2":String(t):"0")}static setFormat(t){this.currentFormat=t,this.configure({format:t})}},Pe(xs,"Logger"),Ef(xs,"instances",{}),Ef(xs,"simpleInstances",{}),Ef(xs,"currentFormat","minimal"),xs);db()&&(Nz(),ja&&Cz.configure());var ve=Cz.get(),Fg={},Rz=typeof globalThis.Deno<"u";function CG(e){return Rz?globalThis.Deno.env.get(e):Fg[e]}Pe(CG,"getEnv");function RG(){return Rz?globalThis.Deno.cwd():process.cwd()}Pe(RG,"getCwd");function Zc(){return globalThis.crypto.randomUUID()}Pe(Zc,"generateUUID");var AG="1.10.0";function fb(){return AG}Pe(fb,"getPackageVersion");var Eu,ko=(Eu=class{},Pe(Eu,"BaseTelemetryEvent"),Eu),xu,IG=(xu=class extends ko{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}}},Pe(xu,"MCPAgentExecutionEvent"),xu);function Az(e,t){const n=Array.from(e.registrations.tools.values()),r=Array.from(e.registrations.prompts.values()),a=Array.from(e.registrations.resources.values()),s=Array.from(e.registrations.resourceTemplates.values()),i=a.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=i.filter(m=>m.mime_type==="text/html+skybridge"),u=i.filter(m=>m.mime_type==="text/uri-list"||m.mime_type==="text/html"),f=i.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:i.length>0?i:null,prompts:r.length>0?r.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:s.length>0?s.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:f.length>0?f:null,mcpAppsResourcesNumber:f.length}}Pe(Az,"createServerRunEventData");var Su,OG=(Su=class extends ko{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}}},Pe(Su,"ServerRunEvent"),Su),_u,DG=(_u=class extends ko{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}}},Pe(_u,"ServerInitializeEvent"),_u),Tu,LG=(Tu=class extends ko{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}}},Pe(Tu,"ServerToolCallEvent"),Tu),Nu,MG=(Nu=class extends ko{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}}},Pe(Nu,"ServerResourceCallEvent"),Nu),ku,jG=(ku=class extends ko{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}}},Pe(ku,"ServerPromptCallEvent"),ku),Cu,PG=(Cu=class extends ko{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}}},Pe(Cu,"ServerContextEvent"),Cu),Ru,UG=(Ru=class extends ko{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}}},Pe(Ru,"MCPClientInitEvent"),Ru),Au,$G=(Au=class extends ko{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}}},Pe(Au,"ConnectorInitEvent"),Au),Iu,zG=(Iu=class extends ko{constructor(t){super(),this.data=t}get name(){return"client_add_server"}get properties(){const{serverName:t,serverConfig:n}=this.data,r=n.url;return{server_name:t,server_url_domain:r?this._extractHostname(r):null,transport:n.transport??null,has_auth:!!(n.authToken||n.authProvider)}}_extractHostname(t){try{return new URL(t).hostname}catch{return null}}},Pe(Iu,"ClientAddServerEvent"),Iu),Ou,FG=(Ou=class extends ko{constructor(t){super(),this.data=t}get name(){return"client_remove_server"}get properties(){return{server_name:this.data.serverName}}},Pe(Ou,"ClientRemoveServerEvent"),Ou);function Iz(e){return e._llm_type||e.constructor.name.toLowerCase()}Pe(Iz,"getModelProvider");function Oz(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}Pe(Oz,"getModelName");function BG(e){return[Iz(e),Oz(e)]}Pe(BG,"extractModelInfo");var NL="mcp_use_user_id";function Dz(){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"}}Pe(Dz,"detectRuntimeEnvironment");function Lz(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"}}Pe(Lz,"getStorageCapability");var Dw=null;function Mz(){return Dw===null&&(Dw=Dz()),Dw}Pe(Mz,"getRuntimeEnvironment");var Du,HG=(Du=class{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,r=setTimeout(()=>n.abort(),this.timeout),a=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(r),!a.ok)throw new Error(`HTTP error! status: ${a.status}`)}catch(n){ve.debug(`Failed to send Scarf event: ${n}`)}}},Pe(Du,"ScarfEventLogger"),Du),yo,jz=(yo=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=Mz(),this._storageCapability=Lz(this._runtimeEnvironment),this._source=typeof process<"u"&&Fg?.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,ve.debug("Telemetry disabled via environment/localStorage");else if(!n)this._posthogNodeClient=null,this._posthogBrowserClient=null,this._scarfClient=null,ve.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`);else{ve.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."),this._posthogLoading=this._initPostHog();try{this._scarfClient=new HG(this.SCARF_GATEWAY_URL,3e3)}catch(r){ve.warn(`Failed to initialize Scarf telemetry: ${r}`),this._scarfClient=null}}}_checkTelemetryDisabled(){return typeof process<"u"&&Fg?.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 rr(()=>import("./module-DXhXtM9n.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:Pe(()=>{ve.debug("PostHog browser client initialized")},"loaded")}),this._posthogBrowserClient=n}catch(t){ve.warn(`Failed to initialize PostHog browser telemetry: ${t}`),this._posthogBrowserClient=null}}async _initPostHogNode(){try{const{PostHog:t}=await rr(async()=>{const{PostHog:a}=await import("./posthog-node-CuYhrq1Q.js");return{PostHog:a}},[]),n=["cloudflare-workers","edge","deno"].includes(this._runtimeEnvironment),r={host:this.HOST,disableGeoip:!1};n&&(r.flushAt=1,r.flushInterval=0),this._posthogNodeClient=new t(this.PROJECT_API_KEY,r),ve.debug("PostHog Node.js client initialized")}catch(t){ve.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 yo.instance||(yo.instance=new yo),yo.instance}setSource(t){this._source=t,ve.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:this._currUserId=`session-${Zc()}`,ve.debug(`Using session-based user ID (${this._runtimeEnvironment} environment)`);break}this._storageCapability==="filesystem"&&this._currUserId&&this._trackPackageDownloadInternal(this._currUserId,{triggered_by:"user_id_property"}).catch(t=>ve.debug(`Failed to track package download: ${t}`))}catch(t){ve.debug(`Failed to get/create user ID: ${t}`),this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}_getUserIdFromFilesystem(){const t=wi("fs"),n=wi("os"),r=wi("path");if(this._userIdPath||(this._userIdPath=r.join(this._getCacheHome(n,r),"mcp_use_3","telemetry_user_id")),!t.existsSync(this._userIdPath)){ve.debug(`Creating user ID path: ${this._userIdPath}`),t.mkdirSync(r.dirname(this._userIdPath),{recursive:!0});const s=Zc();return t.writeFileSync(this._userIdPath,s),ve.debug(`User ID path created: ${this._userIdPath}`),s}return t.readFileSync(this._userIdPath,"utf-8").trim()}_getUserIdFromLocalStorage(){try{let t=localStorage.getItem(NL);return t||(t=Zc(),localStorage.setItem(NL,t),ve.debug("Created new browser user ID")),t}catch(t){return ve.debug(`localStorage access failed: ${t}`),`session-${Zc()}`}}_getCacheHome(t,n){const r=Fg.XDG_CACHE_HOME;if(r&&n.isAbsolute(r))return r;const a=t.homedir();return n.join(a,".cache")}async capture(t){if(this._posthogLoading&&await this._posthogLoading,!this._posthogNodeClient&&!this._posthogBrowserClient&&!this._scarfClient)return;const n={...t.properties};if(n.mcp_use_version=fb(),n.language="typescript",n.source=this._source,n.runtime=this._runtimeEnvironment,this._posthogNodeClient)try{ve.debug(`CAPTURE: PostHog Node Event ${t.name}`),this._posthogNodeClient.capture({distinctId:this.userId,event:t.name,properties:n})}catch(r){ve.debug(`Failed to track PostHog Node event ${t.name}: ${r}`)}if(this._posthogBrowserClient)try{ve.debug(`CAPTURE: PostHog Browser Event ${t.name}`),this._posthogBrowserClient.capture(t.name,{...n,distinct_id:this.userId})}catch(r){ve.debug(`Failed to track PostHog Browser event ${t.name}: ${r}`)}if(this._scarfClient)try{const r={...n,user_id:this.userId,event:t.name};await this._scarfClient.logEvent(r)}catch(r){ve.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 r=wi("fs"),a=wi("path"),s=wi("os");this._versionDownloadPath||(this._versionDownloadPath=a.join(this._getCacheHome(s,a),"mcp_use","download_version"));const i=fb();let c=!1,u=!1;if(!r.existsSync(this._versionDownloadPath))c=!0,u=!0,r.mkdirSync(a.dirname(this._versionDownloadPath),{recursive:!0}),r.writeFileSync(this._versionDownloadPath,i);else{const f=r.readFileSync(this._versionDownloadPath,"utf-8").trim();i>f&&(c=!0,u=!1,r.writeFileSync(this._versionDownloadPath,i))}if(c){ve.debug(`Tracking package download event with properties: ${JSON.stringify(n)}`);const f={...n||{}};f.mcp_use_version=i,f.user_id=t,f.event="package_download",f.first_download=u,f.language="typescript",f.source=this._source,f.runtime=this._runtimeEnvironment,await this._scarfClient.logEvent(f)}}catch(r){ve.debug(`Failed to track Scarf package_download event: ${r}`)}}async trackAgentExecution(t){if(!this.isEnabled)return;const n=new IG(t);await this.capture(n)}async trackServerRunFromServer(t,n){if(!this.isEnabled)return;const r=Az(t,n),a=new OG(r);await this.capture(a)}async trackServerInitialize(t){if(!this.isEnabled)return;const n=new DG(t);await this.capture(n)}async trackServerToolCall(t){if(!this.isEnabled)return;const n=new LG(t);await this.capture(n)}async trackServerResourceCall(t){if(!this.isEnabled)return;const n=new MG(t);await this.capture(n)}async trackServerPromptCall(t){if(!this.isEnabled)return;const n=new jG(t);await this.capture(n)}async trackServerContext(t){if(!this.isEnabled)return;const n=new PG(t);await this.capture(n)}async trackMCPClientInit(t){if(!this.isEnabled)return;const n=new UG(t);await this.capture(n)}async trackConnectorInit(t){if(!this.isEnabled)return;const n=new $G(t);await this.capture(n)}async trackClientAddServer(t,n){if(!this.isEnabled)return;const r=new zG({serverName:t,serverConfig:n});await this.capture(r)}async trackClientRemoveServer(t){if(!this.isEnabled)return;const n=new FG({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(r){ve.debug(`Failed to identify user: ${r}`)}}reset(){if(this._posthogBrowserClient)try{this._posthogBrowserClient.reset()}catch(t){ve.debug(`Failed to reset user: ${t}`)}this._currUserId=null}flush(){if(this._posthogNodeClient)try{this._posthogNodeClient.flush(),ve.debug("PostHog client telemetry queue flushed")}catch(t){ve.debug(`Failed to flush PostHog client: ${t}`)}}shutdown(){if(this._posthogNodeClient)try{this._posthogNodeClient.shutdown(),ve.debug("PostHog client shutdown successfully")}catch(t){ve.debug(`Error shutting down PostHog client: ${t}`)}}},Pe(yo,"Telemetry"),Ef(yo,"instance",null),yo),Uo=jz;function VG(e){Uo.getInstance().setSource(e)}Pe(VG,"setTelemetrySource");const GG=Object.freeze({status:"aborted"});function _e(e,t,n){function r(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);const f=i.prototype,m=Object.keys(f);for(let h=0;h<m.length;h++){const g=m[h];g in c||(c[g]=f[g].bind(c))}}const a=n?.Parent??Object;class s extends a{}Object.defineProperty(s,"name",{value:e});function i(c){var u;const f=n?.Parent?new s:this;r(f,c),(u=f._zod).deferred??(u.deferred=[]);for(const m of f._zod.deferred)m();return f}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class uu extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Pz extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const rx={};function Ai(e){return e&&Object.assign(rx,e),rx}function WG(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,a])=>t.indexOf(+r)===-1).map(([r,a])=>a)}function E0e(e,t="|"){return e.map(n=>XG(n)).join(t)}function ax(e,t){return typeof t=="bigint"?t.toString():t}function dy(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function n_(e){return e==null}function r_(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function KG(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let a=(r.split(".")[1]||"").length;if(a===0&&/\d?e-\d?/.test(r)){const u=r.match(/\d?e-(\d?)/);u?.[1]&&(a=Number.parseInt(u[1]))}const s=n>a?n:a,i=Number.parseInt(e.toFixed(s).replace(".","")),c=Number.parseInt(t.toFixed(s).replace(".",""));return i%c/10**s}const kL=Symbol("evaluating");function Nn(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==kL)return r===void 0&&(r=kL,r=n()),r},set(a){Object.defineProperty(e,t,{value:a})},configurable:!0})}function zl(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Fl(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function CL(e){return JSON.stringify(e)}function YG(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Uz="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function lp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const ZG=dy(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Vu(e){if(lp(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(lp(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function $z(e){return Vu(e)?{...e}:Array.isArray(e)?[...e]:e}const qG=new Set(["string","number","symbol"]);function Gu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $i(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function Qe(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 XG(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function JG(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const QG={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]};function e7(e,t){const n=e._zod.def,r=Fl(e._zod.def,{get shape(){const a={};for(const s in t){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(a[s]=n.shape[s])}return zl(this,"shape",a),a},checks:[]});return $i(e,r)}function t7(e,t){const n=e._zod.def,r=Fl(e._zod.def,{get shape(){const a={...e._zod.def.shape};for(const s in t){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&delete a[s]}return zl(this,"shape",a),a},checks:[]});return $i(e,r)}function n7(e,t){if(!Vu(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 a=Fl(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return zl(this,"shape",s),s},checks:[]});return $i(e,a)}function r7(e,t){if(!Vu(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return zl(this,"shape",r),r},checks:e._zod.def.checks};return $i(e,n)}function a7(e,t){const n=Fl(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return zl(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return $i(e,n)}function o7(e,t,n){const r=Fl(t._zod.def,{get shape(){const a=t._zod.def.shape,s={...a};if(n)for(const i in n){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=e?new e({type:"optional",innerType:a[i]}):a[i])}else for(const i in a)s[i]=e?new e({type:"optional",innerType:a[i]}):a[i];return zl(this,"shape",s),s},checks:[]});return $i(t,r)}function s7(e,t,n){const r=Fl(t._zod.def,{get shape(){const a=t._zod.def.shape,s={...a};if(n)for(const i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=new e({type:"nonoptional",innerType:a[i]}))}else for(const i in a)s[i]=new e({type:"nonoptional",innerType:a[i]});return zl(this,"shape",s),s},checks:[]});return $i(t,r)}function qc(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 Xc(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function kh(e){return typeof e=="string"?e:e?.message}function Ii(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const a=kh(e.inst?._zod.def?.error?.(e))??kh(t?.error?.(e))??kh(n.customError?.(e))??kh(n.localeError?.(e))??"Invalid input";r.message=a}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function a_(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function cp(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const zz=(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,ax,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Fz=_e("$ZodError",zz),fy=_e("$ZodError",zz,{Parent:Error});function i7(e,t=n=>n.message){const n={},r=[];for(const a of e.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(t(a))):r.push(t(a));return{formErrors:r,fieldErrors:n}}function l7(e,t=n=>n.message){const n={_errors:[]},r=a=>{for(const s of a.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(i=>r({issues:i}));else if(s.code==="invalid_key")r({issues:s.issues});else if(s.code==="invalid_element")r({issues:s.issues});else if(s.path.length===0)n._errors.push(t(s));else{let i=n,c=0;for(;c<s.path.length;){const u=s.path[c];c===s.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(t(s))):i[u]=i[u]||{_errors:[]},i=i[u],c++}}};return r(e),n}function c7(e){const t=[],n=e.map(r=>typeof r=="object"?r.key:r);for(const r of n)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function x0e(e){const t=[],n=[...e.issues].sort((r,a)=>(r.path??[]).length-(a.path??[]).length);for(const r of n)t.push(`✖ ${r.message}`),r.path?.length&&t.push(` → at ${c7(r.path)}`);return t.join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/winston-Bk62c_ba.js","assets/util-t-trnxQI.js","assets/__vite-browser-external-D7Ct-6yo.js","assets/index-DRz5BQNA.js","assets/path-C2bN6h38.js","assets/index-BNQethI5.js","assets/index-DTNvsjCH.js","assets/index-Dspemk6u.js","assets/index-8LNRwM-o.js","assets/embeddings-O3HQNRu6.js","assets/index-CZpbYyd9.js","assets/index-BRUKWgxH.js","assets/browser-C3nhYEaN.js"])))=>i.map(i=>d[i]);
2
+ var vG=Object.defineProperty;var wG=(e,t,n)=>t in e?vG(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Ef=(e,t,n)=>wG(e,typeof t!="symbol"?t+"":t,n);function EG(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const a in r)if(a!=="default"&&!(a in e)){const s=Object.getOwnPropertyDescriptor(r,a);s&&Object.defineProperty(e,a,s.get?s:{enumerable:!0,get:()=>r[a]})}}}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 a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const s of a)if(s.type==="childList")for(const i of s.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(a){const s={};return a.integrity&&(s.integrity=a.integrity),a.referrerPolicy&&(s.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?s.credentials="include":a.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(a){if(a.ep)return;a.ep=!0;const s=n(a);fetch(a.href,s)}})();function jp(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function w0e(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var a=!1;try{a=this instanceof r}catch{}return a?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(r){var a=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,a.get?a:{enumerable:!0,get:function(){return e[r]}})}),n}var Ow={exports:{}},xf={};var SL;function xG(){if(SL)return xf;SL=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,a,s){var i=null;if(s!==void 0&&(i=""+s),a.key!==void 0&&(i=""+a.key),"key"in a){s={};for(var c in a)c!=="key"&&(s[c]=a[c])}else s=a;return a=s.ref,{$$typeof:e,type:r,key:i,ref:a!==void 0?a:null,props:s}}return xf.Fragment=t,xf.jsx=n,xf.jsxs=n,xf}var _L;function SG(){return _L||(_L=1,Ow.exports=xG()),Ow.exports}var d=SG();const _G="modulepreload",TG=function(e){return"/inspector/"+e},TL={},rr=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){let u=function(f){return Promise.all(f.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=i?.nonce||i?.getAttribute("nonce");a=u(n.map(f=>{if(f=TG(f),f in TL)return;TL[f]=!0;const m=f.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":_G,m||(g.as="script"),g.crossOrigin="",g.href=f,c&&g.setAttribute("nonce",c),document.head.appendChild(g),m)return new Promise((y,x)=>{g.addEventListener("load",y),g.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${f}`)))})}))}function s(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&s(c.reason);return t().catch(s)})};var NG=Object.defineProperty,Pe=(e,t)=>NG(e,"name",{value:t,configurable:!0}),wi=(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')}),$c={};async function Tz(){if(typeof process<"u")try{const e=await rr(()=>import("./__vite-browser-external-D7Ct-6yo.js").then(n=>n._),[]),t=await rr(()=>import("./path-C2bN6h38.js").then(n=>n.p),[]);return{fs:e.default,path:t.default}}catch{return{fs:null,path:null}}return{fs:null,path:null}}Pe(Tz,"getNodeModules");var ja=null;function Nz(){if(typeof wi<"u")try{ja=wi("winston")}catch{}}Pe(Nz,"loadWinstonSync");async function kz(){return ja||(ja=await rr(()=>import("./winston-Bk62c_ba.js").then(e=>e.w),__vite__mapDeps([0,1,2,3,4]))),ja}Pe(kz,"getWinston");var nx="mcp-use";function db(){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}}Pe(db,"isNodeJSEnvironment");var wu,kG=(wu=class{_level;name;constructor(t=nx,n="info"){this.name=t,this._level=n}shouldLog(t){const n=["error","warn","info","http","verbose","debug","silly"],r=n.indexOf(this._level);return n.indexOf(t)<=r}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}},Pe(wu,"SimpleConsoleLogger"),wu);function zg(e){switch((typeof process<"u"&&$c?e:void 0)?.trim()){case"2":return"debug";case"1":return"info";default:return"info"}}Pe(zg,"resolveLevel");var xs,Cz=(xs=class{static get(t=nx){if(!db()){if(!this.simpleInstances[t]){const n=typeof process<"u"&&$c?.DEBUG||void 0;this.simpleInstances[t]=new kG(t,zg(n))}return this.simpleInstances[t]}if(!this.instances[t]){if(!ja)throw new Error("Winston not loaded - call Logger.configure() first");const{createLogger:n,format:r}=ja,{combine:a,timestamp:s,label:i,colorize:c,splat:u}=r;this.instances[t]=n({level:zg($c.DEBUG),format:a(c(),u(),i({label:t}),s({format:"HH:mm:ss"}),this.getFormatter()),transports:[]})}return this.instances[t]}static getFormatter(){if(!ja)throw new Error("Winston not loaded");const{format:t}=ja,{printf:n}=t,r=n(({level:i,message:c,label:u,timestamp:f})=>`${f} [${u}] ${i}: ${c}`),a=n(({level:i,message:c,label:u,timestamp:f})=>`${f} [${u}] ${i.toUpperCase()}: ${c}`),s=n(({level:i,message:c,label:u,timestamp:f})=>`${f} [${u}] ${i.toUpperCase()}: ${c}`);switch(this.currentFormat){case"minimal":return r;case"detailed":return a;case"emoji":return s;default:return r}}static async configure(t={}){const{level:n,console:r=!0,file:a,format:s="minimal"}=t,i=typeof process<"u"&&$c?.DEBUG||void 0,c=n??zg(i);if(this.currentFormat=s,!db()){Object.values(this.simpleInstances).forEach(w=>{w.level=c});return}if(await kz(),!ja)throw new Error("Failed to load winston");const u=this.get();u.level=c;const f=u;if(f.clear(),r&&f.add(new ja.transports.Console),a){const{fs:w,path:_}=await Tz();if(w&&_){const S=_.dirname(_.resolve(a));w.existsSync(S)||w.mkdirSync(S,{recursive:!0}),f.add(new ja.transports.File({filename:a}))}}const{format:m}=ja,{combine:h,timestamp:g,label:y,colorize:x,splat:E}=m;Object.values(this.instances).forEach(w=>{w&&"format"in w&&(w.level=c,w.format=h(x(),E(),y({label:nx}),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(r=>{r.level=n}),Object.values(this.instances).forEach(r=>{r&&(r.level=n)}),typeof process<"u"&&$c&&($c.DEBUG=t?t===!0?"2":String(t):"0")}static setFormat(t){this.currentFormat=t,this.configure({format:t})}},Pe(xs,"Logger"),Ef(xs,"instances",{}),Ef(xs,"simpleInstances",{}),Ef(xs,"currentFormat","minimal"),xs);db()&&(Nz(),ja&&Cz.configure());var ve=Cz.get(),Fg={},Rz=typeof globalThis.Deno<"u";function CG(e){return Rz?globalThis.Deno.env.get(e):Fg[e]}Pe(CG,"getEnv");function RG(){return Rz?globalThis.Deno.cwd():process.cwd()}Pe(RG,"getCwd");function Zc(){return globalThis.crypto.randomUUID()}Pe(Zc,"generateUUID");var AG="1.10.1-canary.0";function fb(){return AG}Pe(fb,"getPackageVersion");var Eu,ko=(Eu=class{},Pe(Eu,"BaseTelemetryEvent"),Eu),xu,IG=(xu=class extends ko{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}}},Pe(xu,"MCPAgentExecutionEvent"),xu);function Az(e,t){const n=Array.from(e.registrations.tools.values()),r=Array.from(e.registrations.prompts.values()),a=Array.from(e.registrations.resources.values()),s=Array.from(e.registrations.resourceTemplates.values()),i=a.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=i.filter(m=>m.mime_type==="text/html+skybridge"),u=i.filter(m=>m.mime_type==="text/uri-list"||m.mime_type==="text/html"),f=i.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:i.length>0?i:null,prompts:r.length>0?r.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:s.length>0?s.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:f.length>0?f:null,mcpAppsResourcesNumber:f.length}}Pe(Az,"createServerRunEventData");var Su,OG=(Su=class extends ko{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}}},Pe(Su,"ServerRunEvent"),Su),_u,DG=(_u=class extends ko{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}}},Pe(_u,"ServerInitializeEvent"),_u),Tu,LG=(Tu=class extends ko{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}}},Pe(Tu,"ServerToolCallEvent"),Tu),Nu,MG=(Nu=class extends ko{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}}},Pe(Nu,"ServerResourceCallEvent"),Nu),ku,jG=(ku=class extends ko{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}}},Pe(ku,"ServerPromptCallEvent"),ku),Cu,PG=(Cu=class extends ko{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}}},Pe(Cu,"ServerContextEvent"),Cu),Ru,UG=(Ru=class extends ko{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}}},Pe(Ru,"MCPClientInitEvent"),Ru),Au,$G=(Au=class extends ko{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}}},Pe(Au,"ConnectorInitEvent"),Au),Iu,zG=(Iu=class extends ko{constructor(t){super(),this.data=t}get name(){return"client_add_server"}get properties(){const{serverName:t,serverConfig:n}=this.data,r=n.url;return{server_name:t,server_url_domain:r?this._extractHostname(r):null,transport:n.transport??null,has_auth:!!(n.authToken||n.authProvider)}}_extractHostname(t){try{return new URL(t).hostname}catch{return null}}},Pe(Iu,"ClientAddServerEvent"),Iu),Ou,FG=(Ou=class extends ko{constructor(t){super(),this.data=t}get name(){return"client_remove_server"}get properties(){return{server_name:this.data.serverName}}},Pe(Ou,"ClientRemoveServerEvent"),Ou);function Iz(e){return e._llm_type||e.constructor.name.toLowerCase()}Pe(Iz,"getModelProvider");function Oz(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}Pe(Oz,"getModelName");function BG(e){return[Iz(e),Oz(e)]}Pe(BG,"extractModelInfo");var NL="mcp_use_user_id";function Dz(){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"}}Pe(Dz,"detectRuntimeEnvironment");function Lz(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"}}Pe(Lz,"getStorageCapability");var Dw=null;function Mz(){return Dw===null&&(Dw=Dz()),Dw}Pe(Mz,"getRuntimeEnvironment");var Du,HG=(Du=class{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,r=setTimeout(()=>n.abort(),this.timeout),a=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(r),!a.ok)throw new Error(`HTTP error! status: ${a.status}`)}catch(n){ve.debug(`Failed to send Scarf event: ${n}`)}}},Pe(Du,"ScarfEventLogger"),Du),yo,jz=(yo=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=Mz(),this._storageCapability=Lz(this._runtimeEnvironment),this._source=typeof process<"u"&&Fg?.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,ve.debug("Telemetry disabled via environment/localStorage");else if(!n)this._posthogNodeClient=null,this._posthogBrowserClient=null,this._scarfClient=null,ve.debug(`Telemetry disabled - unknown environment: ${this._runtimeEnvironment}`);else{ve.info("Anonymized telemetry enabled. Set MCP_USE_ANONYMIZED_TELEMETRY=false to disable."),this._posthogLoading=this._initPostHog();try{this._scarfClient=new HG(this.SCARF_GATEWAY_URL,3e3)}catch(r){ve.warn(`Failed to initialize Scarf telemetry: ${r}`),this._scarfClient=null}}}_checkTelemetryDisabled(){return typeof process<"u"&&Fg?.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 rr(()=>import("./module-DXhXtM9n.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:Pe(()=>{ve.debug("PostHog browser client initialized")},"loaded")}),this._posthogBrowserClient=n}catch(t){ve.warn(`Failed to initialize PostHog browser telemetry: ${t}`),this._posthogBrowserClient=null}}async _initPostHogNode(){try{const{PostHog:t}=await rr(async()=>{const{PostHog:a}=await import("./posthog-node-CuYhrq1Q.js");return{PostHog:a}},[]),n=["cloudflare-workers","edge","deno"].includes(this._runtimeEnvironment),r={host:this.HOST,disableGeoip:!1};n&&(r.flushAt=1,r.flushInterval=0),this._posthogNodeClient=new t(this.PROJECT_API_KEY,r),ve.debug("PostHog Node.js client initialized")}catch(t){ve.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 yo.instance||(yo.instance=new yo),yo.instance}setSource(t){this._source=t,ve.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:this._currUserId=`session-${Zc()}`,ve.debug(`Using session-based user ID (${this._runtimeEnvironment} environment)`);break}this._storageCapability==="filesystem"&&this._currUserId&&this._trackPackageDownloadInternal(this._currUserId,{triggered_by:"user_id_property"}).catch(t=>ve.debug(`Failed to track package download: ${t}`))}catch(t){ve.debug(`Failed to get/create user ID: ${t}`),this._currUserId=this.UNKNOWN_USER_ID}return this._currUserId}_getUserIdFromFilesystem(){const t=wi("fs"),n=wi("os"),r=wi("path");if(this._userIdPath||(this._userIdPath=r.join(this._getCacheHome(n,r),"mcp_use_3","telemetry_user_id")),!t.existsSync(this._userIdPath)){ve.debug(`Creating user ID path: ${this._userIdPath}`),t.mkdirSync(r.dirname(this._userIdPath),{recursive:!0});const s=Zc();return t.writeFileSync(this._userIdPath,s),ve.debug(`User ID path created: ${this._userIdPath}`),s}return t.readFileSync(this._userIdPath,"utf-8").trim()}_getUserIdFromLocalStorage(){try{let t=localStorage.getItem(NL);return t||(t=Zc(),localStorage.setItem(NL,t),ve.debug("Created new browser user ID")),t}catch(t){return ve.debug(`localStorage access failed: ${t}`),`session-${Zc()}`}}_getCacheHome(t,n){const r=Fg.XDG_CACHE_HOME;if(r&&n.isAbsolute(r))return r;const a=t.homedir();return n.join(a,".cache")}async capture(t){if(this._posthogLoading&&await this._posthogLoading,!this._posthogNodeClient&&!this._posthogBrowserClient&&!this._scarfClient)return;const n={...t.properties};if(n.mcp_use_version=fb(),n.language="typescript",n.source=this._source,n.runtime=this._runtimeEnvironment,this._posthogNodeClient)try{ve.debug(`CAPTURE: PostHog Node Event ${t.name}`),this._posthogNodeClient.capture({distinctId:this.userId,event:t.name,properties:n})}catch(r){ve.debug(`Failed to track PostHog Node event ${t.name}: ${r}`)}if(this._posthogBrowserClient)try{ve.debug(`CAPTURE: PostHog Browser Event ${t.name}`),this._posthogBrowserClient.capture(t.name,{...n,distinct_id:this.userId})}catch(r){ve.debug(`Failed to track PostHog Browser event ${t.name}: ${r}`)}if(this._scarfClient)try{const r={...n,user_id:this.userId,event:t.name};await this._scarfClient.logEvent(r)}catch(r){ve.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 r=wi("fs"),a=wi("path"),s=wi("os");this._versionDownloadPath||(this._versionDownloadPath=a.join(this._getCacheHome(s,a),"mcp_use","download_version"));const i=fb();let c=!1,u=!1;if(!r.existsSync(this._versionDownloadPath))c=!0,u=!0,r.mkdirSync(a.dirname(this._versionDownloadPath),{recursive:!0}),r.writeFileSync(this._versionDownloadPath,i);else{const f=r.readFileSync(this._versionDownloadPath,"utf-8").trim();i>f&&(c=!0,u=!1,r.writeFileSync(this._versionDownloadPath,i))}if(c){ve.debug(`Tracking package download event with properties: ${JSON.stringify(n)}`);const f={...n||{}};f.mcp_use_version=i,f.user_id=t,f.event="package_download",f.first_download=u,f.language="typescript",f.source=this._source,f.runtime=this._runtimeEnvironment,await this._scarfClient.logEvent(f)}}catch(r){ve.debug(`Failed to track Scarf package_download event: ${r}`)}}async trackAgentExecution(t){if(!this.isEnabled)return;const n=new IG(t);await this.capture(n)}async trackServerRunFromServer(t,n){if(!this.isEnabled)return;const r=Az(t,n),a=new OG(r);await this.capture(a)}async trackServerInitialize(t){if(!this.isEnabled)return;const n=new DG(t);await this.capture(n)}async trackServerToolCall(t){if(!this.isEnabled)return;const n=new LG(t);await this.capture(n)}async trackServerResourceCall(t){if(!this.isEnabled)return;const n=new MG(t);await this.capture(n)}async trackServerPromptCall(t){if(!this.isEnabled)return;const n=new jG(t);await this.capture(n)}async trackServerContext(t){if(!this.isEnabled)return;const n=new PG(t);await this.capture(n)}async trackMCPClientInit(t){if(!this.isEnabled)return;const n=new UG(t);await this.capture(n)}async trackConnectorInit(t){if(!this.isEnabled)return;const n=new $G(t);await this.capture(n)}async trackClientAddServer(t,n){if(!this.isEnabled)return;const r=new zG({serverName:t,serverConfig:n});await this.capture(r)}async trackClientRemoveServer(t){if(!this.isEnabled)return;const n=new FG({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(r){ve.debug(`Failed to identify user: ${r}`)}}reset(){if(this._posthogBrowserClient)try{this._posthogBrowserClient.reset()}catch(t){ve.debug(`Failed to reset user: ${t}`)}this._currUserId=null}flush(){if(this._posthogNodeClient)try{this._posthogNodeClient.flush(),ve.debug("PostHog client telemetry queue flushed")}catch(t){ve.debug(`Failed to flush PostHog client: ${t}`)}}shutdown(){if(this._posthogNodeClient)try{this._posthogNodeClient.shutdown(),ve.debug("PostHog client shutdown successfully")}catch(t){ve.debug(`Error shutting down PostHog client: ${t}`)}}},Pe(yo,"Telemetry"),Ef(yo,"instance",null),yo),Uo=jz;function VG(e){Uo.getInstance().setSource(e)}Pe(VG,"setTelemetrySource");const GG=Object.freeze({status:"aborted"});function _e(e,t,n){function r(c,u){if(c._zod||Object.defineProperty(c,"_zod",{value:{def:u,constr:i,traits:new Set},enumerable:!1}),c._zod.traits.has(e))return;c._zod.traits.add(e),t(c,u);const f=i.prototype,m=Object.keys(f);for(let h=0;h<m.length;h++){const g=m[h];g in c||(c[g]=f[g].bind(c))}}const a=n?.Parent??Object;class s extends a{}Object.defineProperty(s,"name",{value:e});function i(c){var u;const f=n?.Parent?new s:this;r(f,c),(u=f._zod).deferred??(u.deferred=[]);for(const m of f._zod.deferred)m();return f}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:c=>n?.Parent&&c instanceof n.Parent?!0:c?._zod?.traits?.has(e)}),Object.defineProperty(i,"name",{value:e}),i}class uu extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Pz extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const rx={};function Ai(e){return e&&Object.assign(rx,e),rx}function WG(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,a])=>t.indexOf(+r)===-1).map(([r,a])=>a)}function E0e(e,t="|"){return e.map(n=>XG(n)).join(t)}function ax(e,t){return typeof t=="bigint"?t.toString():t}function dy(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function n_(e){return e==null}function r_(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function KG(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let a=(r.split(".")[1]||"").length;if(a===0&&/\d?e-\d?/.test(r)){const u=r.match(/\d?e-(\d?)/);u?.[1]&&(a=Number.parseInt(u[1]))}const s=n>a?n:a,i=Number.parseInt(e.toFixed(s).replace(".","")),c=Number.parseInt(t.toFixed(s).replace(".",""));return i%c/10**s}const kL=Symbol("evaluating");function Nn(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==kL)return r===void 0&&(r=kL,r=n()),r},set(a){Object.defineProperty(e,t,{value:a})},configurable:!0})}function zl(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Fl(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function CL(e){return JSON.stringify(e)}function YG(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const Uz="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function lp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const ZG=dy(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function Vu(e){if(lp(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(lp(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function $z(e){return Vu(e)?{...e}:Array.isArray(e)?[...e]:e}const qG=new Set(["string","number","symbol"]);function Gu(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $i(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function Qe(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 XG(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function JG(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const QG={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]};function e7(e,t){const n=e._zod.def,r=Fl(e._zod.def,{get shape(){const a={};for(const s in t){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(a[s]=n.shape[s])}return zl(this,"shape",a),a},checks:[]});return $i(e,r)}function t7(e,t){const n=e._zod.def,r=Fl(e._zod.def,{get shape(){const a={...e._zod.def.shape};for(const s in t){if(!(s in n.shape))throw new Error(`Unrecognized key: "${s}"`);t[s]&&delete a[s]}return zl(this,"shape",a),a},checks:[]});return $i(e,r)}function n7(e,t){if(!Vu(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 a=Fl(e._zod.def,{get shape(){const s={...e._zod.def.shape,...t};return zl(this,"shape",s),s},checks:[]});return $i(e,a)}function r7(e,t){if(!Vu(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n={...e._zod.def,get shape(){const r={...e._zod.def.shape,...t};return zl(this,"shape",r),r},checks:e._zod.def.checks};return $i(e,n)}function a7(e,t){const n=Fl(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t._zod.def.shape};return zl(this,"shape",r),r},get catchall(){return t._zod.def.catchall},checks:[]});return $i(e,n)}function o7(e,t,n){const r=Fl(t._zod.def,{get shape(){const a=t._zod.def.shape,s={...a};if(n)for(const i in n){if(!(i in a))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=e?new e({type:"optional",innerType:a[i]}):a[i])}else for(const i in a)s[i]=e?new e({type:"optional",innerType:a[i]}):a[i];return zl(this,"shape",s),s},checks:[]});return $i(t,r)}function s7(e,t,n){const r=Fl(t._zod.def,{get shape(){const a=t._zod.def.shape,s={...a};if(n)for(const i in n){if(!(i in s))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(s[i]=new e({type:"nonoptional",innerType:a[i]}))}else for(const i in a)s[i]=new e({type:"nonoptional",innerType:a[i]});return zl(this,"shape",s),s},checks:[]});return $i(t,r)}function qc(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 Xc(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function kh(e){return typeof e=="string"?e:e?.message}function Ii(e,t,n){const r={...e,path:e.path??[]};if(!e.message){const a=kh(e.inst?._zod.def?.error?.(e))??kh(t?.error?.(e))??kh(n.customError?.(e))??kh(n.localeError?.(e))??"Invalid input";r.message=a}return delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function a_(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function cp(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const zz=(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,ax,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},Fz=_e("$ZodError",zz),fy=_e("$ZodError",zz,{Parent:Error});function i7(e,t=n=>n.message){const n={},r=[];for(const a of e.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(t(a))):r.push(t(a));return{formErrors:r,fieldErrors:n}}function l7(e,t=n=>n.message){const n={_errors:[]},r=a=>{for(const s of a.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(i=>r({issues:i}));else if(s.code==="invalid_key")r({issues:s.issues});else if(s.code==="invalid_element")r({issues:s.issues});else if(s.path.length===0)n._errors.push(t(s));else{let i=n,c=0;for(;c<s.path.length;){const u=s.path[c];c===s.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(t(s))):i[u]=i[u]||{_errors:[]},i=i[u],c++}}};return r(e),n}function c7(e){const t=[],n=e.map(r=>typeof r=="object"?r.key:r);for(const r of n)typeof r=="number"?t.push(`[${r}]`):typeof r=="symbol"?t.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?t.push(`[${JSON.stringify(r)}]`):(t.length&&t.push("."),t.push(r));return t.join("")}function x0e(e){const t=[],n=[...e.issues].sort((r,a)=>(r.path??[]).length-(a.path??[]).length);for(const r of n)t.push(`✖ ${r.message}`),r.path?.length&&t.push(` → at ${c7(r.path)}`);return t.join(`
3
3
  `)}const py=e=>(t,n,r,a)=>{const s=r?Object.assign(r,{async:!1}):{async:!1},i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new uu;if(i.issues.length){const c=new(a?.Err??e)(i.issues.map(u=>Ii(u,s,Ai())));throw Uz(c,a?.callee),c}return i.value},S0e=py(fy),my=e=>async(t,n,r,a)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let i=t._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){const c=new(a?.Err??e)(i.issues.map(u=>Ii(u,s,Ai())));throw Uz(c,a?.callee),c}return i.value},_0e=my(fy),hy=e=>(t,n,r)=>{const a=r?{...r,async:!1}:{async:!1},s=t._zod.run({value:n,issues:[]},a);if(s instanceof Promise)throw new uu;return s.issues.length?{success:!1,error:new(e??Fz)(s.issues.map(i=>Ii(i,a,Ai())))}:{success:!0,data:s.value}},Bz=hy(fy),gy=e=>async(t,n,r)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},a);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new e(s.issues.map(i=>Ii(i,a,Ai())))}:{success:!0,data:s.value}},u7=gy(fy),d7=e=>(t,n,r)=>{const a=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return py(e)(t,n,a)},f7=e=>(t,n,r)=>py(e)(t,n,r),p7=e=>async(t,n,r)=>{const a=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return my(e)(t,n,a)},m7=e=>async(t,n,r)=>my(e)(t,n,r),h7=e=>(t,n,r)=>{const a=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return hy(e)(t,n,a)},g7=e=>(t,n,r)=>hy(e)(t,n,r),b7=e=>async(t,n,r)=>{const a=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return gy(e)(t,n,a)},y7=e=>async(t,n,r)=>gy(e)(t,n,r),v7=/^[cC][^\s-]{8,}$/,w7=/^[0-9a-z]+$/,E7=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,x7=/^[0-9a-vA-V]{20}$/,S7=/^[A-Za-z0-9]{27}$/,_7=/^[a-zA-Z0-9_-]{21}$/,T7=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,N7=/^([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})$/,RL=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)$/,k7=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,C7="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function R7(){return new RegExp(C7,"u")}const A7=/^(?:(?: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])$/,I7=/^(([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}|:))$/,O7=/^((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])$/,D7=/^(([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])$/,L7=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Hz=/^[A-Za-z0-9_-]*$/,M7=/^\+(?:[0-9]){6,14}[0-9]$/,Vz="(?:(?:\\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])))",j7=new RegExp(`^${Vz}$`);function Gz(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 P7(e){return new RegExp(`^${Gz(e)}$`)}function U7(e){const t=Gz({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Vz}T(?:${r})$`)}const $7=e=>{const t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},z7=/^-?\d+$/,F7=/^-?\d+(?:\.\d+)?/,B7=/^(?:true|false)$/i,H7=/^null$/i,V7=/^[^A-Z]*$/,G7=/^[^a-z]*$/,xa=_e("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Wz={number:"number",bigint:"bigint",object:"date"},Kz=_e("$ZodCheckLessThan",(e,t)=>{xa.init(e,t);const n=Wz[typeof t.value];e._zod.onattach.push(r=>{const a=r._zod.bag,s=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<s&&(t.inclusive?a.maximum=t.value:a.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Yz=_e("$ZodCheckGreaterThan",(e,t)=>{xa.init(e,t);const n=Wz[typeof t.value];e._zod.onattach.push(r=>{const a=r._zod.bag,s=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>s&&(t.inclusive?a.minimum=t.value:a.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),W7=_e("$ZodCheckMultipleOf",(e,t)=>{xa.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.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):KG(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})}}),K7=_e("$ZodCheckNumberFormat",(e,t)=>{xa.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[a,s]=QG[t.format];e._zod.onattach.push(i=>{const c=i._zod.bag;c.format=t.format,c.minimum=a,c.maximum=s,n&&(c.pattern=z7)}),e._zod.check=i=>{const c=i.value;if(n){if(!Number.isInteger(c)){i.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?i.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort}):i.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,continue:!t.abort});return}}c<a&&i.issues.push({origin:"number",input:c,code:"too_small",minimum:a,inclusive:!0,inst:e,continue:!t.abort}),c>s&&i.issues.push({origin:"number",input:c,code:"too_big",maximum:s,inst:e})}}),Y7=_e("$ZodCheckMaxLength",(e,t)=>{var n;xa.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!n_(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<a&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const a=r.value;if(a.length<=t.maximum)return;const i=a_(a);r.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),Z7=_e("$ZodCheckMinLength",(e,t)=>{var n;xa.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!n_(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const a=r.value;if(a.length>=t.minimum)return;const i=a_(a);r.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),q7=_e("$ZodCheckLengthEquals",(e,t)=>{var n;xa.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!n_(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),e._zod.check=r=>{const a=r.value,s=a.length;if(s===t.length)return;const i=a_(a),c=s>t.length;r.issues.push({origin:i,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),by=_e("$ZodCheckStringFormat",(e,t)=>{var n,r;xa.init(e,t),e._zod.onattach.push(a=>{const s=a._zod.bag;s.format=t.format,t.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),X7=_e("$ZodCheckRegex",(e,t)=>{by.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})}}),J7=_e("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=V7),by.init(e,t)}),Q7=_e("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=G7),by.init(e,t)}),eW=_e("$ZodCheckIncludes",(e,t)=>{xa.init(e,t);const n=Gu(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(a=>{const s=a._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),e._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:e,continue:!t.abort})}}),tW=_e("$ZodCheckStartsWith",(e,t)=>{xa.init(e,t);const n=new RegExp(`^${Gu(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),nW=_e("$ZodCheckEndsWith",(e,t)=>{xa.init(e,t);const n=new RegExp(`.*${Gu(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),rW=_e("$ZodCheckOverwrite",(e,t)=>{xa.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class aW{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 r=t.split(`
4
4
  `).filter(i=>i),a=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.map(i=>i.slice(a)).map(i=>" ".repeat(this.indent*2)+i);for(const i of s)this.content.push(i)}compile(){const t=Function,n=this?.args,a=[...(this?.content??[""]).map(s=>` ${s}`)];return new t(...n,a.join(`
5
5
  `))}}const oW={major:4,minor:1,patch:13},Mn=_e("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=oW;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const a of r)for(const s of a._zod.onattach)s(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const a=(i,c,u)=>{let f=qc(i),m;for(const h of c){if(h._zod.def.when){if(!h._zod.def.when(i))continue}else if(f)continue;const g=i.issues.length,y=h._zod.check(i);if(y instanceof Promise&&u?.async===!1)throw new uu;if(m||y instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await y,i.issues.length!==g&&(f||(f=qc(i,g)))});else{if(i.issues.length===g)continue;f||(f=qc(i,g))}}return m?m.then(()=>i):i},s=(i,c,u)=>{if(qc(i))return i.aborted=!0,i;const f=a(c,r,u);if(f instanceof Promise){if(u.async===!1)throw new uu;return f.then(m=>e._zod.parse(m,u))}return e._zod.parse(f,u)};e._zod.run=(i,c)=>{if(c.skipChecks)return e._zod.parse(i,c);if(c.direction==="backward"){const f=e._zod.parse({value:i.value,issues:[]},{...c,skipChecks:!0});return f instanceof Promise?f.then(m=>s(m,i,c)):s(f,i,c)}const u=e._zod.parse(i,c);if(u instanceof Promise){if(c.async===!1)throw new uu;return u.then(f=>a(f,r,c))}return a(u,r,c)}}e["~standard"]={validate:a=>{try{const s=Bz(e,a);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return u7(e,a).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),o_=_e("$ZodString",(e,t)=>{Mn.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??$7(e._zod.bag),e._zod.parse=(n,r)=>{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}}),zn=_e("$ZodStringFormat",(e,t)=>{by.init(e,t),o_.init(e,t)}),sW=_e("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=N7),zn.init(e,t)}),iW=_e("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=RL(r))}else t.pattern??(t.pattern=RL());zn.init(e,t)}),lW=_e("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=k7),zn.init(e,t)}),cW=_e("$ZodURL",(e,t)=>{zn.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),a=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(a.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(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.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=a.href:n.value=r;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),uW=_e("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=R7()),zn.init(e,t)}),dW=_e("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=_7),zn.init(e,t)}),fW=_e("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=v7),zn.init(e,t)}),pW=_e("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=w7),zn.init(e,t)}),mW=_e("$ZodULID",(e,t)=>{t.pattern??(t.pattern=E7),zn.init(e,t)}),hW=_e("$ZodXID",(e,t)=>{t.pattern??(t.pattern=x7),zn.init(e,t)}),gW=_e("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=S7),zn.init(e,t)}),bW=_e("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=U7(t)),zn.init(e,t)}),yW=_e("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=j7),zn.init(e,t)}),vW=_e("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=P7(t)),zn.init(e,t)}),wW=_e("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=T7),zn.init(e,t)}),EW=_e("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=A7),zn.init(e,t),e._zod.bag.format="ipv4"}),xW=_e("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=I7),zn.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})}}}),SW=_e("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=O7),zn.init(e,t)}),_W=_e("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=D7),zn.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[a,s]=r;if(!s)throw new Error;const i=Number(s);if(`${i}`!==s)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${a}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Zz(e){if(e==="")return!0;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const TW=_e("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=L7),zn.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Zz(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function NW(e){if(!Hz.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Zz(n)}const kW=_e("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Hz),zn.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{NW(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),CW=_e("$ZodE164",(e,t)=>{t.pattern??(t.pattern=M7),zn.init(e,t)});function RW(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const a=JSON.parse(atob(r));return!("typ"in a&&a?.typ!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}const AW=_e("$ZodJWT",(e,t)=>{zn.init(e,t),e._zod.check=n=>{RW(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),qz=_e("$ZodNumber",(e,t)=>{Mn.init(e,t),e._zod.pattern=e._zod.bag.pattern??F7,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const a=n.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return n;const s=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:a,inst:e,...s?{received:s}:{}}),n}}),IW=_e("$ZodNumberFormat",(e,t)=>{K7.init(e,t),qz.init(e,t)}),OW=_e("$ZodBoolean",(e,t)=>{Mn.init(e,t),e._zod.pattern=B7,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const a=n.value;return typeof a=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:e}),n}}),DW=_e("$ZodNull",(e,t)=>{Mn.init(e,t),e._zod.pattern=H7,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const a=n.value;return a===null||n.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),n}}),LW=_e("$ZodAny",(e,t)=>{Mn.init(e,t),e._zod.parse=n=>n}),MW=_e("$ZodUnknown",(e,t)=>{Mn.init(e,t),e._zod.parse=n=>n}),jW=_e("$ZodNever",(e,t)=>{Mn.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function AL(e,t,n){e.issues.length&&t.issues.push(...Xc(n,e.issues)),t.value[n]=e.value}const PW=_e("$ZodArray",(e,t)=>{Mn.init(e,t),e._zod.parse=(n,r)=>{const a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:e}),n;n.value=Array(a.length);const s=[];for(let i=0;i<a.length;i++){const c=a[i],u=t.element._zod.run({value:c,issues:[]},r);u instanceof Promise?s.push(u.then(f=>AL(f,n,i))):AL(u,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function pb(e,t,n,r){e.issues.length&&t.issues.push(...Xc(n,e.issues)),e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function Xz(e){const t=Object.keys(e.shape);for(const r of t)if(!e.shape?.[r]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${r}": expected a Zod schema`);const n=JG(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Jz(e,t,n,r,a,s){const i=[],c=a.keySet,u=a.catchall._zod,f=u.def.type;for(const m in t){if(c.has(m))continue;if(f==="never"){i.push(m);continue}const h=u.run({value:t[m],issues:[]},r);h instanceof Promise?e.push(h.then(g=>pb(g,n,m,t))):pb(h,n,m,t)}return i.length&&n.issues.push({code:"unrecognized_keys",keys:i,input:t,inst:s}),e.length?Promise.all(e).then(()=>n):n}const UW=_e("$ZodObject",(e,t)=>{if(Mn.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 r=dy(()=>Xz(t));Nn(e._zod,"propValues",()=>{const c=t.shape,u={};for(const f in c){const m=c[f]._zod;if(m.values){u[f]??(u[f]=new Set);for(const h of m.values)u[f].add(h)}}return u});const a=lp,s=t.catchall;let i;e._zod.parse=(c,u)=>{i??(i=r.value);const f=c.value;if(!a(f))return c.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),c;c.value={};const m=[],h=i.shape;for(const g of i.keys){const x=h[g]._zod.run({value:f[g],issues:[]},u);x instanceof Promise?m.push(x.then(E=>pb(E,c,g,f))):pb(x,c,g,f)}return s?Jz(m,f,c,u,r.value,e):m.length?Promise.all(m).then(()=>c):c}}),$W=_e("$ZodObjectJIT",(e,t)=>{UW.init(e,t);const n=e._zod.parse,r=dy(()=>Xz(t)),a=g=>{const y=new aW(["shape","payload","ctx"]),x=r.value,E=T=>{const R=CL(T);return`shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`};y.write("const input = payload.value;");const w=Object.create(null);let _=0;for(const T of x.keys)w[T]=`key_${_++}`;y.write("const newResult = {};");for(const T of x.keys){const R=w[T],C=CL(T);y.write(`const ${R} = ${E(T)};`),y.write(`
@@ -30,7 +30,7 @@ var vG=Object.defineProperty;var wG=(e,t,n)=>t in e?vG(e,t,{enumerable:!0,config
30
30
  `;break;case"id":c=w.includes("\0")?void 0:w;break;case"retry":/^\d+$/.test(w)?r(parseInt(w,10)):n(new hj(`Invalid \`retry\` value: "${w}"`,{type:"invalid-retry",value:w,line:_}));break;default:n(new hj(`Unknown field "${E.length>20?`${E.slice(0,20)}…`:E}"`,{type:"unknown-field",field:E,value:w,line:_}));break}}function y(){u.length>0&&t({id:c,event:f||void 0,data:u.endsWith(`
31
31
  `)?u.slice(0,-1):u}),c=void 0,u="",f=""}function x(E={}){s&&E.consume&&h(s),i=!0,c=void 0,u="",f="",s=""}return{feed:m,reset:x}}function DJ(e){const t=[];let n="",r=0;for(;r<e.length;){const a=e.indexOf("\r",r),s=e.indexOf(`
32
32
  `,r);let i=-1;if(a!==-1&&s!==-1?i=Math.min(a,s):a!==-1?a===e.length-1?i=-1:i=a:s!==-1&&(i=s),i===-1){n=e.slice(r);break}else{const c=e.slice(r,i);t.push(c),r=i+1,e[r-1]==="\r"&&e[r]===`
33
- `&&r++}}return[t,n]}class LJ extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let a;super({start(s){a=fF({onEvent:i=>{s.enqueue(i)},onError(i){t==="terminate"?s.error(i):typeof t=="function"&&t(i)},onRetry:n,onComment:r})},transform(s){a.feed(s)}})}}const MJ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class bl extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class jJ{constructor(t,n){var r;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=J2(n?.fetch,n?.requestInit),this._sessionId=n?.sessionId,this._reconnectionOptions=(r=n?.reconnectionOptions)!==null&&r!==void 0?r:MJ}async _authThenStart(){var t;if(!this._authProvider)throw new Ja("No auth provider");let n;try{n=await _s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw(t=this.onerror)===null||t===void 0||t.call(this,r),r}if(n!=="AUTHORIZED")throw new Ja;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const n={};if(this._authProvider){const a=await this._authProvider.tokens();a&&(n.Authorization=`Bearer ${a.access_token}`)}this._sessionId&&(n["mcp-session-id"]=this._sessionId),this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const r=vb((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...r})}async _startOrAuthSse(t){var n,r,a,s;const{resumptionToken:i}=t;try{const c=await this._commonHeaders();c.set("Accept","text/event-stream"),i&&c.set("last-event-id",i);const u=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,{method:"GET",headers:c,signal:(r=this._abortController)===null||r===void 0?void 0:r.signal});if(!u.ok){if(await((a=u.body)===null||a===void 0?void 0:a.cancel()),u.status===401&&this._authProvider)return await this._authThenStart();if(u.status===405)return;throw new bl(u.status,`Failed to open SSE stream: ${u.statusText}`)}this._handleSseStream(u.body,t,!0)}catch(c){throw(s=this.onerror)===null||s===void 0||s.call(this,c),c}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const n=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,a=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(r,t),a)}_scheduleReconnection(t,n=0){var r;const a=this._reconnectionOptions.maxRetries;if(n>=a){(r=this.onerror)===null||r===void 0||r.call(this,new Error(`Maximum reconnection attempts (${a}) exceeded.`));return}const s=this._getNextReconnectionDelay(n);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(i=>{var c;(c=this.onerror)===null||c===void 0||c.call(this,new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(t,n+1)})},s)}_handleSseStream(t,n,r){if(!t)return;const{onresumptiontoken:a,replayMessageId:s}=n;let i,c=!1,u=!1;(async()=>{var m,h,g,y;try{const x=t.pipeThrough(new TextDecoderStream).pipeThrough(new LJ({onRetry:_=>{this._serverRetryMs=_}})).getReader();for(;;){const{value:_,done:S}=await x.read();if(S)break;if(_.id&&(i=_.id,c=!0,a?.(_.id)),!!_.data&&(!_.event||_.event==="message"))try{const T=Bg.parse(JSON.parse(_.data));If(T)&&(u=!0,s!==void 0&&(T.id=s)),(m=this.onmessage)===null||m===void 0||m.call(this,T)}catch(T){(h=this.onerror)===null||h===void 0||h.call(this,T)}}(r||c)&&!u&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:s},0)}catch(x){if((g=this.onerror)===null||g===void 0||g.call(this,new Error(`SSE stream disconnected: ${x}`)),(r||c)&&!u&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:s},0)}catch(_){(y=this.onerror)===null||y===void 0||y.call(this,new Error(`Failed to reconnect: ${_ instanceof Error?_.message:String(_)}`))}}})()}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 Ja("No auth provider");if(await _s(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ja("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 r,a,s,i,c,u,f;try{const{resumptionToken:m,onresumptiontoken:h}=n||{};if(m){this._startOrAuthSse({resumptionToken:m,replayMessageId:lx(t)?t.id:void 0}).catch(T=>{var R;return(R=this.onerror)===null||R===void 0?void 0:R.call(this,T)});return}const g=await this._commonHeaders();g.set("content-type","application/json"),g.set("accept","application/json, text/event-stream");const y={...this._requestInit,method:"POST",headers:g,body:JSON.stringify(t),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},x=await((a=this._fetch)!==null&&a!==void 0?a:fetch)(this._url,y),E=x.headers.get("mcp-session-id");if(E&&(this._sessionId=E),!x.ok){const T=await x.text().catch(()=>null);if(x.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new bl(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:R,scope:C}=dp(x);if(this._resourceMetadataUrl=R,this._scope=C,await _s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ja;return this._hasCompletedAuthFlow=!0,this.send(t)}if(x.status===403&&this._authProvider){const{resourceMetadataUrl:R,scope:C,error:I}=dp(x);if(I==="insufficient_scope"){const A=x.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===A)throw new bl(403,"Server returned 403 after trying upscoping");if(C&&(this._scope=C),R&&(this._resourceMetadataUrl=R),this._lastUpscopingHeader=A??void 0,await _s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Ja;return this.send(t)}}throw new bl(x.status,`Error POSTing to endpoint: ${T}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,x.status===202){await((s=x.body)===null||s===void 0?void 0:s.cancel()),kZ(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(T=>{var R;return(R=this.onerror)===null||R===void 0?void 0:R.call(this,T)});return}const _=(Array.isArray(t)?t:[t]).filter(T=>"method"in T&&"id"in T&&T.id!==void 0).length>0,S=x.headers.get("content-type");if(_)if(S?.includes("text/event-stream"))this._handleSseStream(x.body,{onresumptiontoken:h},!1);else if(S?.includes("application/json")){const T=await x.json(),R=Array.isArray(T)?T.map(C=>Bg.parse(C)):[Bg.parse(T)];for(const C of R)(i=this.onmessage)===null||i===void 0||i.call(this,C)}else throw await((c=x.body)===null||c===void 0?void 0:c.cancel()),new bl(-1,`Unexpected content type: ${S}`);else await((u=x.body)===null||u===void 0?void 0:u.cancel())}catch(m){throw(f=this.onerror)===null||f===void 0||f.call(this,m),m}}get sessionId(){return this._sessionId}async terminateSession(){var t,n,r,a;if(this._sessionId)try{const s=await this._commonHeaders(),i={...this._requestInit,method:"DELETE",headers:s,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,i);if(await((r=c.body)===null||r===void 0?void 0:r.cancel()),!c.ok&&c.status!==405)throw new bl(c.status,`Failed to terminate session: ${c.statusText}`);this._sessionId=void 0}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,n){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:n?.onresumptiontoken})}}class gj extends Event{constructor(t,n){var r,a;super(t),this.code=(r=n?.code)!=null?r:void 0,this.message=(a=n?.message)!=null?a:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,r){return r(bj(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(bj(this),n)}}function PJ(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Ex(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Ex).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Ex(e.cause)}`:e.message:`${e}`}function bj(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var pF=e=>{throw TypeError(e)},O_=(e,t,n)=>t.has(e)||pF("Cannot "+n),Bt=(e,t,n)=>(O_(e,t,"read from private field"),n?n.call(e):t.get(e)),mr=(e,t,n)=>t.has(e)?pF("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Pn=(e,t,n,r)=>(O_(e,t,"write to private field"),t.set(e,n),n),ws=(e,t,n)=>(O_(e,t,"access private method"),n),ya,vl,zc,Vg,_b,Hf,Qc,Vf,Si,Fc,du,Bc,Of,mo,xx,Sx,_x,yj,Tx,Nx,Df,kx,Cx;class Gg extends EventTarget{constructor(t,n){var r,a;super(),mr(this,mo),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,mr(this,ya),mr(this,vl),mr(this,zc),mr(this,Vg),mr(this,_b),mr(this,Hf),mr(this,Qc),mr(this,Vf,null),mr(this,Si),mr(this,Fc),mr(this,du,null),mr(this,Bc,null),mr(this,Of,null),mr(this,Sx,async s=>{var i;Bt(this,Fc).reset();const{body:c,redirected:u,status:f,headers:m}=s;if(f===204){ws(this,mo,Df).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Pn(this,zc,new URL(s.url)):Pn(this,zc,void 0),f!==200){ws(this,mo,Df).call(this,`Non-200 status code (${f})`,f);return}if(!(m.get("content-type")||"").startsWith("text/event-stream")){ws(this,mo,Df).call(this,'Invalid content type, expected "text/event-stream"',f);return}if(Bt(this,ya)===this.CLOSED)return;Pn(this,ya,this.OPEN);const h=new Event("open");if((i=Bt(this,Of))==null||i.call(this,h),this.dispatchEvent(h),typeof c!="object"||!c||!("getReader"in c)){ws(this,mo,Df).call(this,"Invalid response body, expected a web ReadableStream",f),this.close();return}const g=new TextDecoder,y=c.getReader();let x=!0;do{const{done:E,value:w}=await y.read();w&&Bt(this,Fc).feed(g.decode(w,{stream:!E})),E&&(x=!1,Bt(this,Fc).reset(),ws(this,mo,kx).call(this))}while(x)}),mr(this,_x,s=>{Pn(this,Si,void 0),!(s.name==="AbortError"||s.type==="aborted")&&ws(this,mo,kx).call(this,Ex(s))}),mr(this,Tx,s=>{typeof s.id=="string"&&Pn(this,Vf,s.id);const i=new MessageEvent(s.event||"message",{data:s.data,origin:Bt(this,zc)?Bt(this,zc).origin:Bt(this,vl).origin,lastEventId:s.id||""});Bt(this,Bc)&&(!s.event||s.event==="message")&&Bt(this,Bc).call(this,i),this.dispatchEvent(i)}),mr(this,Nx,s=>{Pn(this,Hf,s)}),mr(this,Cx,()=>{Pn(this,Qc,void 0),Bt(this,ya)===this.CONNECTING&&ws(this,mo,xx).call(this)});try{if(t instanceof URL)Pn(this,vl,t);else if(typeof t=="string")Pn(this,vl,new URL(t,UJ()));else throw new Error("Invalid URL")}catch{throw PJ("An invalid or illegal string was specified")}Pn(this,Fc,fF({onEvent:Bt(this,Tx),onRetry:Bt(this,Nx)})),Pn(this,ya,this.CONNECTING),Pn(this,Hf,3e3),Pn(this,_b,(r=n?.fetch)!=null?r:globalThis.fetch),Pn(this,Vg,(a=n?.withCredentials)!=null?a:!1),ws(this,mo,xx).call(this)}get readyState(){return Bt(this,ya)}get url(){return Bt(this,vl).href}get withCredentials(){return Bt(this,Vg)}get onerror(){return Bt(this,du)}set onerror(t){Pn(this,du,t)}get onmessage(){return Bt(this,Bc)}set onmessage(t){Pn(this,Bc,t)}get onopen(){return Bt(this,Of)}set onopen(t){Pn(this,Of,t)}addEventListener(t,n,r){const a=n;super.addEventListener(t,a,r)}removeEventListener(t,n,r){const a=n;super.removeEventListener(t,a,r)}close(){Bt(this,Qc)&&clearTimeout(Bt(this,Qc)),Bt(this,ya)!==this.CLOSED&&(Bt(this,Si)&&Bt(this,Si).abort(),Pn(this,ya,this.CLOSED),Pn(this,Si,void 0))}}ya=new WeakMap,vl=new WeakMap,zc=new WeakMap,Vg=new WeakMap,_b=new WeakMap,Hf=new WeakMap,Qc=new WeakMap,Vf=new WeakMap,Si=new WeakMap,Fc=new WeakMap,du=new WeakMap,Bc=new WeakMap,Of=new WeakMap,mo=new WeakSet,xx=function(){Pn(this,ya,this.CONNECTING),Pn(this,Si,new AbortController),Bt(this,_b)(Bt(this,vl),ws(this,mo,yj).call(this)).then(Bt(this,Sx)).catch(Bt(this,_x))},Sx=new WeakMap,_x=new WeakMap,yj=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Bt(this,Vf)?{"Last-Event-ID":Bt(this,Vf)}:void 0},cache:"no-store",signal:(e=Bt(this,Si))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Tx=new WeakMap,Nx=new WeakMap,Df=function(e,t){var n;Bt(this,ya)!==this.CLOSED&&Pn(this,ya,this.CLOSED);const r=new gj("error",{code:t,message:e});(n=Bt(this,du))==null||n.call(this,r),this.dispatchEvent(r)},kx=function(e,t){var n;if(Bt(this,ya)===this.CLOSED)return;Pn(this,ya,this.CONNECTING);const r=new gj("error",{code:t,message:e});(n=Bt(this,du))==null||n.call(this,r),this.dispatchEvent(r),Pn(this,Qc,setTimeout(Bt(this,Cx),Bt(this,Hf)))},Cx=new WeakMap,Gg.CONNECTING=0,Gg.OPEN=1,Gg.CLOSED=2;function UJ(){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 $J extends Error{constructor(t,n,r){super(`SSE error: ${n}`),this.code=t,this.event=r}}class zJ{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=J2(n?.fetch,n?.requestInit)}async _authThenStart(){var t;if(!this._authProvider)throw new Ja("No auth provider");let n;try{n=await _s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw(t=this.onerror)===null||t===void 0||t.call(this,r),r}if(n!=="AUTHORIZED")throw new Ja;return await this._startOrAuth()}async _commonHeaders(){var t;const n={};if(this._authProvider){const a=await this._authProvider.tokens();a&&(n.Authorization=`Bearer ${a.access_token}`)}this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const r=vb((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...r})}_startOrAuth(){var t,n,r;const a=(r=(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&&r!==void 0?r:fetch;return new Promise((s,i)=>{this._eventSource=new Gg(this._url.href,{...this._eventSourceInit,fetch:async(c,u)=>{const f=await this._commonHeaders();f.set("Accept","text/event-stream");const m=await a(c,{...u,headers:f});if(m.status===401&&m.headers.has("www-authenticate")){const{resourceMetadataUrl:h,scope:g}=dp(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(s,i);return}const f=new $J(c.code,c.message,c);i(f),(u=this.onerror)===null||u===void 0||u.call(this,f)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",c=>{var u;const f=c;try{if(this._endpoint=new URL(f.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(m){i(m),(u=this.onerror)===null||u===void 0||u.call(this,m),this.close();return}s()}),this._eventSource.onmessage=c=>{var u,f;const m=c;let h;try{h=Bg.parse(JSON.parse(m.data))}catch(g){(u=this.onerror)===null||u===void 0||u.call(this,g);return}(f=this.onmessage)===null||f===void 0||f.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 Ja("No auth provider");if(await _s(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ja("Failed to authorize")}async close(){var t,n,r;(t=this._abortController)===null||t===void 0||t.abort(),(n=this._eventSource)===null||n===void 0||n.close(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(t){var n,r,a,s;if(!this._endpoint)throw new Error("Not connected");try{const i=await this._commonHeaders();i.set("content-type","application/json");const c={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(t),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},u=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._endpoint,c);if(!u.ok){const f=await u.text().catch(()=>null);if(u.status===401&&this._authProvider){const{resourceMetadataUrl:m,scope:h}=dp(u);if(this._resourceMetadataUrl=m,this._scope=h,await _s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ja;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${u.status}): ${f}`)}await((a=u.body)===null||a===void 0?void 0:a.cancel())}catch(i){throw(s=this.onerror)===null||s===void 0||s.call(this,i),i}}setProtocolVersion(t){this._protocolVersion=t}}var Qw,vj;function FJ(){return vj||(vj=1,Qw=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),Qw}var BJ=FJ();const wj=jp(BJ);var Mu,HJ=(Mu=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}get serverCapabilities(){return this.connector.serverCapabilities}get serverInfo(){return this.connector.serverInfo}async callTool(t,n,r){return this.connector.callTool(t,n,r)}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,r){return this.connector.request(t,n,r)}},Pe(Mu,"MCPSession"),Mu),ju,mF=(ju=class{_readyPromise;_readyResolver;_donePromise;_doneResolver;_exception=null;_connection=null;_task=null;_abortController=null;constructor(){this.reset()}async start(){if(this.reset(),ve.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){ve.debug(`Cancelling ${this.constructor.name} task`),this._abortController.abort();try{await this._task}catch(t){t instanceof Error&&t.name==="AbortError"?ve.debug(`${this.constructor.name} task aborted successfully`):ve.warn(`Error stopping ${this.constructor.name} task: ${t}`)}}await this._donePromise,ve.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(){ve.debug(`Running ${this.constructor.name} task`);try{this._connection=await this.establishConnection(),ve.debug(`${this.constructor.name} connected successfully`),this._readyResolver(),await this.waitForAbort()}catch(t){this._exception=t,ve.error(`Error in ${this.constructor.name} task: ${t}`),this._readyResolver()}finally{if(this._connection!==null){try{await this.closeConnection(this._connection)}catch(t){ve.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 r=this._abortController.signal;if(r.aborted){t();return}const a=Pe(()=>{r.removeEventListener("abort",a),t()},"onAbort");r.addEventListener("abort",a)})}},Pe(ju,"ConnectionManager"),ju),Pu,VJ=(Pu=class extends mF{url;opts;_transport=null;constructor(t,n){super(),this.url=typeof t=="string"?new URL(t):t,this.opts=n}async establishConnection(){return this._transport=new zJ(this.url,this.opts),ve.debug(`${this.constructor.name} connected successfully`),this._transport}async closeConnection(t){if(this._transport)try{await this._transport.close()}catch(n){ve.warn(`Error closing SSE transport: ${n}`)}finally{this._transport=null}}},Pe(Pu,"SseConnectionManager"),Pu),Uu,Ej=(Uu=class extends B2{baseUrl;headers;timeout;sseReadTimeout;clientInfo;preferSse;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}async connect(){if(this.connected){ve.debug("Already connected to MCP implementation");return}const t=this.baseUrl;if(this.preferSse){ve.debug(`Connecting to MCP implementation via HTTP/SSE: ${t}`),await this.connectWithSse(t);return}ve.debug(`Connecting to MCP implementation via HTTP: ${t}`);try{ve.info("🔄 Attempting streamable HTTP transport..."),await this.connectWithStreamableHttp(t),ve.info("✅ Successfully connected via streamable HTTP")}catch(n){let r="Unknown error",a=!1;if(n instanceof bl){const s=n;a=s.code===401,s.code===400&&s.message.includes("Missing session ID")?(r="Server requires session ID (FastMCP compatibility) - using SSE transport",ve.warn(`⚠️ ${r}`)):s.code===404||s.code===405?(r=`Server returned ${s.code} - server likely doesn't support streamable HTTP`,ve.debug(r)):(r=`Server returned ${s.code}: ${s.message}`,ve.debug(r))}else if(n instanceof Error){const s=n.toString(),i=n.message||"";a=s.includes("401")||i.includes("Unauthorized"),s.includes("Missing session ID")||s.includes("Bad Request: Missing session ID")||i.includes("FastMCP session ID error")?(r="Server requires session ID (FastMCP compatibility) - using SSE transport",ve.warn(`⚠️ ${r}`)):s.includes("405 Method Not Allowed")||s.includes("404 Not Found")?(r="Server doesn't support streamable HTTP (405/404)",ve.debug(r)):(r=`Streamable HTTP failed: ${n.message}`,ve.debug(r))}if(a){ve.info("Authentication required - skipping SSE fallback"),await this.cleanupResources();const s=new Error("Authentication required");throw s.code=401,s}ve.info("🔄 Falling back to SSE transport...");try{await this.connectWithSse(t)}catch(s){if(ve.error("Failed to connect with both transports:"),ve.error(` Streamable HTTP: ${r}`),ve.error(` SSE: ${s}`),await this.cleanupResources(),s?.message?.includes("401")||s?.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 jJ(new URL(t),{authProvider:this.opts.authProvider,requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2}});let r=n;if(this.opts.wrapTransport){const s=this.baseUrl;r=this.opts.wrapTransport(r,s)}const a={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};ve.debug("Creating Client with capabilities:",JSON.stringify(a.capabilities,null,2)),this.client=new dj(this.clientInfo,a),this.setupRootsHandler(),ve.debug("Roots handler registered before connect");try{await this.client.connect(r,{timeout:Math.min(this.timeout,3e3)});const s=n.sessionId;s?ve.debug(`Session ID obtained: ${s}`):ve.warn("Session ID not available after connect - this may cause issues with SSE stream")}catch(s){if(s instanceof Error){const i=s.message||s.toString();if(i.includes("Missing session ID")||i.includes("Bad Request: Missing session ID")||i.includes("Mcp-Session-Id header is required")){const c=new Error(`Session ID error: ${i}. The SDK should automatically extract session ID from initialize response.`);throw c.cause=s,c}}throw s}this.streamableTransport=n,this.connectionManager={stop:Pe(async()=>{if(this.streamableTransport)try{await this.streamableTransport.terminateSession(),await this.streamableTransport.close()}catch(s){ve.warn(`Error closing Streamable HTTP transport: ${s}`)}finally{this.streamableTransport=null}},"stop")},this.connected=!0,this.transportType="streamable-http",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),ve.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 VJ(t,{authProvider:this.opts.authProvider,requestInit:{headers:this.headers}});let n=await this.connectionManager.start();if(this.opts.wrapTransport){const a=this.baseUrl;n=this.opts.wrapTransport(n,a)}const r={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};ve.debug("Creating Client with capabilities (SSE):",JSON.stringify(r.capabilities,null,2)),this.client=new dj(this.clientInfo,r),this.setupRootsHandler(),ve.debug("Roots handler registered before connect (SSE)"),await this.client.connect(n),this.connected=!0,this.transportType="sse",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),ve.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}},Pe(Uu,"HttpConnector"),Uu),$u,GJ=($u=class extends mF{url;headers;_ws=null;constructor(t,n={}){super(),this.url=t,this.headers=n}async establishConnection(){return ve.debug(`Connecting to WebSocket: ${this.url}`),new Promise((t,n)=>{const r=new wj(this.url,{headers:this.headers});this._ws=r;const a=Pe(()=>{i(),ve.debug("WebSocket connected successfully"),t(r)},"onOpen"),s=Pe(c=>{i(),ve.error(`Failed to connect to WebSocket: ${c}`),n(c)},"onError"),i=Pe(()=>{r.off("open",a),r.off("error",s)},"cleanup");r.on("open",a),r.on("error",s)})}async closeConnection(t){return ve.debug("Closing WebSocket connection"),new Promise(n=>{const r=Pe(()=>{t.off("close",r),this._ws=null,n()},"onClose");if(t.readyState===wj.CLOSED){r();return}t.on("close",r);try{t.close()}catch(a){ve.warn(`Error closing WebSocket connection: ${a}`),r()}})}},Pe($u,"WebSocketConnectionManager"),$u),zu,WJ=(zu=class extends B2{url;headers;connectionManager=null;ws=null;receiverTask=null;pending=new Map;toolsCache=null;constructor(t,n={}){super(),this.url=t,this.headers={...n.headers??{}},n.authToken&&(this.headers.Authorization=`Bearer ${n.authToken}`)}async connect(){if(this.connected){ve.debug("Already connected to MCP implementation");return}ve.debug(`Connecting via WebSocket: ${this.url}`);try{this.connectionManager=new GJ(this.url,this.headers),this.ws=await this.connectionManager.start(),this.receiverTask=this.receiveLoop(),this.connected=!0,ve.debug("WebSocket connected successfully")}catch(t){throw ve.error(`Failed to connect: ${t}`),await this.cleanupResources(),t}}async disconnect(){if(!this.connected){ve.debug("Not connected to MCP implementation");return}ve.debug("Disconnecting …"),await this.cleanupResources(),this.connected=!1}sendRequest(t,n=null){if(!this.ws)throw new Error("WebSocket is not connected");const r=Zc(),a=JSON.stringify({id:r,method:t,params:n??{}});return new Promise((s,i)=>{this.pending.set(r,{resolve:s,reject:i}),this.ws.send(a,c=>{c&&(this.pending.delete(r),i(c))})})}async receiveLoop(){if(!this.ws)return;const t=this.ws,n=Pe(r=>{let a;try{a=JSON.parse(r.data??r)}catch(i){ve.warn("Received non‑JSON frame",i);return}const s=a.id;if(s&&this.pending.has(s)){const{resolve:i,reject:c}=this.pending.get(s);this.pending.delete(s),"result"in a?i(a.result):"error"in a&&c(a.error)}else a.method&&!a.id?(ve.debug("Received notification",a.method,a.params),this.handleNotification(a)):ve.debug("Received unsolicited message",a)},"onMessage");return t.addEventListener?t.addEventListener("message",n):t.on("message",n),new Promise(r=>{const a=Pe(()=>{t.removeEventListener?t.removeEventListener("message",n):t.off("message",n),this.rejectAll(new Error("WebSocket closed")),r()},"onClose");t.addEventListener?t.addEventListener("close",a):t.on("close",a)})}rejectAll(t){for(const{reject:n}of this.pending.values())n(t);this.pending.clear()}async handleNotification(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({method:t.method,params:t.params})}catch(r){ve.error("Error in notification handler:",r)}}async refreshToolsCache(){try{ve.debug("[Auto] Refreshing tools cache due to list_changed notification");const t=await this.listTools();this.toolsCache=t.map(n=>n),ve.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(t){ve.warn("[Auto] Failed to refresh tools cache:",t)}}async initialize(){ve.debug("Initializing MCP session over WebSocket");const t=await this.sendRequest("initialize"),n=await this.listTools();return this.toolsCache=n.map(r=>r),ve.debug(`Initialized with ${this.toolsCache.length} tools`),t}async listTools(){return(await this.sendRequest("tools/list")).tools??[]}async callTool(t,n){return await this.sendRequest("tools/call",{name:t,arguments:n})}async listResources(){const t=await this.sendRequest("resources/list");return{resources:Array.isArray(t)?t:[]}}async readResource(t){return await this.sendRequest("resources/read",{uri:t})}async request(t,n=null){return await this.sendRequest(t,n)}get tools(){if(!this.toolsCache)throw new Error("MCP client is not initialized");return this.toolsCache}async cleanupResources(){this.receiverTask&&await this.receiverTask.catch(()=>{}),this.receiverTask=null,this.rejectAll(new Error("WebSocket disconnected")),this.connectionManager&&(await this.connectionManager.stop(),this.connectionManager=null,this.ws=null),this.toolsCache=null}get publicIdentifier(){return{type:"websocket",url:this.url}}},Pe(zu,"WebSocketConnector"),zu),Fu,KJ=(Fu=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,Uo.getInstance().trackClientAddServer(t,n)}removeServer(t){this.config.mcpServers?.[t]&&(delete this.config.mcpServers[t],this.activeSessions=this.activeSessions.filter(n=>n!==t),Uo.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 r=this.config.mcpServers??{};if(Object.keys(r).length===0&&ve.warn("No MCP servers defined in config"),!r[t])throw new Error(`Server '${t}' not found in config`);const a=this.createConnectorFromConfig(r[t]),s=new HJ(a);return n&&await s.initialize(),this.sessions[t]=s,this.activeSessions.includes(t)||this.activeSessions.push(t),s}async createAllSessions(t=!0){const n=this.config.mcpServers??{};Object.keys(n).length===0&&ve.warn("No MCP servers defined in config");for(const r of Object.keys(n))await this.createSession(r,t);return this.sessions}getSession(t){const n=this.sessions[t];return n||null}getAllActiveSessions(){return Object.fromEntries(this.activeSessions.map(t=>[t,this.sessions[t]]))}async closeSession(t){const n=this.sessions[t];if(!n){ve.warn(`No session exists for server ${t}, nothing to close`);return}try{ve.debug(`Closing session for server ${t}`),await n.disconnect()}catch(r){ve.error(`Error closing session for server '${t}': ${r}`)}finally{delete this.sessions[t],this.activeSessions=this.activeSessions.filter(r=>r!==t)}}async closeAllSessions(){const t=Object.keys(this.sessions),n=[];for(const r of t)try{ve.debug(`Closing session for server ${r}`),await this.closeSession(r)}catch(a){const s=`Failed to close session for server '${r}': ${a}`;ve.error(s),n.push(s)}n.length?ve.error(`Encountered ${n.length} errors while closing sessions`):ve.debug("All sessions closed successfully")}},Pe(Fu,"BaseMCPClient"),Fu),Rl,YJ=(Rl=class extends KJ{static getPackageVersion(){return fb()}constructor(t){super(t),this._trackClientInit()}_trackClientInit(){const t=Object.keys(this.config.mcpServers??{});Uo.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(n=>ve.debug(`Failed to track BrowserMCPClient init: ${n}`))}static fromDict(t){return new Rl(t)}createConnectorFromConfig(t){const{url:n,transport:r,headers:a,authToken:s,authProvider:i,wrapTransport:c,clientOptions:u,samplingCallback:f,elicitationCallback:m}=t;if(!n)throw new Error("Server URL is required");const h={headers:a,authToken:s,authProvider:i,wrapTransport:c,clientOptions:u,samplingCallback:f,elicitationCallback:m};return u?console.log("[BrowserMCPClient] Passing clientOptions to connector:",JSON.stringify(u,null,2)):console.warn("[BrowserMCPClient] No clientOptions provided to connector!"),r==="websocket"||n.startsWith("ws://")||n.startsWith("wss://")?new WJ(n,h):r==="http"||n.startsWith("http://")||n.startsWith("https://")?new Ej(n,h):new Ej(n,h)}},Pe(Rl,"BrowserMCPClient"),Rl);function eu(e){const t=Pe(()=>{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(hF).join("&"),n.hash=n.hash.slice(0,1)+encodeURIComponent(n.hash.slice(1)),n.href}Pe(eu,"sanitizeUrl");function hF([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:""}`}Pe(hF,"sanitizeParam");var Bu,Wg=(Bu=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=eu(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 eu(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(r){console.warn(`[${this.storageKeyPrefix}] Failed to parse client information:`,r),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(r){console.warn(`[${this.storageKeyPrefix}] Failed to parse tokens:`,r),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(),r=`${this.storageKeyPrefix}:state_${n}`,a={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(r,JSON.stringify(a)),t.searchParams.set("state",n);const s=t.toString(),i=eu(s);return localStorage.setItem(this.getKey("last_auth_url"),i),i}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 r="width=600,height=700,resizable=yes,scrollbars=yes,status=yes";try{const a=window.open(n,`mcp_auth_${this.serverUrlHash}`,r);this.onPopupWindow&&this.onPopupWindow(n,r,a),!a||a.closed||typeof a.closed>"u"?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(a.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(a){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,a)}}getLastAttemptedAuthUrl(){const t=localStorage.getItem(this.getKey("last_auth_url"));return t?eu(t):null}clearStorage(){const t=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,n=`${this.storageKeyPrefix}:state_`,r=[];let a=0;for(let i=0;i<localStorage.length;i++){const c=localStorage.key(i);if(c){if(c.startsWith(t))r.push(c);else if(c.startsWith(n))try{const u=localStorage.getItem(c);u&&JSON.parse(u).serverUrlHash===this.serverUrlHash&&r.push(c)}catch(u){console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${c} during clearStorage:`,u)}}}return[...new Set(r)].forEach(i=>{localStorage.removeItem(i),a++}),a}hashString(t){let n=0;for(let r=0;r<t.length;r++){const a=t.charCodeAt(r);n=(n<<5)-n+a,n=n&n}return Math.abs(n).toString(16)}getKey(t){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${t}`}},Pe(Bu,"BrowserOAuthClientProvider"),Bu);async function D_(){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),r=e.get("error"),a=e.get("error_description"),s="[mcp-callback]";console.log(`${s} Handling callback...`,{code:t,state:n,error:r,errorDescription:a});let i=null,c=null;const u=n?`mcp:auth:state_${n}`:null;try{if(r)throw new Error(`OAuth error: ${r} - ${a||"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 f=localStorage.getItem(u);if(!f)throw new Error(`Invalid or expired state parameter "${n}". No matching state found in storage.`);try{c=JSON.parse(f)}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(`${s} Re-instantiating provider for server: ${m}`),i=new Wg(m,h),console.log(`${s} Calling SDK auth() to exchange code...`);const g=new URL(m).origin,y=await _s(i,{serverUrl:g,authorizationCode:t});if(y==="AUTHORIZED")if(console.log(`${s} Authorization successful via SDK auth().`),c.flowType==="redirect"&&c.returnUrl)console.log(`${s} Redirect flow complete. Returning to: ${c.returnUrl}`),localStorage.removeItem(u),window.location.href=c.returnUrl;else if(window.opener&&!window.opener.closed)console.log(`${s} 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(`${s} No opener window or return URL detected. Redirecting to root.`),localStorage.removeItem(u);const E=window.location.pathname.split("/").filter(Boolean),w=E.length>0&&E[E.length-1]==="callback"?"/"+E.slice(0,-2).join("/"):"/";window.location.href=w||"/"}else throw console.warn(`${s} SDK auth() returned unexpected status: ${y}`),new Error(`Unexpected result from authentication library: ${y}`)}catch(f){console.error(`${s} Error during OAuth callback handling:`,f);const m=f instanceof Error?f.message:String(f);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 y=document.createElement("p");y.style.color="red",y.style.backgroundColor="#ffebeb",y.style.border="1px solid red",y.style.padding="10px",y.style.borderRadius="4px",y.textContent=m,h.appendChild(y);const x=document.createElement("p");x.textContent="You can close this window or ";const E=document.createElement("a");if(E.href="#",E.textContent="click here to close",E.onclick=w=>(w.preventDefault(),window.close(),!1),x.appendChild(E),x.appendChild(document.createTextNode(".")),h.appendChild(x),f instanceof Error&&f.stack){const w=document.createElement("pre");w.style.fontSize="0.8em",w.style.color="#555",w.style.marginTop="20px",w.style.whiteSpace="pre-wrap",w.textContent=f.stack,h.appendChild(w)}document.body.appendChild(h)}catch(h){console.error(`${s} Could not display error in callback window:`,h)}u&&localStorage.removeItem(u),i&&(localStorage.removeItem(i.getKey("code_verifier")),localStorage.removeItem(i.getKey("last_auth_url")))}}Pe(D_,"onMcpAuthorization");var eE={exports:{}},yt={};var xj;function ZJ(){if(xj)return yt;xj=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),i=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),g=Symbol.iterator;function y(D){return D===null||typeof D!="object"?null:(D=g&&D[g]||D["@@iterator"],typeof D=="function"?D:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,w={};function _(D,H,$){this.props=D,this.context=H,this.refs=w,this.updater=$||x}_.prototype.isReactComponent={},_.prototype.setState=function(D,H){if(typeof D!="object"&&typeof D!="function"&&D!=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,D,H,"setState")},_.prototype.forceUpdate=function(D){this.updater.enqueueForceUpdate(this,D,"forceUpdate")};function S(){}S.prototype=_.prototype;function T(D,H,$){this.props=D,this.context=H,this.refs=w,this.updater=$||x}var R=T.prototype=new S;R.constructor=T,E(R,_.prototype),R.isPureReactComponent=!0;var C=Array.isArray;function I(){}var A={H:null,A:null,T:null,S:null},O=Object.prototype.hasOwnProperty;function j(D,H,$){var L=$.ref;return{$$typeof:e,type:D,key:H,ref:L!==void 0?L:null,props:$}}function U(D,H){return j(D.type,H,D.props)}function B(D){return typeof D=="object"&&D!==null&&D.$$typeof===e}function W(D){var H={"=":"=0",":":"=2"};return"$"+D.replace(/[=:]/g,function($){return H[$]})}var J=/\/+/g;function ee(D,H){return typeof D=="object"&&D!==null&&D.key!=null?W(""+D.key):H.toString(36)}function re(D){switch(D.status){case"fulfilled":return D.value;case"rejected":throw D.reason;default:switch(typeof D.status=="string"?D.then(I,I):(D.status="pending",D.then(function(H){D.status==="pending"&&(D.status="fulfilled",D.value=H)},function(H){D.status==="pending"&&(D.status="rejected",D.reason=H)})),D.status){case"fulfilled":return D.value;case"rejected":throw D.reason}}throw D}function F(D,H,$,L,M){var z=typeof D;(z==="undefined"||z==="boolean")&&(D=null);var G=!1;if(D===null)G=!0;else switch(z){case"bigint":case"string":case"number":G=!0;break;case"object":switch(D.$$typeof){case e:case t:G=!0;break;case m:return G=D._init,F(G(D._payload),H,$,L,M)}}if(G)return M=M(D),G=L===""?"."+ee(D,0):L,C(M)?($="",G!=null&&($=G.replace(J,"$&/")+"/"),F(M,H,$,"",function(ie){return ie})):M!=null&&(B(M)&&(M=U(M,$+(M.key==null||D&&D.key===M.key?"":(""+M.key).replace(J,"$&/")+"/")+G)),H.push(M)),1;G=0;var q=L===""?".":L+":";if(C(D))for(var ae=0;ae<D.length;ae++)L=D[ae],z=q+ee(L,ae),G+=F(L,H,$,z,M);else if(ae=y(D),typeof ae=="function")for(D=ae.call(D),ae=0;!(L=D.next()).done;)L=L.value,z=q+ee(L,ae++),G+=F(L,H,$,z,M);else if(z==="object"){if(typeof D.then=="function")return F(re(D),H,$,L,M);throw H=String(D),Error("Objects are not valid as a React child (found: "+(H==="[object Object]"?"object with keys {"+Object.keys(D).join(", ")+"}":H)+"). If you meant to render a collection of children, use an array instead.")}return G}function K(D,H,$){if(D==null)return D;var L=[],M=0;return F(D,L,"","",function(z){return H.call($,z,M++)}),L}function V(D){if(D._status===-1){var H=D._result;H=H(),H.then(function($){(D._status===0||D._status===-1)&&(D._status=1,D._result=$)},function($){(D._status===0||D._status===-1)&&(D._status=2,D._result=$)}),D._status===-1&&(D._status=0,D._result=H)}if(D._status===1)return D._result.default;throw D._result}var ne=typeof reportError=="function"?reportError:function(D){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var H=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof D=="object"&&D!==null&&typeof D.message=="string"?String(D.message):String(D),error:D});if(!window.dispatchEvent(H))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",D);return}console.error(D)},te={map:K,forEach:function(D,H,$){K(D,function(){H.apply(this,arguments)},$)},count:function(D){var H=0;return K(D,function(){H++}),H},toArray:function(D){return K(D,function(H){return H})||[]},only:function(D){if(!B(D))throw Error("React.Children.only expected to receive a single React element child.");return D}};return yt.Activity=h,yt.Children=te,yt.Component=_,yt.Fragment=n,yt.Profiler=a,yt.PureComponent=T,yt.StrictMode=r,yt.Suspense=u,yt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,yt.__COMPILER_RUNTIME={__proto__:null,c:function(D){return A.H.useMemoCache(D)}},yt.cache=function(D){return function(){return D.apply(null,arguments)}},yt.cacheSignal=function(){return null},yt.cloneElement=function(D,H,$){if(D==null)throw Error("The argument must be a React element, but you passed "+D+".");var L=E({},D.props),M=D.key;if(H!=null)for(z in H.key!==void 0&&(M=""+H.key),H)!O.call(H,z)||z==="key"||z==="__self"||z==="__source"||z==="ref"&&H.ref===void 0||(L[z]=H[z]);var z=arguments.length-2;if(z===1)L.children=$;else if(1<z){for(var G=Array(z),q=0;q<z;q++)G[q]=arguments[q+2];L.children=G}return j(D.type,M,L)},yt.createContext=function(D){return D={$$typeof:i,_currentValue:D,_currentValue2:D,_threadCount:0,Provider:null,Consumer:null},D.Provider=D,D.Consumer={$$typeof:s,_context:D},D},yt.createElement=function(D,H,$){var L,M={},z=null;if(H!=null)for(L in H.key!==void 0&&(z=""+H.key),H)O.call(H,L)&&L!=="key"&&L!=="__self"&&L!=="__source"&&(M[L]=H[L]);var G=arguments.length-2;if(G===1)M.children=$;else if(1<G){for(var q=Array(G),ae=0;ae<G;ae++)q[ae]=arguments[ae+2];M.children=q}if(D&&D.defaultProps)for(L in G=D.defaultProps,G)M[L]===void 0&&(M[L]=G[L]);return j(D,z,M)},yt.createRef=function(){return{current:null}},yt.forwardRef=function(D){return{$$typeof:c,render:D}},yt.isValidElement=B,yt.lazy=function(D){return{$$typeof:m,_payload:{_status:-1,_result:D},_init:V}},yt.memo=function(D,H){return{$$typeof:f,type:D,compare:H===void 0?null:H}},yt.startTransition=function(D){var H=A.T,$={};A.T=$;try{var L=D(),M=A.S;M!==null&&M($,L),typeof L=="object"&&L!==null&&typeof L.then=="function"&&L.then(I,ne)}catch(z){ne(z)}finally{H!==null&&$.types!==null&&(H.types=$.types),A.T=H}},yt.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()},yt.use=function(D){return A.H.use(D)},yt.useActionState=function(D,H,$){return A.H.useActionState(D,H,$)},yt.useCallback=function(D,H){return A.H.useCallback(D,H)},yt.useContext=function(D){return A.H.useContext(D)},yt.useDebugValue=function(){},yt.useDeferredValue=function(D,H){return A.H.useDeferredValue(D,H)},yt.useEffect=function(D,H){return A.H.useEffect(D,H)},yt.useEffectEvent=function(D){return A.H.useEffectEvent(D)},yt.useId=function(){return A.H.useId()},yt.useImperativeHandle=function(D,H,$){return A.H.useImperativeHandle(D,H,$)},yt.useInsertionEffect=function(D,H){return A.H.useInsertionEffect(D,H)},yt.useLayoutEffect=function(D,H){return A.H.useLayoutEffect(D,H)},yt.useMemo=function(D,H){return A.H.useMemo(D,H)},yt.useOptimistic=function(D,H){return A.H.useOptimistic(D,H)},yt.useReducer=function(D,H,$){return A.H.useReducer(D,H,$)},yt.useRef=function(D){return A.H.useRef(D)},yt.useState=function(D){return A.H.useState(D)},yt.useSyncExternalStore=function(D,H,$){return A.H.useSyncExternalStore(D,H,$)},yt.useTransition=function(){return A.H.useTransition()},yt.version="19.2.0",yt}var Sj;function L_(){return Sj||(Sj=1,eE.exports=ZJ()),eE.exports}var v=L_();const ce=jp(v),id=EG({__proto__:null,default:ce},[v]);function Rx(e,t){if(!e)throw new Error(t)}Pe(Rx,"assert");var qJ=3e3,XJ=5e3;function M_(e){const{url:t,enabled:n=!0,clientName:r,clientUri:a,callbackUrl:s=typeof window<"u"?eu(new URL("/oauth/callback",window.location.origin).toString()):"/oauth/callback",storageKeyPrefix:i="mcp:auth",clientConfig:c={},customHeaders:u={},debug:f=!1,autoRetry:m=!1,autoReconnect:h=qJ,transportType:g="auto",preventAutoAuth:y=!1,useRedirectFlow:x=!1,onPopupWindow:E,timeout:w=3e4,sseReadTimeout:_=3e5,wrapTransport:S,onNotification:T,samplingCallback:R,onElicitation:C}=e,[I,A]=v.useState("discovering"),[O,j]=v.useState([]),[U,B]=v.useState([]),[W,J]=v.useState([]),[ee,re]=v.useState([]),[F,K]=v.useState(),[V,ne]=v.useState(),[te,D]=v.useState(void 0),[H,$]=v.useState([]),[L,M]=v.useState(void 0),z=v.useRef(null),G=v.useRef(null),q=v.useRef(!1),ae=v.useRef(!0),ie=v.useRef(0),X=v.useRef(null),Z=v.useRef(I),se=v.useRef(h),me=v.useRef(null);v.useEffect(()=>{Z.current=I,se.current=h},[I,h]);const le=v.useCallback((De,ze,...ht)=>{const nt=ht.length>0?`${ze} ${ht.map(kt=>JSON.stringify(kt)).join(" ")}`:ze;console[De](`[useMcp] ${nt}`),ae.current&&$(kt=>[...kt.slice(-100),{level:De,message:nt,timestamp:Date.now()}])},[]),Ne=v.useCallback(async(De=!1)=>{if(De||le("info","Disconnecting..."),q.current=!1,X.current&&clearTimeout(X.current),X.current=null,z.current)try{await z.current.closeSession("inspector-server")}catch(ze){De||le("warn","Error closing session:",ze)}z.current=null,ae.current&&!De&&(A("discovering"),j([]),B([]),J([]),re([]),D(void 0),M(void 0))},[le]),He=v.useCallback((De,ze)=>{if(le("error",De,ze??""),ae.current){A("failed"),D(De);const ht=G.current?.getLastAttemptedAuthUrl();ht&&(M(ht),le("info","Manual authentication URL may be available.",ht))}q.current=!1,t&&Uo.getInstance().trackUseMcpConnection({url:t,transportType:g,success:!1,errorType:ze?.name||"UnknownError",hasOAuth:!!G.current,hasSampling:!!R,hasElicitation:!!C}).catch(()=>{})},[le,t,g,R,C]),xe=v.useCallback(async()=>{if(!n||!t){le("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag.");return}if(q.current){le("debug","Connection attempt already in progress.");return}if(!ae.current){le("debug","Connect called after unmount, aborting.");return}q.current=!0,ie.current+=1,D(void 0),M(void 0),me.current=null,A("discovering"),le("info",`Connecting attempt #${ie.current} to ${t}...`),G.current||(G.current=new Wg(t,{storageKeyPrefix:i,clientName:r,clientUri:a,callbackUrl:s,preventAutoAuth:y,useRedirectFlow:x,onPopupWindow:E}),le("debug","BrowserOAuthClientProvider initialized in connect.")),z.current||(z.current=new YJ,le("debug","BrowserMCPClient initialized in connect."));const De=Pe(async(ht,nt=!1)=>{le("info",`Attempting connection with transport: ${ht}`);try{const kt="inspector-server",ot={url:t,transport:ht==="sse"?"http":ht};if(u&&Object.keys(u).length>0&&(ot.headers=u),G.current){const Et=await G.current.tokens();Et?.access_token&&(ot.headers={...ot.headers,Authorization:`Bearer ${Et.access_token}`})}z.current.addServer(kt,{...ot,authProvider:G.current,clientOptions:c,samplingCallback:R,elicitationCallback:C,wrapTransport:S?Et=>(console.log("[useMcp] Applying transport wrapper for server:",kt,"url:",t),S(Et,t)):void 0});const Ae=await z.current.createSession(kt,!1);T&&Ae.on("notification",T),await Ae.initialize(),le("info","✅ Successfully connected to MCP server"),le("info","Server info:",Ae.connector.serverInfo),le("info","Server capabilities:",Ae.connector.serverCapabilities),console.log("[useMcp] Server info:",Ae.connector.serverInfo),console.log("[useMcp] Server capabilities:",Ae.connector.serverCapabilities),A("ready"),me.current=ht,Uo.getInstance().trackUseMcpConnection({url:t,transportType:ht,success:!0,hasOAuth:!!G.current,hasSampling:!!R,hasElicitation:!!C}).catch(()=>{}),j(Ae.connector.tools||[]);const Me=await Ae.connector.listAllResources();B(Me.resources||[]);const Ve=await Ae.connector.listPrompts();re(Ve.prompts||[]);const it=Ae.connector.serverInfo,pt=Ae.connector.serverCapabilities;return it&&(console.log("[useMcp] Server info:",it),K(it)),pt&&(console.log("[useMcp] Server capabilities:",pt),ne(pt)),"success"}catch(kt){const ot=kt,Ae=ot?.message||String(kt);if(ot.code===401||Ae.includes("401")||Ae.includes("Unauthorized")){if(G.current){le("info","Authentication required. OAuth provider available.");try{const{auth:Me}=await rr(async()=>{const{auth:it}=await Promise.resolve().then(()=>mj);return{auth:it}},void 0),Ve=new URL(t).origin;Me(G.current,{serverUrl:Ve}).catch(()=>{}),setTimeout(()=>{if(ae.current){const it=G.current?.getLastAttemptedAuthUrl();it?(M(it),le("info","Manual authentication URL available:",it)):le("warn","Could not generate authentication URL")}},100)}catch(Me){le("warn","Error generating auth URL:",Me)}return ae.current&&A("pending_auth"),q.current=!1,"auth_redirect"}return u&&Object.keys(u).length>0?(He("Authentication failed: Server returned 401 Unauthorized. Check your Authorization header value is correct."),"failed"):(He("Authentication required: Server returned 401 Unauthorized. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed")}return He(Ae,ot instanceof Error?ot:new Error(String(ot))),"failed"}},"tryConnectWithTransport");let ze="failed";if(g==="sse")le("debug","Using SSE-only transport mode"),ze=await De("sse");else if(g==="http")le("debug","Using HTTP-only transport mode"),ze=await De("http");else{le("debug","Using auto transport mode (HTTP with SSE fallback)");const ht=await De("http");ht==="fallback"&&ae.current&&Z.current!=="authenticating"?(le("info","HTTP failed, attempting SSE fallback..."),ze=await De("sse")):ze=ht}(ze==="success"||ze==="failed"||ze==="auth_redirect")&&(q.current=!1),le("debug",`Connection sequence finished with status: ${ze}`)},[le,He,Ne,t,i,r,a,s,c.name,c.version,u,g,y,x,E,n,w,_]),Te=v.useCallback(async(De,ze,ht)=>{if(Z.current!=="ready"||!z.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot call tool "${De}".`);le("info",`Calling tool: ${De}`,ze);const nt=Date.now();try{const ot=z.current.getSession("inspector-server");if(!ot)throw new Error("No active session found");const Ae=await ot.connector.callTool(De,ze||{},ht);return le("info",`Tool "${De}" call successful:`,Ae),Uo.getInstance().trackUseMcpToolCall({toolName:De,success:!0,executionTimeMs:Date.now()-nt}).catch(()=>{}),Ae}catch(kt){throw le("error",`Tool "${De}" call failed:`,kt),Uo.getInstance().trackUseMcpToolCall({toolName:De,success:!1,errorType:kt instanceof Error?kt.name:"UnknownError",executionTimeMs:Date.now()-nt}).catch(()=>{}),kt}},[I]),$e=v.useCallback(()=>{Z.current==="failed"?(le("info","Retry requested..."),xe()):le("warn",`Retry called but state is not 'failed' (state: ${Z.current}). Ignoring.`)},[le,xe]),fe=v.useCallback(async()=>{le("info","Manual authentication requested...");const De=Z.current;if(De==="failed")le("info","Attempting to reconnect and authenticate via retry..."),$e();else if(De==="pending_auth"){le("info","Proceeding with authentication from pending state...");try{Rx(G.current,"Auth Provider not available for manual auth"),Rx(t,"Server URL is required for authentication"),le("info","Clearing all OAuth state and initiating fresh flow...");const ze=`${i}:${G.current.serverUrlHash}`;Object.keys(localStorage).forEach(ot=>{ot.startsWith(ze)&&(le("debug",`Removing stale OAuth key: ${ot}`),localStorage.removeItem(ot)),ot.startsWith(`${i}:state_`)&&(le("debug",`Removing orphaned state: ${ot}`),localStorage.removeItem(ot))}),A("authenticating");const ht=new Wg(t,{storageKeyPrefix:i,clientName:r,clientUri:a,callbackUrl:s,preventAutoAuth:!1,useRedirectFlow:x,onPopupWindow:E});G.current=ht,le("info","Triggering fresh OAuth authorization...");const{auth:nt}=await rr(async()=>{const{auth:ot}=await Promise.resolve().then(()=>mj);return{auth:ot}},void 0),kt=new URL(t).origin;nt(ht,{serverUrl:kt}).catch(ot=>{le("info","OAuth flow initiated:",ot instanceof Error?ot.message:"Redirecting...")})}catch(ze){if(!ae.current)return;A("pending_auth"),le("error",`Manual authentication failed: ${ze instanceof Error?ze.message:String(ze)}`)}}else if(De==="authenticating"){le("warn","Already attempting authentication. Check for blocked popups or wait for timeout.");const ze=G.current?.getLastAttemptedAuthUrl();ze&&!L&&(M(ze),le("info","Manual authentication URL retrieved:",ze))}else le("info",`Client not in a state requiring manual authentication trigger (state: ${De}). If needed, try disconnecting and reconnecting.`)},[le,$e,L,t,x,E,i,r,a,s]),Ie=v.useCallback(()=>{if(G.current){const De=G.current.clearStorage();le("info",`Cleared ${De} item(s) from localStorage for ${t}.`),M(void 0),Ne()}else le("warn","Auth provider not initialized, cannot clear storage.")},[t,le,Ne]),Fe=v.useCallback(async()=>{if(Z.current!=="ready"||!z.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot list resources.`);le("info","Listing resources");try{const ze=z.current.getSession("inspector-server");if(!ze)throw new Error("No active session found");const ht=await ze.connector.listAllResources();B(ht.resources||[]),le("info","Resources listed successfully")}catch(De){throw le("error","List resources failed:",De),De}},[I]),Ee=v.useCallback(async De=>{if(Z.current!=="ready"||!z.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot read resource.`);le("info",`Reading resource: ${De}`);try{const ht=z.current.getSession("inspector-server");if(!ht)throw new Error("No active session found");const nt=await ht.connector.readResource(De);return le("info","Resource read successful:",nt),Uo.getInstance().trackUseMcpResourceRead({resourceUri:De,success:!0}).catch(()=>{}),nt}catch(ze){throw le("error","Resource read failed:",ze),Uo.getInstance().trackUseMcpResourceRead({resourceUri:De,success:!1,errorType:ze instanceof Error?ze.name:"UnknownError"}).catch(()=>{}),ze}},[I]),at=v.useCallback(async()=>{if(Z.current!=="ready"||!z.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot list prompts.`);le("info","Listing prompts");try{const ze=z.current.getSession("inspector-server");if(!ze)throw new Error("No active session found");const ht=await ze.connector.listPrompts();re(ht.prompts||[]),le("info","Prompts listed successfully")}catch(De){throw le("error","List prompts failed:",De),De}},[I]),lt=v.useCallback(async(De,ze)=>{if(Z.current!=="ready"||!z.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot get prompt.`);le("info",`Getting prompt: ${De}`,ze);try{const nt=z.current.getSession("inspector-server");if(!nt)throw new Error("No active session found");const kt=await nt.connector.getPrompt(De,ze||{});return le("info",`Prompt "${De}" retrieved successfully:`,kt),kt}catch(ht){throw le("error",`Prompt "${De}" retrieval failed:`,ht),ht}},[I]),bt=v.useRef(xe),Rt=v.useRef(He);return v.useEffect(()=>{bt.current=xe,Rt.current=He}),v.useEffect(()=>{const De=Pe(ze=>{ze.origin===window.location.origin&&ze.data?.type==="mcp_auth_callback"&&(le("info","Received auth callback message.",ze.data),X.current&&clearTimeout(X.current),X.current=null,ze.data.success?(le("info","Authentication successful via popup. Reconnecting client..."),q.current&&le("debug","Connection attempt already in progress, resetting flag to allow reconnection."),q.current=!1,setTimeout(()=>{ae.current&&(le("debug","Initiating reconnection after successful auth callback."),bt.current())},100)):Rt.current(`Authentication failed in callback: ${ze.data.error||"Unknown reason."}`))},"messageHandler");return window.addEventListener("message",De),le("debug","Auth callback message listener added."),()=>{window.removeEventListener("message",De),le("debug","Auth callback message listener removed."),X.current&&clearTimeout(X.current)}},[le]),v.useEffect(()=>(ae.current=!0,!n||!t?(le("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag."),A("discovering"),()=>{ae.current=!1}):(le("debug","useMcp mounted, initiating connection."),ie.current=0,(!G.current||G.current.serverUrl!==t)&&(G.current=new Wg(t,{storageKeyPrefix:i,clientName:r,clientUri:a,callbackUrl:s,preventAutoAuth:y,useRedirectFlow:x,onPopupWindow:E}),le("debug","BrowserOAuthClientProvider initialized/updated on mount/option change.")),xe(),()=>{ae.current=!1,le("debug","useMcp unmounting, disconnecting."),Ne(!0)})),[t,n,i,s,r,a,c.name,c.version,x]),v.useEffect(()=>{let De=null;if(I==="failed"&&m&&ie.current>0){const ze=typeof m=="number"?m:XJ;le("info",`Connection failed, auto-retrying in ${ze}ms...`),De=setTimeout(()=>{ae.current&&Z.current==="failed"&&$e()},ze)}return()=>{De&&clearTimeout(De)}},[I,m,$e,le]),{state:I,tools:O,resources:U,resourceTemplates:W,prompts:ee,serverInfo:F,capabilities:V,error:te,log:H,authUrl:L,client:z.current,callTool:Te,readResource:Ee,listResources:Fe,listPrompts:at,getPrompt:lt,retry:$e,disconnect:Ne,authenticate:fe,clearStorage:Ie}}Pe(M_,"useMcp");var Hu,JJ=(Hu=class extends ce.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?ce.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"},ce.createElement("h3",{className:"font-bold mb-2"},"Widget Error"),ce.createElement("pre",{className:"text-sm whitespace-pre-wrap"},this.state.error?.message)):this.props.children}},Pe(Hu,"ErrorBoundary"),Hu),Gf="openai:set_globals";function po(e){return v.useSyncExternalStore(t=>{const n=Pe(r=>{r.detail.globals[e]!==void 0&&t()},"handleSetGlobal");return typeof window<"u"&&window.addEventListener(Gf,n),()=>{typeof window<"u"&&window.removeEventListener(Gf,n)}},()=>typeof window<"u"&&window.openai?window.openai[e]:void 0)}Pe(po,"useOpenAiGlobal");function ld(e){const[t,n]=v.useState(()=>typeof window<"u"&&!!window.openai);v.useEffect(()=>{if(typeof window<"u"&&window.openai){n(!0);return}const O=setInterval(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(O))},100),j=Pe(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(O))},"handleSetGlobals");typeof window<"u"&&window.addEventListener(Gf,j);const U=setTimeout(()=>{clearInterval(O),typeof window<"u"&&window.removeEventListener(Gf,j)},5e3);return()=>{clearInterval(O),clearTimeout(U),typeof window<"u"&&window.removeEventListener(Gf,j)}},[]);const r=v.useMemo(()=>t?"openai":"mcp-ui",[t]),a=typeof window<"u"?window.location.search:"",s=v.useMemo(()=>{const O=new URLSearchParams(a);return O.has("mcpUseParams")?JSON.parse(O.get("mcpUseParams")):{toolInput:{},toolOutput:{},toolId:""}},[a]),i=r==="openai"?po("toolInput"):s.toolInput,c=r==="openai"?po("toolOutput"):s.toolOutput,u=po("toolResponseMetadata"),f=po("widgetState"),m=po("theme"),h=po("displayMode"),g=po("safeArea"),y=po("maxHeight"),x=po("userAgent"),E=po("locale"),w=v.useMemo(()=>typeof window<"u"&&window.__mcpPublicUrl?window.__mcpPublicUrl.replace(/\/mcp-use\/public$/,""):"",[]),[_,S]=v.useState(null);v.useEffect(()=>{f!==void 0&&S(f)},[f]);const T=v.useCallback(async(O,j)=>{if(!window.openai?.callTool)throw new Error("window.openai.callTool is not available");return window.openai.callTool(O,j)},[]),R=v.useCallback(async O=>{if(!window.openai?.sendFollowUpMessage)throw new Error("window.openai.sendFollowUpMessage is not available");return window.openai.sendFollowUpMessage({prompt:O})},[]),C=v.useCallback(O=>{if(!window.openai?.openExternal)throw new Error("window.openai.openExternal is not available");window.openai.openExternal({href:O})},[]),I=v.useCallback(async O=>{if(!window.openai?.requestDisplayMode)throw new Error("window.openai.requestDisplayMode is not available");return window.openai.requestDisplayMode({mode:O})},[]),A=v.useCallback(async O=>{if(!window.openai?.setWidgetState)throw new Error("window.openai.setWidgetState is not available");const U=typeof O=="function"?O(f!==void 0?f:_):O;return S(U),window.openai.setWidgetState(U)},[f,_]);return{props:i||e||{},output:c??null,metadata:u??null,state:_,setState:A,theme:m||"light",displayMode:h||"inline",safeArea:g||{insets:{top:0,bottom:0,left:0,right:0}},maxHeight:y||600,userAgent:x||{device:{type:"desktop"},capabilities:{hover:!0,touch:!1}},locale:E||"en",mcp_url:w,callTool:T,sendFollowUpMessage:R,openExternal:C,requestDisplayMode:I,isAvailable:t}}Pe(ld,"useWidget");function QJ(e){const{props:t}=ld(e);return t}Pe(QJ,"useWidgetProps");function eQ(){const{theme:e}=ld();return e}Pe(eQ,"useWidgetTheme");function tQ(e){const{state:t,setState:n}=ld();return v.useEffect(()=>{t===null&&e!==void 0&&window.openai?.setWidgetState&&n(e)},[]),[t,n]}Pe(tQ,"useWidgetState");var _j=Pe(({children:e})=>{const{theme:t,isAvailable:n}=ld();console.log("theme",t);const[r,a]=v.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");v.useEffect(()=>{if(typeof window>"u")return;const i=window.matchMedia("(prefers-color-scheme: dark)"),c=Pe(u=>{a(u.matches?"dark":"light")},"handleChange");return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[]);const s=n?t:r;return v.useLayoutEffect(()=>{typeof document>"u"||(s==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark"))},[s]),ce.createElement(ce.Fragment,null,e)},"ThemeProvider");function gF({children:e,className:t="",position:n="top-right",attachTo:r,showLabels:a=!0,debugger:s=!1,viewControls:i=!1}){const{props:c,output:u,metadata:f,state:m,theme:h,displayMode:g,safeArea:y,maxHeight:x,userAgent:E,locale:w,isAvailable:_,callTool:S,sendFollowUpMessage:T,openExternal:R,requestDisplayMode:C,setState:I}=ld(),[A,O]=v.useState(!1),[j,U]=v.useState(!1),B=v.useRef(null),W=v.useRef(null),[J,ee]=v.useState([]),[re,F]=v.useState(""),[K,V]=v.useState("get-my-city"),[ne,te]=v.useState("{}"),[D,H]=v.useState("Test follow-up message"),[$,L]=v.useState("https://docs.mcp-use.com"),M=g==="fullscreen"&&_,z=g==="pip"&&_,G=typeof window<"u"&&window.location.pathname.includes("/inspector/api/dev-widget/");v.useEffect(()=>{const Ee=setTimeout(()=>{if(typeof window<"u"&&window.openai)try{const at=Object.keys(window.openai);ee(at)}catch{ee([])}else ee([])},100);return()=>{clearTimeout(Ee)}},[]);const q=h==="dark",ae=Pe(()=>{const Ee=["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[...Ee,"top-4","left-4"];case"top-center":return[...Ee,"top-4","left-1/2","-translate-x-1/2"];case"top-right":return[...Ee,"top-4","right-4"];case"center-left":return[...Ee,"top-1/2","left-4","-translate-y-1/2"];case"center-right":return[...Ee,"top-1/2","right-4","-translate-y-1/2"];case"bottom-left":return[...Ee,"bottom-4","left-4"];case"bottom-center":return[...Ee,"bottom-4","left-1/2","-translate-x-1/2"];case"bottom-right":return[...Ee,"bottom-4","right-4"];default:return[...Ee,"top-4","right-4"]}},"getPositionClasses"),ie=Pe(()=>{const at=y?.insets?.top?Math.max(16,y.insets.top+8):16,lt=y?.insets?.right?Math.max(16,y.insets.right+8):16,bt=y?.insets?.bottom?Math.max(16,y.insets.bottom+8):16,Rt=y?.insets?.left?Math.max(16,y.insets.left+8):16,De={};switch(n){case"top-left":De.top=`${at}px`,De.left=`${Rt}px`;break;case"top-center":De.top=`${at}px`;break;case"top-right":De.top=`${at}px`,De.right=`${lt}px`;break;case"center-left":De.left=`${Rt}px`;break;case"center-right":De.right=`${lt}px`;break;case"bottom-left":De.bottom=`${bt}px`,De.left=`${Rt}px`;break;case"bottom-center":De.bottom=`${bt}px`;break;case"bottom-right":De.bottom=`${bt}px`,De.right=`${lt}px`;break;default:De.top=`${at}px`,De.right=`${lt}px`;break}return De},"getPositionOffsetStyles");v.useEffect(()=>{if(!r)return;const Ee=Pe(()=>O(!0),"handleMouseEnter"),at=Pe(()=>O(!1),"handleMouseLeave");return r.addEventListener("mouseenter",Ee),r.addEventListener("mouseleave",at),()=>{r.removeEventListener("mouseenter",Ee),r.removeEventListener("mouseleave",at)}},[r]),v.useEffect(()=>{if(!j)return;const Ee=Pe(at=>{W.current&&!W.current.contains(at.target)&&U(!1)},"handleClickOutside");return document.addEventListener("mousedown",Ee),()=>{document.removeEventListener("mousedown",Ee)}},[j]),v.useEffect(()=>(j?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[j]);const X=Pe(()=>{U(!j)},"handleToggleOverlay"),Z=Pe(async()=>{try{F("Calling tool...");const Ee=ne.trim()?JSON.parse(ne):{},at=await S(K,Ee);F(`Success: ${JSON.stringify(at,null,2)}`)}catch(Ee){F(`Error: ${Ee.message}`)}},"handleCallTool"),se=Pe(async()=>{try{F("Sending follow-up message..."),await T(D),F("Follow-up message sent successfully")}catch(Ee){F(`Error: ${Ee.message}`)}},"handleSendFollowUpMessage"),me=Pe(()=>{try{R($),F(`Opened external link: ${$}`)}catch(Ee){F(`Error: ${Ee.message}`)}},"handleOpenExternal"),le=Pe(async Ee=>{try{F(`Requesting display mode: ${Ee}...`);const at=await C(Ee);F(`Display mode granted: ${at.mode}`)}catch(at){F(`Error: ${at.message}`)}},"handleRequestDisplayMode"),Ne=Pe(async()=>{try{const Ee=m?{...m,debugTimestamp:new Date().toISOString()}:{debugTimestamp:new Date().toISOString()};F("Setting state..."),await I(Ee),F(`State updated: ${JSON.stringify(Ee,null,2)}`)}catch(Ee){F(`Error: ${Ee.message}`)}},"handleSetState"),He=Pe(async()=>{try{await C("fullscreen")}catch(Ee){console.error("Failed to go fullscreen:",Ee)}},"handleFullscreen"),xe=Pe(async()=>{try{await C("pip")}catch(Ee){console.error("Failed to go pip:",Ee)}},"handlePip"),Te=Pe(()=>{const Ee=["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[...Ee,"top-full","right-0","mt-2"];case"top-left":return[...Ee,"top-full","left-0","mt-2"];case"top-center":return[...Ee,"top-full","left-1/2","-translate-x-1/2","mt-2"];case"bottom-right":return[...Ee,"bottom-full","right-0","mb-2"];case"bottom-left":return[...Ee,"bottom-full","left-0","mb-2"];case"bottom-center":return[...Ee,"bottom-full","left-1/2","-translate-x-1/2","mb-2"];case"center-left":return[...Ee,"left-full","top-1/2","-translate-y-1/2","ml-2"];case"center-right":return[...Ee,"right-full","top-1/2","-translate-y-1/2","mr-2"];default:return[...Ee,"top-full","right-0","mt-2"]}},"getTooltipClasses"),$e=Pe(({onClick:Ee,label:at,children:lt})=>{const[bt,Rt]=v.useState(!1),De=Te();return ce.createElement("button",{className:`p-2 ${q?"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 ${q?"shadow-[0_2px_8px_rgba(0,0,0,0.3)]":"shadow-[0_2px_8px_rgba(0,0,0,0.2)]"} relative`,onMouseEnter:()=>Rt(!0),onMouseLeave:()=>Rt(!1),onClick:Ee,"aria-label":at},ce.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"},lt),a&&ce.createElement("span",{className:`${De.join(" ")} ${bt?"opacity-100":"opacity-0"}`},at))},"IconButton"),fe=Pe(Ee=>{if(Ee===null)return"null";if(Ee===void 0)return"undefined";if(typeof Ee=="object")try{return JSON.stringify(Ee,null,2)}catch{return String(Ee)}return String(Ee)},"formatValue"),Ie=Pe(Ee=>Ee?`${Ee.device?.type||"unknown"}`:"N/A","formatUserAgent"),Fe=Pe(Ee=>{if(!Ee?.insets)return"N/A";const{top:at,bottom:lt,left:bt,right:Rt}=Ee.insets;return`T:${at} B:${lt} L:${bt} R:${Rt}`},"formatSafeArea");return ce.createElement(ce.Fragment,null,ce.createElement("div",{ref:B,className:`${t} relative h-fit`,onMouseEnter:()=>!r&&O(!0),onMouseLeave:()=>!r&&O(!1)},ce.createElement("div",{className:ae().join(" "),style:ie()},!G&&ce.createElement(ce.Fragment,null,!M&&!z&&ce.createElement(ce.Fragment,null,(i===!0||i==="fullscreen")&&ce.createElement($e,{onClick:He,label:"Fullscreen"},ce.createElement("path",{d:"M15 3h6v6"}),ce.createElement("path",{d:"m21 3-7 7"}),ce.createElement("path",{d:"m3 21 7-7"}),ce.createElement("path",{d:"M9 21H3v-6"})),(i===!0||i==="pip")&&ce.createElement($e,{onClick:xe,label:"Picture in Picture"},ce.createElement("path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4"}),ce.createElement("rect",{width:"10",height:"7",x:"12",y:"13",rx:"2"}))),s&&ce.createElement($e,{onClick:X,label:"Debug Info"},ce.createElement("path",{d:"M12 20v-9"}),ce.createElement("path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z"}),ce.createElement("path",{d:"M14.12 3.88 16 2"}),ce.createElement("path",{d:"M21 21a4 4 0 0 0-3.81-4"}),ce.createElement("path",{d:"M21 5a4 4 0 0 1-3.55 3.97"}),ce.createElement("path",{d:"M22 13h-4"}),ce.createElement("path",{d:"M3 21a4 4 0 0 1 3.81-4"}),ce.createElement("path",{d:"M3 5a4 4 0 0 0 3.55 3.97"}),ce.createElement("path",{d:"M6 13H2"}),ce.createElement("path",{d:"m8 2 1.88 1.88"}),ce.createElement("path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13"})))),e),j&&s&&ce.createElement("div",{ref:W,className:"fixed inset-0 bg-black text-white font-mono text-xs z-[10000] overflow-auto p-4",onClick:Ee=>{Ee.target===W.current&&U(!1)}},ce.createElement("button",{onClick:()=>U(!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"},"×"),ce.createElement("div",{className:"max-w-[1200px] mx-auto pt-10"},ce.createElement("h1",{className:"text-lg font-bold mb-4 border-b border-gray-700 pb-2"},"Debug Info"),ce.createElement("table",{className:"w-full border-collapse border-spacing-0"},ce.createElement("tbody",null,ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Props"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(c))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Output"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(u))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Metadata"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(f))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"State"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(m))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Theme"),ce.createElement("td",{className:"p-2"},h)),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Display Mode"),ce.createElement("td",{className:"p-2"},g)),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Locale"),ce.createElement("td",{className:"p-2"},w)),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Max Height"),ce.createElement("td",{className:"p-2"},x,"px")),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"User Agent"),ce.createElement("td",{className:"p-2"},Ie(E))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Safe Area"),ce.createElement("td",{className:"p-2"},Fe(y))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"API Available"),ce.createElement("td",{className:"p-2"},_?"Yes":"No")),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"window.openai Keys"),ce.createElement("td",{className:"p-2"},J.length>0?J.join(", "):"N/A")))),ce.createElement("h2",{className:"text-base font-bold mt-8 mb-4 border-b border-gray-700 pb-2"},"Actions"),ce.createElement("div",{className:"flex flex-col gap-3"},ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("input",{type:"text",value:K,onChange:Ee=>V(Ee.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]"}),ce.createElement("input",{type:"text",value:ne,onChange:Ee=>te(Ee.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"}),ce.createElement("button",{onClick:Z,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Call Tool")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("input",{type:"text",value:D,onChange:Ee=>H(Ee.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"}),ce.createElement("button",{onClick:se,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")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("input",{type:"text",value:$,onChange:Ee=>L(Ee.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"}),ce.createElement("button",{onClick:me,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Open Link")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("span",{className:"w-[150px] text-xs"},"Display Mode:"),ce.createElement("button",{onClick:()=>le("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"),ce.createElement("button",{onClick:()=>le("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"),ce.createElement("button",{onClick:()=>le("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")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.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)")),re&&ce.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"},ce.createElement("div",{className:"font-bold mb-1 text-gray-400"},"Result:"),re,ce.createElement("button",{onClick:()=>F(""),className:"mt-2 py-1 px-2 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-[11px]"},"Clear"))))))}Pe(gF,"WidgetControls");function bF(){if(typeof window>"u")return"/";const t=window.location.pathname.match(/^(\/inspector\/api\/dev-widget\/[^/]+)/);return t?t[1]:"/"}Pe(bF,"getBasename");var nQ=150,rQ=5;function aQ({children:e,debugger:t=!1,viewControls:n=!1,autoSize:r=!1}){const a=bF(),s=v.useRef(null),i=v.useRef(0),c=v.useRef(null),u=v.useRef(!1),[f,m]=v.useState(null),[h,g]=v.useState(null),[y,x]=v.useState(!0);v.useEffect(()=>{let S=!0;return(async()=>{try{const T=await rr(()=>import("./index-1cJS7z-O.js"),[]);S&&(m(()=>T.BrowserRouter),x(!1))}catch{S&&(g(new Error(`❌ react-router-dom not installed!
33
+ `&&r++}}return[t,n]}class LJ extends TransformStream{constructor({onError:t,onRetry:n,onComment:r}={}){let a;super({start(s){a=fF({onEvent:i=>{s.enqueue(i)},onError(i){t==="terminate"?s.error(i):typeof t=="function"&&t(i)},onRetry:n,onComment:r})},transform(s){a.feed(s)}})}}const MJ={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class bl extends Error{constructor(t,n){super(`Streamable HTTP error: ${n}`),this.code=t}}class jJ{constructor(t,n){var r;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=J2(n?.fetch,n?.requestInit),this._sessionId=n?.sessionId,this._reconnectionOptions=(r=n?.reconnectionOptions)!==null&&r!==void 0?r:MJ}async _authThenStart(){var t;if(!this._authProvider)throw new Ja("No auth provider");let n;try{n=await _s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw(t=this.onerror)===null||t===void 0||t.call(this,r),r}if(n!=="AUTHORIZED")throw new Ja;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var t;const n={};if(this._authProvider){const a=await this._authProvider.tokens();a&&(n.Authorization=`Bearer ${a.access_token}`)}this._sessionId&&(n["mcp-session-id"]=this._sessionId),this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const r=vb((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...r})}async _startOrAuthSse(t){var n,r,a,s;const{resumptionToken:i}=t;try{const c=await this._commonHeaders();c.set("Accept","text/event-stream"),i&&c.set("last-event-id",i);const u=await((n=this._fetch)!==null&&n!==void 0?n:fetch)(this._url,{method:"GET",headers:c,signal:(r=this._abortController)===null||r===void 0?void 0:r.signal});if(!u.ok){if(await((a=u.body)===null||a===void 0?void 0:a.cancel()),u.status===401&&this._authProvider)return await this._authThenStart();if(u.status===405)return;throw new bl(u.status,`Failed to open SSE stream: ${u.statusText}`)}this._handleSseStream(u.body,t,!0)}catch(c){throw(s=this.onerror)===null||s===void 0||s.call(this,c),c}}_getNextReconnectionDelay(t){if(this._serverRetryMs!==void 0)return this._serverRetryMs;const n=this._reconnectionOptions.initialReconnectionDelay,r=this._reconnectionOptions.reconnectionDelayGrowFactor,a=this._reconnectionOptions.maxReconnectionDelay;return Math.min(n*Math.pow(r,t),a)}_scheduleReconnection(t,n=0){var r;const a=this._reconnectionOptions.maxRetries;if(n>=a){(r=this.onerror)===null||r===void 0||r.call(this,new Error(`Maximum reconnection attempts (${a}) exceeded.`));return}const s=this._getNextReconnectionDelay(n);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(t).catch(i=>{var c;(c=this.onerror)===null||c===void 0||c.call(this,new Error(`Failed to reconnect SSE stream: ${i instanceof Error?i.message:String(i)}`)),this._scheduleReconnection(t,n+1)})},s)}_handleSseStream(t,n,r){if(!t)return;const{onresumptiontoken:a,replayMessageId:s}=n;let i,c=!1,u=!1;(async()=>{var m,h,g,y;try{const x=t.pipeThrough(new TextDecoderStream).pipeThrough(new LJ({onRetry:_=>{this._serverRetryMs=_}})).getReader();for(;;){const{value:_,done:S}=await x.read();if(S)break;if(_.id&&(i=_.id,c=!0,a?.(_.id)),!!_.data&&(!_.event||_.event==="message"))try{const T=Bg.parse(JSON.parse(_.data));If(T)&&(u=!0,s!==void 0&&(T.id=s)),(m=this.onmessage)===null||m===void 0||m.call(this,T)}catch(T){(h=this.onerror)===null||h===void 0||h.call(this,T)}}(r||c)&&!u&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:s},0)}catch(x){if((g=this.onerror)===null||g===void 0||g.call(this,new Error(`SSE stream disconnected: ${x}`)),(r||c)&&!u&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:i,onresumptiontoken:a,replayMessageId:s},0)}catch(_){(y=this.onerror)===null||y===void 0||y.call(this,new Error(`Failed to reconnect: ${_ instanceof Error?_.message:String(_)}`))}}})()}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 Ja("No auth provider");if(await _s(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ja("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 r,a,s,i,c,u,f;try{const{resumptionToken:m,onresumptiontoken:h}=n||{};if(m){this._startOrAuthSse({resumptionToken:m,replayMessageId:lx(t)?t.id:void 0}).catch(T=>{var R;return(R=this.onerror)===null||R===void 0?void 0:R.call(this,T)});return}const g=await this._commonHeaders();g.set("content-type","application/json"),g.set("accept","application/json, text/event-stream");const y={...this._requestInit,method:"POST",headers:g,body:JSON.stringify(t),signal:(r=this._abortController)===null||r===void 0?void 0:r.signal},x=await((a=this._fetch)!==null&&a!==void 0?a:fetch)(this._url,y),E=x.headers.get("mcp-session-id");if(E&&(this._sessionId=E),!x.ok){const T=await x.text().catch(()=>null);if(x.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new bl(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:R,scope:C}=dp(x);if(this._resourceMetadataUrl=R,this._scope=C,await _s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ja;return this._hasCompletedAuthFlow=!0,this.send(t)}if(x.status===403&&this._authProvider){const{resourceMetadataUrl:R,scope:C,error:I}=dp(x);if(I==="insufficient_scope"){const A=x.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===A)throw new bl(403,"Server returned 403 after trying upscoping");if(C&&(this._scope=C),R&&(this._resourceMetadataUrl=R),this._lastUpscopingHeader=A??void 0,await _s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Ja;return this.send(t)}}throw new bl(x.status,`Error POSTing to endpoint: ${T}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,x.status===202){await((s=x.body)===null||s===void 0?void 0:s.cancel()),kZ(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(T=>{var R;return(R=this.onerror)===null||R===void 0?void 0:R.call(this,T)});return}const _=(Array.isArray(t)?t:[t]).filter(T=>"method"in T&&"id"in T&&T.id!==void 0).length>0,S=x.headers.get("content-type");if(_)if(S?.includes("text/event-stream"))this._handleSseStream(x.body,{onresumptiontoken:h},!1);else if(S?.includes("application/json")){const T=await x.json(),R=Array.isArray(T)?T.map(C=>Bg.parse(C)):[Bg.parse(T)];for(const C of R)(i=this.onmessage)===null||i===void 0||i.call(this,C)}else throw await((c=x.body)===null||c===void 0?void 0:c.cancel()),new bl(-1,`Unexpected content type: ${S}`);else await((u=x.body)===null||u===void 0?void 0:u.cancel())}catch(m){throw(f=this.onerror)===null||f===void 0||f.call(this,m),m}}get sessionId(){return this._sessionId}async terminateSession(){var t,n,r,a;if(this._sessionId)try{const s=await this._commonHeaders(),i={...this._requestInit,method:"DELETE",headers:s,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,i);if(await((r=c.body)===null||r===void 0?void 0:r.cancel()),!c.ok&&c.status!==405)throw new bl(c.status,`Failed to terminate session: ${c.statusText}`);this._sessionId=void 0}catch(s){throw(a=this.onerror)===null||a===void 0||a.call(this,s),s}}setProtocolVersion(t){this._protocolVersion=t}get protocolVersion(){return this._protocolVersion}async resumeStream(t,n){await this._startOrAuthSse({resumptionToken:t,onresumptiontoken:n?.onresumptiontoken})}}class gj extends Event{constructor(t,n){var r,a;super(t),this.code=(r=n?.code)!=null?r:void 0,this.message=(a=n?.message)!=null?a:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,r){return r(bj(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(bj(this),n)}}function PJ(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Ex(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Ex).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Ex(e.cause)}`:e.message:`${e}`}function bj(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var pF=e=>{throw TypeError(e)},O_=(e,t,n)=>t.has(e)||pF("Cannot "+n),Bt=(e,t,n)=>(O_(e,t,"read from private field"),n?n.call(e):t.get(e)),mr=(e,t,n)=>t.has(e)?pF("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Pn=(e,t,n,r)=>(O_(e,t,"write to private field"),t.set(e,n),n),ws=(e,t,n)=>(O_(e,t,"access private method"),n),ya,vl,zc,Vg,_b,Hf,Qc,Vf,Si,Fc,du,Bc,Of,mo,xx,Sx,_x,yj,Tx,Nx,Df,kx,Cx;class Gg extends EventTarget{constructor(t,n){var r,a;super(),mr(this,mo),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,mr(this,ya),mr(this,vl),mr(this,zc),mr(this,Vg),mr(this,_b),mr(this,Hf),mr(this,Qc),mr(this,Vf,null),mr(this,Si),mr(this,Fc),mr(this,du,null),mr(this,Bc,null),mr(this,Of,null),mr(this,Sx,async s=>{var i;Bt(this,Fc).reset();const{body:c,redirected:u,status:f,headers:m}=s;if(f===204){ws(this,mo,Df).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?Pn(this,zc,new URL(s.url)):Pn(this,zc,void 0),f!==200){ws(this,mo,Df).call(this,`Non-200 status code (${f})`,f);return}if(!(m.get("content-type")||"").startsWith("text/event-stream")){ws(this,mo,Df).call(this,'Invalid content type, expected "text/event-stream"',f);return}if(Bt(this,ya)===this.CLOSED)return;Pn(this,ya,this.OPEN);const h=new Event("open");if((i=Bt(this,Of))==null||i.call(this,h),this.dispatchEvent(h),typeof c!="object"||!c||!("getReader"in c)){ws(this,mo,Df).call(this,"Invalid response body, expected a web ReadableStream",f),this.close();return}const g=new TextDecoder,y=c.getReader();let x=!0;do{const{done:E,value:w}=await y.read();w&&Bt(this,Fc).feed(g.decode(w,{stream:!E})),E&&(x=!1,Bt(this,Fc).reset(),ws(this,mo,kx).call(this))}while(x)}),mr(this,_x,s=>{Pn(this,Si,void 0),!(s.name==="AbortError"||s.type==="aborted")&&ws(this,mo,kx).call(this,Ex(s))}),mr(this,Tx,s=>{typeof s.id=="string"&&Pn(this,Vf,s.id);const i=new MessageEvent(s.event||"message",{data:s.data,origin:Bt(this,zc)?Bt(this,zc).origin:Bt(this,vl).origin,lastEventId:s.id||""});Bt(this,Bc)&&(!s.event||s.event==="message")&&Bt(this,Bc).call(this,i),this.dispatchEvent(i)}),mr(this,Nx,s=>{Pn(this,Hf,s)}),mr(this,Cx,()=>{Pn(this,Qc,void 0),Bt(this,ya)===this.CONNECTING&&ws(this,mo,xx).call(this)});try{if(t instanceof URL)Pn(this,vl,t);else if(typeof t=="string")Pn(this,vl,new URL(t,UJ()));else throw new Error("Invalid URL")}catch{throw PJ("An invalid or illegal string was specified")}Pn(this,Fc,fF({onEvent:Bt(this,Tx),onRetry:Bt(this,Nx)})),Pn(this,ya,this.CONNECTING),Pn(this,Hf,3e3),Pn(this,_b,(r=n?.fetch)!=null?r:globalThis.fetch),Pn(this,Vg,(a=n?.withCredentials)!=null?a:!1),ws(this,mo,xx).call(this)}get readyState(){return Bt(this,ya)}get url(){return Bt(this,vl).href}get withCredentials(){return Bt(this,Vg)}get onerror(){return Bt(this,du)}set onerror(t){Pn(this,du,t)}get onmessage(){return Bt(this,Bc)}set onmessage(t){Pn(this,Bc,t)}get onopen(){return Bt(this,Of)}set onopen(t){Pn(this,Of,t)}addEventListener(t,n,r){const a=n;super.addEventListener(t,a,r)}removeEventListener(t,n,r){const a=n;super.removeEventListener(t,a,r)}close(){Bt(this,Qc)&&clearTimeout(Bt(this,Qc)),Bt(this,ya)!==this.CLOSED&&(Bt(this,Si)&&Bt(this,Si).abort(),Pn(this,ya,this.CLOSED),Pn(this,Si,void 0))}}ya=new WeakMap,vl=new WeakMap,zc=new WeakMap,Vg=new WeakMap,_b=new WeakMap,Hf=new WeakMap,Qc=new WeakMap,Vf=new WeakMap,Si=new WeakMap,Fc=new WeakMap,du=new WeakMap,Bc=new WeakMap,Of=new WeakMap,mo=new WeakSet,xx=function(){Pn(this,ya,this.CONNECTING),Pn(this,Si,new AbortController),Bt(this,_b)(Bt(this,vl),ws(this,mo,yj).call(this)).then(Bt(this,Sx)).catch(Bt(this,_x))},Sx=new WeakMap,_x=new WeakMap,yj=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...Bt(this,Vf)?{"Last-Event-ID":Bt(this,Vf)}:void 0},cache:"no-store",signal:(e=Bt(this,Si))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Tx=new WeakMap,Nx=new WeakMap,Df=function(e,t){var n;Bt(this,ya)!==this.CLOSED&&Pn(this,ya,this.CLOSED);const r=new gj("error",{code:t,message:e});(n=Bt(this,du))==null||n.call(this,r),this.dispatchEvent(r)},kx=function(e,t){var n;if(Bt(this,ya)===this.CLOSED)return;Pn(this,ya,this.CONNECTING);const r=new gj("error",{code:t,message:e});(n=Bt(this,du))==null||n.call(this,r),this.dispatchEvent(r),Pn(this,Qc,setTimeout(Bt(this,Cx),Bt(this,Hf)))},Cx=new WeakMap,Gg.CONNECTING=0,Gg.OPEN=1,Gg.CLOSED=2;function UJ(){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 $J extends Error{constructor(t,n,r){super(`SSE error: ${n}`),this.code=t,this.event=r}}class zJ{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=J2(n?.fetch,n?.requestInit)}async _authThenStart(){var t;if(!this._authProvider)throw new Ja("No auth provider");let n;try{n=await _s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw(t=this.onerror)===null||t===void 0||t.call(this,r),r}if(n!=="AUTHORIZED")throw new Ja;return await this._startOrAuth()}async _commonHeaders(){var t;const n={};if(this._authProvider){const a=await this._authProvider.tokens();a&&(n.Authorization=`Bearer ${a.access_token}`)}this._protocolVersion&&(n["mcp-protocol-version"]=this._protocolVersion);const r=vb((t=this._requestInit)===null||t===void 0?void 0:t.headers);return new Headers({...n,...r})}_startOrAuth(){var t,n,r;const a=(r=(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&&r!==void 0?r:fetch;return new Promise((s,i)=>{this._eventSource=new Gg(this._url.href,{...this._eventSourceInit,fetch:async(c,u)=>{const f=await this._commonHeaders();f.set("Accept","text/event-stream");const m=await a(c,{...u,headers:f});if(m.status===401&&m.headers.has("www-authenticate")){const{resourceMetadataUrl:h,scope:g}=dp(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(s,i);return}const f=new $J(c.code,c.message,c);i(f),(u=this.onerror)===null||u===void 0||u.call(this,f)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",c=>{var u;const f=c;try{if(this._endpoint=new URL(f.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(m){i(m),(u=this.onerror)===null||u===void 0||u.call(this,m),this.close();return}s()}),this._eventSource.onmessage=c=>{var u,f;const m=c;let h;try{h=Bg.parse(JSON.parse(m.data))}catch(g){(u=this.onerror)===null||u===void 0||u.call(this,g);return}(f=this.onmessage)===null||f===void 0||f.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 Ja("No auth provider");if(await _s(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ja("Failed to authorize")}async close(){var t,n,r;(t=this._abortController)===null||t===void 0||t.abort(),(n=this._eventSource)===null||n===void 0||n.close(),(r=this.onclose)===null||r===void 0||r.call(this)}async send(t){var n,r,a,s;if(!this._endpoint)throw new Error("Not connected");try{const i=await this._commonHeaders();i.set("content-type","application/json");const c={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(t),signal:(n=this._abortController)===null||n===void 0?void 0:n.signal},u=await((r=this._fetch)!==null&&r!==void 0?r:fetch)(this._endpoint,c);if(!u.ok){const f=await u.text().catch(()=>null);if(u.status===401&&this._authProvider){const{resourceMetadataUrl:m,scope:h}=dp(u);if(this._resourceMetadataUrl=m,this._scope=h,await _s(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ja;return this.send(t)}throw new Error(`Error POSTing to endpoint (HTTP ${u.status}): ${f}`)}await((a=u.body)===null||a===void 0?void 0:a.cancel())}catch(i){throw(s=this.onerror)===null||s===void 0||s.call(this,i),i}}setProtocolVersion(t){this._protocolVersion=t}}var Qw,vj;function FJ(){return vj||(vj=1,Qw=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),Qw}var BJ=FJ();const wj=jp(BJ);var Mu,HJ=(Mu=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}get serverCapabilities(){return this.connector.serverCapabilities}get serverInfo(){return this.connector.serverInfo}async callTool(t,n,r){return this.connector.callTool(t,n,r)}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,r){return this.connector.request(t,n,r)}},Pe(Mu,"MCPSession"),Mu),ju,mF=(ju=class{_readyPromise;_readyResolver;_donePromise;_doneResolver;_exception=null;_connection=null;_task=null;_abortController=null;constructor(){this.reset()}async start(){if(this.reset(),ve.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){ve.debug(`Cancelling ${this.constructor.name} task`),this._abortController.abort();try{await this._task}catch(t){t instanceof Error&&t.name==="AbortError"?ve.debug(`${this.constructor.name} task aborted successfully`):ve.warn(`Error stopping ${this.constructor.name} task: ${t}`)}}await this._donePromise,ve.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(){ve.debug(`Running ${this.constructor.name} task`);try{this._connection=await this.establishConnection(),ve.debug(`${this.constructor.name} connected successfully`),this._readyResolver(),await this.waitForAbort()}catch(t){this._exception=t,ve.error(`Error in ${this.constructor.name} task: ${t}`),this._readyResolver()}finally{if(this._connection!==null){try{await this.closeConnection(this._connection)}catch(t){ve.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 r=this._abortController.signal;if(r.aborted){t();return}const a=Pe(()=>{r.removeEventListener("abort",a),t()},"onAbort");r.addEventListener("abort",a)})}},Pe(ju,"ConnectionManager"),ju),Pu,VJ=(Pu=class extends mF{url;opts;_transport=null;constructor(t,n){super(),this.url=typeof t=="string"?new URL(t):t,this.opts=n}async establishConnection(){return this._transport=new zJ(this.url,this.opts),ve.debug(`${this.constructor.name} connected successfully`),this._transport}async closeConnection(t){if(this._transport)try{await this._transport.close()}catch(n){ve.warn(`Error closing SSE transport: ${n}`)}finally{this._transport=null}}},Pe(Pu,"SseConnectionManager"),Pu),Uu,Ej=(Uu=class extends B2{baseUrl;headers;timeout;sseReadTimeout;clientInfo;preferSse;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}async connect(){if(this.connected){ve.debug("Already connected to MCP implementation");return}const t=this.baseUrl;if(this.preferSse){ve.debug(`Connecting to MCP implementation via HTTP/SSE: ${t}`),await this.connectWithSse(t);return}ve.debug(`Connecting to MCP implementation via HTTP: ${t}`);try{ve.info("🔄 Attempting streamable HTTP transport..."),await this.connectWithStreamableHttp(t),ve.info("✅ Successfully connected via streamable HTTP")}catch(n){let r="Unknown error",a=!1;if(n instanceof bl){const s=n;a=s.code===401,s.code===400&&s.message.includes("Missing session ID")?(r="Server requires session ID (FastMCP compatibility) - using SSE transport",ve.warn(`⚠️ ${r}`)):s.code===404||s.code===405?(r=`Server returned ${s.code} - server likely doesn't support streamable HTTP`,ve.debug(r)):(r=`Server returned ${s.code}: ${s.message}`,ve.debug(r))}else if(n instanceof Error){const s=n.toString(),i=n.message||"";a=s.includes("401")||i.includes("Unauthorized"),s.includes("Missing session ID")||s.includes("Bad Request: Missing session ID")||i.includes("FastMCP session ID error")?(r="Server requires session ID (FastMCP compatibility) - using SSE transport",ve.warn(`⚠️ ${r}`)):s.includes("405 Method Not Allowed")||s.includes("404 Not Found")?(r="Server doesn't support streamable HTTP (405/404)",ve.debug(r)):(r=`Streamable HTTP failed: ${n.message}`,ve.debug(r))}if(a){ve.info("Authentication required - skipping SSE fallback"),await this.cleanupResources();const s=new Error("Authentication required");throw s.code=401,s}ve.info("🔄 Falling back to SSE transport...");try{await this.connectWithSse(t)}catch(s){if(ve.error("Failed to connect with both transports:"),ve.error(` Streamable HTTP: ${r}`),ve.error(` SSE: ${s}`),await this.cleanupResources(),s?.message?.includes("401")||s?.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 jJ(new URL(t),{authProvider:this.opts.authProvider,requestInit:{headers:this.headers},reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:2}});let r=n;if(this.opts.wrapTransport){const s=this.baseUrl;r=this.opts.wrapTransport(r,s)}const a={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};ve.debug("Creating Client with capabilities:",JSON.stringify(a.capabilities,null,2)),this.client=new dj(this.clientInfo,a),this.setupRootsHandler(),ve.debug("Roots handler registered before connect");try{await this.client.connect(r,{timeout:Math.min(this.timeout,3e3)});const s=n.sessionId;s?ve.debug(`Session ID obtained: ${s}`):ve.warn("Session ID not available after connect - this may cause issues with SSE stream")}catch(s){if(s instanceof Error){const i=s.message||s.toString();if(i.includes("Missing session ID")||i.includes("Bad Request: Missing session ID")||i.includes("Mcp-Session-Id header is required")){const c=new Error(`Session ID error: ${i}. The SDK should automatically extract session ID from initialize response.`);throw c.cause=s,c}}throw s}this.streamableTransport=n,this.connectionManager={stop:Pe(async()=>{if(this.streamableTransport)try{await this.streamableTransport.terminateSession(),await this.streamableTransport.close()}catch(s){ve.warn(`Error closing Streamable HTTP transport: ${s}`)}finally{this.streamableTransport=null}},"stop")},this.connected=!0,this.transportType="streamable-http",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),ve.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 VJ(t,{authProvider:this.opts.authProvider,requestInit:{headers:this.headers}});let n=await this.connectionManager.start();if(this.opts.wrapTransport){const a=this.baseUrl;n=this.opts.wrapTransport(n,a)}const r={...this.opts.clientOptions||{},capabilities:{...this.opts.clientOptions?.capabilities||{},roots:{listChanged:!0},...this.opts.samplingCallback?{sampling:{}}:{},...this.opts.elicitationCallback?{elicitation:{form:{},url:{}}}:{}}};ve.debug("Creating Client with capabilities (SSE):",JSON.stringify(r.capabilities,null,2)),this.client=new dj(this.clientInfo,r),this.setupRootsHandler(),ve.debug("Roots handler registered before connect (SSE)"),await this.client.connect(n),this.connected=!0,this.transportType="sse",this.setupNotificationHandler(),this.setupSamplingHandler(),this.setupElicitationHandler(),ve.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}},Pe(Uu,"HttpConnector"),Uu),$u,GJ=($u=class extends mF{url;headers;_ws=null;constructor(t,n={}){super(),this.url=t,this.headers=n}async establishConnection(){return ve.debug(`Connecting to WebSocket: ${this.url}`),new Promise((t,n)=>{const r=new wj(this.url,{headers:this.headers});this._ws=r;const a=Pe(()=>{i(),ve.debug("WebSocket connected successfully"),t(r)},"onOpen"),s=Pe(c=>{i(),ve.error(`Failed to connect to WebSocket: ${c}`),n(c)},"onError"),i=Pe(()=>{r.off("open",a),r.off("error",s)},"cleanup");r.on("open",a),r.on("error",s)})}async closeConnection(t){return ve.debug("Closing WebSocket connection"),new Promise(n=>{const r=Pe(()=>{t.off("close",r),this._ws=null,n()},"onClose");if(t.readyState===wj.CLOSED){r();return}t.on("close",r);try{t.close()}catch(a){ve.warn(`Error closing WebSocket connection: ${a}`),r()}})}},Pe($u,"WebSocketConnectionManager"),$u),zu,WJ=(zu=class extends B2{url;headers;connectionManager=null;ws=null;receiverTask=null;pending=new Map;toolsCache=null;constructor(t,n={}){super(),this.url=t,this.headers={...n.headers??{}},n.authToken&&(this.headers.Authorization=`Bearer ${n.authToken}`)}async connect(){if(this.connected){ve.debug("Already connected to MCP implementation");return}ve.debug(`Connecting via WebSocket: ${this.url}`);try{this.connectionManager=new GJ(this.url,this.headers),this.ws=await this.connectionManager.start(),this.receiverTask=this.receiveLoop(),this.connected=!0,ve.debug("WebSocket connected successfully")}catch(t){throw ve.error(`Failed to connect: ${t}`),await this.cleanupResources(),t}}async disconnect(){if(!this.connected){ve.debug("Not connected to MCP implementation");return}ve.debug("Disconnecting …"),await this.cleanupResources(),this.connected=!1}sendRequest(t,n=null){if(!this.ws)throw new Error("WebSocket is not connected");const r=Zc(),a=JSON.stringify({id:r,method:t,params:n??{}});return new Promise((s,i)=>{this.pending.set(r,{resolve:s,reject:i}),this.ws.send(a,c=>{c&&(this.pending.delete(r),i(c))})})}async receiveLoop(){if(!this.ws)return;const t=this.ws,n=Pe(r=>{let a;try{a=JSON.parse(r.data??r)}catch(i){ve.warn("Received non‑JSON frame",i);return}const s=a.id;if(s&&this.pending.has(s)){const{resolve:i,reject:c}=this.pending.get(s);this.pending.delete(s),"result"in a?i(a.result):"error"in a&&c(a.error)}else a.method&&!a.id?(ve.debug("Received notification",a.method,a.params),this.handleNotification(a)):ve.debug("Received unsolicited message",a)},"onMessage");return t.addEventListener?t.addEventListener("message",n):t.on("message",n),new Promise(r=>{const a=Pe(()=>{t.removeEventListener?t.removeEventListener("message",n):t.off("message",n),this.rejectAll(new Error("WebSocket closed")),r()},"onClose");t.addEventListener?t.addEventListener("close",a):t.on("close",a)})}rejectAll(t){for(const{reject:n}of this.pending.values())n(t);this.pending.clear()}async handleNotification(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({method:t.method,params:t.params})}catch(r){ve.error("Error in notification handler:",r)}}async refreshToolsCache(){try{ve.debug("[Auto] Refreshing tools cache due to list_changed notification");const t=await this.listTools();this.toolsCache=t.map(n=>n),ve.debug(`[Auto] Refreshed tools cache: ${this.toolsCache.length} tools`)}catch(t){ve.warn("[Auto] Failed to refresh tools cache:",t)}}async initialize(){ve.debug("Initializing MCP session over WebSocket");const t=await this.sendRequest("initialize"),n=await this.listTools();return this.toolsCache=n.map(r=>r),ve.debug(`Initialized with ${this.toolsCache.length} tools`),t}async listTools(){return(await this.sendRequest("tools/list")).tools??[]}async callTool(t,n){return await this.sendRequest("tools/call",{name:t,arguments:n})}async listResources(){const t=await this.sendRequest("resources/list");return{resources:Array.isArray(t)?t:[]}}async readResource(t){return await this.sendRequest("resources/read",{uri:t})}async request(t,n=null){return await this.sendRequest(t,n)}get tools(){if(!this.toolsCache)throw new Error("MCP client is not initialized");return this.toolsCache}async cleanupResources(){this.receiverTask&&await this.receiverTask.catch(()=>{}),this.receiverTask=null,this.rejectAll(new Error("WebSocket disconnected")),this.connectionManager&&(await this.connectionManager.stop(),this.connectionManager=null,this.ws=null),this.toolsCache=null}get publicIdentifier(){return{type:"websocket",url:this.url}}},Pe(zu,"WebSocketConnector"),zu),Fu,KJ=(Fu=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,Uo.getInstance().trackClientAddServer(t,n)}removeServer(t){this.config.mcpServers?.[t]&&(delete this.config.mcpServers[t],this.activeSessions=this.activeSessions.filter(n=>n!==t),Uo.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 r=this.config.mcpServers??{};if(Object.keys(r).length===0&&ve.warn("No MCP servers defined in config"),!r[t])throw new Error(`Server '${t}' not found in config`);const a=this.createConnectorFromConfig(r[t]),s=new HJ(a);return n&&await s.initialize(),this.sessions[t]=s,this.activeSessions.includes(t)||this.activeSessions.push(t),s}async createAllSessions(t=!0){const n=this.config.mcpServers??{};Object.keys(n).length===0&&ve.warn("No MCP servers defined in config");for(const r of Object.keys(n))await this.createSession(r,t);return this.sessions}getSession(t){const n=this.sessions[t];return n||null}getAllActiveSessions(){return Object.fromEntries(this.activeSessions.map(t=>[t,this.sessions[t]]))}async closeSession(t){const n=this.sessions[t];if(!n){ve.warn(`No session exists for server ${t}, nothing to close`);return}try{ve.debug(`Closing session for server ${t}`),await n.disconnect()}catch(r){ve.error(`Error closing session for server '${t}': ${r}`)}finally{delete this.sessions[t],this.activeSessions=this.activeSessions.filter(r=>r!==t)}}async closeAllSessions(){const t=Object.keys(this.sessions),n=[];for(const r of t)try{ve.debug(`Closing session for server ${r}`),await this.closeSession(r)}catch(a){const s=`Failed to close session for server '${r}': ${a}`;ve.error(s),n.push(s)}n.length?ve.error(`Encountered ${n.length} errors while closing sessions`):ve.debug("All sessions closed successfully")}},Pe(Fu,"BaseMCPClient"),Fu),Rl,YJ=(Rl=class extends KJ{static getPackageVersion(){return fb()}constructor(t){super(t),this._trackClientInit()}_trackClientInit(){const t=Object.keys(this.config.mcpServers??{});Uo.getInstance().trackMCPClientInit({codeMode:!1,sandbox:!1,allCallbacks:!1,verify:!1,servers:t,numServers:t.length,isBrowser:!0}).catch(n=>ve.debug(`Failed to track BrowserMCPClient init: ${n}`))}static fromDict(t){return new Rl(t)}createConnectorFromConfig(t){const{url:n,transport:r,headers:a,authToken:s,authProvider:i,wrapTransport:c,clientOptions:u,samplingCallback:f,elicitationCallback:m}=t;if(!n)throw new Error("Server URL is required");const h={headers:a,authToken:s,authProvider:i,wrapTransport:c,clientOptions:u,samplingCallback:f,elicitationCallback:m};return u?console.log("[BrowserMCPClient] Passing clientOptions to connector:",JSON.stringify(u,null,2)):console.warn("[BrowserMCPClient] No clientOptions provided to connector!"),r==="websocket"||n.startsWith("ws://")||n.startsWith("wss://")?new WJ(n,h):r==="http"||n.startsWith("http://")||n.startsWith("https://")?new Ej(n,h):new Ej(n,h)}},Pe(Rl,"BrowserMCPClient"),Rl);function eu(e){const t=Pe(()=>{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(hF).join("&"),n.hash=n.hash.slice(0,1)+encodeURIComponent(n.hash.slice(1)),n.href}Pe(eu,"sanitizeUrl");function hF([e,t]){return`${encodeURIComponent(e)}${t.length>0?`=${encodeURIComponent(t)}`:""}`}Pe(hF,"sanitizeParam");var Bu,Wg=(Bu=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=eu(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 eu(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(r){console.warn(`[${this.storageKeyPrefix}] Failed to parse client information:`,r),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(r){console.warn(`[${this.storageKeyPrefix}] Failed to parse tokens:`,r),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(),r=`${this.storageKeyPrefix}:state_${n}`,a={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(r,JSON.stringify(a)),t.searchParams.set("state",n);const s=t.toString(),i=eu(s);return localStorage.setItem(this.getKey("last_auth_url"),i),i}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 r="width=600,height=700,resizable=yes,scrollbars=yes,status=yes";try{const a=window.open(n,`mcp_auth_${this.serverUrlHash}`,r);this.onPopupWindow&&this.onPopupWindow(n,r,a),!a||a.closed||typeof a.closed>"u"?console.warn(`[${this.storageKeyPrefix}] Popup likely blocked by browser. Manual navigation might be required using the stored URL.`):(a.focus(),console.info(`[${this.storageKeyPrefix}] Redirecting to authorization URL in popup.`))}catch(a){console.error(`[${this.storageKeyPrefix}] Error opening popup window:`,a)}}getLastAttemptedAuthUrl(){const t=localStorage.getItem(this.getKey("last_auth_url"));return t?eu(t):null}clearStorage(){const t=`${this.storageKeyPrefix}_${this.serverUrlHash}_`,n=`${this.storageKeyPrefix}:state_`,r=[];let a=0;for(let i=0;i<localStorage.length;i++){const c=localStorage.key(i);if(c){if(c.startsWith(t))r.push(c);else if(c.startsWith(n))try{const u=localStorage.getItem(c);u&&JSON.parse(u).serverUrlHash===this.serverUrlHash&&r.push(c)}catch(u){console.warn(`[${this.storageKeyPrefix}] Error parsing state key ${c} during clearStorage:`,u)}}}return[...new Set(r)].forEach(i=>{localStorage.removeItem(i),a++}),a}hashString(t){let n=0;for(let r=0;r<t.length;r++){const a=t.charCodeAt(r);n=(n<<5)-n+a,n=n&n}return Math.abs(n).toString(16)}getKey(t){return`${this.storageKeyPrefix}_${this.serverUrlHash}_${t}`}},Pe(Bu,"BrowserOAuthClientProvider"),Bu);async function D_(){const e=new URLSearchParams(window.location.search),t=e.get("code"),n=e.get("state"),r=e.get("error"),a=e.get("error_description"),s="[mcp-callback]";console.log(`${s} Handling callback...`,{code:t,state:n,error:r,errorDescription:a});let i=null,c=null;const u=n?`mcp:auth:state_${n}`:null;try{if(r)throw new Error(`OAuth error: ${r} - ${a||"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 f=localStorage.getItem(u);if(!f)throw new Error(`Invalid or expired state parameter "${n}". No matching state found in storage.`);try{c=JSON.parse(f)}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(`${s} Re-instantiating provider for server: ${m}`),i=new Wg(m,h),console.log(`${s} Calling SDK auth() to exchange code...`);const g=new URL(m).origin,y=await _s(i,{serverUrl:g,authorizationCode:t});if(y==="AUTHORIZED")if(console.log(`${s} Authorization successful via SDK auth().`),c.flowType==="redirect"&&c.returnUrl)console.log(`${s} Redirect flow complete. Returning to: ${c.returnUrl}`),localStorage.removeItem(u),window.location.href=c.returnUrl;else if(window.opener&&!window.opener.closed)console.log(`${s} 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(`${s} No opener window or return URL detected. Redirecting to root.`),localStorage.removeItem(u);const E=window.location.pathname.split("/").filter(Boolean),w=E.length>0&&E[E.length-1]==="callback"?"/"+E.slice(0,-2).join("/"):"/";window.location.href=w||"/"}else throw console.warn(`${s} SDK auth() returned unexpected status: ${y}`),new Error(`Unexpected result from authentication library: ${y}`)}catch(f){console.error(`${s} Error during OAuth callback handling:`,f);const m=f instanceof Error?f.message:String(f);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 y=document.createElement("p");y.style.color="red",y.style.backgroundColor="#ffebeb",y.style.border="1px solid red",y.style.padding="10px",y.style.borderRadius="4px",y.textContent=m,h.appendChild(y);const x=document.createElement("p");x.textContent="You can close this window or ";const E=document.createElement("a");if(E.href="#",E.textContent="click here to close",E.onclick=w=>(w.preventDefault(),window.close(),!1),x.appendChild(E),x.appendChild(document.createTextNode(".")),h.appendChild(x),f instanceof Error&&f.stack){const w=document.createElement("pre");w.style.fontSize="0.8em",w.style.color="#555",w.style.marginTop="20px",w.style.whiteSpace="pre-wrap",w.textContent=f.stack,h.appendChild(w)}document.body.appendChild(h)}catch(h){console.error(`${s} Could not display error in callback window:`,h)}u&&localStorage.removeItem(u),i&&(localStorage.removeItem(i.getKey("code_verifier")),localStorage.removeItem(i.getKey("last_auth_url")))}}Pe(D_,"onMcpAuthorization");var eE={exports:{}},yt={};var xj;function ZJ(){if(xj)return yt;xj=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),s=Symbol.for("react.consumer"),i=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),f=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),g=Symbol.iterator;function y(D){return D===null||typeof D!="object"?null:(D=g&&D[g]||D["@@iterator"],typeof D=="function"?D:null)}var x={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,w={};function _(D,H,$){this.props=D,this.context=H,this.refs=w,this.updater=$||x}_.prototype.isReactComponent={},_.prototype.setState=function(D,H){if(typeof D!="object"&&typeof D!="function"&&D!=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,D,H,"setState")},_.prototype.forceUpdate=function(D){this.updater.enqueueForceUpdate(this,D,"forceUpdate")};function S(){}S.prototype=_.prototype;function T(D,H,$){this.props=D,this.context=H,this.refs=w,this.updater=$||x}var R=T.prototype=new S;R.constructor=T,E(R,_.prototype),R.isPureReactComponent=!0;var C=Array.isArray;function I(){}var A={H:null,A:null,T:null,S:null},O=Object.prototype.hasOwnProperty;function j(D,H,$){var L=$.ref;return{$$typeof:e,type:D,key:H,ref:L!==void 0?L:null,props:$}}function U(D,H){return j(D.type,H,D.props)}function B(D){return typeof D=="object"&&D!==null&&D.$$typeof===e}function W(D){var H={"=":"=0",":":"=2"};return"$"+D.replace(/[=:]/g,function($){return H[$]})}var J=/\/+/g;function ee(D,H){return typeof D=="object"&&D!==null&&D.key!=null?W(""+D.key):H.toString(36)}function re(D){switch(D.status){case"fulfilled":return D.value;case"rejected":throw D.reason;default:switch(typeof D.status=="string"?D.then(I,I):(D.status="pending",D.then(function(H){D.status==="pending"&&(D.status="fulfilled",D.value=H)},function(H){D.status==="pending"&&(D.status="rejected",D.reason=H)})),D.status){case"fulfilled":return D.value;case"rejected":throw D.reason}}throw D}function F(D,H,$,L,M){var z=typeof D;(z==="undefined"||z==="boolean")&&(D=null);var G=!1;if(D===null)G=!0;else switch(z){case"bigint":case"string":case"number":G=!0;break;case"object":switch(D.$$typeof){case e:case t:G=!0;break;case m:return G=D._init,F(G(D._payload),H,$,L,M)}}if(G)return M=M(D),G=L===""?"."+ee(D,0):L,C(M)?($="",G!=null&&($=G.replace(J,"$&/")+"/"),F(M,H,$,"",function(ie){return ie})):M!=null&&(B(M)&&(M=U(M,$+(M.key==null||D&&D.key===M.key?"":(""+M.key).replace(J,"$&/")+"/")+G)),H.push(M)),1;G=0;var q=L===""?".":L+":";if(C(D))for(var ae=0;ae<D.length;ae++)L=D[ae],z=q+ee(L,ae),G+=F(L,H,$,z,M);else if(ae=y(D),typeof ae=="function")for(D=ae.call(D),ae=0;!(L=D.next()).done;)L=L.value,z=q+ee(L,ae++),G+=F(L,H,$,z,M);else if(z==="object"){if(typeof D.then=="function")return F(re(D),H,$,L,M);throw H=String(D),Error("Objects are not valid as a React child (found: "+(H==="[object Object]"?"object with keys {"+Object.keys(D).join(", ")+"}":H)+"). If you meant to render a collection of children, use an array instead.")}return G}function K(D,H,$){if(D==null)return D;var L=[],M=0;return F(D,L,"","",function(z){return H.call($,z,M++)}),L}function V(D){if(D._status===-1){var H=D._result;H=H(),H.then(function($){(D._status===0||D._status===-1)&&(D._status=1,D._result=$)},function($){(D._status===0||D._status===-1)&&(D._status=2,D._result=$)}),D._status===-1&&(D._status=0,D._result=H)}if(D._status===1)return D._result.default;throw D._result}var ne=typeof reportError=="function"?reportError:function(D){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var H=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof D=="object"&&D!==null&&typeof D.message=="string"?String(D.message):String(D),error:D});if(!window.dispatchEvent(H))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",D);return}console.error(D)},te={map:K,forEach:function(D,H,$){K(D,function(){H.apply(this,arguments)},$)},count:function(D){var H=0;return K(D,function(){H++}),H},toArray:function(D){return K(D,function(H){return H})||[]},only:function(D){if(!B(D))throw Error("React.Children.only expected to receive a single React element child.");return D}};return yt.Activity=h,yt.Children=te,yt.Component=_,yt.Fragment=n,yt.Profiler=a,yt.PureComponent=T,yt.StrictMode=r,yt.Suspense=u,yt.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=A,yt.__COMPILER_RUNTIME={__proto__:null,c:function(D){return A.H.useMemoCache(D)}},yt.cache=function(D){return function(){return D.apply(null,arguments)}},yt.cacheSignal=function(){return null},yt.cloneElement=function(D,H,$){if(D==null)throw Error("The argument must be a React element, but you passed "+D+".");var L=E({},D.props),M=D.key;if(H!=null)for(z in H.key!==void 0&&(M=""+H.key),H)!O.call(H,z)||z==="key"||z==="__self"||z==="__source"||z==="ref"&&H.ref===void 0||(L[z]=H[z]);var z=arguments.length-2;if(z===1)L.children=$;else if(1<z){for(var G=Array(z),q=0;q<z;q++)G[q]=arguments[q+2];L.children=G}return j(D.type,M,L)},yt.createContext=function(D){return D={$$typeof:i,_currentValue:D,_currentValue2:D,_threadCount:0,Provider:null,Consumer:null},D.Provider=D,D.Consumer={$$typeof:s,_context:D},D},yt.createElement=function(D,H,$){var L,M={},z=null;if(H!=null)for(L in H.key!==void 0&&(z=""+H.key),H)O.call(H,L)&&L!=="key"&&L!=="__self"&&L!=="__source"&&(M[L]=H[L]);var G=arguments.length-2;if(G===1)M.children=$;else if(1<G){for(var q=Array(G),ae=0;ae<G;ae++)q[ae]=arguments[ae+2];M.children=q}if(D&&D.defaultProps)for(L in G=D.defaultProps,G)M[L]===void 0&&(M[L]=G[L]);return j(D,z,M)},yt.createRef=function(){return{current:null}},yt.forwardRef=function(D){return{$$typeof:c,render:D}},yt.isValidElement=B,yt.lazy=function(D){return{$$typeof:m,_payload:{_status:-1,_result:D},_init:V}},yt.memo=function(D,H){return{$$typeof:f,type:D,compare:H===void 0?null:H}},yt.startTransition=function(D){var H=A.T,$={};A.T=$;try{var L=D(),M=A.S;M!==null&&M($,L),typeof L=="object"&&L!==null&&typeof L.then=="function"&&L.then(I,ne)}catch(z){ne(z)}finally{H!==null&&$.types!==null&&(H.types=$.types),A.T=H}},yt.unstable_useCacheRefresh=function(){return A.H.useCacheRefresh()},yt.use=function(D){return A.H.use(D)},yt.useActionState=function(D,H,$){return A.H.useActionState(D,H,$)},yt.useCallback=function(D,H){return A.H.useCallback(D,H)},yt.useContext=function(D){return A.H.useContext(D)},yt.useDebugValue=function(){},yt.useDeferredValue=function(D,H){return A.H.useDeferredValue(D,H)},yt.useEffect=function(D,H){return A.H.useEffect(D,H)},yt.useEffectEvent=function(D){return A.H.useEffectEvent(D)},yt.useId=function(){return A.H.useId()},yt.useImperativeHandle=function(D,H,$){return A.H.useImperativeHandle(D,H,$)},yt.useInsertionEffect=function(D,H){return A.H.useInsertionEffect(D,H)},yt.useLayoutEffect=function(D,H){return A.H.useLayoutEffect(D,H)},yt.useMemo=function(D,H){return A.H.useMemo(D,H)},yt.useOptimistic=function(D,H){return A.H.useOptimistic(D,H)},yt.useReducer=function(D,H,$){return A.H.useReducer(D,H,$)},yt.useRef=function(D){return A.H.useRef(D)},yt.useState=function(D){return A.H.useState(D)},yt.useSyncExternalStore=function(D,H,$){return A.H.useSyncExternalStore(D,H,$)},yt.useTransition=function(){return A.H.useTransition()},yt.version="19.2.0",yt}var Sj;function L_(){return Sj||(Sj=1,eE.exports=ZJ()),eE.exports}var v=L_();const ce=jp(v),id=EG({__proto__:null,default:ce},[v]);function Rx(e,t){if(!e)throw new Error(t)}Pe(Rx,"assert");var qJ=3e3,XJ=5e3;function M_(e){const{url:t,enabled:n=!0,clientName:r,clientUri:a,callbackUrl:s=typeof window<"u"?eu(new URL("/oauth/callback",window.location.origin).toString()):"/oauth/callback",storageKeyPrefix:i="mcp:auth",clientConfig:c={},customHeaders:u={},debug:f=!1,autoRetry:m=!1,autoReconnect:h=qJ,transportType:g="auto",preventAutoAuth:y=!1,useRedirectFlow:x=!1,onPopupWindow:E,timeout:w=3e4,sseReadTimeout:_=3e5,wrapTransport:S,onNotification:T,samplingCallback:R,onElicitation:C}=e,[I,A]=v.useState("discovering"),[O,j]=v.useState([]),[U,B]=v.useState([]),[W,J]=v.useState([]),[ee,re]=v.useState([]),[F,K]=v.useState(),[V,ne]=v.useState(),[te,D]=v.useState(void 0),[H,$]=v.useState([]),[L,M]=v.useState(void 0),z=v.useRef(null),G=v.useRef(null),q=v.useRef(!1),ae=v.useRef(!0),ie=v.useRef(0),X=v.useRef(null),Z=v.useRef(I),se=v.useRef(h),me=v.useRef(null);v.useEffect(()=>{Z.current=I,se.current=h},[I,h]);const le=v.useCallback((De,ze,...ht)=>{const nt=ht.length>0?`${ze} ${ht.map(kt=>JSON.stringify(kt)).join(" ")}`:ze;console[De](`[useMcp] ${nt}`),ae.current&&$(kt=>[...kt.slice(-100),{level:De,message:nt,timestamp:Date.now()}])},[]),Ne=v.useCallback(async(De=!1)=>{if(De||le("info","Disconnecting..."),q.current=!1,X.current&&clearTimeout(X.current),X.current=null,z.current)try{await z.current.closeSession("inspector-server")}catch(ze){De||le("warn","Error closing session:",ze)}z.current=null,ae.current&&!De&&(A("discovering"),j([]),B([]),J([]),re([]),D(void 0),M(void 0))},[le]),He=v.useCallback((De,ze)=>{if(le("error",De,ze??""),ae.current){A("failed"),D(De);const ht=G.current?.getLastAttemptedAuthUrl();ht&&(M(ht),le("info","Manual authentication URL may be available.",ht))}q.current=!1,t&&Uo.getInstance().trackUseMcpConnection({url:t,transportType:g,success:!1,errorType:ze?.name||"UnknownError",hasOAuth:!!G.current,hasSampling:!!R,hasElicitation:!!C}).catch(()=>{})},[le,t,g,R,C]),xe=v.useCallback(async()=>{if(!n||!t){le("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag.");return}if(q.current){le("debug","Connection attempt already in progress.");return}if(!ae.current){le("debug","Connect called after unmount, aborting.");return}q.current=!0,ie.current+=1,D(void 0),M(void 0),me.current=null,A("discovering"),le("info",`Connecting attempt #${ie.current} to ${t}...`),G.current||(G.current=new Wg(t,{storageKeyPrefix:i,clientName:r,clientUri:a,callbackUrl:s,preventAutoAuth:y,useRedirectFlow:x,onPopupWindow:E}),le("debug","BrowserOAuthClientProvider initialized in connect.")),z.current||(z.current=new YJ,le("debug","BrowserMCPClient initialized in connect."));const De=Pe(async(ht,nt=!1)=>{le("info",`Attempting connection with transport: ${ht}`);try{const kt="inspector-server",ot={url:t,transport:ht==="sse"?"http":ht};if(u&&Object.keys(u).length>0&&(ot.headers=u),G.current){const Et=await G.current.tokens();Et?.access_token&&(ot.headers={...ot.headers,Authorization:`Bearer ${Et.access_token}`})}z.current.addServer(kt,{...ot,authProvider:G.current,clientOptions:c,samplingCallback:R,elicitationCallback:C,wrapTransport:S?Et=>(console.log("[useMcp] Applying transport wrapper for server:",kt,"url:",t),S(Et,t)):void 0});const Ae=await z.current.createSession(kt,!1);T&&Ae.on("notification",T),await Ae.initialize(),le("info","✅ Successfully connected to MCP server"),le("info","Server info:",Ae.connector.serverInfo),le("info","Server capabilities:",Ae.connector.serverCapabilities),console.log("[useMcp] Server info:",Ae.connector.serverInfo),console.log("[useMcp] Server capabilities:",Ae.connector.serverCapabilities),A("ready"),me.current=ht,Uo.getInstance().trackUseMcpConnection({url:t,transportType:ht,success:!0,hasOAuth:!!G.current,hasSampling:!!R,hasElicitation:!!C}).catch(()=>{}),j(Ae.connector.tools||[]);const Me=await Ae.connector.listAllResources();B(Me.resources||[]);const Ve=await Ae.connector.listPrompts();re(Ve.prompts||[]);const it=Ae.connector.serverInfo,pt=Ae.connector.serverCapabilities;return it&&(console.log("[useMcp] Server info:",it),K(it)),pt&&(console.log("[useMcp] Server capabilities:",pt),ne(pt)),"success"}catch(kt){const ot=kt,Ae=ot?.message||String(kt);if(ot.code===401||Ae.includes("401")||Ae.includes("Unauthorized")){if(G.current){le("info","Authentication required. OAuth provider available.");try{const{auth:Me}=await rr(async()=>{const{auth:it}=await Promise.resolve().then(()=>mj);return{auth:it}},void 0),Ve=new URL(t).origin;Me(G.current,{serverUrl:Ve}).catch(()=>{}),setTimeout(()=>{if(ae.current){const it=G.current?.getLastAttemptedAuthUrl();it?(M(it),le("info","Manual authentication URL available:",it)):le("warn","Could not generate authentication URL")}},100)}catch(Me){le("warn","Error generating auth URL:",Me)}return ae.current&&A("pending_auth"),q.current=!1,"auth_redirect"}return u&&Object.keys(u).length>0?(He("Authentication failed: Server returned 401 Unauthorized. Check your Authorization header value is correct."),"failed"):(He("Authentication required: Server returned 401 Unauthorized. Add an Authorization header in the Custom Headers section (e.g., Authorization: Bearer YOUR_API_KEY)."),"failed")}return He(Ae,ot instanceof Error?ot:new Error(String(ot))),"failed"}},"tryConnectWithTransport");let ze="failed";if(g==="sse")le("debug","Using SSE-only transport mode"),ze=await De("sse");else if(g==="http")le("debug","Using HTTP-only transport mode"),ze=await De("http");else{le("debug","Using auto transport mode (HTTP with SSE fallback)");const ht=await De("http");ht==="fallback"&&ae.current&&Z.current!=="authenticating"?(le("info","HTTP failed, attempting SSE fallback..."),ze=await De("sse")):ze=ht}(ze==="success"||ze==="failed"||ze==="auth_redirect")&&(q.current=!1),le("debug",`Connection sequence finished with status: ${ze}`)},[le,He,Ne,t,i,r,a,s,c.name,c.version,u,g,y,x,E,n,w,_]),Te=v.useCallback(async(De,ze,ht)=>{if(Z.current!=="ready"||!z.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot call tool "${De}".`);le("info",`Calling tool: ${De}`,ze);const nt=Date.now();try{const ot=z.current.getSession("inspector-server");if(!ot)throw new Error("No active session found");const Ae=await ot.connector.callTool(De,ze||{},ht);return le("info",`Tool "${De}" call successful:`,Ae),Uo.getInstance().trackUseMcpToolCall({toolName:De,success:!0,executionTimeMs:Date.now()-nt}).catch(()=>{}),Ae}catch(kt){throw le("error",`Tool "${De}" call failed:`,kt),Uo.getInstance().trackUseMcpToolCall({toolName:De,success:!1,errorType:kt instanceof Error?kt.name:"UnknownError",executionTimeMs:Date.now()-nt}).catch(()=>{}),kt}},[I]),$e=v.useCallback(()=>{Z.current==="failed"?(le("info","Retry requested..."),xe()):le("warn",`Retry called but state is not 'failed' (state: ${Z.current}). Ignoring.`)},[le,xe]),fe=v.useCallback(async()=>{le("info","Manual authentication requested...");const De=Z.current;if(De==="failed")le("info","Attempting to reconnect and authenticate via retry..."),$e();else if(De==="pending_auth"){le("info","Proceeding with authentication from pending state...");try{Rx(G.current,"Auth Provider not available for manual auth"),Rx(t,"Server URL is required for authentication"),le("info","Clearing all OAuth state and initiating fresh flow...");const ze=`${i}:${G.current.serverUrlHash}`;Object.keys(localStorage).forEach(ot=>{ot.startsWith(ze)&&(le("debug",`Removing stale OAuth key: ${ot}`),localStorage.removeItem(ot)),ot.startsWith(`${i}:state_`)&&(le("debug",`Removing orphaned state: ${ot}`),localStorage.removeItem(ot))}),A("authenticating");const ht=new Wg(t,{storageKeyPrefix:i,clientName:r,clientUri:a,callbackUrl:s,preventAutoAuth:!1,useRedirectFlow:x,onPopupWindow:E});G.current=ht,le("info","Triggering fresh OAuth authorization...");const{auth:nt}=await rr(async()=>{const{auth:ot}=await Promise.resolve().then(()=>mj);return{auth:ot}},void 0),kt=new URL(t).origin;nt(ht,{serverUrl:kt}).catch(ot=>{le("info","OAuth flow initiated:",ot instanceof Error?ot.message:"Redirecting...")})}catch(ze){if(!ae.current)return;A("pending_auth"),le("error",`Manual authentication failed: ${ze instanceof Error?ze.message:String(ze)}`)}}else if(De==="authenticating"){le("warn","Already attempting authentication. Check for blocked popups or wait for timeout.");const ze=G.current?.getLastAttemptedAuthUrl();ze&&!L&&(M(ze),le("info","Manual authentication URL retrieved:",ze))}else le("info",`Client not in a state requiring manual authentication trigger (state: ${De}). If needed, try disconnecting and reconnecting.`)},[le,$e,L,t,x,E,i,r,a,s]),Ie=v.useCallback(()=>{if(G.current){const De=G.current.clearStorage();le("info",`Cleared ${De} item(s) from localStorage for ${t}.`),M(void 0),Ne()}else le("warn","Auth provider not initialized, cannot clear storage.")},[t,le,Ne]),Fe=v.useCallback(async()=>{if(Z.current!=="ready"||!z.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot list resources.`);le("info","Listing resources");try{const ze=z.current.getSession("inspector-server");if(!ze)throw new Error("No active session found");const ht=await ze.connector.listAllResources();B(ht.resources||[]),le("info","Resources listed successfully")}catch(De){throw le("error","List resources failed:",De),De}},[I]),Ee=v.useCallback(async De=>{if(Z.current!=="ready"||!z.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot read resource.`);le("info",`Reading resource: ${De}`);try{const ht=z.current.getSession("inspector-server");if(!ht)throw new Error("No active session found");const nt=await ht.connector.readResource(De);return le("info","Resource read successful:",nt),Uo.getInstance().trackUseMcpResourceRead({resourceUri:De,success:!0}).catch(()=>{}),nt}catch(ze){throw le("error","Resource read failed:",ze),Uo.getInstance().trackUseMcpResourceRead({resourceUri:De,success:!1,errorType:ze instanceof Error?ze.name:"UnknownError"}).catch(()=>{}),ze}},[I]),at=v.useCallback(async()=>{if(Z.current!=="ready"||!z.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot list prompts.`);le("info","Listing prompts");try{const ze=z.current.getSession("inspector-server");if(!ze)throw new Error("No active session found");const ht=await ze.connector.listPrompts();re(ht.prompts||[]),le("info","Prompts listed successfully")}catch(De){throw le("error","List prompts failed:",De),De}},[I]),lt=v.useCallback(async(De,ze)=>{if(Z.current!=="ready"||!z.current)throw new Error(`MCP client is not ready (current state: ${I}). Cannot get prompt.`);le("info",`Getting prompt: ${De}`,ze);try{const nt=z.current.getSession("inspector-server");if(!nt)throw new Error("No active session found");const kt=await nt.connector.getPrompt(De,ze||{});return le("info",`Prompt "${De}" retrieved successfully:`,kt),kt}catch(ht){throw le("error",`Prompt "${De}" retrieval failed:`,ht),ht}},[I]),bt=v.useRef(xe),Rt=v.useRef(He);return v.useEffect(()=>{bt.current=xe,Rt.current=He}),v.useEffect(()=>{const De=Pe(ze=>{ze.origin===window.location.origin&&ze.data?.type==="mcp_auth_callback"&&(le("info","Received auth callback message.",ze.data),X.current&&clearTimeout(X.current),X.current=null,ze.data.success?(le("info","Authentication successful via popup. Reconnecting client..."),q.current&&le("debug","Connection attempt already in progress, resetting flag to allow reconnection."),q.current=!1,setTimeout(()=>{ae.current&&(le("debug","Initiating reconnection after successful auth callback."),bt.current())},100)):Rt.current(`Authentication failed in callback: ${ze.data.error||"Unknown reason."}`))},"messageHandler");return window.addEventListener("message",De),le("debug","Auth callback message listener added."),()=>{window.removeEventListener("message",De),le("debug","Auth callback message listener removed."),X.current&&clearTimeout(X.current)}},[le]),v.useEffect(()=>(ae.current=!0,!n||!t?(le("debug",n?"No server URL provided, skipping connection.":"Connection disabled via enabled flag."),A("discovering"),()=>{ae.current=!1}):(le("debug","useMcp mounted, initiating connection."),ie.current=0,(!G.current||G.current.serverUrl!==t)&&(G.current=new Wg(t,{storageKeyPrefix:i,clientName:r,clientUri:a,callbackUrl:s,preventAutoAuth:y,useRedirectFlow:x,onPopupWindow:E}),le("debug","BrowserOAuthClientProvider initialized/updated on mount/option change.")),xe(),()=>{ae.current=!1,le("debug","useMcp unmounting, disconnecting."),Ne(!0)})),[t,n,i,s,r,a,c.name,c.version,x]),v.useEffect(()=>{let De=null;if(I==="failed"&&m&&ie.current>0){const ze=typeof m=="number"?m:XJ;le("info",`Connection failed, auto-retrying in ${ze}ms...`),De=setTimeout(()=>{ae.current&&Z.current==="failed"&&$e()},ze)}return()=>{De&&clearTimeout(De)}},[I,m,$e,le]),{state:I,tools:O,resources:U,resourceTemplates:W,prompts:ee,serverInfo:F,capabilities:V,error:te,log:H,authUrl:L,client:z.current,callTool:Te,readResource:Ee,listResources:Fe,listPrompts:at,getPrompt:lt,retry:$e,disconnect:Ne,authenticate:fe,clearStorage:Ie}}Pe(M_,"useMcp");var Hu,JJ=(Hu=class extends ce.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?ce.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"},ce.createElement("h3",{className:"font-bold mb-2"},"Widget Error"),ce.createElement("pre",{className:"text-sm whitespace-pre-wrap"},this.state.error?.message)):this.props.children}},Pe(Hu,"ErrorBoundary"),Hu),Gf="openai:set_globals";function po(e){return v.useSyncExternalStore(t=>{const n=Pe(r=>{r.detail.globals[e]!==void 0&&t()},"handleSetGlobal");return typeof window<"u"&&window.addEventListener(Gf,n),()=>{typeof window<"u"&&window.removeEventListener(Gf,n)}},()=>typeof window<"u"&&window.openai?window.openai[e]:void 0)}Pe(po,"useOpenAiGlobal");function ld(e){const[t,n]=v.useState(()=>typeof window<"u"&&!!window.openai);v.useEffect(()=>{if(typeof window<"u"&&window.openai){n(!0);return}const O=setInterval(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(O))},100),j=Pe(()=>{typeof window<"u"&&window.openai&&(n(!0),clearInterval(O))},"handleSetGlobals");typeof window<"u"&&window.addEventListener(Gf,j);const U=setTimeout(()=>{clearInterval(O),typeof window<"u"&&window.removeEventListener(Gf,j)},5e3);return()=>{clearInterval(O),clearTimeout(U),typeof window<"u"&&window.removeEventListener(Gf,j)}},[]);const r=v.useMemo(()=>t?"openai":"mcp-ui",[t]),a=typeof window<"u"?window.location.search:"",s=v.useMemo(()=>{const O=new URLSearchParams(a);return O.has("mcpUseParams")?JSON.parse(O.get("mcpUseParams")):{toolInput:{},toolOutput:{},toolId:""}},[a]),i=r==="openai"?po("toolInput"):s.toolInput,c=r==="openai"?po("toolOutput"):s.toolOutput,u=po("toolResponseMetadata"),f=po("widgetState"),m=po("theme"),h=po("displayMode"),g=po("safeArea"),y=po("maxHeight"),x=po("userAgent"),E=po("locale"),w=v.useMemo(()=>typeof window<"u"&&window.__mcpPublicUrl?window.__mcpPublicUrl.replace(/\/mcp-use\/public$/,""):"",[]),[_,S]=v.useState(null);v.useEffect(()=>{f!==void 0&&S(f)},[f]);const T=v.useCallback(async(O,j)=>{if(!window.openai?.callTool)throw new Error("window.openai.callTool is not available");return window.openai.callTool(O,j)},[]),R=v.useCallback(async O=>{if(!window.openai?.sendFollowUpMessage)throw new Error("window.openai.sendFollowUpMessage is not available");return window.openai.sendFollowUpMessage({prompt:O})},[]),C=v.useCallback(O=>{if(!window.openai?.openExternal)throw new Error("window.openai.openExternal is not available");window.openai.openExternal({href:O})},[]),I=v.useCallback(async O=>{if(!window.openai?.requestDisplayMode)throw new Error("window.openai.requestDisplayMode is not available");return window.openai.requestDisplayMode({mode:O})},[]),A=v.useCallback(async O=>{if(!window.openai?.setWidgetState)throw new Error("window.openai.setWidgetState is not available");const U=typeof O=="function"?O(f!==void 0?f:_):O;return S(U),window.openai.setWidgetState(U)},[f,_]);return{props:i||e||{},output:c??null,metadata:u??null,state:_,setState:A,theme:m||"light",displayMode:h||"inline",safeArea:g||{insets:{top:0,bottom:0,left:0,right:0}},maxHeight:y||600,userAgent:x||{device:{type:"desktop"},capabilities:{hover:!0,touch:!1}},locale:E||"en",mcp_url:w,callTool:T,sendFollowUpMessage:R,openExternal:C,requestDisplayMode:I,isAvailable:t}}Pe(ld,"useWidget");function QJ(e){const{props:t}=ld(e);return t}Pe(QJ,"useWidgetProps");function eQ(){const{theme:e}=ld();return e}Pe(eQ,"useWidgetTheme");function tQ(e){const{state:t,setState:n}=ld();return v.useEffect(()=>{t===null&&e!==void 0&&window.openai?.setWidgetState&&n(e)},[]),[t,n]}Pe(tQ,"useWidgetState");var _j=Pe(({children:e})=>{const{theme:t,isAvailable:n}=ld();console.log("theme",t);const[r,a]=v.useState(()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");v.useEffect(()=>{if(typeof window>"u")return;const i=window.matchMedia("(prefers-color-scheme: dark)"),c=Pe(u=>{a(u.matches?"dark":"light")},"handleChange");return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[]);const s=n?t:r;return v.useLayoutEffect(()=>{typeof document>"u"||(s==="dark"?document.documentElement.classList.add("dark"):document.documentElement.classList.remove("dark"))},[s]),ce.createElement(ce.Fragment,null,e)},"ThemeProvider");function gF({children:e,className:t="",position:n="top-right",attachTo:r,showLabels:a=!0,debugger:s=!1,viewControls:i=!1}){const{props:c,output:u,metadata:f,state:m,theme:h,displayMode:g,safeArea:y,maxHeight:x,userAgent:E,locale:w,isAvailable:_,callTool:S,sendFollowUpMessage:T,openExternal:R,requestDisplayMode:C,setState:I}=ld(),[A,O]=v.useState(!1),[j,U]=v.useState(!1),B=v.useRef(null),W=v.useRef(null),[J,ee]=v.useState([]),[re,F]=v.useState(""),[K,V]=v.useState("get-my-city"),[ne,te]=v.useState("{}"),[D,H]=v.useState("Test follow-up message"),[$,L]=v.useState("https://docs.mcp-use.com"),M=g==="fullscreen"&&_,z=g==="pip"&&_,G=typeof window<"u"&&window.location.pathname.includes("/inspector/api/dev-widget/");v.useEffect(()=>{const Ee=setTimeout(()=>{if(typeof window<"u"&&window.openai)try{const at=Object.keys(window.openai);ee(at)}catch{ee([])}else ee([])},100);return()=>{clearTimeout(Ee)}},[]);const q=h==="dark",ae=Pe(()=>{const Ee=["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[...Ee,"top-4","left-4"];case"top-center":return[...Ee,"top-4","left-1/2","-translate-x-1/2"];case"top-right":return[...Ee,"top-4","right-4"];case"center-left":return[...Ee,"top-1/2","left-4","-translate-y-1/2"];case"center-right":return[...Ee,"top-1/2","right-4","-translate-y-1/2"];case"bottom-left":return[...Ee,"bottom-4","left-4"];case"bottom-center":return[...Ee,"bottom-4","left-1/2","-translate-x-1/2"];case"bottom-right":return[...Ee,"bottom-4","right-4"];default:return[...Ee,"top-4","right-4"]}},"getPositionClasses"),ie=Pe(()=>{const at=y?.insets?.top?Math.max(16,y.insets.top+8):16,lt=y?.insets?.right?Math.max(16,y.insets.right+8):16,bt=y?.insets?.bottom?Math.max(16,y.insets.bottom+8):16,Rt=y?.insets?.left?Math.max(16,y.insets.left+8):16,De={};switch(n){case"top-left":De.top=`${at}px`,De.left=`${Rt}px`;break;case"top-center":De.top=`${at}px`;break;case"top-right":De.top=`${at}px`,De.right=`${lt}px`;break;case"center-left":De.left=`${Rt}px`;break;case"center-right":De.right=`${lt}px`;break;case"bottom-left":De.bottom=`${bt}px`,De.left=`${Rt}px`;break;case"bottom-center":De.bottom=`${bt}px`;break;case"bottom-right":De.bottom=`${bt}px`,De.right=`${lt}px`;break;default:De.top=`${at}px`,De.right=`${lt}px`;break}return De},"getPositionOffsetStyles");v.useEffect(()=>{if(!r)return;const Ee=Pe(()=>O(!0),"handleMouseEnter"),at=Pe(()=>O(!1),"handleMouseLeave");return r.addEventListener("mouseenter",Ee),r.addEventListener("mouseleave",at),()=>{r.removeEventListener("mouseenter",Ee),r.removeEventListener("mouseleave",at)}},[r]),v.useEffect(()=>{if(!j)return;const Ee=Pe(at=>{W.current&&!W.current.contains(at.target)&&U(!1)},"handleClickOutside");return document.addEventListener("mousedown",Ee),()=>{document.removeEventListener("mousedown",Ee)}},[j]),v.useEffect(()=>(j?document.body.style.overflow="hidden":document.body.style.overflow="",()=>{document.body.style.overflow=""}),[j]);const X=Pe(()=>{U(!j)},"handleToggleOverlay"),Z=Pe(async()=>{try{F("Calling tool...");const Ee=ne.trim()?JSON.parse(ne):{},at=await S(K,Ee);F(`Success: ${JSON.stringify(at,null,2)}`)}catch(Ee){F(`Error: ${Ee.message}`)}},"handleCallTool"),se=Pe(async()=>{try{F("Sending follow-up message..."),await T(D),F("Follow-up message sent successfully")}catch(Ee){F(`Error: ${Ee.message}`)}},"handleSendFollowUpMessage"),me=Pe(()=>{try{R($),F(`Opened external link: ${$}`)}catch(Ee){F(`Error: ${Ee.message}`)}},"handleOpenExternal"),le=Pe(async Ee=>{try{F(`Requesting display mode: ${Ee}...`);const at=await C(Ee);F(`Display mode granted: ${at.mode}`)}catch(at){F(`Error: ${at.message}`)}},"handleRequestDisplayMode"),Ne=Pe(async()=>{try{const Ee=m?{...m,debugTimestamp:new Date().toISOString()}:{debugTimestamp:new Date().toISOString()};F("Setting state..."),await I(Ee),F(`State updated: ${JSON.stringify(Ee,null,2)}`)}catch(Ee){F(`Error: ${Ee.message}`)}},"handleSetState"),He=Pe(async()=>{try{await C("fullscreen")}catch(Ee){console.error("Failed to go fullscreen:",Ee)}},"handleFullscreen"),xe=Pe(async()=>{try{await C("pip")}catch(Ee){console.error("Failed to go pip:",Ee)}},"handlePip"),Te=Pe(()=>{const Ee=["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[...Ee,"top-full","right-0","mt-2"];case"top-left":return[...Ee,"top-full","left-0","mt-2"];case"top-center":return[...Ee,"top-full","left-1/2","-translate-x-1/2","mt-2"];case"bottom-right":return[...Ee,"bottom-full","right-0","mb-2"];case"bottom-left":return[...Ee,"bottom-full","left-0","mb-2"];case"bottom-center":return[...Ee,"bottom-full","left-1/2","-translate-x-1/2","mb-2"];case"center-left":return[...Ee,"left-full","top-1/2","-translate-y-1/2","ml-2"];case"center-right":return[...Ee,"right-full","top-1/2","-translate-y-1/2","mr-2"];default:return[...Ee,"top-full","right-0","mt-2"]}},"getTooltipClasses"),$e=Pe(({onClick:Ee,label:at,children:lt})=>{const[bt,Rt]=v.useState(!1),De=Te();return ce.createElement("button",{className:`p-2 ${q?"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 ${q?"shadow-[0_2px_8px_rgba(0,0,0,0.3)]":"shadow-[0_2px_8px_rgba(0,0,0,0.2)]"} relative`,onMouseEnter:()=>Rt(!0),onMouseLeave:()=>Rt(!1),onClick:Ee,"aria-label":at},ce.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"},lt),a&&ce.createElement("span",{className:`${De.join(" ")} ${bt?"opacity-100":"opacity-0"}`},at))},"IconButton"),fe=Pe(Ee=>{if(Ee===null)return"null";if(Ee===void 0)return"undefined";if(typeof Ee=="object")try{return JSON.stringify(Ee,null,2)}catch{return String(Ee)}return String(Ee)},"formatValue"),Ie=Pe(Ee=>Ee?`${Ee.device?.type||"unknown"}`:"N/A","formatUserAgent"),Fe=Pe(Ee=>{if(!Ee?.insets)return"N/A";const{top:at,bottom:lt,left:bt,right:Rt}=Ee.insets;return`T:${at} B:${lt} L:${bt} R:${Rt}`},"formatSafeArea");return ce.createElement(ce.Fragment,null,ce.createElement("div",{ref:B,className:`${t} relative h-fit`,onMouseEnter:()=>!r&&O(!0),onMouseLeave:()=>!r&&O(!1)},ce.createElement("div",{className:ae().join(" "),style:ie()},!G&&ce.createElement(ce.Fragment,null,!M&&!z&&ce.createElement(ce.Fragment,null,(i===!0||i==="fullscreen")&&ce.createElement($e,{onClick:He,label:"Fullscreen"},ce.createElement("path",{d:"M15 3h6v6"}),ce.createElement("path",{d:"m21 3-7 7"}),ce.createElement("path",{d:"m3 21 7-7"}),ce.createElement("path",{d:"M9 21H3v-6"})),(i===!0||i==="pip")&&ce.createElement($e,{onClick:xe,label:"Picture in Picture"},ce.createElement("path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4"}),ce.createElement("rect",{width:"10",height:"7",x:"12",y:"13",rx:"2"}))),s&&ce.createElement($e,{onClick:X,label:"Debug Info"},ce.createElement("path",{d:"M12 20v-9"}),ce.createElement("path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z"}),ce.createElement("path",{d:"M14.12 3.88 16 2"}),ce.createElement("path",{d:"M21 21a4 4 0 0 0-3.81-4"}),ce.createElement("path",{d:"M21 5a4 4 0 0 1-3.55 3.97"}),ce.createElement("path",{d:"M22 13h-4"}),ce.createElement("path",{d:"M3 21a4 4 0 0 1 3.81-4"}),ce.createElement("path",{d:"M3 5a4 4 0 0 0 3.55 3.97"}),ce.createElement("path",{d:"M6 13H2"}),ce.createElement("path",{d:"m8 2 1.88 1.88"}),ce.createElement("path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13"})))),e),j&&s&&ce.createElement("div",{ref:W,className:"fixed inset-0 bg-black text-white font-mono text-xs z-[10000] overflow-auto p-4",onClick:Ee=>{Ee.target===W.current&&U(!1)}},ce.createElement("button",{onClick:()=>U(!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"},"×"),ce.createElement("div",{className:"max-w-[1200px] mx-auto pt-10"},ce.createElement("h1",{className:"text-lg font-bold mb-4 border-b border-gray-700 pb-2"},"Debug Info"),ce.createElement("table",{className:"w-full border-collapse border-spacing-0"},ce.createElement("tbody",null,ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Props"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(c))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Output"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(u))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Metadata"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(f))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"State"),ce.createElement("td",{className:"p-2 whitespace-pre-wrap break-all"},fe(m))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Theme"),ce.createElement("td",{className:"p-2"},h)),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Display Mode"),ce.createElement("td",{className:"p-2"},g)),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Locale"),ce.createElement("td",{className:"p-2"},w)),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Max Height"),ce.createElement("td",{className:"p-2"},x,"px")),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"User Agent"),ce.createElement("td",{className:"p-2"},Ie(E))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"Safe Area"),ce.createElement("td",{className:"p-2"},Fe(y))),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"API Available"),ce.createElement("td",{className:"p-2"},_?"Yes":"No")),ce.createElement("tr",{className:"border-b border-gray-700"},ce.createElement("td",{className:"p-2 font-bold w-[200px] align-top"},"window.openai Keys"),ce.createElement("td",{className:"p-2"},J.length>0?J.join(", "):"N/A")))),ce.createElement("h2",{className:"text-base font-bold mt-8 mb-4 border-b border-gray-700 pb-2"},"Actions"),ce.createElement("div",{className:"flex flex-col gap-3"},ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("input",{type:"text",value:K,onChange:Ee=>V(Ee.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]"}),ce.createElement("input",{type:"text",value:ne,onChange:Ee=>te(Ee.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"}),ce.createElement("button",{onClick:Z,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Call Tool")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("input",{type:"text",value:D,onChange:Ee=>H(Ee.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"}),ce.createElement("button",{onClick:se,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")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("input",{type:"text",value:$,onChange:Ee=>L(Ee.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"}),ce.createElement("button",{onClick:me,className:"py-1.5 px-3 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-xs"},"Open Link")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.createElement("span",{className:"w-[150px] text-xs"},"Display Mode:"),ce.createElement("button",{onClick:()=>le("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"),ce.createElement("button",{onClick:()=>le("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"),ce.createElement("button",{onClick:()=>le("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")),ce.createElement("div",{className:"flex gap-2 items-center"},ce.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)")),re&&ce.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"},ce.createElement("div",{className:"font-bold mb-1 text-gray-400"},"Result:"),re,ce.createElement("button",{onClick:()=>F(""),className:"mt-2 py-1 px-2 bg-gray-800 text-white border border-gray-600 rounded cursor-pointer font-mono text-[11px]"},"Clear"))))))}Pe(gF,"WidgetControls");function bF(){if(typeof window>"u")return"/";const t=window.location.pathname.match(/^(\/inspector\/api\/dev-widget\/[^/]+)/);return t?t[1]:"/"}Pe(bF,"getBasename");var nQ=150,rQ=5;function aQ({children:e,debugger:t=!1,viewControls:n=!1,autoSize:r=!1}){const a=bF(),s=v.useRef(null),i=v.useRef(0),c=v.useRef(null),u=v.useRef(!1),[f,m]=v.useState(null),[h,g]=v.useState(null),[y,x]=v.useState(!0);v.useEffect(()=>{let S=!0;return(async()=>{try{const T=await rr(()=>import("./index-ClqnDjM6.js"),[]);S&&(m(()=>T.BrowserRouter),x(!1))}catch{S&&(g(new Error(`❌ react-router-dom not installed!
34
34
 
35
35
  To use MCP widgets with McpUseProvider, you need to install:
36
36
 
@@ -88,7 +88,7 @@ Please change the parent <Route path="${S}"> to <Route path="${S==="/"?"*":`${S}
88
88
  `)},uP=function(){var e=parseInt(document.body.getAttribute(pu)||"0",10);return isFinite(e)?e:0},dae=function(){v.useEffect(function(){return document.body.setAttribute(pu,(uP()+1).toString()),function(){var e=uP()-1;e<=0?document.body.removeAttribute(pu):document.body.setAttribute(pu,e.toString())}},[])},fae=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,a=r===void 0?"margin":r;dae();var s=v.useMemo(function(){return lae(a)},[a]);return v.createElement(cae,{styles:uae(s,!t,a,n?"":"!important")})},$x=!1;if(typeof window<"u")try{var Sg=Object.defineProperty({},"passive",{get:function(){return $x=!0,!0}});window.addEventListener("test",Sg,Sg),window.removeEventListener("test",Sg,Sg)}catch{$x=!1}var Mc=$x?{passive:!1}:!1,pae=function(e){return e.tagName==="TEXTAREA"},U4=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!pae(e)&&n[t]==="visible")},mae=function(e){return U4(e,"overflowY")},hae=function(e){return U4(e,"overflowX")},dP=function(e,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=$4(e,r);if(a){var s=z4(e,r),i=s[1],c=s[2];if(i>c)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},gae=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},bae=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},$4=function(e,t){return e==="v"?mae(t):hae(t)},z4=function(e,t){return e==="v"?gae(t):bae(t)},yae=function(e,t){return e==="h"&&t==="rtl"?-1:1},vae=function(e,t,n,r,a){var s=yae(e,window.getComputedStyle(t).direction),i=s*r,c=n.target,u=t.contains(c),f=!1,m=i>0,h=0,g=0;do{if(!c)break;var y=z4(e,c),x=y[0],E=y[1],w=y[2],_=E-w-s*x;(x||_)&&$4(e,c)&&(h+=_,g+=x);var S=c.parentNode;c=S&&S.nodeType===Node.DOCUMENT_FRAGMENT_NODE?S.host:S}while(!u&&c!==document.body||u&&(t.contains(c)||t===c));return(m&&Math.abs(h)<1||!m&&Math.abs(g)<1)&&(f=!0),f},_g=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},fP=function(e){return[e.deltaX,e.deltaY]},pP=function(e){return e&&"current"in e?e.current:e},wae=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Eae=function(e){return`
89
89
  .block-interactivity-`.concat(e,` {pointer-events: none;}
90
90
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
91
- `)},xae=0,jc=[];function Sae(e){var t=v.useRef([]),n=v.useRef([0,0]),r=v.useRef(),a=v.useState(xae++)[0],s=v.useState(P4)[0],i=v.useRef(e);v.useEffect(function(){i.current=e},[e]),v.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var E=Vre([e.lockRef.current],(e.shards||[]).map(pP),!0).filter(Boolean);return E.forEach(function(w){return w.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),E.forEach(function(w){return w.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var c=v.useCallback(function(E,w){if("touches"in E&&E.touches.length===2||E.type==="wheel"&&E.ctrlKey)return!i.current.allowPinchZoom;var _=_g(E),S=n.current,T="deltaX"in E?E.deltaX:S[0]-_[0],R="deltaY"in E?E.deltaY:S[1]-_[1],C,I=E.target,A=Math.abs(T)>Math.abs(R)?"h":"v";if("touches"in E&&A==="h"&&I.type==="range")return!1;var O=dP(A,I);if(!O)return!0;if(O?C=A:(C=A==="v"?"h":"v",O=dP(A,I)),!O)return!1;if(!r.current&&"changedTouches"in E&&(T||R)&&(r.current=C),!C)return!0;var j=r.current||C;return vae(j,w,E,j==="h"?T:R)},[]),u=v.useCallback(function(E){var w=E;if(!(!jc.length||jc[jc.length-1]!==s)){var _="deltaY"in w?fP(w):_g(w),S=t.current.filter(function(C){return C.name===w.type&&(C.target===w.target||w.target===C.shadowParent)&&wae(C.delta,_)})[0];if(S&&S.should){w.cancelable&&w.preventDefault();return}if(!S){var T=(i.current.shards||[]).map(pP).filter(Boolean).filter(function(C){return C.contains(w.target)}),R=T.length>0?c(w,T[0]):!i.current.noIsolation;R&&w.cancelable&&w.preventDefault()}}},[]),f=v.useCallback(function(E,w,_,S){var T={name:E,delta:w,target:_,should:S,shadowParent:_ae(_)};t.current.push(T),setTimeout(function(){t.current=t.current.filter(function(R){return R!==T})},1)},[]),m=v.useCallback(function(E){n.current=_g(E),r.current=void 0},[]),h=v.useCallback(function(E){f(E.type,fP(E),E.target,c(E,e.lockRef.current))},[]),g=v.useCallback(function(E){f(E.type,_g(E),E.target,c(E,e.lockRef.current))},[]);v.useEffect(function(){return jc.push(s),e.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:g}),document.addEventListener("wheel",u,Mc),document.addEventListener("touchmove",u,Mc),document.addEventListener("touchstart",m,Mc),function(){jc=jc.filter(function(E){return E!==s}),document.removeEventListener("wheel",u,Mc),document.removeEventListener("touchmove",u,Mc),document.removeEventListener("touchstart",m,Mc)}},[]);var y=e.removeScrollBar,x=e.inert;return v.createElement(v.Fragment,null,x?v.createElement(s,{styles:Eae(a)}):null,y?v.createElement(fae,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function _ae(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Tae=Qre(j4,Sae);var Zp=v.forwardRef(function(e,t){return v.createElement(Uy,$o({},e,{ref:t,sideCar:Tae}))});Zp.classNames=Uy.classNames;var zx=["Enter"," "],Nae=["ArrowDown","PageUp","Home"],F4=["ArrowUp","PageDown","End"],kae=[...Nae,...F4],Cae={ltr:[...zx,"ArrowRight"],rtl:[...zx,"ArrowLeft"]},Rae={ltr:["ArrowLeft"],rtl:["ArrowRight"]},qp="Menu",[hp,Aae,Iae]=B_(qp),[Hl,B4]=Ro(qp,[Iae,Fi,C4]),$y=Fi(),H4=C4(),[Oae,Vl]=Hl(qp),[Dae,Xp]=Hl(qp),V4=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:s,modal:i=!0}=e,c=$y(t),[u,f]=v.useState(null),m=v.useRef(!1),h=Wo(s),g=H_(a);return v.useEffect(()=>{const y=()=>{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",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),d.jsx(Ly,{...c,children:d.jsx(Oae,{scope:t,open:n,onOpenChange:h,content:u,onContentChange:f,children:d.jsx(Dae,{scope:t,onClose:v.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:m,dir:g,modal:i,children:r})})})};V4.displayName=qp;var Lae="MenuAnchor",Q_=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,a=$y(n);return d.jsx(Kp,{...a,...r,ref:t})});Q_.displayName=Lae;var eT="MenuPortal",[Mae,G4]=Hl(eT,{forceMount:void 0}),W4=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=e,s=Vl(eT,t);return d.jsx(Mae,{scope:t,forceMount:n,children:d.jsx(za,{present:n||s.open,children:d.jsx(yd,{asChild:!0,container:a,children:r})})})};W4.displayName=eT;var to="MenuContent",[jae,tT]=Hl(to),K4=v.forwardRef((e,t)=>{const n=G4(to,e.__scopeMenu),{forceMount:r=n.forceMount,...a}=e,s=Vl(to,e.__scopeMenu),i=Xp(to,e.__scopeMenu);return d.jsx(hp.Provider,{scope:e.__scopeMenu,children:d.jsx(za,{present:r||s.open,children:d.jsx(hp.Slot,{scope:e.__scopeMenu,children:i.modal?d.jsx(Pae,{...a,ref:t}):d.jsx(Uae,{...a,ref:t})})})})}),Pae=v.forwardRef((e,t)=>{const n=Vl(to,e.__scopeMenu),r=v.useRef(null),a=Jt(t,r);return v.useEffect(()=>{const s=r.current;if(s)return Py(s)},[]),d.jsx(nT,{...e,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ge(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Uae=v.forwardRef((e,t)=>{const n=Vl(to,e.__scopeMenu);return d.jsx(nT,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),$ae=Al("MenuContent.ScrollLock"),nT=v.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:a,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:c,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,...E}=e,w=Vl(to,n),_=Xp(to,n),S=$y(n),T=H4(n),R=Aae(n),[C,I]=v.useState(null),A=v.useRef(null),O=Jt(t,A,w.onContentChange),j=v.useRef(0),U=v.useRef(""),B=v.useRef(0),W=v.useRef(null),J=v.useRef("right"),ee=v.useRef(0),re=x?Zp:v.Fragment,F=x?{as:$ae,allowPinchZoom:!0}:void 0,K=ne=>{const te=U.current+ne,D=R().filter(G=>!G.disabled),H=document.activeElement,$=D.find(G=>G.ref.current===H)?.textValue,L=D.map(G=>G.textValue),M=Xae(L,te,$),z=D.find(G=>G.textValue===M)?.ref.current;(function G(q){U.current=q,window.clearTimeout(j.current),q!==""&&(j.current=window.setTimeout(()=>G(""),1e3))})(te),z&&setTimeout(()=>z.focus())};v.useEffect(()=>()=>window.clearTimeout(j.current),[]),Ry();const V=v.useCallback(ne=>J.current===W.current?.side&&Qae(ne,W.current?.area),[]);return d.jsx(jae,{scope:n,searchRef:U,onItemEnter:v.useCallback(ne=>{V(ne)&&ne.preventDefault()},[V]),onItemLeave:v.useCallback(ne=>{V(ne)||(A.current?.focus(),I(null))},[V]),onTriggerLeave:v.useCallback(ne=>{V(ne)&&ne.preventDefault()},[V]),pointerGraceTimerRef:B,onPointerGraceIntentChange:v.useCallback(ne=>{W.current=ne},[]),children:d.jsx(re,{...F,children:d.jsx(Gp,{asChild:!0,trapped:a,onMountAutoFocus:Ge(s,ne=>{ne.preventDefault(),A.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:d.jsx(hd,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:y,children:d.jsx($re,{asChild:!0,...T,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:C,onCurrentTabStopIdChange:I,onEntryFocus:Ge(u,ne=>{_.isUsingKeyboardRef.current||ne.preventDefault()}),preventScrollOnEntryFocus:!0,children:d.jsx(My,{role:"menu","aria-orientation":"vertical","data-state":c3(w.open),"data-radix-menu-content":"",dir:_.dir,...S,...E,ref:O,style:{outline:"none",...E.style},onKeyDown:Ge(E.onKeyDown,ne=>{const D=ne.target.closest("[data-radix-menu-content]")===ne.currentTarget,H=ne.ctrlKey||ne.altKey||ne.metaKey,$=ne.key.length===1;D&&(ne.key==="Tab"&&ne.preventDefault(),!H&&$&&K(ne.key));const L=A.current;if(ne.target!==L||!kae.includes(ne.key))return;ne.preventDefault();const z=R().filter(G=>!G.disabled).map(G=>G.ref.current);F4.includes(ne.key)&&z.reverse(),Zae(z)}),onBlur:Ge(e.onBlur,ne=>{ne.currentTarget.contains(ne.target)||(window.clearTimeout(j.current),U.current="")}),onPointerMove:Ge(e.onPointerMove,gp(ne=>{const te=ne.target,D=ee.current!==ne.clientX;if(ne.currentTarget.contains(te)&&D){const H=ne.clientX>ee.current?"right":"left";J.current=H,ee.current=ne.clientX}}))})})})})})})});K4.displayName=to;var zae="MenuGroup",rT=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(_t.div,{role:"group",...r,ref:t})});rT.displayName=zae;var Fae="MenuLabel",Y4=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(_t.div,{...r,ref:t})});Y4.displayName=Fae;var Ob="MenuItem",mP="menu.itemSelect",zy=v.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...a}=e,s=v.useRef(null),i=Xp(Ob,e.__scopeMenu),c=tT(Ob,e.__scopeMenu),u=Jt(t,s),f=v.useRef(!1),m=()=>{const h=s.current;if(!n&&h){const g=new CustomEvent(mP,{bubbles:!0,cancelable:!0});h.addEventListener(mP,y=>r?.(y),{once:!0}),n4(h,g),g.defaultPrevented?f.current=!1:i.onClose()}};return d.jsx(Z4,{...a,ref:u,disabled:n,onClick:Ge(e.onClick,m),onPointerDown:h=>{e.onPointerDown?.(h),f.current=!0},onPointerUp:Ge(e.onPointerUp,h=>{f.current||h.currentTarget?.click()}),onKeyDown:Ge(e.onKeyDown,h=>{const g=c.searchRef.current!=="";n||g&&h.key===" "||zx.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});zy.displayName=Ob;var Z4=v.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...s}=e,i=tT(Ob,n),c=H4(n),u=v.useRef(null),f=Jt(t,u),[m,h]=v.useState(!1),[g,y]=v.useState("");return v.useEffect(()=>{const x=u.current;x&&y((x.textContent??"").trim())},[s.children]),d.jsx(hp.ItemSlot,{scope:n,disabled:r,textValue:a??g,children:d.jsx(zre,{asChild:!0,...c,focusable:!r,children:d.jsx(_t.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:f,onPointerMove:Ge(e.onPointerMove,gp(x=>{r?i.onItemLeave(x):(i.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ge(e.onPointerLeave,gp(x=>i.onItemLeave(x))),onFocus:Ge(e.onFocus,()=>h(!0)),onBlur:Ge(e.onBlur,()=>h(!1))})})})}),Bae="MenuCheckboxItem",q4=v.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=e;return d.jsx(t3,{scope:e.__scopeMenu,checked:n,children:d.jsx(zy,{role:"menuitemcheckbox","aria-checked":Db(n)?"mixed":n,...a,ref:t,"data-state":oT(n),onSelect:Ge(a.onSelect,()=>r?.(Db(n)?!0:!n),{checkForDefaultPrevented:!1})})})});q4.displayName=Bae;var X4="MenuRadioGroup",[Hae,Vae]=Hl(X4,{value:void 0,onValueChange:()=>{}}),J4=v.forwardRef((e,t)=>{const{value:n,onValueChange:r,...a}=e,s=Wo(r);return d.jsx(Hae,{scope:e.__scopeMenu,value:n,onValueChange:s,children:d.jsx(rT,{...a,ref:t})})});J4.displayName=X4;var Q4="MenuRadioItem",e3=v.forwardRef((e,t)=>{const{value:n,...r}=e,a=Vae(Q4,e.__scopeMenu),s=n===a.value;return d.jsx(t3,{scope:e.__scopeMenu,checked:s,children:d.jsx(zy,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":oT(s),onSelect:Ge(r.onSelect,()=>a.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});e3.displayName=Q4;var aT="MenuItemIndicator",[t3,Gae]=Hl(aT,{checked:!1}),n3=v.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...a}=e,s=Gae(aT,n);return d.jsx(za,{present:r||Db(s.checked)||s.checked===!0,children:d.jsx(_t.span,{...a,ref:t,"data-state":oT(s.checked)})})});n3.displayName=aT;var Wae="MenuSeparator",r3=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(_t.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});r3.displayName=Wae;var Kae="MenuArrow",a3=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,a=$y(n);return d.jsx(jy,{...a,...r,ref:t})});a3.displayName=Kae;var Yae="MenuSub",[T0e,o3]=Hl(Yae),Lf="MenuSubTrigger",s3=v.forwardRef((e,t)=>{const n=Vl(Lf,e.__scopeMenu),r=Xp(Lf,e.__scopeMenu),a=o3(Lf,e.__scopeMenu),s=tT(Lf,e.__scopeMenu),i=v.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:u}=s,f={__scopeMenu:e.__scopeMenu},m=v.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return v.useEffect(()=>m,[m]),v.useEffect(()=>{const h=c.current;return()=>{window.clearTimeout(h),u(null)}},[c,u]),d.jsx(Q_,{asChild:!0,...f,children:d.jsx(Z4,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":c3(n.open),...e,ref:Go(t,a.onTriggerChange),onClick:h=>{e.onClick?.(h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ge(e.onPointerMove,gp(h=>{s.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(s.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:Ge(e.onPointerLeave,gp(h=>{m();const g=n.content?.getBoundingClientRect();if(g){const y=n.content?.dataset.side,x=y==="right",E=x?-5:5,w=g[x?"left":"right"],_=g[x?"right":"left"];s.onPointerGraceIntentChange({area:[{x:h.clientX+E,y:h.clientY},{x:w,y:g.top},{x:_,y:g.top},{x:_,y:g.bottom},{x:w,y:g.bottom}],side:y}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(h),h.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:Ge(e.onKeyDown,h=>{const g=s.searchRef.current!=="";e.disabled||g&&h.key===" "||Cae[r.dir].includes(h.key)&&(n.onOpenChange(!0),n.content?.focus(),h.preventDefault())})})})});s3.displayName=Lf;var i3="MenuSubContent",l3=v.forwardRef((e,t)=>{const n=G4(to,e.__scopeMenu),{forceMount:r=n.forceMount,...a}=e,s=Vl(to,e.__scopeMenu),i=Xp(to,e.__scopeMenu),c=o3(i3,e.__scopeMenu),u=v.useRef(null),f=Jt(t,u);return d.jsx(hp.Provider,{scope:e.__scopeMenu,children:d.jsx(za,{present:r||s.open,children:d.jsx(hp.Slot,{scope:e.__scopeMenu,children:d.jsx(nT,{id:c.contentId,"aria-labelledby":c.triggerId,...a,ref:f,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{i.isUsingKeyboardRef.current&&u.current?.focus(),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:Ge(e.onFocusOutside,m=>{m.target!==c.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:Ge(e.onEscapeKeyDown,m=>{i.onClose(),m.preventDefault()}),onKeyDown:Ge(e.onKeyDown,m=>{const h=m.currentTarget.contains(m.target),g=Rae[i.dir].includes(m.key);h&&g&&(s.onOpenChange(!1),c.trigger?.focus(),m.preventDefault())})})})})})});l3.displayName=i3;function c3(e){return e?"open":"closed"}function Db(e){return e==="indeterminate"}function oT(e){return Db(e)?"indeterminate":e?"checked":"unchecked"}function Zae(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function qae(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Xae(e,t,n){const a=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=qae(e,Math.max(s,0));a.length===1&&(i=i.filter(f=>f!==n));const u=i.find(f=>f.toLowerCase().startsWith(a.toLowerCase()));return u!==n?u:void 0}function Jae(e,t){const{x:n,y:r}=e;let a=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const c=t[s],u=t[i],f=c.x,m=c.y,h=u.x,g=u.y;m>r!=g>r&&n<(h-f)*(r-m)/(g-m)+f&&(a=!a)}return a}function Qae(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Jae(n,t)}function gp(e){return t=>t.pointerType==="mouse"?e(t):void 0}var eoe=V4,toe=Q_,noe=W4,roe=K4,aoe=rT,ooe=Y4,soe=zy,ioe=q4,loe=J4,coe=e3,uoe=n3,doe=r3,foe=a3,poe=s3,moe=l3,Fy="DropdownMenu",[hoe]=Ro(Fy,[B4]),ia=B4(),[goe,u3]=hoe(Fy),d3=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:s,onOpenChange:i,modal:c=!0}=e,u=ia(t),f=v.useRef(null),[m,h]=Os({prop:a,defaultProp:s??!1,onChange:i,caller:Fy});return d.jsx(goe,{scope:t,triggerId:$r(),triggerRef:f,contentId:$r(),open:m,onOpenChange:h,onOpenToggle:v.useCallback(()=>h(g=>!g),[h]),modal:c,children:d.jsx(eoe,{...u,open:m,onOpenChange:h,dir:r,modal:c,children:n})})};d3.displayName=Fy;var f3="DropdownMenuTrigger",p3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=e,s=u3(f3,n),i=ia(n);return d.jsx(toe,{asChild:!0,...i,children:d.jsx(_t.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...a,ref:Go(t,s.triggerRef),onPointerDown:Ge(e.onPointerDown,c=>{!r&&c.button===0&&c.ctrlKey===!1&&(s.onOpenToggle(),s.open||c.preventDefault())}),onKeyDown:Ge(e.onKeyDown,c=>{r||(["Enter"," "].includes(c.key)&&s.onOpenToggle(),c.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});p3.displayName=f3;var boe="DropdownMenuPortal",m3=e=>{const{__scopeDropdownMenu:t,...n}=e,r=ia(t);return d.jsx(noe,{...r,...n})};m3.displayName=boe;var h3="DropdownMenuContent",g3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=u3(h3,n),s=ia(n),i=v.useRef(!1);return d.jsx(roe,{id:a.contentId,"aria-labelledby":a.triggerId,...s,...r,ref:t,onCloseAutoFocus:Ge(e.onCloseAutoFocus,c=>{i.current||a.triggerRef.current?.focus(),i.current=!1,c.preventDefault()}),onInteractOutside:Ge(e.onInteractOutside,c=>{const u=c.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,m=u.button===2||f;(!a.modal||m)&&(i.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)"}})});g3.displayName=h3;var yoe="DropdownMenuGroup",voe=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(aoe,{...a,...r,ref:t})});voe.displayName=yoe;var woe="DropdownMenuLabel",b3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(ooe,{...a,...r,ref:t})});b3.displayName=woe;var Eoe="DropdownMenuItem",y3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(soe,{...a,...r,ref:t})});y3.displayName=Eoe;var xoe="DropdownMenuCheckboxItem",v3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(ioe,{...a,...r,ref:t})});v3.displayName=xoe;var Soe="DropdownMenuRadioGroup",_oe=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(loe,{...a,...r,ref:t})});_oe.displayName=Soe;var Toe="DropdownMenuRadioItem",w3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(coe,{...a,...r,ref:t})});w3.displayName=Toe;var Noe="DropdownMenuItemIndicator",koe=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(uoe,{...a,...r,ref:t})});koe.displayName=Noe;var Coe="DropdownMenuSeparator",E3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(doe,{...a,...r,ref:t})});E3.displayName=Coe;var Roe="DropdownMenuArrow",Aoe=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(foe,{...a,...r,ref:t})});Aoe.displayName=Roe;var Ioe="DropdownMenuSubTrigger",x3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(poe,{...a,...r,ref:t})});x3.displayName=Ioe;var Ooe="DropdownMenuSubContent",S3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(moe,{...a,...r,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)"}})});S3.displayName=Ooe;var Doe=d3,Loe=p3,Moe=m3,_3=g3,T3=b3,N3=y3,joe=v3,Poe=w3,k3=E3,Uoe=x3,$oe=S3;const Fx=Doe,Bx=Loe;Uoe.displayName;$oe.displayName;function Lb({ref:e,className:t,sideOffset:n=4,...r}){return d.jsx(Moe,{children:d.jsx(_3,{ref:e,sideOffset:n,className:Oe("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),...r})})}Lb.displayName=_3.displayName;function Ts({ref:e,className:t,inset:n,...r}){return d.jsx(N3,{ref:e,className:Oe("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),...r})}Ts.displayName=N3.displayName;joe.displayName;Poe.displayName;function Hx({ref:e,className:t,inset:n,...r}){return d.jsx(T3,{ref:e,className:Oe("px-2 py-1.5 text-sm font-semibold",n&&"pl-8",t),...r})}Hx.displayName=T3.displayName;function Mf({ref:e,className:t,...n}){return d.jsx(k3,{ref:e,className:Oe("-mx-1 my-1 h-px bg-muted",t),...n})}Mf.displayName=k3.displayName;var zoe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],zs=zoe.reduce((e,t)=>{const n=UF(`Primitive.${t}`),r=v.forwardRef((a,s)=>{const{asChild:i,...c}=a,u=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),d.jsx(u,{...c,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Foe="Label",C3=v.forwardRef((e,t)=>d.jsx(zs.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));C3.displayName=Foe;var Boe=C3;function Wt({className:e,...t}){return d.jsx(Boe,{"data-slot":"label",className:Oe("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 vd({message:e,className:t="",vertical:n,noBorder:r}){return d.jsx("div",{className:Oe(`mt-2 rounded-md p-6 ${t}`,!r&&"border"),children:d.jsxs("p",{className:Oe("text-sm text-muted-foreground flex items-center gap-4",n&&"flex-col"),children:[d.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:d.jsx("g",{stroke:"none",strokeWidth:"1",fill:"none",fillRule:"evenodd",children:d.jsxs("g",{transform:"translate(5.320900, 5.320900)",fillRule:"nonzero",className:"stroke-black dark:stroke-white",strokeWidth:"4",children:[d.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"}),d.jsx("circle",{cx:"50",cy:"212.0001",r:"52.5"}),d.jsx("circle",{cx:"212.0001",cy:"50",r:"52.5"})]})})}),e]})})}function R3({className:e,color:t,children:n,grayscaled:r=!1}){const a=v.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[1]||"0")}return r?0:.2},[t,r]),s=v.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[0]||"0.5")}return r?.3:.4},[t,r]),i=v.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=v.useMemo(()=>t||`oklch(${Math.min(s,1)} ${a} ${i})`,[i,a,s]),u=v.useMemo(()=>`oklch(${Math.min(s*2,1)} ${a} ${i})`,[i,a,s,t]),f=v.useMemo(()=>Math.floor(Math.random()*360),[i]),m=v.useMemo(()=>"1000%",[]);return d.jsx("section",{className:Oe("relative w-full h-full overflow-hidden",e),style:{background:`${u}`},children:d.jsxs("div",{className:"isolate relative w-full h-full",children:[d.jsx("div",{className:"noise w-full h-full",style:{background:`linear-gradient(${f}deg, ${c}, transparent), url(https://grainy-gradients.vercel.app/noise.svg)`,filter:`contrast(120%) brightness(${m})`}}),n&&d.jsx("div",{className:"relative z-10 w-full h-full",children:n})]})})}function sT(e){const t=v.useRef({value:e,previous:e});return v.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var By="Switch",[Hoe]=Ro(By),[Voe,Goe]=Hoe(By),A3=v.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:a,defaultChecked:s,required:i,disabled:c,value:u="on",onCheckedChange:f,form:m,...h}=e,[g,y]=v.useState(null),x=Jt(t,T=>y(T)),E=v.useRef(!1),w=g?m||!!g.closest("form"):!0,[_,S]=Os({prop:a,defaultProp:s??!1,onChange:f,caller:By});return d.jsxs(Voe,{scope:n,checked:_,disabled:c,children:[d.jsx(_t.button,{type:"button",role:"switch","aria-checked":_,"aria-required":i,"data-state":L3(_),"data-disabled":c?"":void 0,disabled:c,value:u,...h,ref:x,onClick:Ge(e.onClick,T=>{S(R=>!R),w&&(E.current=T.isPropagationStopped(),E.current||T.stopPropagation())})}),w&&d.jsx(D3,{control:g,bubbles:!E.current,name:r,value:u,checked:_,required:i,disabled:c,form:m,style:{transform:"translateX(-100%)"}})]})});A3.displayName=By;var I3="SwitchThumb",O3=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,a=Goe(I3,n);return d.jsx(_t.span,{"data-state":L3(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});O3.displayName=I3;var Woe="SwitchBubbleInput",D3=v.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...a},s)=>{const i=v.useRef(null),c=Jt(i,s),u=sT(n),f=q_(t);return v.useEffect(()=>{const m=i.current;if(!m)return;const h=window.HTMLInputElement.prototype,y=Object.getOwnPropertyDescriptor(h,"checked").set;if(u!==n&&y){const x=new Event("click",{bubbles:r});y.call(m,n),m.dispatchEvent(x)}},[u,n,r]),d.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...a,tabIndex:-1,ref:c,style:{...a.style,...f,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});D3.displayName=Woe;function L3(e){return e?"checked":"unchecked"}var M3=A3,Koe=O3;function Hy({ref:e,className:t,...n}){return d.jsx(M3,{className:Oe("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:d.jsx(Koe,{className:Oe("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")})})}Hy.displayName=M3.displayName;var j3=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"}),Yoe="VisuallyHidden",P3=v.forwardRef((e,t)=>d.jsx(_t.span,{...e,ref:t,style:{...j3,...e.style}}));P3.displayName=Yoe;var Zoe=P3,[Vy]=Ro("Tooltip",[Fi]),Gy=Fi(),U3="TooltipProvider",qoe=700,Vx="tooltip.open",[Xoe,iT]=Vy(U3),$3=e=>{const{__scopeTooltip:t,delayDuration:n=qoe,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:s}=e,i=v.useRef(!0),c=v.useRef(!1),u=v.useRef(0);return v.useEffect(()=>{const f=u.current;return()=>window.clearTimeout(f)},[]),d.jsx(Xoe,{scope:t,isOpenDelayedRef:i,delayDuration:n,onOpen:v.useCallback(()=>{window.clearTimeout(u.current),i.current=!1},[]),onClose:v.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>i.current=!0,r)},[r]),isPointerInTransitRef:c,onPointerInTransitChange:v.useCallback(f=>{c.current=f},[]),disableHoverableContent:a,children:s})};$3.displayName=U3;var bp="Tooltip",[Joe,Jp]=Vy(bp),z3=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:s,disableHoverableContent:i,delayDuration:c}=e,u=iT(bp,e.__scopeTooltip),f=Gy(t),[m,h]=v.useState(null),g=$r(),y=v.useRef(0),x=i??u.disableHoverableContent,E=c??u.delayDuration,w=v.useRef(!1),[_,S]=Os({prop:r,defaultProp:a??!1,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(Vx))):u.onClose(),s?.(A)},caller:bp}),T=v.useMemo(()=>_?w.current?"delayed-open":"instant-open":"closed",[_]),R=v.useCallback(()=>{window.clearTimeout(y.current),y.current=0,w.current=!1,S(!0)},[S]),C=v.useCallback(()=>{window.clearTimeout(y.current),y.current=0,S(!1)},[S]),I=v.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{w.current=!0,S(!0),y.current=0},E)},[E,S]);return v.useEffect(()=>()=>{y.current&&(window.clearTimeout(y.current),y.current=0)},[]),d.jsx(Ly,{...f,children:d.jsx(Joe,{scope:t,contentId:g,open:_,stateAttribute:T,trigger:m,onTriggerChange:h,onTriggerEnter:v.useCallback(()=>{u.isOpenDelayedRef.current?I():R()},[u.isOpenDelayedRef,I,R]),onTriggerLeave:v.useCallback(()=>{x?C():(window.clearTimeout(y.current),y.current=0)},[C,x]),onOpen:R,onClose:C,disableHoverableContent:x,children:n})})};z3.displayName=bp;var Gx="TooltipTrigger",F3=v.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,a=Jp(Gx,n),s=iT(Gx,n),i=Gy(n),c=v.useRef(null),u=Jt(t,c,a.onTriggerChange),f=v.useRef(!1),m=v.useRef(!1),h=v.useCallback(()=>f.current=!1,[]);return v.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),d.jsx(Kp,{asChild:!0,...i,children:d.jsx(_t.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:u,onPointerMove:Ge(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!s.isPointerInTransitRef.current&&(a.onTriggerEnter(),m.current=!0)}),onPointerLeave:Ge(e.onPointerLeave,()=>{a.onTriggerLeave(),m.current=!1}),onPointerDown:Ge(e.onPointerDown,()=>{a.open&&a.onClose(),f.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:Ge(e.onFocus,()=>{f.current||a.onOpen()}),onBlur:Ge(e.onBlur,a.onClose),onClick:Ge(e.onClick,a.onClose)})})});F3.displayName=Gx;var lT="TooltipPortal",[Qoe,ese]=Vy(lT,{forceMount:void 0}),B3=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:a}=e,s=Jp(lT,t);return d.jsx(Qoe,{scope:t,forceMount:n,children:d.jsx(za,{present:n||s.open,children:d.jsx(yd,{asChild:!0,container:a,children:r})})})};B3.displayName=lT;var Zu="TooltipContent",H3=v.forwardRef((e,t)=>{const n=ese(Zu,e.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...s}=e,i=Jp(Zu,e.__scopeTooltip);return d.jsx(za,{present:r||i.open,children:i.disableHoverableContent?d.jsx(V3,{side:a,...s,ref:t}):d.jsx(tse,{side:a,...s,ref:t})})}),tse=v.forwardRef((e,t)=>{const n=Jp(Zu,e.__scopeTooltip),r=iT(Zu,e.__scopeTooltip),a=v.useRef(null),s=Jt(t,a),[i,c]=v.useState(null),{trigger:u,onClose:f}=n,m=a.current,{onPointerInTransitChange:h}=r,g=v.useCallback(()=>{c(null),h(!1)},[h]),y=v.useCallback((x,E)=>{const w=x.currentTarget,_={x:x.clientX,y:x.clientY},S=ose(_,w.getBoundingClientRect()),T=sse(_,S),R=ise(E.getBoundingClientRect()),C=cse([...T,...R]);c(C),h(!0)},[h]);return v.useEffect(()=>()=>g(),[g]),v.useEffect(()=>{if(u&&m){const x=w=>y(w,m),E=w=>y(w,u);return u.addEventListener("pointerleave",x),m.addEventListener("pointerleave",E),()=>{u.removeEventListener("pointerleave",x),m.removeEventListener("pointerleave",E)}}},[u,m,y,g]),v.useEffect(()=>{if(i){const x=E=>{const w=E.target,_={x:E.clientX,y:E.clientY},S=u?.contains(w)||m?.contains(w),T=!lse(_,i);S?g():T&&(g(),f())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,m,i,f,g]),d.jsx(V3,{...e,ref:s})}),[nse,rse]=Vy(bp,{isInside:!1}),ase=Ute("TooltipContent"),V3=v.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:s,onPointerDownOutside:i,...c}=e,u=Jp(Zu,n),f=Gy(n),{onClose:m}=u;return v.useEffect(()=>(document.addEventListener(Vx,m),()=>document.removeEventListener(Vx,m)),[m]),v.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]),d.jsx(hd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:h=>h.preventDefault(),onDismiss:m,children:d.jsxs(My,{"data-state":u.stateAttribute,...f,...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:[d.jsx(ase,{children:r}),d.jsx(nse,{scope:n,isInside:!0,children:d.jsx(Zoe,{id:u.contentId,role:"tooltip",children:a||r})})]})})});H3.displayName=Zu;var G3="TooltipArrow",W3=v.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,a=Gy(n);return rse(G3,n).isInside?null:d.jsx(jy,{...a,...r,ref:t})});W3.displayName=G3;function ose(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),a=Math.abs(t.right-e.x),s=Math.abs(t.left-e.x);switch(Math.min(n,r,a,s)){case s:return"left";case a:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function sse(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function ise(e){const{top:t,right:n,bottom:r,left:a}=e;return[{x:a,y:t},{x:n,y:t},{x:n,y:r},{x:a,y:r}]}function lse(e,t){const{x:n,y:r}=e;let a=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const c=t[s],u=t[i],f=c.x,m=c.y,h=u.x,g=u.y;m>r!=g>r&&n<(h-f)*(r-m)/(g-m)+f&&(a=!a)}return a}function cse(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),use(t)}function use(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const a=e[r];for(;t.length>=2;){const s=t[t.length-1],i=t[t.length-2];if((s.x-i.x)*(a.y-i.y)>=(s.y-i.y)*(a.x-i.x))t.pop();else break}t.push(a)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const a=e[r];for(;n.length>=2;){const s=n[n.length-1],i=n[n.length-2];if((s.x-i.x)*(a.y-i.y)>=(s.y-i.y)*(a.x-i.x))n.pop();else break}n.push(a)}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 dse=$3,fse=z3,pse=F3,mse=B3,hse=H3,gse=W3;function K3({delayDuration:e=0,...t}){return d.jsx(dse,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Dt({...e}){return d.jsx(K3,{children:d.jsx(fse,{"data-slot":"tooltip",...e})})}function Lt({...e}){return d.jsx(pse,{"data-slot":"tooltip-trigger",...e})}function Mt({className:e,sideOffset:t=0,children:n,...r}){return d.jsx(mse,{children:d.jsxs(hse,{"data-slot":"tooltip-content",sideOffset:t,className:Oe("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),...r,children:[n,d.jsx(gse,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}class bse{name="mcp_inspector_open";properties;constructor(t){this.properties={server_url:t.serverUrl,connection_count:t.connectionCount}}}class hP{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 gP{name="mcp_resource_read";properties;constructor(t){this.properties={resource_uri:t.resourceUri,server_id:t.serverId,success:t.success,error:t.error}}}class bP{name="mcp_prompt_call";properties;constructor(t){this.properties={prompt_name:t.promptName,server_id:t.serverId,success:t.success,error:t.error}}}class yP{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 yse{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 vse{name="mcp_server_removed";properties;constructor(t){this.properties={server_id:t.serverId}}}class wse{name="mcp_command_palette_open";properties;constructor(t){this.properties={trigger:t.trigger}}}class Ese{name="mcp_tool_saved";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId}}}function vE(){try{return"0.12.0"}catch{return"0.0.0"}}var xse={};function wE(){try{return typeof window<"u"&&typeof document<"u"}catch{return!1}}class vP{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,r=setTimeout(()=>n.abort(),this.timeout),a=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(r),!a.ok)throw new Error(`HTTP error! status: ${a.status}`)}catch{}}}function mi(e){return`mcp_inspector_telemetry_${e}`}class Tr{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=wE(),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 vP(this.POSTHOG_PROXY_URL,3e3)}catch{this._posthogClient=null}try{this._scarfClient=new vP(this.SCARF_PROXY_URL,3e3)}catch{this._scarfClient=null}}}isTelemetryDisabled(){return typeof localStorage<"u"&&localStorage.getItem(mi("disabled"))==="true"||typeof process<"u"&&xse?.MCP_USE_ANONYMIZED_TELEMETRY==="false"}getStoredSource(){return typeof localStorage<"u"?localStorage.getItem(mi("source")):null}static getInstance(){return Tr.instance||(Tr.instance=new Tr),Tr.instance}setSource(t){this._source=t,typeof localStorage<"u"&&localStorage.setItem(mi("source"),t)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!wE())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{const t=localStorage.getItem(mi("user_id"));if(t)this._currUserId=t;else{const n=this.generateUserId();localStorage.setItem(mi("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(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=Math.random()*16|0;return(t==="x"?n:n&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:vE(),language:"typescript",source:this._source,package:"inspector"}};await this._posthogClient.logEvent(n)}catch{}if(this._scarfClient)try{const n={};n.mcp_use_version=vE(),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&&wE())try{const n=vE();let r=!1,a=!1;const s=localStorage.getItem(mi("download_version"));if(s?n>s&&(r=!0,a=!1,localStorage.setItem(mi("download_version"),n)):(r=!0,a=!0,localStorage.setItem(mi("download_version"),n)),r){const i={...t||{}};i.mcp_use_version=n,i.user_id=this.userId,i.event="package_download",i.first_download=a,i.language="typescript",i.source=this._source,i.package="inspector",await this._scarfClient.logEvent(i)}}catch{}}async trackInspectorOpen(t){const n=new bse(t);await this.capture(n)}}const Sse={model:"stub-model",stopReason:"endTurn",role:"assistant",content:{type:"text",text:"positive"}};function _se({requestId:e,serverName:t,onViewDetails:n,onApprove:r,onDeny:a}){return d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{children:[d.jsx("strong",{children:"Sampling Request Received"}),d.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["New request from ",t]})]}),d.jsxs("div",{className:"flex gap-2",children:[d.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:s=>{s.stopPropagation(),n()},children:"View Details"}),d.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:s=>{s.stopPropagation(),r(Sse)},children:"Approve"}),d.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:s=>{s.stopPropagation(),a()},children:"Deny"})]})]})}function Tse({requestId:e,serverName:t,mode:n,message:r,url:a,onViewDetails:s,onOpenUrl:i,onCancel:c}){return d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{children:[d.jsx("strong",{children:"Elicitation Request Received"}),d.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["From ",t,": ",r]}),n==="url"&&a&&d.jsx("p",{className:"text-xs text-muted-foreground mt-1 font-mono",children:a})]}),d.jsxs("div",{className:"flex gap-2 flex-wrap",children:[d.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:"View Details"}),n==="url"&&i&&d.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:"Open URL"}),d.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 Tg=()=>{},Ng=()=>{},kg=()=>{},Cg=()=>{},Y3=v.createContext(null);function cT(){const e=v.use(Y3);if(!e)throw new Error("useMcpContext must be used within a McpProvider");return e}function Nse({url:e,name:t,proxyConfig:n,transportType:r,connectionId:a,onUpdate:s,onRemove:i}){const c=typeof window<"u"?new URL("/inspector/oauth/callback",window.location.origin).toString():"/inspector/oauth/callback";let u=e,f={};if(n?.proxyAddress){const L=new URL(n.proxyAddress),M=new URL(e);u=`${L.origin}${L.pathname}${M.pathname}${M.search}`,f["X-Target-URL"]=e}n?.customHeaders&&(f={...f,...n.customHeaders});const[m,h]=v.useState([]),g=v.useRef(0),[y,x]=v.useState([]),E=v.useRef(0),w=v.useMemo(()=>m.map(L=>({id:L.id,request:L.request,timestamp:L.timestamp,serverName:L.serverName})),[m]),_=v.useMemo(()=>y.map(L=>({id:L.id,request:L.request,timestamp:L.timestamp,serverName:L.serverName})),[y]),S=v.useRef(null),[T,R]=v.useState(!1),C=v.useRef(!1);v.useEffect(()=>{typeof window<"u"&&!C.current&&(C.current=!0,rr(()=>import("./transport-wrapper-browser-BI4dDu3b.js"),[]).then(L=>{S.current=L.wrapTransportForLogging,R(!0),console.log("[McpContext] Transport wrapper loaded")}).catch(L=>{console.error("[McpContext] Failed to load transport wrapper:",L)}))},[]);const I=v.useMemo(()=>{if(!(!T||!S.current))return(L,M)=>{const z=a;return console.log("[McpContext] Applying transport wrapper, serverId:",z,"from connector:",M),S.current(L,z)}},[T,a]),A=`mcp-inspector-notifications-${a}`,O=500,[j,U]=v.useState([]);v.useEffect(()=>{try{const L=localStorage.getItem(A);if(L){const M=JSON.parse(L);Array.isArray(M)&&U(M)}}catch(L){console.error("Failed to load notifications from localStorage:",L)}},[A]),v.useEffect(()=>{try{localStorage.setItem(A,JSON.stringify(j))}catch(L){console.error("Failed to save notifications to localStorage:",L)}},[j,A]);const B=v.useCallback(L=>{U(M=>M.map(z=>z.id===L?{...z,read:!0}:z))},[]),W=v.useCallback(()=>{U(L=>L.map(M=>({...M,read:!0})))},[]),J=v.useCallback(()=>{U([])},[]),ee=v.useCallback(L=>{U(M=>{const z=[L,...M];return z.length>O?z.slice(0,O):z})},[]),re=v.useCallback((L,M)=>{h(z=>{const G=z.find(q=>q.id===L);return G?(G.resolve(M),z.filter(q=>q.id!==L)):z})},[]),F=v.useCallback((L,M)=>{h(z=>{const G=z.find(q=>q.id===L);return G?(G.reject(new Error(M||"User rejected sampling request")),z.filter(q=>q.id!==L)):z})},[]),K=v.useCallback((L,M)=>{x(z=>{const G=z.find(q=>q.id===L);return G?(G.resolve(M),z.filter(q=>q.id!==L)):z})},[]),V=v.useCallback((L,M)=>{x(z=>{const G=z.find(q=>q.id===L);return G?(G.reject(new Error(M||"User rejected elicitation request")),z.filter(q=>q.id!==L)):z})},[]),ne=v.useCallback(async L=>new Promise((M,z)=>{const G=`sampling-${g.current++}`,q={id:G,request:{params:L},timestamp:Date.now(),serverName:t,resolve:M,reject:z};h(ae=>[...ae,q]),typeof window<"u"&&rr(async()=>{const{toast:ae}=await Promise.resolve().then(()=>NP);return{toast:ae}},void 0).then(({toast:ae})=>{const ie=ae(d.jsx(_se,{requestId:G,serverName:t,onViewDetails:()=>{const X=new globalThis.CustomEvent("navigate-to-sampling",{detail:{requestId:G}});window.dispatchEvent(X),ae.dismiss(ie)},onApprove:X=>{h(Z=>{const se=Z.find(me=>me.id===G);return se?(se.resolve(X),ae.success("Sampling request approved"),Z.filter(me=>me.id!==G)):Z}),ae.dismiss(ie)},onDeny:()=>{h(X=>{const Z=X.find(se=>se.id===G);return Z?(Z.reject(new Error("User denied sampling request from toast")),ae.error("Sampling request denied"),X.filter(se=>se.id!==G)):X}),ae.dismiss(ie)}}),{duration:5e3})})}),[t]),te=v.useCallback(async L=>new Promise((M,z)=>{const G=`elicitation-${E.current++}`,q={id:G,request:L,timestamp:Date.now(),serverName:t,resolve:M,reject:z};x(ae=>[...ae,q]),typeof window<"u"&&rr(async()=>{const{toast:ae}=await Promise.resolve().then(()=>NP);return{toast:ae}},void 0).then(({toast:ae})=>{const ie=ae(d.jsx(Tse,{requestId:G,serverName:t,mode:L.mode||"form",message:L.message,url:L.mode==="url"?L.url:void 0,onViewDetails:()=>{const X=new globalThis.CustomEvent("navigate-to-elicitation",{detail:{requestId:G}});window.dispatchEvent(X),ae.dismiss(ie)},onOpenUrl:L.mode==="url"?()=>{window.open(L.url,"_blank"),ae.dismiss(ie)}:void 0,onCancel:()=>{x(X=>{const Z=X.find(se=>se.id===G);return Z?(Z.reject(new Error("User cancelled elicitation request from toast")),ae.error("Elicitation request cancelled"),X.filter(se=>se.id!==G)):X}),ae.dismiss(ie)}}),{duration:5e3})})}),[t]),D=M_({url:u,callbackUrl:c,customHeaders:Object.keys(f).length>0?f:void 0,transportType:r||"http",preventAutoAuth:!0,useRedirectFlow:!0,enabled:T,wrapTransport:I,onNotification:L=>{ee({id:globalThis.crypto.randomUUID(),method:L.method,params:L.params,timestamp:Date.now(),read:!1})},samplingCallback:ne,onElicitation:te}),H=v.useRef(s),$=v.useRef(null);return v.useEffect(()=>{H.current=s},[s]),v.useEffect(()=>{if(typeof queueMicrotask<"u")queueMicrotask(()=>{D.state==="ready"&&D.serverInfo&&console.log("[McpContext] Server info available:",D.serverInfo);const L=j.filter(G=>!G.read).length,M={id:a,url:e,name:D.serverInfo?.name||t,state:D.state,tools:D.tools,resources:D.resources,prompts:D.prompts,error:D.error??null,authUrl:D.authUrl??null,customHeaders:f,transportType:r,proxyConfig:n,serverInfo:D.serverInfo,capabilities:D.capabilities,notifications:j,unreadNotificationCount:L,markNotificationRead:B,markAllNotificationsRead:W,clearNotifications:J,pendingSamplingRequests:w,approveSampling:re,rejectSampling:F,pendingElicitationRequests:_,approveElicitation:K,rejectElicitation:V,callTool:D.callTool,readResource:D.readResource,listPrompts:D.listPrompts,getPrompt:D.getPrompt,authenticate:D.authenticate,retry:D.retry,clearStorage:D.clearStorage,disconnect:D.disconnect,client:D.client},z=$.current;(!z||z.state!==M.state||z.error!==M.error||z.authUrl!==M.authUrl||z.name!==M.name||z.tools.length!==M.tools.length||z.resources.length!==M.resources.length||z.prompts.length!==M.prompts.length||z.serverInfo!==M.serverInfo||z.capabilities!==M.capabilities||z.notifications.length!==M.notifications.length||z.unreadNotificationCount!==M.unreadNotificationCount||z.pendingSamplingRequests.length!==M.pendingSamplingRequests.length||z.pendingElicitationRequests.length!==M.pendingElicitationRequests.length||!z.client)&&($.current=M,H.current(M))});else{const L=j.filter(G=>!G.read).length,M={id:a,url:e,name:D.serverInfo?.name||t,state:D.state,tools:D.tools,resources:D.resources,prompts:D.prompts,error:D.error??null,authUrl:D.authUrl??null,customHeaders:f,transportType:r,proxyConfig:n,serverInfo:D.serverInfo,capabilities:D.capabilities,notifications:j,unreadNotificationCount:L,markNotificationRead:B,markAllNotificationsRead:W,clearNotifications:J,pendingSamplingRequests:w,approveSampling:re,rejectSampling:F,pendingElicitationRequests:_,approveElicitation:K,rejectElicitation:V,callTool:D.callTool,readResource:D.readResource,listPrompts:D.listPrompts,getPrompt:D.getPrompt,authenticate:D.authenticate,retry:D.retry,clearStorage:D.clearStorage,disconnect:D.disconnect,client:D.client},z=$.current;(!z||z.state!==M.state||z.error!==M.error||z.authUrl!==M.authUrl||z.name!==M.name||z.tools.length!==M.tools.length||z.resources.length!==M.resources.length||z.prompts.length!==M.prompts.length||z.serverInfo!==M.serverInfo||z.capabilities!==M.capabilities||z.notifications.length!==M.notifications.length||z.unreadNotificationCount!==M.unreadNotificationCount||z.pendingSamplingRequests.length!==M.pendingSamplingRequests.length||z.pendingElicitationRequests.length!==M.pendingElicitationRequests.length||!z.client)&&($.current=M,H.current(M))}},[e,t,r,n,f,a,D.state,D.tools,D.resources,D.prompts,D.error,D.authUrl,D.serverInfo,D.capabilities,D.client,j,B,W,J,D.callTool,D.readResource,D.listPrompts,D.getPrompt,D.authenticate,D.retry,D.clearStorage,m,re,F,_,K,V]),null}function kse({children:e}){const[t,n]=v.useState([]),[r,a]=v.useState(!1),[s,i]=v.useState(!0),[c,u]=v.useState([]);v.useEffect(()=>{try{const w=localStorage.getItem("mcp-inspector-connections");if(w){const S=JSON.parse(w);Array.isArray(S)&&(u(S),n(S.map(T=>({id:T.id||T.url,url:T.url,name:T.name||"MCP Server",state:"discovering",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:T.proxyConfig?.customHeaders,transportType:T.transportType,proxyConfig:T.proxyConfig,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:Tg,rejectSampling:Ng,pendingElicitationRequests:[],approveElicitation:kg,rejectElicitation:Cg,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}))))}const _=localStorage.getItem("mcp-inspector-auto-connect");_!==null&&i(_==="true")}catch(w){console.error("Failed to load connections from localStorage:",w)}finally{a(!0)}},[]),v.useEffect(()=>{r&&localStorage.setItem("mcp-inspector-connections",JSON.stringify(c))},[c,r]),v.useEffect(()=>{r&&localStorage.setItem("mcp-inspector-auto-connect",String(s))},[s,r]);const f=v.useCallback((w,_,S,T)=>{const R=c.find(A=>A.url===w),C=t.find(A=>A.url===w);if(R&&C){if(JSON.stringify(R.proxyConfig)!==JSON.stringify(S)&&S){u(O=>O.filter(j=>j.url!==w)),n(O=>O.filter(j=>j.url!==w)),setTimeout(()=>{const O={id:w,url:w,name:_||R.name||"MCP Server",proxyConfig:S,transportType:T||R.transportType};u(j=>[...j,O]),n(j=>[...j,{id:w,url:w,name:_||R.name||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:S?.customHeaders,transportType:T||R.transportType,proxyConfig:S,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:Tg,rejectSampling:Ng,pendingElicitationRequests:[],approveElicitation:kg,rejectElicitation:Cg,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}])},10);return}return}if(R&&!C){(S||T)&&u(A=>A.map(O=>O.url===w?{...O,proxyConfig:S||O.proxyConfig,transportType:T||O.transportType,name:_||O.name}:O)),n(A=>[...A,{id:R.id||w,url:w,name:_||R.name||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:S?.customHeaders||R.proxyConfig?.customHeaders,transportType:T||R.transportType,proxyConfig:S||R.proxyConfig,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:Tg,rejectSampling:Ng,pendingElicitationRequests:[],approveElicitation:kg,rejectElicitation:Cg,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}]);return}const I={id:w,url:w,name:_||"MCP Server",proxyConfig:S,transportType:T};u(A=>[...A,I]),n(A=>[...A,{id:w,url:w,name:_||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:S?.customHeaders,transportType:T,proxyConfig:S,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:Tg,rejectSampling:Ng,pendingElicitationRequests:[],approveElicitation:kg,rejectElicitation:Cg,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}])},[c,t]),m=v.useCallback(w=>{const _=t.find(T=>T.id===w);_&&(console.log(`[McpContext] Cleaning up connection: ${w}`),_.disconnect&&(console.log(`[McpContext] Disconnecting from server: ${w}`),_.disconnect()),_.clearStorage&&(console.log(`[McpContext] Clearing OAuth storage for connection: ${w}`),_.clearStorage())),u(T=>T.filter(R=>R.id!==w)),n(T=>T.filter(R=>R.id!==w));const S=localStorage.getItem("mcp-inspector-connections");if(S)try{const R=JSON.parse(S).filter(C=>(C.id||C.url)!==w);localStorage.setItem("mcp-inspector-connections",JSON.stringify(R))}catch(T){console.error("Failed to update localStorage on remove:",T)}Tr.getInstance().capture(new vse({serverId:w}))},[t]),h=v.useCallback((w,_)=>{u(S=>S.map(T=>T.id===w||T.url===w?{...T,..._}:T)),n(S=>S.map(T=>T.id===w?{...T,..._}:T))},[]),g=v.useCallback(w=>{n(_=>{const S=_.findIndex(C=>C.id===w.id);if(S===-1)return _;const T=_[S];if(T.state===w.state&&T.tools===w.tools&&T.resources===w.resources&&T.prompts===w.prompts&&T.error===w.error&&T.serverInfo===w.serverInfo&&T.client===w.client&&T.notifications===w.notifications&&T.unreadNotificationCount===w.unreadNotificationCount&&T.pendingSamplingRequests.length===w.pendingSamplingRequests.length&&T.pendingElicitationRequests.length===w.pendingElicitationRequests.length)return _;const R=[..._];return R[S]=w,R})},[]),y=v.useCallback(w=>{console.log("Connect requested for:",w)},[]),x=v.useCallback(w=>{console.log("Disconnect requested for:",w)},[]),E=v.useMemo(()=>({connections:t,addConnection:f,removeConnection:m,updateConnectionConfig:h,autoConnect:s,setAutoConnect:i,connectServer:y,disconnectServer:x,configLoaded:r}),[t,f,m,h,s,y,x,r]);return d.jsxs(Y3.Provider,{value:E,children:[e,r&&s&&c.map(w=>{const _=`${w.id||w.url}-${w.proxyConfig?.proxyAddress?"proxy":"direct"}`;return console.warn("[McpContext] Rendering McpConnectionWrapper with key:",_,"proxyConfig:",w.proxyConfig),d.jsx(Nse,{url:w.url,name:w.name,proxyConfig:w.proxyConfig,transportType:w.transportType,connectionId:w.id||w.url,onUpdate:g,onRemove:()=>m(w.id||w.url)},_)})]})}const Cse=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Rse=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),wP=e=>{const t=Rse(e);return t.charAt(0).toUpperCase()+t.slice(1)},Z3=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Ase=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Ise={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 Ose=v.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:s,iconNode:i,...c},u)=>v.createElement("svg",{ref:u,...Ise,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:Z3("lucide",a),...!s&&!Ase(c)&&{"aria-hidden":"true"},...c},[...i.map(([f,m])=>v.createElement(f,m)),...Array.isArray(s)?s:[s]]));const Xe=(e,t)=>{const n=v.forwardRef(({className:r,...a},s)=>v.createElement(Ose,{ref:s,iconNode:t,className:Z3(`lucide-${Cse(wP(e))}`,`lucide-${e}`,r),...a}));return n.displayName=wP(e),n};const Dse=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],Lse=Xe("arrow-down-to-line",Dse);const Mse=[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]],jse=Xe("arrow-up-from-line",Mse);const Pse=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Use=Xe("arrow-up",Pse);const $se=[["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"}]],uT=Xe("bell",$se);const zse=[["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"}]],q3=Xe("brush",zse);const Fse=[["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"}]],Bse=Xe("bug",Fse);const Hse=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],oa=Xe("check",Hse);const Vse=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Gl=Xe("chevron-down",Vse);const Gse=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Wse=Xe("chevron-right",Gse);const Kse=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],dT=Xe("chevron-left",Kse);const Yse=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Zse=Xe("chevron-up",Yse);const qse=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],Xse=Xe("chevrons-up-down",qse);const Jse=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]],EP=Xe("circle-minus",Jse);const Qse=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],qu=Xe("clock",Qse);const eie=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],fT=Xe("code",eie);const tie=[["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"}]],nie=Xe("cog",tie);const rie=[["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"}]],aie=Xe("command",rie);const oie=[["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"}]],zr=Xe("copy",oie);const sie=[["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"}]],Wy=Xe("database",sie);const iie=[["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"}]],Qp=Xe("download",iie);const lie=[["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"}]],cie=Xe("ellipsis-vertical",lie);const uie=[["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"}]],Wx=Xe("external-link",uie);const die=[["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"}]],X3=Xe("eye-off",die);const fie=[["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"}]],Kx=Xe("eye",fie);const pie=[["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"}]],mie=Xe("file-code",pie);const hie=[["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"}]],gie=Xe("file-image",hie);const bie=[["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"}]],pT=Xe("file-text",bie);const yie=[["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"}]],vie=Xe("file",yie);const wie=[["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"}]],Eie=Xe("folder-open",wie);const xie=[["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"}]],Sie=Xe("globe",xie);const _ie=[["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"}]],Tie=Xe("grip-vertical",_ie);const Nie=[["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"}]],J3=Xe("hash",Nie);const kie=[["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"}]],Mb=Xe("history",kie);const Cie=[["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"}]],Q3=Xe("key",Cie);const Rie=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Li=Xe("loader-circle",Rie);const Aie=[["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"}]],mT=Xe("maximize-2",Aie);const Iie=[["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"}]],hT=Xe("maximize",Iie);const Oie=[["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"}]],Die=Xe("message-circle",Oie);const Lie=[["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"}]],yp=Xe("message-square",Lie);const Mie=[["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"}]],jie=Xe("minimize",Mie);const Pie=[["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"}]],xP=Xe("monitor",Pie);const Uie=[["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"}]],$ie=Xe("moon",Uie);const zie=[["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"}]],Fie=Xe("picture-in-picture",zie);const Bie=[["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"}]],eB=Xe("play",Bie);const Hie=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],tB=Xe("plus",Hie);const Vie=[["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"}]],SP=Xe("rotate-ccw",Vie);const Gie=[["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"}]],gT=Xe("save",Gie);const Wie=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],wd=Xe("search",Wie);const Kie=[["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"}]],Yie=Xe("send",Kie);const Zie=[["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"}]],qie=Xe("server",Zie);const Xie=[["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"}]],mu=Xe("settings",Xie);const Jie=[["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"}]],Qie=Xe("shield",Jie);const ele=[["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"}]],tle=Xe("sparkles",ele);const nle=[["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"}]],nB=Xe("square-check-big",nle);const rle=[["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"}]],ale=Xe("square-pen",rle);const ole=[["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"}]],sle=Xe("sun-dim",ole);const ile=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],EE=Xe("terminal",ile);const lle=[["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"}]],Mi=Xe("trash-2",lle);const cle=[["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"}]],ule=Xe("trash",cle);const dle=[["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"}]],Ol=Xe("wrench",dle);const fle=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],qo=Xe("x",fle);const ple=[["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=Xe("zap",ple);function mle(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 hle=e=>{switch(e){case"success":return yle;case"info":return wle;case"warning":return vle;case"error":return Ele;default:return null}},gle=Array(12).fill(0),ble=({visible:e,className:t})=>ce.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ce.createElement("div",{className:"sonner-spinner"},gle.map((n,r)=>ce.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),yle=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ce.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"})),vle=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ce.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"})),wle=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ce.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"})),Ele=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ce.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"})),xle=ce.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"},ce.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ce.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Sle=()=>{const[e,t]=ce.useState(document.hidden);return ce.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Yx=1;class _le{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:r,...a}=t,s=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Yx++,i=this.toasts.find(u=>u.id===s),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(s)&&this.dismissedToasts.delete(s),i?this.toasts=this.toasts.map(u=>u.id===s?(this.publish({...u,...t,id:s,title:r}),{...u,...t,id:s,dismissible:c,title:r}):u):this.addToast({title:r,...a,dismissible:c,id:s}),s},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(r=>r({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 r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const a=Promise.resolve(t instanceof Function?t():t);let s=r!==void 0,i;const c=a.then(async f=>{if(i=["resolve",f],ce.isValidElement(f))s=!1,this.create({id:r,type:"default",message:f});else if(Nle(f)&&!f.ok){s=!1;const h=typeof n.error=="function"?await n.error(`HTTP error! status: ${f.status}`):n.error,g=typeof n.description=="function"?await n.description(`HTTP error! status: ${f.status}`):n.description,x=typeof h=="object"&&!ce.isValidElement(h)?h:{message:h};this.create({id:r,type:"error",description:g,...x})}else if(f instanceof Error){s=!1;const h=typeof n.error=="function"?await n.error(f):n.error,g=typeof n.description=="function"?await n.description(f):n.description,x=typeof h=="object"&&!ce.isValidElement(h)?h:{message:h};this.create({id:r,type:"error",description:g,...x})}else if(n.success!==void 0){s=!1;const h=typeof n.success=="function"?await n.success(f):n.success,g=typeof n.description=="function"?await n.description(f):n.description,x=typeof h=="object"&&!ce.isValidElement(h)?h:{message:h};this.create({id:r,type:"success",description:g,...x})}}).catch(async f=>{if(i=["reject",f],n.error!==void 0){s=!1;const m=typeof n.error=="function"?await n.error(f):n.error,h=typeof n.description=="function"?await n.description(f):n.description,y=typeof m=="object"&&!ce.isValidElement(m)?m:{message:m};this.create({id:r,type:"error",description:h,...y})}}).finally(()=>{s&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),u=()=>new Promise((f,m)=>c.then(()=>i[0]==="reject"?m(i[1]):f(i[1])).catch(m));return typeof r!="string"&&typeof r!="number"?{unwrap:u}:Object.assign(r,{unwrap:u})},this.custom=(t,n)=>{const r=n?.id||Yx++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const ba=new _le,Tle=(e,t)=>{const n=t?.id||Yx++;return ba.addToast({title:e,...t,id:n}),n},Nle=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",kle=Tle,Cle=()=>ba.toasts,Rle=()=>ba.getActiveToasts(),Xt=Object.assign(kle,{success:ba.success,info:ba.info,warning:ba.warning,error:ba.error,custom:ba.custom,message:ba.message,promise:ba.promise,dismiss:ba.dismiss,loading:ba.loading},{getHistory:Cle,getToasts:Rle});mle("[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 Rg(e){return e.label!==void 0}const Ale=3,Ile="24px",Ole="16px",_P=4e3,Dle=356,Lle=14,Mle=45,jle=200;function Po(...e){return e.filter(Boolean).join(" ")}function Ple(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const Ule=e=>{var t,n,r,a,s,i,c,u,f;const{invert:m,toast:h,unstyled:g,interacting:y,setHeights:x,visibleToasts:E,heights:w,index:_,toasts:S,expanded:T,removeToast:R,defaultRichColors:C,closeButton:I,style:A,cancelButtonStyle:O,actionButtonStyle:j,className:U="",descriptionClassName:B="",duration:W,position:J,gap:ee,expandByDefault:re,classNames:F,icons:K,closeButtonAriaLabel:V="Close toast"}=e,[ne,te]=ce.useState(null),[D,H]=ce.useState(null),[$,L]=ce.useState(!1),[M,z]=ce.useState(!1),[G,q]=ce.useState(!1),[ae,ie]=ce.useState(!1),[X,Z]=ce.useState(!1),[se,me]=ce.useState(0),[le,Ne]=ce.useState(0),He=ce.useRef(h.duration||W||_P),xe=ce.useRef(null),Te=ce.useRef(null),$e=_===0,fe=_+1<=E,Ie=h.type,Fe=h.dismissible!==!1,Ee=h.className||"",at=h.descriptionClassName||"",lt=ce.useMemo(()=>w.findIndex(Ze=>Ze.toastId===h.id)||0,[w,h.id]),bt=ce.useMemo(()=>{var Ze;return(Ze=h.closeButton)!=null?Ze:I},[h.closeButton,I]),Rt=ce.useMemo(()=>h.duration||W||_P,[h.duration,W]),De=ce.useRef(0),ze=ce.useRef(0),ht=ce.useRef(0),nt=ce.useRef(null),[kt,ot]=J.split("-"),Ae=ce.useMemo(()=>w.reduce((Ze,vt,Pt)=>Pt>=lt?Ze:Ze+vt.height,0),[w,lt]),Me=Sle(),Ve=h.invert||m,it=Ie==="loading";ze.current=ce.useMemo(()=>lt*ee+Ae,[lt,Ae]),ce.useEffect(()=>{He.current=Rt},[Rt]),ce.useEffect(()=>{L(!0)},[]),ce.useEffect(()=>{const Ze=Te.current;if(Ze){const vt=Ze.getBoundingClientRect().height;return Ne(vt),x(Pt=>[{toastId:h.id,height:vt,position:h.position},...Pt]),()=>x(Pt=>Pt.filter(Ut=>Ut.toastId!==h.id))}},[x,h.id]),ce.useLayoutEffect(()=>{if(!$)return;const Ze=Te.current,vt=Ze.style.height;Ze.style.height="auto";const Pt=Ze.getBoundingClientRect().height;Ze.style.height=vt,Ne(Pt),x(Ut=>Ut.find(dn=>dn.toastId===h.id)?Ut.map(dn=>dn.toastId===h.id?{...dn,height:Pt}:dn):[{toastId:h.id,height:Pt,position:h.position},...Ut])},[$,h.title,h.description,x,h.id,h.jsx,h.action,h.cancel]);const pt=ce.useCallback(()=>{z(!0),me(ze.current),x(Ze=>Ze.filter(vt=>vt.toastId!==h.id)),setTimeout(()=>{R(h)},jle)},[h,R,x,ze]);ce.useEffect(()=>{if(h.promise&&Ie==="loading"||h.duration===1/0||h.type==="loading")return;let Ze;return T||y||Me?(()=>{if(ht.current<De.current){const Ut=new Date().getTime()-De.current;He.current=He.current-Ut}ht.current=new Date().getTime()})():(()=>{He.current!==1/0&&(De.current=new Date().getTime(),Ze=setTimeout(()=>{h.onAutoClose==null||h.onAutoClose.call(h,h),pt()},He.current))})(),()=>clearTimeout(Ze)},[T,y,h,Ie,Me,pt]),ce.useEffect(()=>{h.delete&&(pt(),h.onDismiss==null||h.onDismiss.call(h,h))},[pt,h.delete]);function Et(){var Ze;if(K?.loading){var vt;return ce.createElement("div",{className:Po(F?.loader,h==null||(vt=h.classNames)==null?void 0:vt.loader,"sonner-loader"),"data-visible":Ie==="loading"},K.loading)}return ce.createElement(ble,{className:Po(F?.loader,h==null||(Ze=h.classNames)==null?void 0:Ze.loader),visible:Ie==="loading"})}const xt=h.icon||K?.[Ie]||hle(Ie);var un,mn;return ce.createElement("li",{tabIndex:0,ref:Te,className:Po(U,Ee,F?.toast,h==null||(t=h.classNames)==null?void 0:t.toast,F?.default,F?.[Ie],h==null||(n=h.classNames)==null?void 0:n[Ie]),"data-sonner-toast":"","data-rich-colors":(un=h.richColors)!=null?un:C,"data-styled":!(h.jsx||h.unstyled||g),"data-mounted":$,"data-promise":!!h.promise,"data-swiped":X,"data-removed":M,"data-visible":fe,"data-y-position":kt,"data-x-position":ot,"data-index":_,"data-front":$e,"data-swiping":G,"data-dismissible":Fe,"data-type":Ie,"data-invert":Ve,"data-swipe-out":ae,"data-swipe-direction":D,"data-expanded":!!(T||re&&$),"data-testid":h.testId,style:{"--index":_,"--toasts-before":_,"--z-index":S.length-_,"--offset":`${M?se:ze.current}px`,"--initial-height":re?"auto":`${le}px`,...A,...h.style},onDragEnd:()=>{q(!1),te(null),nt.current=null},onPointerDown:Ze=>{Ze.button!==2&&(it||!Fe||(xe.current=new Date,me(ze.current),Ze.target.setPointerCapture(Ze.pointerId),Ze.target.tagName!=="BUTTON"&&(q(!0),nt.current={x:Ze.clientX,y:Ze.clientY})))},onPointerUp:()=>{var Ze,vt,Pt;if(ae||!Fe)return;nt.current=null;const Ut=Number(((Ze=Te.current)==null?void 0:Ze.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),yr=Number(((vt=Te.current)==null?void 0:vt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),dn=new Date().getTime()-((Pt=xe.current)==null?void 0:Pt.getTime()),Xn=ne==="x"?Ut:yr,Jn=Math.abs(Xn)/dn;if(Math.abs(Xn)>=Mle||Jn>.11){me(ze.current),h.onDismiss==null||h.onDismiss.call(h,h),H(ne==="x"?Ut>0?"right":"left":yr>0?"down":"up"),pt(),ie(!0);return}else{var wn,fn;(wn=Te.current)==null||wn.style.setProperty("--swipe-amount-x","0px"),(fn=Te.current)==null||fn.style.setProperty("--swipe-amount-y","0px")}Z(!1),q(!1),te(null)},onPointerMove:Ze=>{var vt,Pt,Ut;if(!nt.current||!Fe||((vt=window.getSelection())==null?void 0:vt.toString().length)>0)return;const dn=Ze.clientY-nt.current.y,Xn=Ze.clientX-nt.current.x;var Jn;const wn=(Jn=e.swipeDirections)!=null?Jn:Ple(J);!ne&&(Math.abs(Xn)>1||Math.abs(dn)>1)&&te(Math.abs(Xn)>Math.abs(dn)?"x":"y");let fn={x:0,y:0};const la=Qt=>1/(1.5+Math.abs(Qt)/20);if(ne==="y"){if(wn.includes("top")||wn.includes("bottom"))if(wn.includes("top")&&dn<0||wn.includes("bottom")&&dn>0)fn.y=dn;else{const Qt=dn*la(dn);fn.y=Math.abs(Qt)<Math.abs(dn)?Qt:dn}}else if(ne==="x"&&(wn.includes("left")||wn.includes("right")))if(wn.includes("left")&&Xn<0||wn.includes("right")&&Xn>0)fn.x=Xn;else{const Qt=Xn*la(Xn);fn.x=Math.abs(Qt)<Math.abs(Xn)?Qt:Xn}(Math.abs(fn.x)>0||Math.abs(fn.y)>0)&&Z(!0),(Pt=Te.current)==null||Pt.style.setProperty("--swipe-amount-x",`${fn.x}px`),(Ut=Te.current)==null||Ut.style.setProperty("--swipe-amount-y",`${fn.y}px`)}},bt&&!h.jsx&&Ie!=="loading"?ce.createElement("button",{"aria-label":V,"data-disabled":it,"data-close-button":!0,onClick:it||!Fe?()=>{}:()=>{pt(),h.onDismiss==null||h.onDismiss.call(h,h)},className:Po(F?.closeButton,h==null||(r=h.classNames)==null?void 0:r.closeButton)},(mn=K?.close)!=null?mn:xle):null,(Ie||h.icon||h.promise)&&h.icon!==null&&(K?.[Ie]!==null||h.icon)?ce.createElement("div",{"data-icon":"",className:Po(F?.icon,h==null||(a=h.classNames)==null?void 0:a.icon)},h.promise||h.type==="loading"&&!h.icon?h.icon||Et():null,h.type!=="loading"?xt:null):null,ce.createElement("div",{"data-content":"",className:Po(F?.content,h==null||(s=h.classNames)==null?void 0:s.content)},ce.createElement("div",{"data-title":"",className:Po(F?.title,h==null||(i=h.classNames)==null?void 0:i.title)},h.jsx?h.jsx:typeof h.title=="function"?h.title():h.title),h.description?ce.createElement("div",{"data-description":"",className:Po(B,at,F?.description,h==null||(c=h.classNames)==null?void 0:c.description)},typeof h.description=="function"?h.description():h.description):null),ce.isValidElement(h.cancel)?h.cancel:h.cancel&&Rg(h.cancel)?ce.createElement("button",{"data-button":!0,"data-cancel":!0,style:h.cancelButtonStyle||O,onClick:Ze=>{Rg(h.cancel)&&Fe&&(h.cancel.onClick==null||h.cancel.onClick.call(h.cancel,Ze),pt())},className:Po(F?.cancelButton,h==null||(u=h.classNames)==null?void 0:u.cancelButton)},h.cancel.label):null,ce.isValidElement(h.action)?h.action:h.action&&Rg(h.action)?ce.createElement("button",{"data-button":!0,"data-action":!0,style:h.actionButtonStyle||j,onClick:Ze=>{Rg(h.action)&&(h.action.onClick==null||h.action.onClick.call(h.action,Ze),!Ze.defaultPrevented&&pt())},className:Po(F?.actionButton,h==null||(f=h.classNames)==null?void 0:f.actionButton)},h.action.label):null)};function TP(){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 $le(e,t){const n={};return[e,t].forEach((r,a)=>{const s=a===1,i=s?"--mobile-offset":"--offset",c=s?Ole:Ile;function u(f){["top","right","bottom","left"].forEach(m=>{n[`${i}-${m}`]=typeof f=="number"?`${f}px`:f})}typeof r=="number"||typeof r=="string"?u(r):typeof r=="object"?["top","right","bottom","left"].forEach(f=>{r[f]===void 0?n[`${i}-${f}`]=c:n[`${i}-${f}`]=typeof r[f]=="number"?`${r[f]}px`:r[f]}):u(c)}),n}const rB=ce.forwardRef(function(t,n){const{id:r,invert:a,position:s="bottom-right",hotkey:i=["altKey","KeyT"],expand:c,closeButton:u,className:f,offset:m,mobileOffset:h,theme:g="light",richColors:y,duration:x,style:E,visibleToasts:w=Ale,toastOptions:_,dir:S=TP(),gap:T=Lle,icons:R,containerAriaLabel:C="Notifications"}=t,[I,A]=ce.useState([]),O=ce.useMemo(()=>r?I.filter($=>$.toasterId===r):I.filter($=>!$.toasterId),[I,r]),j=ce.useMemo(()=>Array.from(new Set([s].concat(O.filter($=>$.position).map($=>$.position)))),[O,s]),[U,B]=ce.useState([]),[W,J]=ce.useState(!1),[ee,re]=ce.useState(!1),[F,K]=ce.useState(g!=="system"?g:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ce.useRef(null),ne=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),te=ce.useRef(null),D=ce.useRef(!1),H=ce.useCallback($=>{A(L=>{var M;return(M=L.find(z=>z.id===$.id))!=null&&M.delete||ba.dismiss($.id),L.filter(({id:z})=>z!==$.id)})},[]);return ce.useEffect(()=>ba.subscribe($=>{if($.dismiss){requestAnimationFrame(()=>{A(L=>L.map(M=>M.id===$.id?{...M,delete:!0}:M))});return}setTimeout(()=>{jF.flushSync(()=>{A(L=>{const M=L.findIndex(z=>z.id===$.id);return M!==-1?[...L.slice(0,M),{...L[M],...$},...L.slice(M+1)]:[$,...L]})})})}),[I]),ce.useEffect(()=>{if(g!=="system"){K(g);return}if(g==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?K("dark"):K("light")),typeof window>"u")return;const $=window.matchMedia("(prefers-color-scheme: dark)");try{$.addEventListener("change",({matches:L})=>{K(L?"dark":"light")})}catch{$.addListener(({matches:M})=>{try{K(M?"dark":"light")}catch(z){console.error(z)}})}},[g]),ce.useEffect(()=>{I.length<=1&&J(!1)},[I]),ce.useEffect(()=>{const $=L=>{var M;if(i.every(q=>L[q]||L.code===q)){var G;J(!0),(G=V.current)==null||G.focus()}L.code==="Escape"&&(document.activeElement===V.current||(M=V.current)!=null&&M.contains(document.activeElement))&&J(!1)};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[i]),ce.useEffect(()=>{if(V.current)return()=>{te.current&&(te.current.focus({preventScroll:!0}),te.current=null,D.current=!1)}},[V.current]),ce.createElement("section",{ref:n,"aria-label":`${C} ${ne}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},j.map(($,L)=>{var M;const[z,G]=$.split("-");return O.length?ce.createElement("ol",{key:$,dir:S==="auto"?TP():S,tabIndex:-1,ref:V,className:f,"data-sonner-toaster":!0,"data-sonner-theme":F,"data-y-position":z,"data-x-position":G,style:{"--front-toast-height":`${((M=U[0])==null?void 0:M.height)||0}px`,"--width":`${Dle}px`,"--gap":`${T}px`,...E,...$le(m,h)},onBlur:q=>{D.current&&!q.currentTarget.contains(q.relatedTarget)&&(D.current=!1,te.current&&(te.current.focus({preventScroll:!0}),te.current=null))},onFocus:q=>{q.target instanceof HTMLElement&&q.target.dataset.dismissible==="false"||D.current||(D.current=!0,te.current=q.relatedTarget)},onMouseEnter:()=>J(!0),onMouseMove:()=>J(!0),onMouseLeave:()=>{ee||J(!1)},onDragEnd:()=>J(!1),onPointerDown:q=>{q.target instanceof HTMLElement&&q.target.dataset.dismissible==="false"||re(!0)},onPointerUp:()=>re(!1)},O.filter(q=>!q.position&&L===0||q.position===$).map((q,ae)=>{var ie,X;return ce.createElement(Ule,{key:q.id,icons:R,index:ae,toast:q,defaultRichColors:y,duration:(ie=_?.duration)!=null?ie:x,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:a,visibleToasts:w,closeButton:(X=_?.closeButton)!=null?X:u,interacting:ee,position:$,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:H,toasts:O.filter(Z=>Z.position==q.position),heights:U.filter(Z=>Z.position==q.position),setHeights:B,expandByDefault:c,gap:T,expanded:W,swipeDirections:t.swipeDirections})})):null}))}),NP=Object.freeze(Object.defineProperty({__proto__:null,Toaster:rB,toast:Xt},Symbol.toStringTag,{value:"Module"}));var Ky="Dialog",[aB]=Ro(Ky),[zle,Ao]=aB(Ky),oB=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:a,onOpenChange:s,modal:i=!0}=e,c=v.useRef(null),u=v.useRef(null),[f,m]=Os({prop:r,defaultProp:a??!1,onChange:s,caller:Ky});return d.jsx(zle,{scope:t,triggerRef:c,contentRef:u,contentId:$r(),titleId:$r(),descriptionId:$r(),open:f,onOpenChange:m,onOpenToggle:v.useCallback(()=>m(h=>!h),[m]),modal:i,children:n})};oB.displayName=Ky;var sB="DialogTrigger",iB=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,a=Ao(sB,n),s=Jt(t,a.triggerRef);return d.jsx(_t.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":vT(a.open),...r,ref:s,onClick:Ge(e.onClick,a.onOpenToggle)})});iB.displayName=sB;var bT="DialogPortal",[Fle,lB]=aB(bT,{forceMount:void 0}),cB=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=e,s=Ao(bT,t);return d.jsx(Fle,{scope:t,forceMount:n,children:v.Children.map(r,i=>d.jsx(za,{present:n||s.open,children:d.jsx(yd,{asChild:!0,container:a,children:i})}))})};cB.displayName=bT;var jb="DialogOverlay",uB=v.forwardRef((e,t)=>{const n=lB(jb,e.__scopeDialog),{forceMount:r=n.forceMount,...a}=e,s=Ao(jb,e.__scopeDialog);return s.modal?d.jsx(za,{present:r||s.open,children:d.jsx(Hle,{...a,ref:t})}):null});uB.displayName=jb;var Ble=Al("DialogOverlay.RemoveScroll"),Hle=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,a=Ao(jb,n);return d.jsx(Zp,{as:Ble,allowPinchZoom:!0,shards:[a.contentRef],children:d.jsx(_t.div,{"data-state":vT(a.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Dl="DialogContent",dB=v.forwardRef((e,t)=>{const n=lB(Dl,e.__scopeDialog),{forceMount:r=n.forceMount,...a}=e,s=Ao(Dl,e.__scopeDialog);return d.jsx(za,{present:r||s.open,children:s.modal?d.jsx(Vle,{...a,ref:t}):d.jsx(Gle,{...a,ref:t})})});dB.displayName=Dl;var Vle=v.forwardRef((e,t)=>{const n=Ao(Dl,e.__scopeDialog),r=v.useRef(null),a=Jt(t,n.contentRef,r);return v.useEffect(()=>{const s=r.current;if(s)return Py(s)},[]),d.jsx(fB,{...e,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ge(e.onCloseAutoFocus,s=>{s.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ge(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&s.preventDefault()}),onFocusOutside:Ge(e.onFocusOutside,s=>s.preventDefault())})}),Gle=v.forwardRef((e,t)=>{const n=Ao(Dl,e.__scopeDialog),r=v.useRef(!1),a=v.useRef(!1);return d.jsx(fB,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{e.onCloseAutoFocus?.(s),s.defaultPrevented||(r.current||n.triggerRef.current?.focus(),s.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:s=>{e.onInteractOutside?.(s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=s.target;n.triggerRef.current?.contains(i)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&a.current&&s.preventDefault()}})}),fB=v.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:s,...i}=e,c=Ao(Dl,n),u=v.useRef(null),f=Jt(t,u);return Ry(),d.jsxs(d.Fragment,{children:[d.jsx(Gp,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:s,children:d.jsx(hd,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":vT(c.open),...i,ref:f,onDismiss:()=>c.onOpenChange(!1)})}),d.jsxs(d.Fragment,{children:[d.jsx(Wle,{titleId:c.titleId}),d.jsx(Yle,{contentRef:u,descriptionId:c.descriptionId})]})]})}),yT="DialogTitle",pB=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,a=Ao(yT,n);return d.jsx(_t.h2,{id:a.titleId,...r,ref:t})});pB.displayName=yT;var mB="DialogDescription",hB=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,a=Ao(mB,n);return d.jsx(_t.p,{id:a.descriptionId,...r,ref:t})});hB.displayName=mB;var gB="DialogClose",bB=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,a=Ao(gB,n);return d.jsx(_t.button,{type:"button",...r,ref:t,onClick:Ge(e.onClick,()=>a.onOpenChange(!1))})});bB.displayName=gB;function vT(e){return e?"open":"closed"}var yB="DialogTitleWarning",[N0e,vB]=Ote(yB,{contentName:Dl,titleName:yT,docsSlug:"dialog"}),Wle=({titleId:e})=>{const t=vB(yB),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
91
+ `)},xae=0,jc=[];function Sae(e){var t=v.useRef([]),n=v.useRef([0,0]),r=v.useRef(),a=v.useState(xae++)[0],s=v.useState(P4)[0],i=v.useRef(e);v.useEffect(function(){i.current=e},[e]),v.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var E=Vre([e.lockRef.current],(e.shards||[]).map(pP),!0).filter(Boolean);return E.forEach(function(w){return w.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),E.forEach(function(w){return w.classList.remove("allow-interactivity-".concat(a))})}}},[e.inert,e.lockRef.current,e.shards]);var c=v.useCallback(function(E,w){if("touches"in E&&E.touches.length===2||E.type==="wheel"&&E.ctrlKey)return!i.current.allowPinchZoom;var _=_g(E),S=n.current,T="deltaX"in E?E.deltaX:S[0]-_[0],R="deltaY"in E?E.deltaY:S[1]-_[1],C,I=E.target,A=Math.abs(T)>Math.abs(R)?"h":"v";if("touches"in E&&A==="h"&&I.type==="range")return!1;var O=dP(A,I);if(!O)return!0;if(O?C=A:(C=A==="v"?"h":"v",O=dP(A,I)),!O)return!1;if(!r.current&&"changedTouches"in E&&(T||R)&&(r.current=C),!C)return!0;var j=r.current||C;return vae(j,w,E,j==="h"?T:R)},[]),u=v.useCallback(function(E){var w=E;if(!(!jc.length||jc[jc.length-1]!==s)){var _="deltaY"in w?fP(w):_g(w),S=t.current.filter(function(C){return C.name===w.type&&(C.target===w.target||w.target===C.shadowParent)&&wae(C.delta,_)})[0];if(S&&S.should){w.cancelable&&w.preventDefault();return}if(!S){var T=(i.current.shards||[]).map(pP).filter(Boolean).filter(function(C){return C.contains(w.target)}),R=T.length>0?c(w,T[0]):!i.current.noIsolation;R&&w.cancelable&&w.preventDefault()}}},[]),f=v.useCallback(function(E,w,_,S){var T={name:E,delta:w,target:_,should:S,shadowParent:_ae(_)};t.current.push(T),setTimeout(function(){t.current=t.current.filter(function(R){return R!==T})},1)},[]),m=v.useCallback(function(E){n.current=_g(E),r.current=void 0},[]),h=v.useCallback(function(E){f(E.type,fP(E),E.target,c(E,e.lockRef.current))},[]),g=v.useCallback(function(E){f(E.type,_g(E),E.target,c(E,e.lockRef.current))},[]);v.useEffect(function(){return jc.push(s),e.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:g}),document.addEventListener("wheel",u,Mc),document.addEventListener("touchmove",u,Mc),document.addEventListener("touchstart",m,Mc),function(){jc=jc.filter(function(E){return E!==s}),document.removeEventListener("wheel",u,Mc),document.removeEventListener("touchmove",u,Mc),document.removeEventListener("touchstart",m,Mc)}},[]);var y=e.removeScrollBar,x=e.inert;return v.createElement(v.Fragment,null,x?v.createElement(s,{styles:Eae(a)}):null,y?v.createElement(fae,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function _ae(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}const Tae=Qre(j4,Sae);var Zp=v.forwardRef(function(e,t){return v.createElement(Uy,$o({},e,{ref:t,sideCar:Tae}))});Zp.classNames=Uy.classNames;var zx=["Enter"," "],Nae=["ArrowDown","PageUp","Home"],F4=["ArrowUp","PageDown","End"],kae=[...Nae,...F4],Cae={ltr:[...zx,"ArrowRight"],rtl:[...zx,"ArrowLeft"]},Rae={ltr:["ArrowLeft"],rtl:["ArrowRight"]},qp="Menu",[hp,Aae,Iae]=B_(qp),[Hl,B4]=Ro(qp,[Iae,Fi,C4]),$y=Fi(),H4=C4(),[Oae,Vl]=Hl(qp),[Dae,Xp]=Hl(qp),V4=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:s,modal:i=!0}=e,c=$y(t),[u,f]=v.useState(null),m=v.useRef(!1),h=Wo(s),g=H_(a);return v.useEffect(()=>{const y=()=>{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",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),d.jsx(Ly,{...c,children:d.jsx(Oae,{scope:t,open:n,onOpenChange:h,content:u,onContentChange:f,children:d.jsx(Dae,{scope:t,onClose:v.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:m,dir:g,modal:i,children:r})})})};V4.displayName=qp;var Lae="MenuAnchor",Q_=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,a=$y(n);return d.jsx(Kp,{...a,...r,ref:t})});Q_.displayName=Lae;var eT="MenuPortal",[Mae,G4]=Hl(eT,{forceMount:void 0}),W4=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=e,s=Vl(eT,t);return d.jsx(Mae,{scope:t,forceMount:n,children:d.jsx(za,{present:n||s.open,children:d.jsx(yd,{asChild:!0,container:a,children:r})})})};W4.displayName=eT;var to="MenuContent",[jae,tT]=Hl(to),K4=v.forwardRef((e,t)=>{const n=G4(to,e.__scopeMenu),{forceMount:r=n.forceMount,...a}=e,s=Vl(to,e.__scopeMenu),i=Xp(to,e.__scopeMenu);return d.jsx(hp.Provider,{scope:e.__scopeMenu,children:d.jsx(za,{present:r||s.open,children:d.jsx(hp.Slot,{scope:e.__scopeMenu,children:i.modal?d.jsx(Pae,{...a,ref:t}):d.jsx(Uae,{...a,ref:t})})})})}),Pae=v.forwardRef((e,t)=>{const n=Vl(to,e.__scopeMenu),r=v.useRef(null),a=Jt(t,r);return v.useEffect(()=>{const s=r.current;if(s)return Py(s)},[]),d.jsx(nT,{...e,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Ge(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),Uae=v.forwardRef((e,t)=>{const n=Vl(to,e.__scopeMenu);return d.jsx(nT,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),$ae=Al("MenuContent.ScrollLock"),nT=v.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:a,onOpenAutoFocus:s,onCloseAutoFocus:i,disableOutsidePointerEvents:c,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,...E}=e,w=Vl(to,n),_=Xp(to,n),S=$y(n),T=H4(n),R=Aae(n),[C,I]=v.useState(null),A=v.useRef(null),O=Jt(t,A,w.onContentChange),j=v.useRef(0),U=v.useRef(""),B=v.useRef(0),W=v.useRef(null),J=v.useRef("right"),ee=v.useRef(0),re=x?Zp:v.Fragment,F=x?{as:$ae,allowPinchZoom:!0}:void 0,K=ne=>{const te=U.current+ne,D=R().filter(G=>!G.disabled),H=document.activeElement,$=D.find(G=>G.ref.current===H)?.textValue,L=D.map(G=>G.textValue),M=Xae(L,te,$),z=D.find(G=>G.textValue===M)?.ref.current;(function G(q){U.current=q,window.clearTimeout(j.current),q!==""&&(j.current=window.setTimeout(()=>G(""),1e3))})(te),z&&setTimeout(()=>z.focus())};v.useEffect(()=>()=>window.clearTimeout(j.current),[]),Ry();const V=v.useCallback(ne=>J.current===W.current?.side&&Qae(ne,W.current?.area),[]);return d.jsx(jae,{scope:n,searchRef:U,onItemEnter:v.useCallback(ne=>{V(ne)&&ne.preventDefault()},[V]),onItemLeave:v.useCallback(ne=>{V(ne)||(A.current?.focus(),I(null))},[V]),onTriggerLeave:v.useCallback(ne=>{V(ne)&&ne.preventDefault()},[V]),pointerGraceTimerRef:B,onPointerGraceIntentChange:v.useCallback(ne=>{W.current=ne},[]),children:d.jsx(re,{...F,children:d.jsx(Gp,{asChild:!0,trapped:a,onMountAutoFocus:Ge(s,ne=>{ne.preventDefault(),A.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:i,children:d.jsx(hd,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:h,onInteractOutside:g,onDismiss:y,children:d.jsx($re,{asChild:!0,...T,dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:C,onCurrentTabStopIdChange:I,onEntryFocus:Ge(u,ne=>{_.isUsingKeyboardRef.current||ne.preventDefault()}),preventScrollOnEntryFocus:!0,children:d.jsx(My,{role:"menu","aria-orientation":"vertical","data-state":c3(w.open),"data-radix-menu-content":"",dir:_.dir,...S,...E,ref:O,style:{outline:"none",...E.style},onKeyDown:Ge(E.onKeyDown,ne=>{const D=ne.target.closest("[data-radix-menu-content]")===ne.currentTarget,H=ne.ctrlKey||ne.altKey||ne.metaKey,$=ne.key.length===1;D&&(ne.key==="Tab"&&ne.preventDefault(),!H&&$&&K(ne.key));const L=A.current;if(ne.target!==L||!kae.includes(ne.key))return;ne.preventDefault();const z=R().filter(G=>!G.disabled).map(G=>G.ref.current);F4.includes(ne.key)&&z.reverse(),Zae(z)}),onBlur:Ge(e.onBlur,ne=>{ne.currentTarget.contains(ne.target)||(window.clearTimeout(j.current),U.current="")}),onPointerMove:Ge(e.onPointerMove,gp(ne=>{const te=ne.target,D=ee.current!==ne.clientX;if(ne.currentTarget.contains(te)&&D){const H=ne.clientX>ee.current?"right":"left";J.current=H,ee.current=ne.clientX}}))})})})})})})});K4.displayName=to;var zae="MenuGroup",rT=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(_t.div,{role:"group",...r,ref:t})});rT.displayName=zae;var Fae="MenuLabel",Y4=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(_t.div,{...r,ref:t})});Y4.displayName=Fae;var Ob="MenuItem",mP="menu.itemSelect",zy=v.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...a}=e,s=v.useRef(null),i=Xp(Ob,e.__scopeMenu),c=tT(Ob,e.__scopeMenu),u=Jt(t,s),f=v.useRef(!1),m=()=>{const h=s.current;if(!n&&h){const g=new CustomEvent(mP,{bubbles:!0,cancelable:!0});h.addEventListener(mP,y=>r?.(y),{once:!0}),n4(h,g),g.defaultPrevented?f.current=!1:i.onClose()}};return d.jsx(Z4,{...a,ref:u,disabled:n,onClick:Ge(e.onClick,m),onPointerDown:h=>{e.onPointerDown?.(h),f.current=!0},onPointerUp:Ge(e.onPointerUp,h=>{f.current||h.currentTarget?.click()}),onKeyDown:Ge(e.onKeyDown,h=>{const g=c.searchRef.current!=="";n||g&&h.key===" "||zx.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});zy.displayName=Ob;var Z4=v.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...s}=e,i=tT(Ob,n),c=H4(n),u=v.useRef(null),f=Jt(t,u),[m,h]=v.useState(!1),[g,y]=v.useState("");return v.useEffect(()=>{const x=u.current;x&&y((x.textContent??"").trim())},[s.children]),d.jsx(hp.ItemSlot,{scope:n,disabled:r,textValue:a??g,children:d.jsx(zre,{asChild:!0,...c,focusable:!r,children:d.jsx(_t.div,{role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:f,onPointerMove:Ge(e.onPointerMove,gp(x=>{r?i.onItemLeave(x):(i.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ge(e.onPointerLeave,gp(x=>i.onItemLeave(x))),onFocus:Ge(e.onFocus,()=>h(!0)),onBlur:Ge(e.onBlur,()=>h(!1))})})})}),Bae="MenuCheckboxItem",q4=v.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=e;return d.jsx(t3,{scope:e.__scopeMenu,checked:n,children:d.jsx(zy,{role:"menuitemcheckbox","aria-checked":Db(n)?"mixed":n,...a,ref:t,"data-state":oT(n),onSelect:Ge(a.onSelect,()=>r?.(Db(n)?!0:!n),{checkForDefaultPrevented:!1})})})});q4.displayName=Bae;var X4="MenuRadioGroup",[Hae,Vae]=Hl(X4,{value:void 0,onValueChange:()=>{}}),J4=v.forwardRef((e,t)=>{const{value:n,onValueChange:r,...a}=e,s=Wo(r);return d.jsx(Hae,{scope:e.__scopeMenu,value:n,onValueChange:s,children:d.jsx(rT,{...a,ref:t})})});J4.displayName=X4;var Q4="MenuRadioItem",e3=v.forwardRef((e,t)=>{const{value:n,...r}=e,a=Vae(Q4,e.__scopeMenu),s=n===a.value;return d.jsx(t3,{scope:e.__scopeMenu,checked:s,children:d.jsx(zy,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":oT(s),onSelect:Ge(r.onSelect,()=>a.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});e3.displayName=Q4;var aT="MenuItemIndicator",[t3,Gae]=Hl(aT,{checked:!1}),n3=v.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...a}=e,s=Gae(aT,n);return d.jsx(za,{present:r||Db(s.checked)||s.checked===!0,children:d.jsx(_t.span,{...a,ref:t,"data-state":oT(s.checked)})})});n3.displayName=aT;var Wae="MenuSeparator",r3=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.jsx(_t.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});r3.displayName=Wae;var Kae="MenuArrow",a3=v.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,a=$y(n);return d.jsx(jy,{...a,...r,ref:t})});a3.displayName=Kae;var Yae="MenuSub",[T0e,o3]=Hl(Yae),Lf="MenuSubTrigger",s3=v.forwardRef((e,t)=>{const n=Vl(Lf,e.__scopeMenu),r=Xp(Lf,e.__scopeMenu),a=o3(Lf,e.__scopeMenu),s=tT(Lf,e.__scopeMenu),i=v.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:u}=s,f={__scopeMenu:e.__scopeMenu},m=v.useCallback(()=>{i.current&&window.clearTimeout(i.current),i.current=null},[]);return v.useEffect(()=>m,[m]),v.useEffect(()=>{const h=c.current;return()=>{window.clearTimeout(h),u(null)}},[c,u]),d.jsx(Q_,{asChild:!0,...f,children:d.jsx(Z4,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":c3(n.open),...e,ref:Go(t,a.onTriggerChange),onClick:h=>{e.onClick?.(h),!(e.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:Ge(e.onPointerMove,gp(h=>{s.onItemEnter(h),!h.defaultPrevented&&!e.disabled&&!n.open&&!i.current&&(s.onPointerGraceIntentChange(null),i.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:Ge(e.onPointerLeave,gp(h=>{m();const g=n.content?.getBoundingClientRect();if(g){const y=n.content?.dataset.side,x=y==="right",E=x?-5:5,w=g[x?"left":"right"],_=g[x?"right":"left"];s.onPointerGraceIntentChange({area:[{x:h.clientX+E,y:h.clientY},{x:w,y:g.top},{x:_,y:g.top},{x:_,y:g.bottom},{x:w,y:g.bottom}],side:y}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(h),h.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:Ge(e.onKeyDown,h=>{const g=s.searchRef.current!=="";e.disabled||g&&h.key===" "||Cae[r.dir].includes(h.key)&&(n.onOpenChange(!0),n.content?.focus(),h.preventDefault())})})})});s3.displayName=Lf;var i3="MenuSubContent",l3=v.forwardRef((e,t)=>{const n=G4(to,e.__scopeMenu),{forceMount:r=n.forceMount,...a}=e,s=Vl(to,e.__scopeMenu),i=Xp(to,e.__scopeMenu),c=o3(i3,e.__scopeMenu),u=v.useRef(null),f=Jt(t,u);return d.jsx(hp.Provider,{scope:e.__scopeMenu,children:d.jsx(za,{present:r||s.open,children:d.jsx(hp.Slot,{scope:e.__scopeMenu,children:d.jsx(nT,{id:c.contentId,"aria-labelledby":c.triggerId,...a,ref:f,align:"start",side:i.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{i.isUsingKeyboardRef.current&&u.current?.focus(),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:Ge(e.onFocusOutside,m=>{m.target!==c.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:Ge(e.onEscapeKeyDown,m=>{i.onClose(),m.preventDefault()}),onKeyDown:Ge(e.onKeyDown,m=>{const h=m.currentTarget.contains(m.target),g=Rae[i.dir].includes(m.key);h&&g&&(s.onOpenChange(!1),c.trigger?.focus(),m.preventDefault())})})})})})});l3.displayName=i3;function c3(e){return e?"open":"closed"}function Db(e){return e==="indeterminate"}function oT(e){return Db(e)?"indeterminate":e?"checked":"unchecked"}function Zae(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function qae(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Xae(e,t,n){const a=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=qae(e,Math.max(s,0));a.length===1&&(i=i.filter(f=>f!==n));const u=i.find(f=>f.toLowerCase().startsWith(a.toLowerCase()));return u!==n?u:void 0}function Jae(e,t){const{x:n,y:r}=e;let a=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const c=t[s],u=t[i],f=c.x,m=c.y,h=u.x,g=u.y;m>r!=g>r&&n<(h-f)*(r-m)/(g-m)+f&&(a=!a)}return a}function Qae(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Jae(n,t)}function gp(e){return t=>t.pointerType==="mouse"?e(t):void 0}var eoe=V4,toe=Q_,noe=W4,roe=K4,aoe=rT,ooe=Y4,soe=zy,ioe=q4,loe=J4,coe=e3,uoe=n3,doe=r3,foe=a3,poe=s3,moe=l3,Fy="DropdownMenu",[hoe]=Ro(Fy,[B4]),ia=B4(),[goe,u3]=hoe(Fy),d3=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:s,onOpenChange:i,modal:c=!0}=e,u=ia(t),f=v.useRef(null),[m,h]=Os({prop:a,defaultProp:s??!1,onChange:i,caller:Fy});return d.jsx(goe,{scope:t,triggerId:$r(),triggerRef:f,contentId:$r(),open:m,onOpenChange:h,onOpenToggle:v.useCallback(()=>h(g=>!g),[h]),modal:c,children:d.jsx(eoe,{...u,open:m,onOpenChange:h,dir:r,modal:c,children:n})})};d3.displayName=Fy;var f3="DropdownMenuTrigger",p3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=e,s=u3(f3,n),i=ia(n);return d.jsx(toe,{asChild:!0,...i,children:d.jsx(_t.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...a,ref:Go(t,s.triggerRef),onPointerDown:Ge(e.onPointerDown,c=>{!r&&c.button===0&&c.ctrlKey===!1&&(s.onOpenToggle(),s.open||c.preventDefault())}),onKeyDown:Ge(e.onKeyDown,c=>{r||(["Enter"," "].includes(c.key)&&s.onOpenToggle(),c.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(c.key)&&c.preventDefault())})})})});p3.displayName=f3;var boe="DropdownMenuPortal",m3=e=>{const{__scopeDropdownMenu:t,...n}=e,r=ia(t);return d.jsx(noe,{...r,...n})};m3.displayName=boe;var h3="DropdownMenuContent",g3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=u3(h3,n),s=ia(n),i=v.useRef(!1);return d.jsx(roe,{id:a.contentId,"aria-labelledby":a.triggerId,...s,...r,ref:t,onCloseAutoFocus:Ge(e.onCloseAutoFocus,c=>{i.current||a.triggerRef.current?.focus(),i.current=!1,c.preventDefault()}),onInteractOutside:Ge(e.onInteractOutside,c=>{const u=c.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,m=u.button===2||f;(!a.modal||m)&&(i.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)"}})});g3.displayName=h3;var yoe="DropdownMenuGroup",voe=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(aoe,{...a,...r,ref:t})});voe.displayName=yoe;var woe="DropdownMenuLabel",b3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(ooe,{...a,...r,ref:t})});b3.displayName=woe;var Eoe="DropdownMenuItem",y3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(soe,{...a,...r,ref:t})});y3.displayName=Eoe;var xoe="DropdownMenuCheckboxItem",v3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(ioe,{...a,...r,ref:t})});v3.displayName=xoe;var Soe="DropdownMenuRadioGroup",_oe=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(loe,{...a,...r,ref:t})});_oe.displayName=Soe;var Toe="DropdownMenuRadioItem",w3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(coe,{...a,...r,ref:t})});w3.displayName=Toe;var Noe="DropdownMenuItemIndicator",koe=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(uoe,{...a,...r,ref:t})});koe.displayName=Noe;var Coe="DropdownMenuSeparator",E3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(doe,{...a,...r,ref:t})});E3.displayName=Coe;var Roe="DropdownMenuArrow",Aoe=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(foe,{...a,...r,ref:t})});Aoe.displayName=Roe;var Ioe="DropdownMenuSubTrigger",x3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(poe,{...a,...r,ref:t})});x3.displayName=Ioe;var Ooe="DropdownMenuSubContent",S3=v.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,a=ia(n);return d.jsx(moe,{...a,...r,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)"}})});S3.displayName=Ooe;var Doe=d3,Loe=p3,Moe=m3,_3=g3,T3=b3,N3=y3,joe=v3,Poe=w3,k3=E3,Uoe=x3,$oe=S3;const Fx=Doe,Bx=Loe;Uoe.displayName;$oe.displayName;function Lb({ref:e,className:t,sideOffset:n=4,...r}){return d.jsx(Moe,{children:d.jsx(_3,{ref:e,sideOffset:n,className:Oe("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),...r})})}Lb.displayName=_3.displayName;function Ts({ref:e,className:t,inset:n,...r}){return d.jsx(N3,{ref:e,className:Oe("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),...r})}Ts.displayName=N3.displayName;joe.displayName;Poe.displayName;function Hx({ref:e,className:t,inset:n,...r}){return d.jsx(T3,{ref:e,className:Oe("px-2 py-1.5 text-sm font-semibold",n&&"pl-8",t),...r})}Hx.displayName=T3.displayName;function Mf({ref:e,className:t,...n}){return d.jsx(k3,{ref:e,className:Oe("-mx-1 my-1 h-px bg-muted",t),...n})}Mf.displayName=k3.displayName;var zoe=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],zs=zoe.reduce((e,t)=>{const n=UF(`Primitive.${t}`),r=v.forwardRef((a,s)=>{const{asChild:i,...c}=a,u=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),d.jsx(u,{...c,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),Foe="Label",C3=v.forwardRef((e,t)=>d.jsx(zs.label,{...e,ref:t,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(e.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));C3.displayName=Foe;var Boe=C3;function Wt({className:e,...t}){return d.jsx(Boe,{"data-slot":"label",className:Oe("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 vd({message:e,className:t="",vertical:n,noBorder:r}){return d.jsx("div",{className:Oe(`mt-2 rounded-md p-6 ${t}`,!r&&"border"),children:d.jsxs("p",{className:Oe("text-sm text-muted-foreground flex items-center gap-4",n&&"flex-col"),children:[d.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:d.jsx("g",{stroke:"none",strokeWidth:"1",fill:"none",fillRule:"evenodd",children:d.jsxs("g",{transform:"translate(5.320900, 5.320900)",fillRule:"nonzero",className:"stroke-black dark:stroke-white",strokeWidth:"4",children:[d.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"}),d.jsx("circle",{cx:"50",cy:"212.0001",r:"52.5"}),d.jsx("circle",{cx:"212.0001",cy:"50",r:"52.5"})]})})}),e]})})}function R3({className:e,color:t,children:n,grayscaled:r=!1}){const a=v.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[1]||"0")}return r?0:.2},[t,r]),s=v.useMemo(()=>{if(t){const h=t.split("(")[1].split(")")[0].trim().split(/\s+/);return Number.parseFloat(h[0]||"0.5")}return r?.3:.4},[t,r]),i=v.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=v.useMemo(()=>t||`oklch(${Math.min(s,1)} ${a} ${i})`,[i,a,s]),u=v.useMemo(()=>`oklch(${Math.min(s*2,1)} ${a} ${i})`,[i,a,s,t]),f=v.useMemo(()=>Math.floor(Math.random()*360),[i]),m=v.useMemo(()=>"1000%",[]);return d.jsx("section",{className:Oe("relative w-full h-full overflow-hidden",e),style:{background:`${u}`},children:d.jsxs("div",{className:"isolate relative w-full h-full",children:[d.jsx("div",{className:"noise w-full h-full",style:{background:`linear-gradient(${f}deg, ${c}, transparent), url(https://grainy-gradients.vercel.app/noise.svg)`,filter:`contrast(120%) brightness(${m})`}}),n&&d.jsx("div",{className:"relative z-10 w-full h-full",children:n})]})})}function sT(e){const t=v.useRef({value:e,previous:e});return v.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var By="Switch",[Hoe]=Ro(By),[Voe,Goe]=Hoe(By),A3=v.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:a,defaultChecked:s,required:i,disabled:c,value:u="on",onCheckedChange:f,form:m,...h}=e,[g,y]=v.useState(null),x=Jt(t,T=>y(T)),E=v.useRef(!1),w=g?m||!!g.closest("form"):!0,[_,S]=Os({prop:a,defaultProp:s??!1,onChange:f,caller:By});return d.jsxs(Voe,{scope:n,checked:_,disabled:c,children:[d.jsx(_t.button,{type:"button",role:"switch","aria-checked":_,"aria-required":i,"data-state":L3(_),"data-disabled":c?"":void 0,disabled:c,value:u,...h,ref:x,onClick:Ge(e.onClick,T=>{S(R=>!R),w&&(E.current=T.isPropagationStopped(),E.current||T.stopPropagation())})}),w&&d.jsx(D3,{control:g,bubbles:!E.current,name:r,value:u,checked:_,required:i,disabled:c,form:m,style:{transform:"translateX(-100%)"}})]})});A3.displayName=By;var I3="SwitchThumb",O3=v.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,a=Goe(I3,n);return d.jsx(_t.span,{"data-state":L3(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});O3.displayName=I3;var Woe="SwitchBubbleInput",D3=v.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...a},s)=>{const i=v.useRef(null),c=Jt(i,s),u=sT(n),f=q_(t);return v.useEffect(()=>{const m=i.current;if(!m)return;const h=window.HTMLInputElement.prototype,y=Object.getOwnPropertyDescriptor(h,"checked").set;if(u!==n&&y){const x=new Event("click",{bubbles:r});y.call(m,n),m.dispatchEvent(x)}},[u,n,r]),d.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...a,tabIndex:-1,ref:c,style:{...a.style,...f,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});D3.displayName=Woe;function L3(e){return e?"checked":"unchecked"}var M3=A3,Koe=O3;function Hy({ref:e,className:t,...n}){return d.jsx(M3,{className:Oe("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:d.jsx(Koe,{className:Oe("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")})})}Hy.displayName=M3.displayName;var j3=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"}),Yoe="VisuallyHidden",P3=v.forwardRef((e,t)=>d.jsx(_t.span,{...e,ref:t,style:{...j3,...e.style}}));P3.displayName=Yoe;var Zoe=P3,[Vy]=Ro("Tooltip",[Fi]),Gy=Fi(),U3="TooltipProvider",qoe=700,Vx="tooltip.open",[Xoe,iT]=Vy(U3),$3=e=>{const{__scopeTooltip:t,delayDuration:n=qoe,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:s}=e,i=v.useRef(!0),c=v.useRef(!1),u=v.useRef(0);return v.useEffect(()=>{const f=u.current;return()=>window.clearTimeout(f)},[]),d.jsx(Xoe,{scope:t,isOpenDelayedRef:i,delayDuration:n,onOpen:v.useCallback(()=>{window.clearTimeout(u.current),i.current=!1},[]),onClose:v.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>i.current=!0,r)},[r]),isPointerInTransitRef:c,onPointerInTransitChange:v.useCallback(f=>{c.current=f},[]),disableHoverableContent:a,children:s})};$3.displayName=U3;var bp="Tooltip",[Joe,Jp]=Vy(bp),z3=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:s,disableHoverableContent:i,delayDuration:c}=e,u=iT(bp,e.__scopeTooltip),f=Gy(t),[m,h]=v.useState(null),g=$r(),y=v.useRef(0),x=i??u.disableHoverableContent,E=c??u.delayDuration,w=v.useRef(!1),[_,S]=Os({prop:r,defaultProp:a??!1,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(Vx))):u.onClose(),s?.(A)},caller:bp}),T=v.useMemo(()=>_?w.current?"delayed-open":"instant-open":"closed",[_]),R=v.useCallback(()=>{window.clearTimeout(y.current),y.current=0,w.current=!1,S(!0)},[S]),C=v.useCallback(()=>{window.clearTimeout(y.current),y.current=0,S(!1)},[S]),I=v.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{w.current=!0,S(!0),y.current=0},E)},[E,S]);return v.useEffect(()=>()=>{y.current&&(window.clearTimeout(y.current),y.current=0)},[]),d.jsx(Ly,{...f,children:d.jsx(Joe,{scope:t,contentId:g,open:_,stateAttribute:T,trigger:m,onTriggerChange:h,onTriggerEnter:v.useCallback(()=>{u.isOpenDelayedRef.current?I():R()},[u.isOpenDelayedRef,I,R]),onTriggerLeave:v.useCallback(()=>{x?C():(window.clearTimeout(y.current),y.current=0)},[C,x]),onOpen:R,onClose:C,disableHoverableContent:x,children:n})})};z3.displayName=bp;var Gx="TooltipTrigger",F3=v.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,a=Jp(Gx,n),s=iT(Gx,n),i=Gy(n),c=v.useRef(null),u=Jt(t,c,a.onTriggerChange),f=v.useRef(!1),m=v.useRef(!1),h=v.useCallback(()=>f.current=!1,[]);return v.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),d.jsx(Kp,{asChild:!0,...i,children:d.jsx(_t.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:u,onPointerMove:Ge(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!s.isPointerInTransitRef.current&&(a.onTriggerEnter(),m.current=!0)}),onPointerLeave:Ge(e.onPointerLeave,()=>{a.onTriggerLeave(),m.current=!1}),onPointerDown:Ge(e.onPointerDown,()=>{a.open&&a.onClose(),f.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:Ge(e.onFocus,()=>{f.current||a.onOpen()}),onBlur:Ge(e.onBlur,a.onClose),onClick:Ge(e.onClick,a.onClose)})})});F3.displayName=Gx;var lT="TooltipPortal",[Qoe,ese]=Vy(lT,{forceMount:void 0}),B3=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:a}=e,s=Jp(lT,t);return d.jsx(Qoe,{scope:t,forceMount:n,children:d.jsx(za,{present:n||s.open,children:d.jsx(yd,{asChild:!0,container:a,children:r})})})};B3.displayName=lT;var Zu="TooltipContent",H3=v.forwardRef((e,t)=>{const n=ese(Zu,e.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...s}=e,i=Jp(Zu,e.__scopeTooltip);return d.jsx(za,{present:r||i.open,children:i.disableHoverableContent?d.jsx(V3,{side:a,...s,ref:t}):d.jsx(tse,{side:a,...s,ref:t})})}),tse=v.forwardRef((e,t)=>{const n=Jp(Zu,e.__scopeTooltip),r=iT(Zu,e.__scopeTooltip),a=v.useRef(null),s=Jt(t,a),[i,c]=v.useState(null),{trigger:u,onClose:f}=n,m=a.current,{onPointerInTransitChange:h}=r,g=v.useCallback(()=>{c(null),h(!1)},[h]),y=v.useCallback((x,E)=>{const w=x.currentTarget,_={x:x.clientX,y:x.clientY},S=ose(_,w.getBoundingClientRect()),T=sse(_,S),R=ise(E.getBoundingClientRect()),C=cse([...T,...R]);c(C),h(!0)},[h]);return v.useEffect(()=>()=>g(),[g]),v.useEffect(()=>{if(u&&m){const x=w=>y(w,m),E=w=>y(w,u);return u.addEventListener("pointerleave",x),m.addEventListener("pointerleave",E),()=>{u.removeEventListener("pointerleave",x),m.removeEventListener("pointerleave",E)}}},[u,m,y,g]),v.useEffect(()=>{if(i){const x=E=>{const w=E.target,_={x:E.clientX,y:E.clientY},S=u?.contains(w)||m?.contains(w),T=!lse(_,i);S?g():T&&(g(),f())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,m,i,f,g]),d.jsx(V3,{...e,ref:s})}),[nse,rse]=Vy(bp,{isInside:!1}),ase=Ute("TooltipContent"),V3=v.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:s,onPointerDownOutside:i,...c}=e,u=Jp(Zu,n),f=Gy(n),{onClose:m}=u;return v.useEffect(()=>(document.addEventListener(Vx,m),()=>document.removeEventListener(Vx,m)),[m]),v.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]),d.jsx(hd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:h=>h.preventDefault(),onDismiss:m,children:d.jsxs(My,{"data-state":u.stateAttribute,...f,...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:[d.jsx(ase,{children:r}),d.jsx(nse,{scope:n,isInside:!0,children:d.jsx(Zoe,{id:u.contentId,role:"tooltip",children:a||r})})]})})});H3.displayName=Zu;var G3="TooltipArrow",W3=v.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,a=Gy(n);return rse(G3,n).isInside?null:d.jsx(jy,{...a,...r,ref:t})});W3.displayName=G3;function ose(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),a=Math.abs(t.right-e.x),s=Math.abs(t.left-e.x);switch(Math.min(n,r,a,s)){case s:return"left";case a:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function sse(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function ise(e){const{top:t,right:n,bottom:r,left:a}=e;return[{x:a,y:t},{x:n,y:t},{x:n,y:r},{x:a,y:r}]}function lse(e,t){const{x:n,y:r}=e;let a=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const c=t[s],u=t[i],f=c.x,m=c.y,h=u.x,g=u.y;m>r!=g>r&&n<(h-f)*(r-m)/(g-m)+f&&(a=!a)}return a}function cse(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),use(t)}function use(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const a=e[r];for(;t.length>=2;){const s=t[t.length-1],i=t[t.length-2];if((s.x-i.x)*(a.y-i.y)>=(s.y-i.y)*(a.x-i.x))t.pop();else break}t.push(a)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const a=e[r];for(;n.length>=2;){const s=n[n.length-1],i=n[n.length-2];if((s.x-i.x)*(a.y-i.y)>=(s.y-i.y)*(a.x-i.x))n.pop();else break}n.push(a)}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 dse=$3,fse=z3,pse=F3,mse=B3,hse=H3,gse=W3;function K3({delayDuration:e=0,...t}){return d.jsx(dse,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Dt({...e}){return d.jsx(K3,{children:d.jsx(fse,{"data-slot":"tooltip",...e})})}function Lt({...e}){return d.jsx(pse,{"data-slot":"tooltip-trigger",...e})}function Mt({className:e,sideOffset:t=0,children:n,...r}){return d.jsx(mse,{children:d.jsxs(hse,{"data-slot":"tooltip-content",sideOffset:t,className:Oe("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),...r,children:[n,d.jsx(gse,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}class bse{name="mcp_inspector_open";properties;constructor(t){this.properties={server_url:t.serverUrl,connection_count:t.connectionCount}}}class hP{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 gP{name="mcp_resource_read";properties;constructor(t){this.properties={resource_uri:t.resourceUri,server_id:t.serverId,success:t.success,error:t.error}}}class bP{name="mcp_prompt_call";properties;constructor(t){this.properties={prompt_name:t.promptName,server_id:t.serverId,success:t.success,error:t.error}}}class yP{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 yse{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 vse{name="mcp_server_removed";properties;constructor(t){this.properties={server_id:t.serverId}}}class wse{name="mcp_command_palette_open";properties;constructor(t){this.properties={trigger:t.trigger}}}class Ese{name="mcp_tool_saved";properties;constructor(t){this.properties={tool_name:t.toolName,server_id:t.serverId}}}function vE(){try{return"0.12.1-canary.0"}catch{return"0.0.0"}}var xse={};function wE(){try{return typeof window<"u"&&typeof document<"u"}catch{return!1}}class vP{endpoint;timeout;constructor(t,n=3e3){this.endpoint=t,this.timeout=n}async logEvent(t){try{const n=new AbortController,r=setTimeout(()=>n.abort(),this.timeout),a=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:n.signal});if(clearTimeout(r),!a.ok)throw new Error(`HTTP error! status: ${a.status}`)}catch{}}}function mi(e){return`mcp_inspector_telemetry_${e}`}class Tr{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=wE(),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 vP(this.POSTHOG_PROXY_URL,3e3)}catch{this._posthogClient=null}try{this._scarfClient=new vP(this.SCARF_PROXY_URL,3e3)}catch{this._scarfClient=null}}}isTelemetryDisabled(){return typeof localStorage<"u"&&localStorage.getItem(mi("disabled"))==="true"||typeof process<"u"&&xse?.MCP_USE_ANONYMIZED_TELEMETRY==="false"}getStoredSource(){return typeof localStorage<"u"?localStorage.getItem(mi("source")):null}static getInstance(){return Tr.instance||(Tr.instance=new Tr),Tr.instance}setSource(t){this._source=t,typeof localStorage<"u"&&localStorage.setItem(mi("source"),t)}getSource(){return this._source}get userId(){if(this._currUserId)return this._currUserId;if(!wE())return this._currUserId=this.UNKNOWN_USER_ID,this._currUserId;try{const t=localStorage.getItem(mi("user_id"));if(t)this._currUserId=t;else{const n=this.generateUserId();localStorage.setItem(mi("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(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const n=Math.random()*16|0;return(t==="x"?n:n&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:vE(),language:"typescript",source:this._source,package:"inspector"}};await this._posthogClient.logEvent(n)}catch{}if(this._scarfClient)try{const n={};n.mcp_use_version=vE(),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&&wE())try{const n=vE();let r=!1,a=!1;const s=localStorage.getItem(mi("download_version"));if(s?n>s&&(r=!0,a=!1,localStorage.setItem(mi("download_version"),n)):(r=!0,a=!0,localStorage.setItem(mi("download_version"),n)),r){const i={...t||{}};i.mcp_use_version=n,i.user_id=this.userId,i.event="package_download",i.first_download=a,i.language="typescript",i.source=this._source,i.package="inspector",await this._scarfClient.logEvent(i)}}catch{}}async trackInspectorOpen(t){const n=new bse(t);await this.capture(n)}}const Sse={model:"stub-model",stopReason:"endTurn",role:"assistant",content:{type:"text",text:"positive"}};function _se({requestId:e,serverName:t,onViewDetails:n,onApprove:r,onDeny:a}){return d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{children:[d.jsx("strong",{children:"Sampling Request Received"}),d.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["New request from ",t]})]}),d.jsxs("div",{className:"flex gap-2",children:[d.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:s=>{s.stopPropagation(),n()},children:"View Details"}),d.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:s=>{s.stopPropagation(),r(Sse)},children:"Approve"}),d.jsx("button",{className:"px-3 py-1.5 text-xs font-medium rounded-md hover:bg-accent hover:text-accent-foreground",onClick:s=>{s.stopPropagation(),a()},children:"Deny"})]})]})}function Tse({requestId:e,serverName:t,mode:n,message:r,url:a,onViewDetails:s,onOpenUrl:i,onCancel:c}){return d.jsxs("div",{className:"space-y-3",children:[d.jsxs("div",{children:[d.jsx("strong",{children:"Elicitation Request Received"}),d.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["From ",t,": ",r]}),n==="url"&&a&&d.jsx("p",{className:"text-xs text-muted-foreground mt-1 font-mono",children:a})]}),d.jsxs("div",{className:"flex gap-2 flex-wrap",children:[d.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:"View Details"}),n==="url"&&i&&d.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:"Open URL"}),d.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 Tg=()=>{},Ng=()=>{},kg=()=>{},Cg=()=>{},Y3=v.createContext(null);function cT(){const e=v.use(Y3);if(!e)throw new Error("useMcpContext must be used within a McpProvider");return e}function Nse({url:e,name:t,proxyConfig:n,transportType:r,connectionId:a,onUpdate:s,onRemove:i}){const c=typeof window<"u"?new URL("/inspector/oauth/callback",window.location.origin).toString():"/inspector/oauth/callback";let u=e,f={};if(n?.proxyAddress){const L=new URL(n.proxyAddress),M=new URL(e);u=`${L.origin}${L.pathname}${M.pathname}${M.search}`,f["X-Target-URL"]=e}n?.customHeaders&&(f={...f,...n.customHeaders});const[m,h]=v.useState([]),g=v.useRef(0),[y,x]=v.useState([]),E=v.useRef(0),w=v.useMemo(()=>m.map(L=>({id:L.id,request:L.request,timestamp:L.timestamp,serverName:L.serverName})),[m]),_=v.useMemo(()=>y.map(L=>({id:L.id,request:L.request,timestamp:L.timestamp,serverName:L.serverName})),[y]),S=v.useRef(null),[T,R]=v.useState(!1),C=v.useRef(!1);v.useEffect(()=>{typeof window<"u"&&!C.current&&(C.current=!0,rr(()=>import("./transport-wrapper-browser-BI4dDu3b.js"),[]).then(L=>{S.current=L.wrapTransportForLogging,R(!0),console.log("[McpContext] Transport wrapper loaded")}).catch(L=>{console.error("[McpContext] Failed to load transport wrapper:",L)}))},[]);const I=v.useMemo(()=>{if(!(!T||!S.current))return(L,M)=>{const z=a;return console.log("[McpContext] Applying transport wrapper, serverId:",z,"from connector:",M),S.current(L,z)}},[T,a]),A=`mcp-inspector-notifications-${a}`,O=500,[j,U]=v.useState([]);v.useEffect(()=>{try{const L=localStorage.getItem(A);if(L){const M=JSON.parse(L);Array.isArray(M)&&U(M)}}catch(L){console.error("Failed to load notifications from localStorage:",L)}},[A]),v.useEffect(()=>{try{localStorage.setItem(A,JSON.stringify(j))}catch(L){console.error("Failed to save notifications to localStorage:",L)}},[j,A]);const B=v.useCallback(L=>{U(M=>M.map(z=>z.id===L?{...z,read:!0}:z))},[]),W=v.useCallback(()=>{U(L=>L.map(M=>({...M,read:!0})))},[]),J=v.useCallback(()=>{U([])},[]),ee=v.useCallback(L=>{U(M=>{const z=[L,...M];return z.length>O?z.slice(0,O):z})},[]),re=v.useCallback((L,M)=>{h(z=>{const G=z.find(q=>q.id===L);return G?(G.resolve(M),z.filter(q=>q.id!==L)):z})},[]),F=v.useCallback((L,M)=>{h(z=>{const G=z.find(q=>q.id===L);return G?(G.reject(new Error(M||"User rejected sampling request")),z.filter(q=>q.id!==L)):z})},[]),K=v.useCallback((L,M)=>{x(z=>{const G=z.find(q=>q.id===L);return G?(G.resolve(M),z.filter(q=>q.id!==L)):z})},[]),V=v.useCallback((L,M)=>{x(z=>{const G=z.find(q=>q.id===L);return G?(G.reject(new Error(M||"User rejected elicitation request")),z.filter(q=>q.id!==L)):z})},[]),ne=v.useCallback(async L=>new Promise((M,z)=>{const G=`sampling-${g.current++}`,q={id:G,request:{params:L},timestamp:Date.now(),serverName:t,resolve:M,reject:z};h(ae=>[...ae,q]),typeof window<"u"&&rr(async()=>{const{toast:ae}=await Promise.resolve().then(()=>NP);return{toast:ae}},void 0).then(({toast:ae})=>{const ie=ae(d.jsx(_se,{requestId:G,serverName:t,onViewDetails:()=>{const X=new globalThis.CustomEvent("navigate-to-sampling",{detail:{requestId:G}});window.dispatchEvent(X),ae.dismiss(ie)},onApprove:X=>{h(Z=>{const se=Z.find(me=>me.id===G);return se?(se.resolve(X),ae.success("Sampling request approved"),Z.filter(me=>me.id!==G)):Z}),ae.dismiss(ie)},onDeny:()=>{h(X=>{const Z=X.find(se=>se.id===G);return Z?(Z.reject(new Error("User denied sampling request from toast")),ae.error("Sampling request denied"),X.filter(se=>se.id!==G)):X}),ae.dismiss(ie)}}),{duration:5e3})})}),[t]),te=v.useCallback(async L=>new Promise((M,z)=>{const G=`elicitation-${E.current++}`,q={id:G,request:L,timestamp:Date.now(),serverName:t,resolve:M,reject:z};x(ae=>[...ae,q]),typeof window<"u"&&rr(async()=>{const{toast:ae}=await Promise.resolve().then(()=>NP);return{toast:ae}},void 0).then(({toast:ae})=>{const ie=ae(d.jsx(Tse,{requestId:G,serverName:t,mode:L.mode||"form",message:L.message,url:L.mode==="url"?L.url:void 0,onViewDetails:()=>{const X=new globalThis.CustomEvent("navigate-to-elicitation",{detail:{requestId:G}});window.dispatchEvent(X),ae.dismiss(ie)},onOpenUrl:L.mode==="url"?()=>{window.open(L.url,"_blank"),ae.dismiss(ie)}:void 0,onCancel:()=>{x(X=>{const Z=X.find(se=>se.id===G);return Z?(Z.reject(new Error("User cancelled elicitation request from toast")),ae.error("Elicitation request cancelled"),X.filter(se=>se.id!==G)):X}),ae.dismiss(ie)}}),{duration:5e3})})}),[t]),D=M_({url:u,callbackUrl:c,customHeaders:Object.keys(f).length>0?f:void 0,transportType:r||"http",preventAutoAuth:!0,useRedirectFlow:!0,enabled:T,wrapTransport:I,onNotification:L=>{ee({id:globalThis.crypto.randomUUID(),method:L.method,params:L.params,timestamp:Date.now(),read:!1})},samplingCallback:ne,onElicitation:te}),H=v.useRef(s),$=v.useRef(null);return v.useEffect(()=>{H.current=s},[s]),v.useEffect(()=>{if(typeof queueMicrotask<"u")queueMicrotask(()=>{D.state==="ready"&&D.serverInfo&&console.log("[McpContext] Server info available:",D.serverInfo);const L=j.filter(G=>!G.read).length,M={id:a,url:e,name:D.serverInfo?.name||t,state:D.state,tools:D.tools,resources:D.resources,prompts:D.prompts,error:D.error??null,authUrl:D.authUrl??null,customHeaders:f,transportType:r,proxyConfig:n,serverInfo:D.serverInfo,capabilities:D.capabilities,notifications:j,unreadNotificationCount:L,markNotificationRead:B,markAllNotificationsRead:W,clearNotifications:J,pendingSamplingRequests:w,approveSampling:re,rejectSampling:F,pendingElicitationRequests:_,approveElicitation:K,rejectElicitation:V,callTool:D.callTool,readResource:D.readResource,listPrompts:D.listPrompts,getPrompt:D.getPrompt,authenticate:D.authenticate,retry:D.retry,clearStorage:D.clearStorage,disconnect:D.disconnect,client:D.client},z=$.current;(!z||z.state!==M.state||z.error!==M.error||z.authUrl!==M.authUrl||z.name!==M.name||z.tools.length!==M.tools.length||z.resources.length!==M.resources.length||z.prompts.length!==M.prompts.length||z.serverInfo!==M.serverInfo||z.capabilities!==M.capabilities||z.notifications.length!==M.notifications.length||z.unreadNotificationCount!==M.unreadNotificationCount||z.pendingSamplingRequests.length!==M.pendingSamplingRequests.length||z.pendingElicitationRequests.length!==M.pendingElicitationRequests.length||!z.client)&&($.current=M,H.current(M))});else{const L=j.filter(G=>!G.read).length,M={id:a,url:e,name:D.serverInfo?.name||t,state:D.state,tools:D.tools,resources:D.resources,prompts:D.prompts,error:D.error??null,authUrl:D.authUrl??null,customHeaders:f,transportType:r,proxyConfig:n,serverInfo:D.serverInfo,capabilities:D.capabilities,notifications:j,unreadNotificationCount:L,markNotificationRead:B,markAllNotificationsRead:W,clearNotifications:J,pendingSamplingRequests:w,approveSampling:re,rejectSampling:F,pendingElicitationRequests:_,approveElicitation:K,rejectElicitation:V,callTool:D.callTool,readResource:D.readResource,listPrompts:D.listPrompts,getPrompt:D.getPrompt,authenticate:D.authenticate,retry:D.retry,clearStorage:D.clearStorage,disconnect:D.disconnect,client:D.client},z=$.current;(!z||z.state!==M.state||z.error!==M.error||z.authUrl!==M.authUrl||z.name!==M.name||z.tools.length!==M.tools.length||z.resources.length!==M.resources.length||z.prompts.length!==M.prompts.length||z.serverInfo!==M.serverInfo||z.capabilities!==M.capabilities||z.notifications.length!==M.notifications.length||z.unreadNotificationCount!==M.unreadNotificationCount||z.pendingSamplingRequests.length!==M.pendingSamplingRequests.length||z.pendingElicitationRequests.length!==M.pendingElicitationRequests.length||!z.client)&&($.current=M,H.current(M))}},[e,t,r,n,f,a,D.state,D.tools,D.resources,D.prompts,D.error,D.authUrl,D.serverInfo,D.capabilities,D.client,j,B,W,J,D.callTool,D.readResource,D.listPrompts,D.getPrompt,D.authenticate,D.retry,D.clearStorage,m,re,F,_,K,V]),null}function kse({children:e}){const[t,n]=v.useState([]),[r,a]=v.useState(!1),[s,i]=v.useState(!0),[c,u]=v.useState([]);v.useEffect(()=>{try{const w=localStorage.getItem("mcp-inspector-connections");if(w){const S=JSON.parse(w);Array.isArray(S)&&(u(S),n(S.map(T=>({id:T.id||T.url,url:T.url,name:T.name||"MCP Server",state:"discovering",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:T.proxyConfig?.customHeaders,transportType:T.transportType,proxyConfig:T.proxyConfig,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:Tg,rejectSampling:Ng,pendingElicitationRequests:[],approveElicitation:kg,rejectElicitation:Cg,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}))))}const _=localStorage.getItem("mcp-inspector-auto-connect");_!==null&&i(_==="true")}catch(w){console.error("Failed to load connections from localStorage:",w)}finally{a(!0)}},[]),v.useEffect(()=>{r&&localStorage.setItem("mcp-inspector-connections",JSON.stringify(c))},[c,r]),v.useEffect(()=>{r&&localStorage.setItem("mcp-inspector-auto-connect",String(s))},[s,r]);const f=v.useCallback((w,_,S,T)=>{const R=c.find(A=>A.url===w),C=t.find(A=>A.url===w);if(R&&C){if(JSON.stringify(R.proxyConfig)!==JSON.stringify(S)&&S){u(O=>O.filter(j=>j.url!==w)),n(O=>O.filter(j=>j.url!==w)),setTimeout(()=>{const O={id:w,url:w,name:_||R.name||"MCP Server",proxyConfig:S,transportType:T||R.transportType};u(j=>[...j,O]),n(j=>[...j,{id:w,url:w,name:_||R.name||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:S?.customHeaders,transportType:T||R.transportType,proxyConfig:S,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:Tg,rejectSampling:Ng,pendingElicitationRequests:[],approveElicitation:kg,rejectElicitation:Cg,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}])},10);return}return}if(R&&!C){(S||T)&&u(A=>A.map(O=>O.url===w?{...O,proxyConfig:S||O.proxyConfig,transportType:T||O.transportType,name:_||O.name}:O)),n(A=>[...A,{id:R.id||w,url:w,name:_||R.name||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:S?.customHeaders||R.proxyConfig?.customHeaders,transportType:T||R.transportType,proxyConfig:S||R.proxyConfig,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:Tg,rejectSampling:Ng,pendingElicitationRequests:[],approveElicitation:kg,rejectElicitation:Cg,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}]);return}const I={id:w,url:w,name:_||"MCP Server",proxyConfig:S,transportType:T};u(A=>[...A,I]),n(A=>[...A,{id:w,url:w,name:_||"MCP Server",state:"connecting",tools:[],resources:[],prompts:[],error:null,authUrl:null,customHeaders:S?.customHeaders,transportType:T,proxyConfig:S,notifications:[],unreadNotificationCount:0,markNotificationRead:()=>{},markAllNotificationsRead:()=>{},clearNotifications:()=>{},pendingSamplingRequests:[],approveSampling:Tg,rejectSampling:Ng,pendingElicitationRequests:[],approveElicitation:kg,rejectElicitation:Cg,callTool:async()=>{},readResource:async()=>{},listPrompts:async()=>{},getPrompt:async()=>{},authenticate:()=>{},retry:()=>{},clearStorage:()=>{},disconnect:()=>{},client:null}])},[c,t]),m=v.useCallback(w=>{const _=t.find(T=>T.id===w);_&&(console.log(`[McpContext] Cleaning up connection: ${w}`),_.disconnect&&(console.log(`[McpContext] Disconnecting from server: ${w}`),_.disconnect()),_.clearStorage&&(console.log(`[McpContext] Clearing OAuth storage for connection: ${w}`),_.clearStorage())),u(T=>T.filter(R=>R.id!==w)),n(T=>T.filter(R=>R.id!==w));const S=localStorage.getItem("mcp-inspector-connections");if(S)try{const R=JSON.parse(S).filter(C=>(C.id||C.url)!==w);localStorage.setItem("mcp-inspector-connections",JSON.stringify(R))}catch(T){console.error("Failed to update localStorage on remove:",T)}Tr.getInstance().capture(new vse({serverId:w}))},[t]),h=v.useCallback((w,_)=>{u(S=>S.map(T=>T.id===w||T.url===w?{...T,..._}:T)),n(S=>S.map(T=>T.id===w?{...T,..._}:T))},[]),g=v.useCallback(w=>{n(_=>{const S=_.findIndex(C=>C.id===w.id);if(S===-1)return _;const T=_[S];if(T.state===w.state&&T.tools===w.tools&&T.resources===w.resources&&T.prompts===w.prompts&&T.error===w.error&&T.serverInfo===w.serverInfo&&T.client===w.client&&T.notifications===w.notifications&&T.unreadNotificationCount===w.unreadNotificationCount&&T.pendingSamplingRequests.length===w.pendingSamplingRequests.length&&T.pendingElicitationRequests.length===w.pendingElicitationRequests.length)return _;const R=[..._];return R[S]=w,R})},[]),y=v.useCallback(w=>{console.log("Connect requested for:",w)},[]),x=v.useCallback(w=>{console.log("Disconnect requested for:",w)},[]),E=v.useMemo(()=>({connections:t,addConnection:f,removeConnection:m,updateConnectionConfig:h,autoConnect:s,setAutoConnect:i,connectServer:y,disconnectServer:x,configLoaded:r}),[t,f,m,h,s,y,x,r]);return d.jsxs(Y3.Provider,{value:E,children:[e,r&&s&&c.map(w=>{const _=`${w.id||w.url}-${w.proxyConfig?.proxyAddress?"proxy":"direct"}`;return console.warn("[McpContext] Rendering McpConnectionWrapper with key:",_,"proxyConfig:",w.proxyConfig),d.jsx(Nse,{url:w.url,name:w.name,proxyConfig:w.proxyConfig,transportType:w.transportType,connectionId:w.id||w.url,onUpdate:g,onRemove:()=>m(w.id||w.url)},_)})]})}const Cse=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Rse=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,n,r)=>r?r.toUpperCase():n.toLowerCase()),wP=e=>{const t=Rse(e);return t.charAt(0).toUpperCase()+t.slice(1)},Z3=(...e)=>e.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim(),Ase=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var Ise={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 Ose=v.forwardRef(({color:e="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:s,iconNode:i,...c},u)=>v.createElement("svg",{ref:u,...Ise,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:Z3("lucide",a),...!s&&!Ase(c)&&{"aria-hidden":"true"},...c},[...i.map(([f,m])=>v.createElement(f,m)),...Array.isArray(s)?s:[s]]));const Xe=(e,t)=>{const n=v.forwardRef(({className:r,...a},s)=>v.createElement(Ose,{ref:s,iconNode:t,className:Z3(`lucide-${Cse(wP(e))}`,`lucide-${e}`,r),...a}));return n.displayName=wP(e),n};const Dse=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],Lse=Xe("arrow-down-to-line",Dse);const Mse=[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]],jse=Xe("arrow-up-from-line",Mse);const Pse=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Use=Xe("arrow-up",Pse);const $se=[["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"}]],uT=Xe("bell",$se);const zse=[["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"}]],q3=Xe("brush",zse);const Fse=[["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"}]],Bse=Xe("bug",Fse);const Hse=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],oa=Xe("check",Hse);const Vse=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Gl=Xe("chevron-down",Vse);const Gse=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Wse=Xe("chevron-right",Gse);const Kse=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],dT=Xe("chevron-left",Kse);const Yse=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Zse=Xe("chevron-up",Yse);const qse=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],Xse=Xe("chevrons-up-down",qse);const Jse=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]],EP=Xe("circle-minus",Jse);const Qse=[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],qu=Xe("clock",Qse);const eie=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],fT=Xe("code",eie);const tie=[["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"}]],nie=Xe("cog",tie);const rie=[["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"}]],aie=Xe("command",rie);const oie=[["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"}]],zr=Xe("copy",oie);const sie=[["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"}]],Wy=Xe("database",sie);const iie=[["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"}]],Qp=Xe("download",iie);const lie=[["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"}]],cie=Xe("ellipsis-vertical",lie);const uie=[["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"}]],Wx=Xe("external-link",uie);const die=[["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"}]],X3=Xe("eye-off",die);const fie=[["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"}]],Kx=Xe("eye",fie);const pie=[["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"}]],mie=Xe("file-code",pie);const hie=[["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"}]],gie=Xe("file-image",hie);const bie=[["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"}]],pT=Xe("file-text",bie);const yie=[["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"}]],vie=Xe("file",yie);const wie=[["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"}]],Eie=Xe("folder-open",wie);const xie=[["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"}]],Sie=Xe("globe",xie);const _ie=[["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"}]],Tie=Xe("grip-vertical",_ie);const Nie=[["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"}]],J3=Xe("hash",Nie);const kie=[["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"}]],Mb=Xe("history",kie);const Cie=[["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"}]],Q3=Xe("key",Cie);const Rie=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Li=Xe("loader-circle",Rie);const Aie=[["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"}]],mT=Xe("maximize-2",Aie);const Iie=[["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"}]],hT=Xe("maximize",Iie);const Oie=[["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"}]],Die=Xe("message-circle",Oie);const Lie=[["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"}]],yp=Xe("message-square",Lie);const Mie=[["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"}]],jie=Xe("minimize",Mie);const Pie=[["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"}]],xP=Xe("monitor",Pie);const Uie=[["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"}]],$ie=Xe("moon",Uie);const zie=[["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"}]],Fie=Xe("picture-in-picture",zie);const Bie=[["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"}]],eB=Xe("play",Bie);const Hie=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],tB=Xe("plus",Hie);const Vie=[["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"}]],SP=Xe("rotate-ccw",Vie);const Gie=[["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"}]],gT=Xe("save",Gie);const Wie=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],wd=Xe("search",Wie);const Kie=[["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"}]],Yie=Xe("send",Kie);const Zie=[["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"}]],qie=Xe("server",Zie);const Xie=[["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"}]],mu=Xe("settings",Xie);const Jie=[["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"}]],Qie=Xe("shield",Jie);const ele=[["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"}]],tle=Xe("sparkles",ele);const nle=[["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"}]],nB=Xe("square-check-big",nle);const rle=[["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"}]],ale=Xe("square-pen",rle);const ole=[["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"}]],sle=Xe("sun-dim",ole);const ile=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],EE=Xe("terminal",ile);const lle=[["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"}]],Mi=Xe("trash-2",lle);const cle=[["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"}]],ule=Xe("trash",cle);const dle=[["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"}]],Ol=Xe("wrench",dle);const fle=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],qo=Xe("x",fle);const ple=[["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=Xe("zap",ple);function mle(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 hle=e=>{switch(e){case"success":return yle;case"info":return wle;case"warning":return vle;case"error":return Ele;default:return null}},gle=Array(12).fill(0),ble=({visible:e,className:t})=>ce.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ce.createElement("div",{className:"sonner-spinner"},gle.map((n,r)=>ce.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),yle=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ce.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"})),vle=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ce.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"})),wle=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ce.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"})),Ele=ce.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ce.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"})),xle=ce.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"},ce.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ce.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Sle=()=>{const[e,t]=ce.useState(document.hidden);return ce.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let Yx=1;class _le{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:r,...a}=t,s=typeof t?.id=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:Yx++,i=this.toasts.find(u=>u.id===s),c=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(s)&&this.dismissedToasts.delete(s),i?this.toasts=this.toasts.map(u=>u.id===s?(this.publish({...u,...t,id:s,title:r}),{...u,...t,id:s,dismissible:c,title:r}):u):this.addToast({title:r,...a,dismissible:c,id:s}),s},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(r=>r({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 r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const a=Promise.resolve(t instanceof Function?t():t);let s=r!==void 0,i;const c=a.then(async f=>{if(i=["resolve",f],ce.isValidElement(f))s=!1,this.create({id:r,type:"default",message:f});else if(Nle(f)&&!f.ok){s=!1;const h=typeof n.error=="function"?await n.error(`HTTP error! status: ${f.status}`):n.error,g=typeof n.description=="function"?await n.description(`HTTP error! status: ${f.status}`):n.description,x=typeof h=="object"&&!ce.isValidElement(h)?h:{message:h};this.create({id:r,type:"error",description:g,...x})}else if(f instanceof Error){s=!1;const h=typeof n.error=="function"?await n.error(f):n.error,g=typeof n.description=="function"?await n.description(f):n.description,x=typeof h=="object"&&!ce.isValidElement(h)?h:{message:h};this.create({id:r,type:"error",description:g,...x})}else if(n.success!==void 0){s=!1;const h=typeof n.success=="function"?await n.success(f):n.success,g=typeof n.description=="function"?await n.description(f):n.description,x=typeof h=="object"&&!ce.isValidElement(h)?h:{message:h};this.create({id:r,type:"success",description:g,...x})}}).catch(async f=>{if(i=["reject",f],n.error!==void 0){s=!1;const m=typeof n.error=="function"?await n.error(f):n.error,h=typeof n.description=="function"?await n.description(f):n.description,y=typeof m=="object"&&!ce.isValidElement(m)?m:{message:m};this.create({id:r,type:"error",description:h,...y})}}).finally(()=>{s&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),u=()=>new Promise((f,m)=>c.then(()=>i[0]==="reject"?m(i[1]):f(i[1])).catch(m));return typeof r!="string"&&typeof r!="number"?{unwrap:u}:Object.assign(r,{unwrap:u})},this.custom=(t,n)=>{const r=n?.id||Yx++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const ba=new _le,Tle=(e,t)=>{const n=t?.id||Yx++;return ba.addToast({title:e,...t,id:n}),n},Nle=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",kle=Tle,Cle=()=>ba.toasts,Rle=()=>ba.getActiveToasts(),Xt=Object.assign(kle,{success:ba.success,info:ba.info,warning:ba.warning,error:ba.error,custom:ba.custom,message:ba.message,promise:ba.promise,dismiss:ba.dismiss,loading:ba.loading},{getHistory:Cle,getToasts:Rle});mle("[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 Rg(e){return e.label!==void 0}const Ale=3,Ile="24px",Ole="16px",_P=4e3,Dle=356,Lle=14,Mle=45,jle=200;function Po(...e){return e.filter(Boolean).join(" ")}function Ple(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const Ule=e=>{var t,n,r,a,s,i,c,u,f;const{invert:m,toast:h,unstyled:g,interacting:y,setHeights:x,visibleToasts:E,heights:w,index:_,toasts:S,expanded:T,removeToast:R,defaultRichColors:C,closeButton:I,style:A,cancelButtonStyle:O,actionButtonStyle:j,className:U="",descriptionClassName:B="",duration:W,position:J,gap:ee,expandByDefault:re,classNames:F,icons:K,closeButtonAriaLabel:V="Close toast"}=e,[ne,te]=ce.useState(null),[D,H]=ce.useState(null),[$,L]=ce.useState(!1),[M,z]=ce.useState(!1),[G,q]=ce.useState(!1),[ae,ie]=ce.useState(!1),[X,Z]=ce.useState(!1),[se,me]=ce.useState(0),[le,Ne]=ce.useState(0),He=ce.useRef(h.duration||W||_P),xe=ce.useRef(null),Te=ce.useRef(null),$e=_===0,fe=_+1<=E,Ie=h.type,Fe=h.dismissible!==!1,Ee=h.className||"",at=h.descriptionClassName||"",lt=ce.useMemo(()=>w.findIndex(Ze=>Ze.toastId===h.id)||0,[w,h.id]),bt=ce.useMemo(()=>{var Ze;return(Ze=h.closeButton)!=null?Ze:I},[h.closeButton,I]),Rt=ce.useMemo(()=>h.duration||W||_P,[h.duration,W]),De=ce.useRef(0),ze=ce.useRef(0),ht=ce.useRef(0),nt=ce.useRef(null),[kt,ot]=J.split("-"),Ae=ce.useMemo(()=>w.reduce((Ze,vt,Pt)=>Pt>=lt?Ze:Ze+vt.height,0),[w,lt]),Me=Sle(),Ve=h.invert||m,it=Ie==="loading";ze.current=ce.useMemo(()=>lt*ee+Ae,[lt,Ae]),ce.useEffect(()=>{He.current=Rt},[Rt]),ce.useEffect(()=>{L(!0)},[]),ce.useEffect(()=>{const Ze=Te.current;if(Ze){const vt=Ze.getBoundingClientRect().height;return Ne(vt),x(Pt=>[{toastId:h.id,height:vt,position:h.position},...Pt]),()=>x(Pt=>Pt.filter(Ut=>Ut.toastId!==h.id))}},[x,h.id]),ce.useLayoutEffect(()=>{if(!$)return;const Ze=Te.current,vt=Ze.style.height;Ze.style.height="auto";const Pt=Ze.getBoundingClientRect().height;Ze.style.height=vt,Ne(Pt),x(Ut=>Ut.find(dn=>dn.toastId===h.id)?Ut.map(dn=>dn.toastId===h.id?{...dn,height:Pt}:dn):[{toastId:h.id,height:Pt,position:h.position},...Ut])},[$,h.title,h.description,x,h.id,h.jsx,h.action,h.cancel]);const pt=ce.useCallback(()=>{z(!0),me(ze.current),x(Ze=>Ze.filter(vt=>vt.toastId!==h.id)),setTimeout(()=>{R(h)},jle)},[h,R,x,ze]);ce.useEffect(()=>{if(h.promise&&Ie==="loading"||h.duration===1/0||h.type==="loading")return;let Ze;return T||y||Me?(()=>{if(ht.current<De.current){const Ut=new Date().getTime()-De.current;He.current=He.current-Ut}ht.current=new Date().getTime()})():(()=>{He.current!==1/0&&(De.current=new Date().getTime(),Ze=setTimeout(()=>{h.onAutoClose==null||h.onAutoClose.call(h,h),pt()},He.current))})(),()=>clearTimeout(Ze)},[T,y,h,Ie,Me,pt]),ce.useEffect(()=>{h.delete&&(pt(),h.onDismiss==null||h.onDismiss.call(h,h))},[pt,h.delete]);function Et(){var Ze;if(K?.loading){var vt;return ce.createElement("div",{className:Po(F?.loader,h==null||(vt=h.classNames)==null?void 0:vt.loader,"sonner-loader"),"data-visible":Ie==="loading"},K.loading)}return ce.createElement(ble,{className:Po(F?.loader,h==null||(Ze=h.classNames)==null?void 0:Ze.loader),visible:Ie==="loading"})}const xt=h.icon||K?.[Ie]||hle(Ie);var un,mn;return ce.createElement("li",{tabIndex:0,ref:Te,className:Po(U,Ee,F?.toast,h==null||(t=h.classNames)==null?void 0:t.toast,F?.default,F?.[Ie],h==null||(n=h.classNames)==null?void 0:n[Ie]),"data-sonner-toast":"","data-rich-colors":(un=h.richColors)!=null?un:C,"data-styled":!(h.jsx||h.unstyled||g),"data-mounted":$,"data-promise":!!h.promise,"data-swiped":X,"data-removed":M,"data-visible":fe,"data-y-position":kt,"data-x-position":ot,"data-index":_,"data-front":$e,"data-swiping":G,"data-dismissible":Fe,"data-type":Ie,"data-invert":Ve,"data-swipe-out":ae,"data-swipe-direction":D,"data-expanded":!!(T||re&&$),"data-testid":h.testId,style:{"--index":_,"--toasts-before":_,"--z-index":S.length-_,"--offset":`${M?se:ze.current}px`,"--initial-height":re?"auto":`${le}px`,...A,...h.style},onDragEnd:()=>{q(!1),te(null),nt.current=null},onPointerDown:Ze=>{Ze.button!==2&&(it||!Fe||(xe.current=new Date,me(ze.current),Ze.target.setPointerCapture(Ze.pointerId),Ze.target.tagName!=="BUTTON"&&(q(!0),nt.current={x:Ze.clientX,y:Ze.clientY})))},onPointerUp:()=>{var Ze,vt,Pt;if(ae||!Fe)return;nt.current=null;const Ut=Number(((Ze=Te.current)==null?void 0:Ze.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),yr=Number(((vt=Te.current)==null?void 0:vt.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),dn=new Date().getTime()-((Pt=xe.current)==null?void 0:Pt.getTime()),Xn=ne==="x"?Ut:yr,Jn=Math.abs(Xn)/dn;if(Math.abs(Xn)>=Mle||Jn>.11){me(ze.current),h.onDismiss==null||h.onDismiss.call(h,h),H(ne==="x"?Ut>0?"right":"left":yr>0?"down":"up"),pt(),ie(!0);return}else{var wn,fn;(wn=Te.current)==null||wn.style.setProperty("--swipe-amount-x","0px"),(fn=Te.current)==null||fn.style.setProperty("--swipe-amount-y","0px")}Z(!1),q(!1),te(null)},onPointerMove:Ze=>{var vt,Pt,Ut;if(!nt.current||!Fe||((vt=window.getSelection())==null?void 0:vt.toString().length)>0)return;const dn=Ze.clientY-nt.current.y,Xn=Ze.clientX-nt.current.x;var Jn;const wn=(Jn=e.swipeDirections)!=null?Jn:Ple(J);!ne&&(Math.abs(Xn)>1||Math.abs(dn)>1)&&te(Math.abs(Xn)>Math.abs(dn)?"x":"y");let fn={x:0,y:0};const la=Qt=>1/(1.5+Math.abs(Qt)/20);if(ne==="y"){if(wn.includes("top")||wn.includes("bottom"))if(wn.includes("top")&&dn<0||wn.includes("bottom")&&dn>0)fn.y=dn;else{const Qt=dn*la(dn);fn.y=Math.abs(Qt)<Math.abs(dn)?Qt:dn}}else if(ne==="x"&&(wn.includes("left")||wn.includes("right")))if(wn.includes("left")&&Xn<0||wn.includes("right")&&Xn>0)fn.x=Xn;else{const Qt=Xn*la(Xn);fn.x=Math.abs(Qt)<Math.abs(Xn)?Qt:Xn}(Math.abs(fn.x)>0||Math.abs(fn.y)>0)&&Z(!0),(Pt=Te.current)==null||Pt.style.setProperty("--swipe-amount-x",`${fn.x}px`),(Ut=Te.current)==null||Ut.style.setProperty("--swipe-amount-y",`${fn.y}px`)}},bt&&!h.jsx&&Ie!=="loading"?ce.createElement("button",{"aria-label":V,"data-disabled":it,"data-close-button":!0,onClick:it||!Fe?()=>{}:()=>{pt(),h.onDismiss==null||h.onDismiss.call(h,h)},className:Po(F?.closeButton,h==null||(r=h.classNames)==null?void 0:r.closeButton)},(mn=K?.close)!=null?mn:xle):null,(Ie||h.icon||h.promise)&&h.icon!==null&&(K?.[Ie]!==null||h.icon)?ce.createElement("div",{"data-icon":"",className:Po(F?.icon,h==null||(a=h.classNames)==null?void 0:a.icon)},h.promise||h.type==="loading"&&!h.icon?h.icon||Et():null,h.type!=="loading"?xt:null):null,ce.createElement("div",{"data-content":"",className:Po(F?.content,h==null||(s=h.classNames)==null?void 0:s.content)},ce.createElement("div",{"data-title":"",className:Po(F?.title,h==null||(i=h.classNames)==null?void 0:i.title)},h.jsx?h.jsx:typeof h.title=="function"?h.title():h.title),h.description?ce.createElement("div",{"data-description":"",className:Po(B,at,F?.description,h==null||(c=h.classNames)==null?void 0:c.description)},typeof h.description=="function"?h.description():h.description):null),ce.isValidElement(h.cancel)?h.cancel:h.cancel&&Rg(h.cancel)?ce.createElement("button",{"data-button":!0,"data-cancel":!0,style:h.cancelButtonStyle||O,onClick:Ze=>{Rg(h.cancel)&&Fe&&(h.cancel.onClick==null||h.cancel.onClick.call(h.cancel,Ze),pt())},className:Po(F?.cancelButton,h==null||(u=h.classNames)==null?void 0:u.cancelButton)},h.cancel.label):null,ce.isValidElement(h.action)?h.action:h.action&&Rg(h.action)?ce.createElement("button",{"data-button":!0,"data-action":!0,style:h.actionButtonStyle||j,onClick:Ze=>{Rg(h.action)&&(h.action.onClick==null||h.action.onClick.call(h.action,Ze),!Ze.defaultPrevented&&pt())},className:Po(F?.actionButton,h==null||(f=h.classNames)==null?void 0:f.actionButton)},h.action.label):null)};function TP(){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 $le(e,t){const n={};return[e,t].forEach((r,a)=>{const s=a===1,i=s?"--mobile-offset":"--offset",c=s?Ole:Ile;function u(f){["top","right","bottom","left"].forEach(m=>{n[`${i}-${m}`]=typeof f=="number"?`${f}px`:f})}typeof r=="number"||typeof r=="string"?u(r):typeof r=="object"?["top","right","bottom","left"].forEach(f=>{r[f]===void 0?n[`${i}-${f}`]=c:n[`${i}-${f}`]=typeof r[f]=="number"?`${r[f]}px`:r[f]}):u(c)}),n}const rB=ce.forwardRef(function(t,n){const{id:r,invert:a,position:s="bottom-right",hotkey:i=["altKey","KeyT"],expand:c,closeButton:u,className:f,offset:m,mobileOffset:h,theme:g="light",richColors:y,duration:x,style:E,visibleToasts:w=Ale,toastOptions:_,dir:S=TP(),gap:T=Lle,icons:R,containerAriaLabel:C="Notifications"}=t,[I,A]=ce.useState([]),O=ce.useMemo(()=>r?I.filter($=>$.toasterId===r):I.filter($=>!$.toasterId),[I,r]),j=ce.useMemo(()=>Array.from(new Set([s].concat(O.filter($=>$.position).map($=>$.position)))),[O,s]),[U,B]=ce.useState([]),[W,J]=ce.useState(!1),[ee,re]=ce.useState(!1),[F,K]=ce.useState(g!=="system"?g:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),V=ce.useRef(null),ne=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),te=ce.useRef(null),D=ce.useRef(!1),H=ce.useCallback($=>{A(L=>{var M;return(M=L.find(z=>z.id===$.id))!=null&&M.delete||ba.dismiss($.id),L.filter(({id:z})=>z!==$.id)})},[]);return ce.useEffect(()=>ba.subscribe($=>{if($.dismiss){requestAnimationFrame(()=>{A(L=>L.map(M=>M.id===$.id?{...M,delete:!0}:M))});return}setTimeout(()=>{jF.flushSync(()=>{A(L=>{const M=L.findIndex(z=>z.id===$.id);return M!==-1?[...L.slice(0,M),{...L[M],...$},...L.slice(M+1)]:[$,...L]})})})}),[I]),ce.useEffect(()=>{if(g!=="system"){K(g);return}if(g==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?K("dark"):K("light")),typeof window>"u")return;const $=window.matchMedia("(prefers-color-scheme: dark)");try{$.addEventListener("change",({matches:L})=>{K(L?"dark":"light")})}catch{$.addListener(({matches:M})=>{try{K(M?"dark":"light")}catch(z){console.error(z)}})}},[g]),ce.useEffect(()=>{I.length<=1&&J(!1)},[I]),ce.useEffect(()=>{const $=L=>{var M;if(i.every(q=>L[q]||L.code===q)){var G;J(!0),(G=V.current)==null||G.focus()}L.code==="Escape"&&(document.activeElement===V.current||(M=V.current)!=null&&M.contains(document.activeElement))&&J(!1)};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[i]),ce.useEffect(()=>{if(V.current)return()=>{te.current&&(te.current.focus({preventScroll:!0}),te.current=null,D.current=!1)}},[V.current]),ce.createElement("section",{ref:n,"aria-label":`${C} ${ne}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},j.map(($,L)=>{var M;const[z,G]=$.split("-");return O.length?ce.createElement("ol",{key:$,dir:S==="auto"?TP():S,tabIndex:-1,ref:V,className:f,"data-sonner-toaster":!0,"data-sonner-theme":F,"data-y-position":z,"data-x-position":G,style:{"--front-toast-height":`${((M=U[0])==null?void 0:M.height)||0}px`,"--width":`${Dle}px`,"--gap":`${T}px`,...E,...$le(m,h)},onBlur:q=>{D.current&&!q.currentTarget.contains(q.relatedTarget)&&(D.current=!1,te.current&&(te.current.focus({preventScroll:!0}),te.current=null))},onFocus:q=>{q.target instanceof HTMLElement&&q.target.dataset.dismissible==="false"||D.current||(D.current=!0,te.current=q.relatedTarget)},onMouseEnter:()=>J(!0),onMouseMove:()=>J(!0),onMouseLeave:()=>{ee||J(!1)},onDragEnd:()=>J(!1),onPointerDown:q=>{q.target instanceof HTMLElement&&q.target.dataset.dismissible==="false"||re(!0)},onPointerUp:()=>re(!1)},O.filter(q=>!q.position&&L===0||q.position===$).map((q,ae)=>{var ie,X;return ce.createElement(Ule,{key:q.id,icons:R,index:ae,toast:q,defaultRichColors:y,duration:(ie=_?.duration)!=null?ie:x,className:_?.className,descriptionClassName:_?.descriptionClassName,invert:a,visibleToasts:w,closeButton:(X=_?.closeButton)!=null?X:u,interacting:ee,position:$,style:_?.style,unstyled:_?.unstyled,classNames:_?.classNames,cancelButtonStyle:_?.cancelButtonStyle,actionButtonStyle:_?.actionButtonStyle,closeButtonAriaLabel:_?.closeButtonAriaLabel,removeToast:H,toasts:O.filter(Z=>Z.position==q.position),heights:U.filter(Z=>Z.position==q.position),setHeights:B,expandByDefault:c,gap:T,expanded:W,swipeDirections:t.swipeDirections})})):null}))}),NP=Object.freeze(Object.defineProperty({__proto__:null,Toaster:rB,toast:Xt},Symbol.toStringTag,{value:"Module"}));var Ky="Dialog",[aB]=Ro(Ky),[zle,Ao]=aB(Ky),oB=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:a,onOpenChange:s,modal:i=!0}=e,c=v.useRef(null),u=v.useRef(null),[f,m]=Os({prop:r,defaultProp:a??!1,onChange:s,caller:Ky});return d.jsx(zle,{scope:t,triggerRef:c,contentRef:u,contentId:$r(),titleId:$r(),descriptionId:$r(),open:f,onOpenChange:m,onOpenToggle:v.useCallback(()=>m(h=>!h),[m]),modal:i,children:n})};oB.displayName=Ky;var sB="DialogTrigger",iB=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,a=Ao(sB,n),s=Jt(t,a.triggerRef);return d.jsx(_t.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":vT(a.open),...r,ref:s,onClick:Ge(e.onClick,a.onOpenToggle)})});iB.displayName=sB;var bT="DialogPortal",[Fle,lB]=aB(bT,{forceMount:void 0}),cB=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=e,s=Ao(bT,t);return d.jsx(Fle,{scope:t,forceMount:n,children:v.Children.map(r,i=>d.jsx(za,{present:n||s.open,children:d.jsx(yd,{asChild:!0,container:a,children:i})}))})};cB.displayName=bT;var jb="DialogOverlay",uB=v.forwardRef((e,t)=>{const n=lB(jb,e.__scopeDialog),{forceMount:r=n.forceMount,...a}=e,s=Ao(jb,e.__scopeDialog);return s.modal?d.jsx(za,{present:r||s.open,children:d.jsx(Hle,{...a,ref:t})}):null});uB.displayName=jb;var Ble=Al("DialogOverlay.RemoveScroll"),Hle=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,a=Ao(jb,n);return d.jsx(Zp,{as:Ble,allowPinchZoom:!0,shards:[a.contentRef],children:d.jsx(_t.div,{"data-state":vT(a.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),Dl="DialogContent",dB=v.forwardRef((e,t)=>{const n=lB(Dl,e.__scopeDialog),{forceMount:r=n.forceMount,...a}=e,s=Ao(Dl,e.__scopeDialog);return d.jsx(za,{present:r||s.open,children:s.modal?d.jsx(Vle,{...a,ref:t}):d.jsx(Gle,{...a,ref:t})})});dB.displayName=Dl;var Vle=v.forwardRef((e,t)=>{const n=Ao(Dl,e.__scopeDialog),r=v.useRef(null),a=Jt(t,n.contentRef,r);return v.useEffect(()=>{const s=r.current;if(s)return Py(s)},[]),d.jsx(fB,{...e,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Ge(e.onCloseAutoFocus,s=>{s.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:Ge(e.onPointerDownOutside,s=>{const i=s.detail.originalEvent,c=i.button===0&&i.ctrlKey===!0;(i.button===2||c)&&s.preventDefault()}),onFocusOutside:Ge(e.onFocusOutside,s=>s.preventDefault())})}),Gle=v.forwardRef((e,t)=>{const n=Ao(Dl,e.__scopeDialog),r=v.useRef(!1),a=v.useRef(!1);return d.jsx(fB,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{e.onCloseAutoFocus?.(s),s.defaultPrevented||(r.current||n.triggerRef.current?.focus(),s.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:s=>{e.onInteractOutside?.(s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const i=s.target;n.triggerRef.current?.contains(i)&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&a.current&&s.preventDefault()}})}),fB=v.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:s,...i}=e,c=Ao(Dl,n),u=v.useRef(null),f=Jt(t,u);return Ry(),d.jsxs(d.Fragment,{children:[d.jsx(Gp,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:s,children:d.jsx(hd,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionId,"aria-labelledby":c.titleId,"data-state":vT(c.open),...i,ref:f,onDismiss:()=>c.onOpenChange(!1)})}),d.jsxs(d.Fragment,{children:[d.jsx(Wle,{titleId:c.titleId}),d.jsx(Yle,{contentRef:u,descriptionId:c.descriptionId})]})]})}),yT="DialogTitle",pB=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,a=Ao(yT,n);return d.jsx(_t.h2,{id:a.titleId,...r,ref:t})});pB.displayName=yT;var mB="DialogDescription",hB=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,a=Ao(mB,n);return d.jsx(_t.p,{id:a.descriptionId,...r,ref:t})});hB.displayName=mB;var gB="DialogClose",bB=v.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,a=Ao(gB,n);return d.jsx(_t.button,{type:"button",...r,ref:t,onClick:Ge(e.onClick,()=>a.onOpenChange(!1))})});bB.displayName=gB;function vT(e){return e?"open":"closed"}var yB="DialogTitleWarning",[N0e,vB]=Ote(yB,{contentName:Dl,titleName:yT,docsSlug:"dialog"}),Wle=({titleId:e})=>{const t=vB(yB),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
92
92
 
93
93
  If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
94
94
 
@@ -1655,7 +1655,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1655
1655
  <\/script>
1656
1656
  </body>
1657
1657
  </html>`,_6=1,L$=2,T6=3,M$=4,N6=5,j$=Symbol.for("quilt.threads.serialize"),$ye=Symbol.for("quilt.threads.transferable");class zye extends AbortController{constructor(...t){super();const n=t.find(r=>r.aborted);if(n)this.abort(n.reason);else{const r=s=>this.abort(s.target.reason),a={signal:this.signal};for(const s of t)s.addEventListener("abort",r,a)}}}class P$ extends Error{constructor(){super("You attempted to call a function on a closed thread.")}}let Fye="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";function k6(e=21){let t="",n=crypto.getRandomValues(new Uint8Array(e));for(let r=0;r<e;r++)t+=Fye[63&n[r]];return t}var $f,Wc,zf,lb,ZS,C6;class Bye{constructor(){bo(this,ZS),bo(this,$f,new Map),bo(this,Wc,new Map),bo(this,zf,new Map),bo(this,lb,new WeakMap)}get(t){return Un(this,Wc).get(t)}release(t){const n=Un(this,Wc).get(t);return n&&(Un(this,Wc).delete(t),Un(this,$f).delete(n)),!!n}serialize(t){let n=Un(this,$f).get(t);return n==null&&(n=k6(),Un(this,$f).set(t,n),Un(this,Wc).set(n,t)),n}deserialize(t,n){var r,a;let s=(r=Un(this,zf).get(t))==null?void 0:r.deref();return s||(s=(...i)=>{if(!Un(this,zf).has(t))throw new Error("You attempted to call a function that was already revoked.");return n.call((c,u,f)=>{n.messages.send([T6,c,t,u],f)},i)},(a=Mr(this,ZS,C6).call(this,n))==null||a.register(s,t),Un(this,zf).set(t,new WeakRef(s)),s)}}$f=new WeakMap,Wc=new WeakMap,zf=new WeakMap,lb=new WeakMap,ZS=new WeakSet,C6=function(e){let t=Un(this,lb).get(e);if(!(typeof FinalizationRegistry>"u"))return t||(t=new FinalizationRegistry(n=>{e.messages.send([N6,n])}),Un(this,lb).set(e,t)),t};function Hye(e){return e!=null&&(Symbol.asyncIterator in e||Symbol.iterator in e)&&typeof e.next=="function"}function U$(e){if(e==null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t==null||t===Object.prototype}const qE="_@f",$$="_@i";var sp,ip,Xa,cb,yi;class Vye{constructor(t){bo(this,Xa),bo(this,sp),bo(this,ip),KS(this,sp,t?.serialize),KS(this,ip,t?.deserialize)}serialize(t,n,r){return Mr(this,Xa,cb).call(this,t,n,r)}deserialize(t,n){return Mr(this,Xa,yi).call(this,t,n)}}sp=new WeakMap,ip=new WeakMap,Xa=new WeakSet,cb=function(e,t,n,r=new Map,a=!1){if(e==null)return e;if(r.has(e))return r.get(e);if(r.set(e,void 0),typeof e=="object"){if(Un(this,sp)&&!a){const c=Un(this,sp).call(this,e,u=>Mr(this,Xa,cb).call(this,u,t,n,r,!0),t,n);if(c!==void 0)return r.set(e,c),c}if(e[$ye])return n?.push(e),r.set(e,e),e;const s=c=>Mr(this,Xa,cb).call(this,c,t,n,r);if(typeof e[j$]=="function"){const c=e[j$]({serialize:s});return r.set(e,c),c}if(Array.isArray(e)){const c=e.map(u=>s(u));return r.set(e,c),c}if(e instanceof Map){const c=[...e.entries()].map(([f,m])=>[s(f),s(m)]),u=new Map(c);return r.set(e,u),u}if(e instanceof Set){const c=[...e].map(f=>s(f)),u=new Set(c);return r.set(e,u),u}const i=Hye(e);if(U$(e)||i){const c={};for(const u of Object.keys(e))c[u]=s(e[u]);return i&&(c.next??(c.next=s(e.next.bind(e))),c.return??(c.return=s(e.return.bind(e))),c.throw??(c.throw=s(e.throw.bind(e))),c[$$]=!0),r.set(e,c),c}}if(typeof e=="function"){const s=t.functions.serialize(e,t,n),i={[qE]:s};return r.set(e,i),i}return r.set(e,e),e},yi=function(e,t,n=!1){if(e==null)return e;if(typeof e=="object"){if(Un(this,ip)&&!n){const a=Un(this,ip).call(this,e,s=>Mr(this,Xa,yi).call(this,s,t,!0),t);if(a!==void 0)return a}if(e==null)return e;if(Array.isArray(e))return e.map(a=>Mr(this,Xa,yi).call(this,a,t));if(e instanceof Map)return new Map([...e].map(([a,s])=>[Mr(this,Xa,yi).call(this,a,t),Mr(this,Xa,yi).call(this,s,t)]));if(e instanceof Set)return new Set([...e].map(a=>Mr(this,Xa,yi).call(this,a,t)));if(qE in e)return t.functions.deserialize(e[qE],t);if(!U$(e))return e;const r={};for(const a of Object.keys(e))a===$$?r[Symbol.asyncIterator]=()=>r:r[a]=Mr(this,Xa,yi).call(this,e[a],t);return r}return e};var Kc,Tl,vi,qS,R6,XS,A6;class Gye{constructor(t,{imports:n,exports:r,functions:a=new Bye,serialization:s=new Vye,signal:i}={}){bo(this,vi),bo(this,Kc),bo(this,Tl,new Map);var c,u,f,m;this.messages=t,KS(this,Kc,i?new zye(i):new AbortController),this.exports=r??{},this.imports=Wye(Mr(this,vi,R6).bind(this),n),this.functions=a,this.serialization=s,(u=(c=this.functions).start)==null||u.call(c,this),(m=(f=this.serialization).start)==null||m.call(f,this),this.signal.addEventListener("abort",()=>{for(const h of Un(this,Tl).keys())Mr(this,vi,XS).call(this,h,void 0,new P$);Un(this,Tl).clear()},{once:!0}),t.listen(async h=>{if(!(Array.isArray(h)&&typeof h[0]=="number"))return;const g=h;switch(g[0]){case _6:{const[,y,x,E]=g,w=this.exports[x]??(()=>{throw new Error(`No '${x}' method is exported from this thread`)});await Mr(this,vi,qS).call(this,w,E,(_,S,T)=>{this.messages.send([L$,y,_,S],T)});break}case T6:{const[,y,x,E]=g,w=this.functions.get(x,this)??Kye;await Mr(this,vi,qS).call(this,w,E,(_,S,T)=>{this.messages.send([M$,y,_,S],T)});break}case L$:case M$:{Mr(this,vi,XS).call(this,...g.slice(1));break}case N6:{const y=g[1];this.functions.release(y,this);break}}},{signal:this.signal})}get signal(){return Un(this,Kc).signal}get closed(){return Un(this,Kc).signal.aborted}close(){Un(this,Kc).abort()}call(t,n){if(this.closed)return Promise.reject(new P$);const r=[],a=this.serialization.serialize(n,this,r),s=k6(),i=Mr(this,vi,A6).call(this,s);return t(s,a,r),i}}Kc=new WeakMap,Tl=new WeakMap,vi=new WeakSet,qS=async function(e,t,n){try{const r=this.functions.call?await this.functions.call(e,t,this):await e(...this.serialization.deserialize(t,this)),a=[],s=this.serialization.serialize(r,this,a);n(s,void 0,a)}catch(r){n(void 0,this.serialization.serialize(r,this))}},R6=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,r,a)=>{this.messages.send([_6,n,e,r],a)},t)}catch(n){return Promise.reject(n)}}},XS=function(...e){const t=e[0],n=Un(this,Tl).get(t);n&&(n(...e),Un(this,Tl).delete(t))},A6=function(e){const t=new Promise((n,r)=>{Un(this,Tl).set(e,(a,s,i)=>{i==null?n(this.serialization.deserialize(s,this)):r(this.serialization.deserialize(i,this))})});return Object.defineProperty(t,Symbol.asyncIterator,{async*value(){const n=await t;Object.defineProperty(n,Symbol.asyncIterator,{value:()=>n}),yield*n}}),t};function Wye(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 r=new Map;n=new Proxy({},{get(a,s){if(r.has(s))return r.get(s);const i=e(s);return r.set(s,i),i}})}else{n={};for(const r of t)Object.defineProperty(n,r,{value:e(r),writable:!1,configurable:!0,enumerable:!0})}return n}function Kye(){throw new Error("You attempted to call a function that is not stored. It may have already been released.")}const Yye="quilt.threads.ping",z$="quilt.threads.pong";function Zye(e,{targetOrigin:t="*"}={}){let n=!1;const r=function(s,i){e.postMessage(s,t,i)},a=new Promise(s=>{const i=new AbortController;globalThis.window.addEventListener("message",c=>{c.source===e&&c.data===z$&&(n=!0,i.abort(),s())},{signal:i.signal}),i.signal.addEventListener("abort",()=>s(),{once:!0}),r(Yye)});return{send(s,i){return n?r(s,i):a.then(()=>{if(n)return r(s,i)})},listen(s,{signal:i}){self.addEventListener("message",c=>{c.source===e&&c.data!==z$&&s(c.data)},{signal:i})}}}class qye extends Gye{constructor(t,{targetOrigin:n="*",...r}={}){super(Zye(t.contentWindow,{targetOrigin:n}),r),this.iframe=t}}const I6=ce.forwardRef(({content:e,children:t,...n},r)=>d.jsx("span",{ref:r,...n,children:e||t}));I6.displayName="UIText";const O6=ce.forwardRef(({label:e,onPress:t,onClick:n,children:r,...a},s)=>d.jsx("button",{ref:s,onClick:i=>{t&&t(),n&&n(i)},style:{padding:"8px 16px",backgroundColor:"#007bff",color:"white",border:"none",borderRadius:"4px",cursor:"pointer"},...a,children:e||r}));O6.displayName="UIButton";const D6=ce.forwardRef(({direction:e="vertical",spacing:t="8",align:n="stretch",justify:r="flex-start",children:a,...s},i)=>d.jsx("div",{ref:i,style:{display:"flex",flexDirection:e==="horizontal"?"row":"column",gap:`${t}px`,alignItems:n,justifyContent:r},...s,children:a}));D6.displayName="UIStack";const L6=ce.forwardRef(({src:e,alt:t,width:n,height:r,children:a,...s},i)=>d.jsx("img",{ref:i,src:e,alt:t,width:n,height:r,style:{maxWidth:"100%",height:"auto",borderRadius:"8px",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.1)"},...s}));L6.displayName="UIImage";const M1={name:"basic",elements:[{tagName:"ui-text",component:I6,propMapping:{content:"content"},eventMapping:{}},{tagName:"ui-button",component:O6,propMapping:{label:"label"},eventMapping:{press:"onPress"}},{tagName:"ui-stack",component:D6,propMapping:{direction:"direction",spacing:"spacing",align:"align",justify:"justify"},eventMapping:{}},{tagName:"ui-image",component:L6,propMapping:{src:"src",alt:"alt",width:"width",height:"height"},eventMapping:{}}]},Xye=({receiver:e})=>{const t=v.useRef(null);return v.useEffect(()=>{if(t.current)return e.connect(t.current),()=>{e.disconnect()}},[e]),d.jsx("div",{ref:t,"data-testid":"standard-dom-renderer-container"})},Jye=({resource:e,library:t,remoteElements:n=[],onUIAction:r})=>{const a=v.useRef(null),s=v.useRef(null),[i,c]=v.useState(null),u=v.useMemo(()=>(e.mimeType||"").includes("framework=react")?"react":"webcomponents",[e.mimeType]),f=`${t?.name}-${u}`,{receiver:m,components:h}=v.useMemo(()=>{switch(u){case"react":{const y=new Rye,x=t||M1,E=new Map;return x&&x.elements.forEach(w=>{const _=Mye(w.component);E.set(w.tagName,_)}),{receiver:y,components:E}}case"webcomponents":default:return{receiver:new Aye,components:null}}},[e,t,n]);v.useEffect(()=>{function y(x){var E;if(a.current&&x.source===a.current.contentWindow){const w=x.data;if(!w)return;(E=r?.(w))==null||E.catch(_=>{console.error("Error handling UI action result in RemoteDOMResourceRenderer:",_)})}}return window.addEventListener("message",y),()=>window.removeEventListener("message",y)},[r]),v.useEffect(()=>{const y=s.current;return s.current=null,()=>{y?.close()}},[f]);const g=()=>{const y=a.current;if(!y||s.current)return;const x=new qye(y);s.current=x;const{code:E,error:w}=wye(e);if(w){c(w);return}if(E&&m!=null&&m.connection){const _={code:E,remoteElements:n,useReactRenderer:u==="react",componentLibrary:t?.name};x.imports.render(_,m.connection).catch(S=>console.error("Error calling remote render:",S))}};return i?d.jsx("p",{className:"text-red-500",children:i}):d.jsxs(d.Fragment,{children:[d.jsx("iframe",{ref:a,srcDoc:Uye,sandbox:"allow-scripts",style:{display:"none"},title:"Remote DOM Sandbox",onLoad:g},f),u==="react"&&h?d.jsx(Pye,{receiver:m,components:h}):d.jsx(Xye,{receiver:m})]})};function Qye(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 j1=e=>{const{resource:t,onUIAction:n,supportedContentTypes:r,htmlProps:a,remoteDomProps:s}=e,i=Qye(t);if(r&&i&&!r.includes(i))return d.jsxs("p",{className:"text-red-500",children:["Unsupported content type: ",i,"."]});switch(i){case"rawHtml":case"externalUrl":return d.jsx(y6,{resource:t,onUIAction:n,...a});case"remoteDom":return d.jsx(Jye,{resource:t,onUIAction:n,library:s?.library||M1,...s});default:return d.jsx("p",{className:"text-red-500",children:"Unsupported resource type."})}};j1.displayName="UIResourceRenderer";const eve={tagName:"ui-button",remoteAttributes:["label"],remoteEvents:["click","press"]},tve={tagName:"ui-text",remoteAttributes:["content"]},nve={tagName:"ui-stack",remoteAttributes:["direction","spacing","align","justify"]},rve={tagName:"ui-image",remoteAttributes:["src","alt","width","height"]},ave=v.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://")?d.jsx("div",{className:"my-4 p-0 border h-[350px] rounded-2xl border-zinc-200 overflow-hidden bg-card",children:d.jsx(j1,{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 F$({toolName:e,toolArgs:t,result:n,serverId:r,readResource:a,toolMeta:s}){const[i,c]=v.useState(null);v.useEffect(()=>{console.log("[ToolResultRenderer] Rendering:",{toolName:e,hasToolMeta:!!s,outputTemplate:s?.["openai/outputTemplate"],hasResult:!!n,hasServerId:!!r,hasReadResource:!!a})},[e,s,n,r,a]);const u=v.useMemo(()=>{if(typeof n=="string")try{return JSON.parse(n)}catch(y){return console.error("[ToolResultRenderer] Failed to parse result:",y),n}return n},[n]),f=v.useMemo(()=>!!s?.["openai/outputTemplate"],[s]),m=v.useMemo(()=>!!(u?.content&&Array.isArray(u.content)&&u.content.some(y=>y.type==="resource"&&y.resource?.uri?.startsWith("ui://")&&y.resource?.mimeType==="text/html+skybridge")),[u]),h=v.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(v.useEffect(()=>{if(h){c(h);return}if(f&&s&&a){const y=s["openai/outputTemplate"];console.log("[ToolResultRenderer] Fetching resource for Apps SDK tool:",y),a(y).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,f,s,a]),(f||m)&&i&&r&&a)return d.jsx(A1,{componentUrl:i.uri,toolName:e,toolArgs:t,toolResult:u,serverId:r,readResource:a,noWrapper:!0,className:"my-4",showConsole:!1});if((f||m)&&!i)return d.jsx("div",{className:"flex items-center justify-center w-full h-[200px] rounded border",children:d.jsx(_o,{className:"size-5"})});if(f&&(!r||!a))return console.error("[ToolResultRenderer] Apps SDK tool but missing serverId or readResource:",{toolName:e,hasServerId:!!r,hasReadResource:!!a}),d.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:d.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 y of u.content)y.type==="resource"&&y.resource?.uri?.startsWith("ui://")&&y.resource?.mimeType!=="text/html+skybridge"&&g.push(y.resource);return g.length>0?d.jsx(d.Fragment,{children:g.map(y=>d.jsx(ave,{resource:y},`${e}-mcp-ui-${y.uri}`))}):(console.log("[ToolResultRenderer] Not rendering (no UI resources found):",{toolName:e,isAppsSdkTool:f,hasAppsSdkComponent:m,hasResourceData:!!i,contentLength:u?.content?.length}),null)}function ove({content:e,timestamp:t}){return!e||e.length===0?null:d.jsx("div",{className:"flex items-start gap-3 justify-end group/user-message",children:d.jsxs("div",{className:"flex-1 min-w-0 flex flex-col items-end",children:[d.jsx("div",{className:"bg-zinc-200 dark:bg-zinc-800 text-primary rounded-3xl px-4 py-2 max-w-[80%] break-words",children:d.jsx("p",{className:"text-base leading-7 font-sans text-start break-words",children:e})}),t&&d.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:new Date(t).toLocaleTimeString()})]})})}const sve=v.memo(({messages:e,isLoading:t,serverId:n,readResource:r,tools:a})=>{const s=v.useRef(null),i=f=>a?.find(h=>h.name===f)?._meta;v.useEffect(()=>{e.length>0&&s.current&&s.current.scrollIntoView({behavior:t?"auto":"smooth",block:"start"})},[e.length,t]);const c=t&&(()=>{if(e.length===0)return!0;const f=e[e.length-1];if(f.role==="user")return!0;if(f.role==="assistant"){const m=typeof f.content=="string"?f.content:Array.isArray(f.content)?f.content.map(g=>typeof g=="string"?g:g.text||JSON.stringify(g)).join(""):JSON.stringify(f.content);return!(m&&m.trim().length>0)}return!1})(),u=f=>{if(!t)return!1;const m=e[e.length-1];return f.id===m.id&&m.role==="assistant"};return d.jsxs("div",{className:"space-y-6 max-w-3xl mx-auto px-2",children:[e.map(f=>{const m=typeof f.content=="string"?f.content:Array.isArray(f.content)?f.content.map(h=>typeof h=="string"?h:h.text||JSON.stringify(h)).join(""):JSON.stringify(f.content);return f.role==="user"?d.jsx(ove,{content:m,timestamp:f.timestamp},f.id):f.role==="assistant"?d.jsx("div",{className:"space-y-4",children:f.parts&&f.parts.length>0?f.parts.map((h,g)=>{const y=h.type==="text"?`${f.id}-text-${g}-${h.text?.slice(0,20)}`:`${f.id}-tool-${h.toolInvocation?.toolName}-${g}`;return h.type==="text"?d.jsx(_$,{content:h.text||"",timestamp:g===f.parts.length-1?f.timestamp:void 0,_isStreaming:u(f)},y):h.type==="tool-invocation"&&h.toolInvocation?d.jsxs("div",{children:[d.jsx(T$,{toolName:h.toolInvocation.toolName,args:h.toolInvocation.args,result:h.toolInvocation.result,state:h.toolInvocation.result?"result":"call"}),h.toolInvocation.result&&d.jsx(F$,{toolName:h.toolInvocation.toolName,toolArgs:h.toolInvocation.args,result:h.toolInvocation.result,serverId:n,readResource:r,toolMeta:i(h.toolInvocation.toolName)})]},y):null}):d.jsxs(d.Fragment,{children:[d.jsx(_$,{content:m,timestamp:f.timestamp,_isStreaming:u(f)}),f.toolCalls&&f.toolCalls.length>0&&d.jsx("div",{className:"space-y-2",children:f.toolCalls.map(h=>{const g=`${f.id}-${h.toolName}-${JSON.stringify(h.args).slice(0,50)}`;return d.jsxs("div",{children:[d.jsx(T$,{toolName:h.toolName,args:h.args,result:h.result,state:h.result?"result":"call"}),h.result&&d.jsx(F$,{toolName:h.toolName,toolArgs:h.args,result:h.result,serverId:n,readResource:r,toolMeta:i(h.toolName)})]},g)})})]})},f.id):null}),c&&d.jsx("div",{className:"flex items-start gap-3",children:d.jsx("div",{className:"flex-1",children:d.jsx("div",{className:"rounded-lg p-4 max-w-fit",children:d.jsx("div",{className:"flex items-center gap-2",children:d.jsx("span",{className:"text-sm",children:d.jsx(_he,{duration:2,spread:1,children:"Thinking..."})})})})})}),d.jsx("div",{ref:s})]})});function M6(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(16)}function ive({mcpServerUrl:e,llmConfig:t,authConfig:n,isConnected:r}){const[a,s]=v.useState([]),[i,c]=v.useState(!1),u=v.useCallback(async m=>{if(!m.trim()||!t||!r)return;const h={id:`user-${Date.now()}`,role:"user",content:m.trim(),timestamp:Date.now()};s(g=>[...g,h]),c(!0);try{let g=n;if(n?.type==="oauth")try{const R="mcp:auth",C=M6(e),I=`${R}_${C}_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(R){console.warn("Failed to retrieve OAuth tokens:",R)}const y=await fetch("/inspector/api/chat/stream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mcpServerUrl:e,llmConfig:t,authConfig:g,messages:[...a,h].map(R=>({role:R.role,content:R.content}))})});if(!y.ok)throw new Error(`HTTP error! status: ${y.status}`);const x=`assistant-${Date.now()}`;let E="";const w=[];s(R=>[...R,{id:x,role:"assistant",content:"",timestamp:Date.now(),parts:[]}]);const _=y.body?.getReader(),S=new TextDecoder;if(!_)throw new Error("No response body");let T="";for(;;){const{done:R,value:C}=await _.read();if(R)break;T+=S.decode(C,{stream:!0});const I=T.split(`
1658
- `);T=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"){E+=O.content;const j=w[w.length-1];j&&j.type==="text"?j.text=E:w.push({type:"text",text:E}),console.log("[Parts after text]",w.length,"parts, text length:",E.length),s(U=>U.map(B=>B.id===x?{...B,parts:[...w]}:B))}else if(O.type==="tool-call")E&&(E=""),w.push({type:"tool-invocation",toolInvocation:{toolName:O.toolName,args:O.args,state:"pending"}}),console.log("[Parts after tool-call]",w.length,"parts, tool:",O.toolName),s(j=>j.map(U=>U.id===x?{...U,parts:[...w]}:U));else if(O.type==="tool-result"){const j=w.find(U=>U.type==="tool-invocation"&&U.toolInvocation?.toolName===O.toolName&&!U.toolInvocation?.result);j&&j.toolInvocation?(j.toolInvocation.result=O.result,j.toolInvocation.state="result",console.log("[Parts after tool-result]",w.length,"parts, updated:",O.toolName),s(U=>U.map(B=>B.id===x?{...B,parts:[...w]}:B))):console.warn("[tool-result] Could not find matching tool part for",O.toolName)}else if(O.type==="done")console.log("[Done] Final parts:",w.length),s(j=>j.map(U=>U.id===x?{...U,parts:[...w],content:""}:U));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 y="Unknown error occurred";if(g instanceof Error){y=g.message;const E=g;E.status&&(y=`HTTP ${E.status}: ${y}`),(E.code===401||y.includes("401")||y.includes("Unauthorized"))&&(y="Authentication failed (401). Check your Authorization header in the connection settings.")}const x={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${y}`,timestamp:Date.now()};s(E=>[...E,x])}finally{c(!1)}},[t,r,e,a,n]),f=v.useCallback(()=>{s([])},[]);return{messages:a,isLoading:i,sendMessage:u,clearMessages:f}}function lve({connection:e,llmConfig:t,isConnected:n,readResource:r}){const[a,s]=v.useState([]),[i,c]=v.useState(!1),u=v.useRef(null),f=v.useRef(null),m=v.useRef(null),h=v.useCallback(async y=>{if(!y.trim()||!t||!n)return;const x={id:`user-${Date.now()}`,role:"user",content:y.trim(),timestamp:Date.now()};s(_=>[..._,x]),c(!0),u.current=new AbortController;const E=Date.now();let w=0;try{const _=`assistant-${Date.now()}`;let S="";const T=[];if(s(R=>[...R,{id:_,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 R;if(t.provider==="openai"){const{ChatOpenAI:C}=await rr(async()=>{const{ChatOpenAI:I}=await import("./index-D3h9OtLD.js");return{ChatOpenAI:I}},__vite__mapDeps([5,6,7,3,8,9]));R=new C({model:t.model,apiKey:t.apiKey})}else if(t.provider==="anthropic"){const{ChatAnthropic:C}=await rr(async()=>{const{ChatAnthropic:I}=await import("./index-B-y3tpvd.js");return{ChatAnthropic:I}},__vite__mapDeps([10,7,6,3]));R=new C({model:t.model,apiKey:t.apiKey})}else if(t.provider==="google"){const{ChatGoogleGenerativeAI:C}=await rr(async()=>{const{ChatGoogleGenerativeAI:I}=await import("./index-DVE3PVDT.js");return{ChatGoogleGenerativeAI:I}},__vite__mapDeps([11,7,6,3,9]));R=new C({model:t.model,apiKey:t.apiKey})}else throw new Error(`Unsupported LLM provider: ${t.provider}`);m.current={instance:R,provider:t.provider,model:t.model,apiKey:t.apiKey}}if(!f.current||f.current.llm!==m.current.instance){const{MCPAgent:R}=await rr(async()=>{const{MCPAgent:C}=await import("./browser-Cx0JHZqb.js");return{MCPAgent:C}},__vite__mapDeps([12,8,6,7,3,9]));f.current=new R({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 f.current.initialize()}else console.log("[useChatMessagesClientSide] Reusing existing agent. History length:",f.current.conversationHistory?.length);for await(const R of f.current.streamEvents(y,10,!1,void 0)){if(u.current?.signal.aborted)break;if(R.event==="on_chat_model_stream"&&R.data?.chunk?.text){const C=R.data.chunk.text;if(typeof C=="string"&&C.length>0){S+=C;const I=T[T.length-1];I&&I.type==="text"?I.text=S:T.push({type:"text",text:S}),s(A=>A.map(O=>O.id===_?{...O,parts:[...T]}:O))}}else if(R.event==="on_tool_start"){S&&(S="");let C={};R.data?.input?C=R.data.input:R.data?.tool_input?C=R.data.tool_input:R.data&&(C=R.data),console.log("[useChatMessagesClientSide] on_tool_start:",{toolName:R.name,eventData:R.data,extractedArgs:C}),w++,T.push({type:"tool-invocation",toolInvocation:{toolName:R.name||"unknown",args:C,state:"pending"}}),s(I=>I.map(A=>A.id===_?{...A,parts:[...T]}:A))}else if(R.event==="on_tool_end"){const C=T.find(I=>I.type==="tool-invocation"&&I.toolInvocation?.toolName===R.name&&!I.toolInvocation?.result);if(console.log("[useChatMessagesClientSide] on_tool_end event:",{toolName:R.name,hasToolPart:!!C,output:R.data?.output}),C&&C.toolInvocation){let I=R.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}C.toolInvocation.result=I,C.toolInvocation.state="result";const A=I?._meta?.["openai/outputTemplate"];if(console.log("[useChatMessagesClientSide] Tool result:",{toolName:R.name,hasMeta:!!I?._meta,hasStructuredContent:!!I?.structuredContent,appsSdkUri:A}),A&&typeof A=="string"&&r){console.log("[useChatMessagesClientSide] Detected Apps SDK component, fetching resource:",A);try{const O=await r(A);console.log("[useChatMessagesClientSide] Resource fetched:",O);const j=I?.structuredContent||null;if(O?.contents&&Array.isArray(O.contents)){const U=O.contents.map(W=>({type:"resource",resource:W}));console.log("[useChatMessagesClientSide] Created MCP resources:",U);const B={...I,content:[...I.content||[],...U],structuredContent:j};C.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)}}s(O=>O.map(j=>j.id===_?{...j,parts:[...T]}:j))}}}s(R=>R.map(C=>C.id===_?{...C,parts:[...T],content:""}:C)),t&&Tr.getInstance().capture(new yP({serverId:e.url,provider:t.provider,model:t.model,messageCount:a.length+1,toolCallsCount:w,success:!0,executionMode:"client-side",duration:Date.now()-E})).catch(()=>{})}catch(_){console.error("Client-side agent error:",_);let S="Unknown error occurred";if(_ instanceof Error){S=_.message;const R=_;R.status&&(S=`HTTP ${R.status}: ${S}`),(R.code===401||S.includes("401")||S.includes("Unauthorized"))&&(S="Authentication failed (401). Check your Authorization header in the connection settings.")}t&&Tr.getInstance().capture(new yP({serverId:e.url,provider:t.provider,model:t.model,messageCount:a.length+1,toolCallsCount:w,success:!1,executionMode:"client-side",duration:Date.now()-E,error:S})).catch(()=>{});const T={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${S}`,timestamp:Date.now()};s(R=>[...R,T])}finally{c(!1),u.current=null}},[e,t,n,a,r]),g=v.useCallback(()=>{s([]),f.current&&f.current.clearConversationHistory()},[]);return{messages:a,isLoading:i,sendMessage:h,clearMessages:g}}const B$={openai:"gpt-4o",anthropic:"claude-haiku-4-5-20251001",google:"gemini-2.5-flash"};function j6({mcpServerUrl:e}){const[t,n]=v.useState(null),[r,a]=v.useState(null),[s,i]=v.useState(!1),[c,u]=v.useState("openai"),[f,m]=v.useState(""),[h,g]=v.useState(B$.openai),y=v.useCallback(()=>{const j=localStorage.getItem("mcp-inspector-api-keys");if(j)try{return JSON.parse(j)}catch(U){return console.error("Failed to load API keys:",U),{}}return{}},[]),x=v.useCallback(j=>{localStorage.setItem("mcp-inspector-api-keys",JSON.stringify(j))},[]),[E,w]=v.useState("none"),[_,S]=v.useState(""),[T,R]=v.useState(""),[C,I]=v.useState("");v.useEffect(()=>{const j=localStorage.getItem("mcp-inspector-llm-config"),U=y();if(j)try{const B=JSON.parse(j);n(B),u(B.provider),m(U[B.provider]||B.apiKey||""),g(B.model)}catch(B){console.error("Failed to load LLM config:",B)}},[y]),v.useEffect(()=>{const j=localStorage.getItem("mcp-inspector-auth-config");if(j)try{const U=JSON.parse(j);a(U),w(U.type),U.username&&S(U.username),U.password&&R(U.password),U.token&&I(U.token)}catch(U){console.error("Failed to load auth config:",U)}else try{const U="mcp:auth",B=M6(e),W=`${U}_${B}_tokens`;localStorage.getItem(W)&&(a({type:"oauth"}),w("oauth"))}catch(U){console.error("Failed to check for OAuth tokens:",U)}},[e]),v.useEffect(()=>{g(B$[c]);const j=y();m(j[c]||"")},[c,y]);const A=v.useCallback(()=>{if(!f.trim())return;const j=y();j[c]=f,x(j);const U={provider:c,apiKey:f,model:h},B={type:E,...E==="basic"&&{username:_.trim(),password:T.trim()},...E==="bearer"&&{token:C.trim()}};n(U),a(B),localStorage.setItem("mcp-inspector-llm-config",JSON.stringify(U)),localStorage.setItem("mcp-inspector-auth-config",JSON.stringify(B)),i(!1)},[c,f,h,E,_,T,C,y,x]),O=v.useCallback(()=>{n(null),a(null);const j=y();delete j[c],x(j),m(""),S(""),R(""),I(""),w("none"),localStorage.removeItem("mcp-inspector-llm-config"),localStorage.removeItem("mcp-inspector-auth-config")},[c,y,x]);return{llmConfig:t,authConfig:r,configDialogOpen:s,setConfigDialogOpen:i,tempProvider:c,setTempProvider:u,tempApiKey:f,setTempApiKey:m,tempModel:h,setTempModel:g,tempAuthType:E,saveLLMConfig:A,clearConfig:O}}function cve({connection:e,isConnected:t,useClientSide:n=!0,readResource:r}){const[a,s]=v.useState(""),i=v.useRef(null),{llmConfig:c,authConfig:u,configDialogOpen:f,setConfigDialogOpen:m,tempProvider:h,setTempProvider:g,tempApiKey:y,setTempApiKey:x,tempModel:E,setTempModel:w,saveLLMConfig:_,clearConfig:S}=j6({mcpServerUrl:e.url}),T={connection:e,llmConfig:c,isConnected:t,readResource:r},R=ive({mcpServerUrl:e.url,llmConfig:c,authConfig:u,isConnected:t}),C=lve(T),{messages:I,isLoading:A,sendMessage:O,clearMessages:j}=n?C:R;LH({onNewChat:j}),v.useEffect(()=>{c&&I.length===0&&i.current&&i.current.focus()},[c,I.length]),v.useEffect(()=>{!A&&I.length>0&&i.current&&i.current.focus()},[A,I.length]);const U=v.useCallback(()=>{a.trim()&&(O(a),s(""))},[a,O]),B=v.useCallback(J=>{J.key==="Enter"&&!J.shiftKey&&(J.preventDefault(),U())},[U]),W=v.useCallback(()=>{S(),j()},[S,j]);return c&&I.length===0?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx("div",{className:"absolute top-4 right-4 z-10",children:d.jsx(SS,{open:f,onOpenChange:m,tempProvider:h,tempModel:E,tempApiKey:y,onProviderChange:g,onModelChange:w,onApiKeyChange:x,onSave:_,onClear:W,showClearButton:!0,buttonLabel:"Change API Key"})}),d.jsx(xhe,{mcpServerUrl:e.url,inputValue:a,isConnected:t,isLoading:A,textareaRef:i,llmConfig:c,onInputChange:s,onKeyDown:B,onSubmit:J=>{J.preventDefault(),U()},onConfigDialogOpenChange:m})]}):d.jsxs("div",{className:"flex flex-col h-full relative",children:[d.jsx(vhe,{llmConfig:c,hasMessages:I.length>0,configDialogOpen:f,onConfigDialogOpenChange:m,onClearChat:j,tempProvider:h,tempModel:E,tempApiKey:y,onProviderChange:g,onModelChange:w,onApiKeyChange:x,onSaveConfig:_,onClearConfig:W}),d.jsx("div",{className:"flex-1 overflow-y-auto p-2 sm:p-4 pt-[80px] sm:pt-[100px]",children:c?d.jsx(sve,{messages:I,isLoading:A,serverId:e.url,readResource:r,tools:e.tools}):d.jsx(She,{onConfigureClick:()=>m(!0)})}),c&&d.jsx(whe,{inputValue:a,isConnected:t,isLoading:A,textareaRef:i,onInputChange:s,onKeyDown:B,onSendMessage:U})]})}const wv=v.createContext(null);wv.displayName="PanelGroupContext";const qn={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"},P1=10,Cl=v.useLayoutEffect,H$=id.useId,uve=typeof H$=="function"?H$:()=>null;let dve=0;function U1(e=null){const t=uve(),n=v.useRef(e||t||null);return n.current===null&&(n.current=""+dve++),e??n.current}function P6({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:a,forwardedRef:s,id:i,maxSize:c,minSize:u,onCollapse:f,onExpand:m,onResize:h,order:g,style:y,tagName:x="div",...E}){const w=v.useContext(wv);if(w===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:_,expandPanel:S,getPanelSize:T,getPanelStyle:R,groupId:C,isPanelCollapsed:I,reevaluatePanelConstraints:A,registerPanel:O,resizePanel:j,unregisterPanel:U}=w,B=U1(i),W=v.useRef({callbacks:{onCollapse:f,onExpand:m,onResize:h},constraints:{collapsedSize:n,collapsible:r,defaultSize:a,maxSize:c,minSize:u},id:B,idIsFromProps:i!==void 0,order:g});v.useRef({didLogMissingDefaultSizeWarning:!1}),Cl(()=>{const{callbacks:ee,constraints:re}=W.current,F={...re};W.current.id=B,W.current.idIsFromProps=i!==void 0,W.current.order=g,ee.onCollapse=f,ee.onExpand=m,ee.onResize=h,re.collapsedSize=n,re.collapsible=r,re.defaultSize=a,re.maxSize=c,re.minSize=u,(F.collapsedSize!==re.collapsedSize||F.collapsible!==re.collapsible||F.maxSize!==re.maxSize||F.minSize!==re.minSize)&&A(W.current,F)}),Cl(()=>{const ee=W.current;return O(ee),()=>{U(ee)}},[g,B,O,U]),v.useImperativeHandle(s,()=>({collapse:()=>{_(W.current)},expand:ee=>{S(W.current,ee)},getId(){return B},getSize(){return T(W.current)},isCollapsed(){return I(W.current)},isExpanded(){return!I(W.current)},resize:ee=>{j(W.current,ee)}}),[_,S,T,I,B,j]);const J=R(W.current,a);return v.createElement(x,{...E,children:e,className:t,id:B,style:{...J,...y},[qn.groupId]:C,[qn.panel]:"",[qn.panelCollapsible]:r||void 0,[qn.panelId]:B,[qn.panelSize]:parseFloat(""+J.flexGrow).toFixed(1)})}const U6=v.forwardRef((e,t)=>v.createElement(P6,{...e,forwardedRef:t}));P6.displayName="Panel";U6.displayName="forwardRef(Panel)";let JS=null,ub=-1,_i=null;function fve(e,t,n){const r=(t&H6)!==0,a=(t&V6)!==0,s=(t&G6)!==0,i=(t&W6)!==0;if(t){if(r)return s?"se-resize":i?"ne-resize":"e-resize";if(a)return s?"sw-resize":i?"nw-resize":"w-resize";if(s)return"s-resize";if(i)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function pve(){_i!==null&&(document.head.removeChild(_i),JS=null,_i=null,ub=-1)}function XE(e,t,n){var r,a;const s=fve(e,t);if(JS!==s){if(JS=s,_i===null&&(_i=document.createElement("style"),document.head.appendChild(_i)),ub>=0){var i;(i=_i.sheet)===null||i===void 0||i.removeRule(ub)}ub=(r=(a=_i.sheet)===null||a===void 0?void 0:a.insertRule(`*{cursor: ${s} !important;}`))!==null&&r!==void 0?r:-1}}function $6(e){return e.type==="keydown"}function z6(e){return e.type.startsWith("pointer")}function F6(e){return e.type.startsWith("mouse")}function Ev(e){if(z6(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(F6(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function mve(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function hve(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 gve(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:W$(e),b:W$(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;Ct(r,"Stacking order can only be calculated for elements with a common ancestor");const a={a:G$(V$(n.a)),b:G$(V$(n.b))};if(a.a===a.b){const s=r.childNodes,i={a:n.a.at(-1),b:n.b.at(-1)};let c=s.length;for(;c--;){const u=s[c];if(u===i.a)return 1;if(u===i.b)return-1}}return Math.sign(a.a-a.b)}const bve=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function yve(e){var t;const n=getComputedStyle((t=B6(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function vve(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||yve(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"||bve.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function V$(e){let t=e.length;for(;t--;){const n=e[t];if(Ct(n,"Missing node"),vve(n))return n}return null}function G$(e){return e&&Number(getComputedStyle(e).zIndex)||0}function W$(e){const t=[];for(;e;)t.push(e),e=B6(e);return t}function B6(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const H6=1,V6=2,G6=4,W6=8,wve=mve()==="coarse";let vo=[],yu=!1,Ti=new Map,xv=new Map;const Lp=new Set;function Eve(e,t,n,r,a){var s;const{ownerDocument:i}=t,c={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:a},u=(s=Ti.get(i))!==null&&s!==void 0?s:0;return Ti.set(i,u+1),Lp.add(c),ly(),function(){var m;xv.delete(e),Lp.delete(c);const h=(m=Ti.get(i))!==null&&m!==void 0?m:1;if(Ti.set(i,h-1),ly(),h===1&&Ti.delete(i),vo.includes(c)){const g=vo.indexOf(c);g>=0&&vo.splice(g,1),Sv(),a("up",!0,null)}}}function xve(e){const{target:t}=e,{x:n,y:r}=Ev(e);yu=!0,$1({target:t,x:n,y:r}),ly(),vo.length>0&&(cy("down",e),Sv(),e.preventDefault(),K6(t)||e.stopImmediatePropagation())}function JE(e){const{x:t,y:n}=Ev(e);if(yu&&e.type!=="pointerleave"&&e.buttons===0&&(yu=!1,cy("up",e)),!yu){const{target:r}=e;$1({target:r,x:t,y:n})}cy("move",e),Sv(),vo.length>0&&e.preventDefault()}function QE(e){const{target:t}=e,{x:n,y:r}=Ev(e);xv.clear(),yu=!1,vo.length>0&&(e.preventDefault(),K6(t)||e.stopImmediatePropagation()),cy("up",e),$1({target:t,x:n,y:r}),Sv(),ly()}function K6(e){let t=e;for(;t;){if(t.hasAttribute(qn.resizeHandle))return!0;t=t.parentElement}return!1}function $1({target:e,x:t,y:n}){vo.splice(0);let r=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(r=e),Lp.forEach(a=>{const{element:s,hitAreaMargins:i}=a,c=s.getBoundingClientRect(),{bottom:u,left:f,right:m,top:h}=c,g=wve?i.coarse:i.fine;if(t>=f-g&&t<=m+g&&n>=h-g&&n<=u+g){if(r!==null&&document.contains(r)&&s!==r&&!s.contains(r)&&!r.contains(s)&&gve(r,s)>0){let x=r,E=!1;for(;x&&!x.contains(s);){if(hve(x.getBoundingClientRect(),c)){E=!0;break}x=x.parentElement}if(E)return}vo.push(a)}})}function ex(e,t){xv.set(e,t)}function Sv(){let e=!1,t=!1;vo.forEach(r=>{const{direction:a}=r;a==="horizontal"?e=!0:t=!0});let n=0;xv.forEach(r=>{n|=r}),e&&t?XE("intersection",n):e?XE("horizontal",n):t?XE("vertical",n):pve()}let tx;function ly(){var e;(e=tx)===null||e===void 0||e.abort(),tx=new AbortController;const t={capture:!0,signal:tx.signal};Lp.size&&(yu?(vo.length>0&&Ti.forEach((n,r)=>{const{body:a}=r;n>0&&(a.addEventListener("contextmenu",QE,t),a.addEventListener("pointerleave",JE,t),a.addEventListener("pointermove",JE,t))}),Ti.forEach((n,r)=>{const{body:a}=r;a.addEventListener("pointerup",QE,t),a.addEventListener("pointercancel",QE,t)})):Ti.forEach((n,r)=>{const{body:a}=r;n>0&&(a.addEventListener("pointerdown",xve,t),a.addEventListener("pointermove",JE,t))}))}function cy(e,t){Lp.forEach(n=>{const{setResizeHandlerState:r}=n,a=vo.includes(n);r(e,a,t)})}function Sve(){const[e,t]=v.useState(0);return v.useCallback(()=>t(n=>n+1),[])}function Ct(e,t){if(!e)throw console.error(t),Error(t)}function $l(e,t,n=P1){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function Ss(e,t,n=P1){return $l(e,t,n)===0}function Pa(e,t,n){return $l(e,t,n)===0}function _ve(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++){const a=e[r],s=t[r];if(!Pa(a,s,n))return!1}return!0}function cu({panelConstraints:e,panelIndex:t,size:n}){const r=e[t];Ct(r!=null,`Panel constraints not found for index ${t}`);let{collapsedSize:a=0,collapsible:s,maxSize:i=100,minSize:c=0}=r;if($l(n,c)<0)if(s){const u=(a+c)/2;$l(n,u)<0?n=a:n=c}else n=c;return n=Math.min(i,n),n=parseFloat(n.toFixed(P1)),n}function Ff({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:r,prevLayout:a,trigger:s}){if(Pa(e,0))return t;const i=[...t],[c,u]=r;Ct(c!=null,"Invalid first pivot index"),Ct(u!=null,"Invalid second pivot index");let f=0;if(s==="keyboard"){{const h=e<0?u:c,g=n[h];Ct(g,`Panel constraints not found for index ${h}`);const{collapsedSize:y=0,collapsible:x,minSize:E=0}=g;if(x){const w=t[h];if(Ct(w!=null,`Previous layout not found for panel index ${h}`),Pa(w,y)){const _=E-w;$l(_,Math.abs(e))>0&&(e=e<0?0-_:_)}}}{const h=e<0?c:u,g=n[h];Ct(g,`No panel constraints found for index ${h}`);const{collapsedSize:y=0,collapsible:x,minSize:E=0}=g;if(x){const w=t[h];if(Ct(w!=null,`Previous layout not found for panel index ${h}`),Pa(w,E)){const _=w-y;$l(_,Math.abs(e))>0&&(e=e<0?0-_:_)}}}}{const h=e<0?1:-1;let g=e<0?u:c,y=0;for(;;){const E=t[g];Ct(E!=null,`Previous layout not found for panel index ${g}`);const _=cu({panelConstraints:n,panelIndex:g,size:100})-E;if(y+=_,g+=h,g<0||g>=n.length)break}const x=Math.min(Math.abs(e),Math.abs(y));e=e<0?0-x:x}{let g=e<0?c:u;for(;g>=0&&g<n.length;){const y=Math.abs(e)-Math.abs(f),x=t[g];Ct(x!=null,`Previous layout not found for panel index ${g}`);const E=x-y,w=cu({panelConstraints:n,panelIndex:g,size:E});if(!Pa(x,w)&&(f+=x-w,i[g]=w,f.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?g--:g++}}if(_ve(a,i))return a;{const h=e<0?u:c,g=t[h];Ct(g!=null,`Previous layout not found for panel index ${h}`);const y=g+f,x=cu({panelConstraints:n,panelIndex:h,size:y});if(i[h]=x,!Pa(x,y)){let E=y-x,_=e<0?u:c;for(;_>=0&&_<n.length;){const S=i[_];Ct(S!=null,`Previous layout not found for panel index ${_}`);const T=S+E,R=cu({panelConstraints:n,panelIndex:_,size:T});if(Pa(S,R)||(E-=R-S,i[_]=R),Pa(E,0))break;e>0?_--:_++}}}const m=i.reduce((h,g)=>g+h,0);return Pa(m,100)?i:a}function Tve({layout:e,panelsArray:t,pivotIndices:n}){let r=0,a=100,s=0,i=0;const c=n[0];Ct(c!=null,"No pivot index found"),t.forEach((h,g)=>{const{constraints:y}=h,{maxSize:x=100,minSize:E=0}=y;g===c?(r=E,a=x):(s+=E,i+=x)});const u=Math.min(a,100-s),f=Math.max(r,100-i),m=e[c];return{valueMax:u,valueMin:f,valueNow:m}}function Mp(e,t=document){return Array.from(t.querySelectorAll(`[${qn.resizeHandleId}][data-panel-group-id="${e}"]`))}function Y6(e,t,n=document){const a=Mp(e,n).findIndex(s=>s.getAttribute(qn.resizeHandleId)===t);return a??null}function Z6(e,t,n){const r=Y6(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function Nve(e){return e instanceof HTMLElement?!0:typeof e=="object"&&e!==null&&"tagName"in e&&"getAttribute"in e}function q6(e,t=document){if(Nve(t)&&t.dataset.panelGroupId==e)return t;const n=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return n||null}function _v(e,t=document){const n=t.querySelector(`[${qn.resizeHandleId}="${e}"]`);return n||null}function kve(e,t,n,r=document){var a,s,i,c;const u=_v(t,r),f=Mp(e,r),m=u?f.indexOf(u):-1,h=(a=(s=n[m])===null||s===void 0?void 0:s.id)!==null&&a!==void 0?a:null,g=(i=(c=n[m+1])===null||c===void 0?void 0:c.id)!==null&&i!==void 0?i:null;return[h,g]}function Cve({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:a,panelGroupElement:s,setLayout:i}){v.useRef({didWarnAboutMissingResizeHandle:!1}),Cl(()=>{if(!s)return;const c=Mp(n,s);for(let u=0;u<a.length-1;u++){const{valueMax:f,valueMin:m,valueNow:h}=Tve({layout:r,panelsArray:a,pivotIndices:[u,u+1]}),g=c[u];if(g!=null){const y=a[u];Ct(y,`No panel data found for index "${u}"`),g.setAttribute("aria-controls",y.id),g.setAttribute("aria-valuemax",""+Math.round(f)),g.setAttribute("aria-valuemin",""+Math.round(m)),g.setAttribute("aria-valuenow",h!=null?""+Math.round(h):"")}}return()=>{c.forEach((u,f)=>{u.removeAttribute("aria-controls"),u.removeAttribute("aria-valuemax"),u.removeAttribute("aria-valuemin"),u.removeAttribute("aria-valuenow")})}},[n,r,a,s]),v.useEffect(()=>{if(!s)return;const c=t.current;Ct(c,"Eager values not found");const{panelDataArray:u}=c,f=q6(n,s);Ct(f!=null,`No group found for id "${n}"`);const m=Mp(n,s);Ct(m,`No resize handles found for group id "${n}"`);const h=m.map(g=>{const y=g.getAttribute(qn.resizeHandleId);Ct(y,"Resize handle element has no handle id attribute");const[x,E]=kve(n,y,u,s);if(x==null||E==null)return()=>{};const w=_=>{if(!_.defaultPrevented)switch(_.key){case"Enter":{_.preventDefault();const S=u.findIndex(T=>T.id===x);if(S>=0){const T=u[S];Ct(T,`No panel data found for index ${S}`);const R=r[S],{collapsedSize:C=0,collapsible:I,minSize:A=0}=T.constraints;if(R!=null&&I){const O=Ff({delta:Pa(R,C)?A-C:C-R,initialLayout:r,panelConstraints:u.map(j=>j.constraints),pivotIndices:Z6(n,y,s),prevLayout:r,trigger:"keyboard"});r!==O&&i(O)}}break}}};return g.addEventListener("keydown",w),()=>{g.removeEventListener("keydown",w)}});return()=>{h.forEach(g=>g())}},[s,e,t,n,r,a,i])}function K$(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 X6(e,t){const n=e==="horizontal",{x:r,y:a}=Ev(t);return n?r:a}function Rve(e,t,n,r,a){const s=n==="horizontal",i=_v(t,a);Ct(i,`No resize handle element found for id "${t}"`);const c=i.getAttribute(qn.groupId);Ct(c,"Resize handle element has no group id attribute");let{initialCursorPosition:u}=r;const f=X6(n,e),m=q6(c,a);Ct(m,`No group element found for id "${c}"`);const h=m.getBoundingClientRect(),g=s?h.width:h.height;return(f-u)/g*100}function Ave(e,t,n,r,a,s){if($6(e)){const i=n==="horizontal";let c=0;e.shiftKey?c=100:a!=null?c=a:c=10;let u=0;switch(e.key){case"ArrowDown":u=i?0:c;break;case"ArrowLeft":u=i?-c:0;break;case"ArrowRight":u=i?c:0;break;case"ArrowUp":u=i?0:-c;break;case"End":u=100;break;case"Home":u=-100;break}return u}else return r==null?0:Rve(e,t,n,r,s)}function Ive({panelDataArray:e}){const t=Array(e.length),n=e.map(s=>s.constraints);let r=0,a=100;for(let s=0;s<e.length;s++){const i=n[s];Ct(i,`Panel constraints not found for index ${s}`);const{defaultSize:c}=i;c!=null&&(r++,t[s]=c,a-=c)}for(let s=0;s<e.length;s++){const i=n[s];Ct(i,`Panel constraints not found for index ${s}`);const{defaultSize:c}=i;if(c!=null)continue;const u=e.length-r,f=a/u;r++,t[s]=f,a-=f}return t}function Uc(e,t,n){t.forEach((r,a)=>{const s=e[a];Ct(s,`Panel data not found for index ${a}`);const{callbacks:i,constraints:c,id:u}=s,{collapsedSize:f=0,collapsible:m}=c,h=n[u];if(h==null||r!==h){n[u]=r;const{onCollapse:g,onExpand:y,onResize:x}=i;x&&x(r,h),m&&(g||y)&&(y&&(h==null||Ss(h,f))&&!Ss(r,f)&&y(),g&&(h==null||!Ss(h,f))&&Ss(r,f)&&g())}})}function $g(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 Ove({defaultSize:e,dragState:t,layout:n,panelData:r,panelIndex:a,precision:s=3}){const i=n[a];let c;return i==null?c=e!=null?e.toFixed(s):"1":r.length===1?c="1":c=i.toFixed(s),{flexBasis:0,flexGrow:c,flexShrink:1,overflow:"hidden",pointerEvents:t!==null?"none":void 0}}function Dve(e,t=10){let n=null;return(...a)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...a)},t)}}function Y$(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 J6(e){return`react-resizable-panels:${e}`}function Q6(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:a,order:s}=t;return a?r:s?`${s}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function e8(e,t){try{const n=J6(e),r=t.getItem(n);if(r){const a=JSON.parse(r);if(typeof a=="object"&&a!=null)return a}}catch{}return null}function Lve(e,t,n){var r,a;const s=(r=e8(e,n))!==null&&r!==void 0?r:{},i=Q6(t);return(a=s[i])!==null&&a!==void 0?a:null}function Mve(e,t,n,r,a){var s;const i=J6(e),c=Q6(t),u=(s=e8(e,a))!==null&&s!==void 0?s:{};u[c]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{a.setItem(i,JSON.stringify(u))}catch(f){console.error(f)}}function Z$({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((s,i)=>s+i,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(s=>`${s}%`).join(", ")}`);if(!Pa(r,100)&&n.length>0)for(let s=0;s<t.length;s++){const i=n[s];Ct(i!=null,`No layout data found for index ${s}`);const c=100/r*i;n[s]=c}let a=0;for(let s=0;s<t.length;s++){const i=n[s];Ct(i!=null,`No layout data found for index ${s}`);const c=cu({panelConstraints:t,panelIndex:s,size:i});i!=c&&(a+=i-c,n[s]=c)}if(!Pa(a,0))for(let s=0;s<t.length;s++){const i=n[s];Ct(i!=null,`No layout data found for index ${s}`);const c=i+a,u=cu({panelConstraints:t,panelIndex:s,size:c});if(i!==u&&(a-=u-i,n[s]=u,Pa(a,0)))break}return n}const jve=100,Bf={getItem:e=>(Y$(Bf),Bf.getItem(e)),setItem:(e,t)=>{Y$(Bf),Bf.setItem(e,t)}},q$={};function t8({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:a,id:s=null,onLayout:i=null,keyboardResizeBy:c=null,storage:u=Bf,style:f,tagName:m="div",...h}){const g=U1(s),y=v.useRef(null),[x,E]=v.useState(null),[w,_]=v.useState([]),S=Sve(),T=v.useRef({}),R=v.useRef(new Map),C=v.useRef(0),I=v.useRef({autoSaveId:e,direction:r,dragState:x,id:g,keyboardResizeBy:c,onLayout:i,storage:u}),A=v.useRef({layout:w,panelDataArray:[],panelDataArrayChanged:!1});v.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),v.useImperativeHandle(a,()=>({getId:()=>I.current.id,getLayout:()=>{const{layout:$}=A.current;return $},setLayout:$=>{const{onLayout:L}=I.current,{layout:M,panelDataArray:z}=A.current,G=Z$({layout:$,panelConstraints:z.map(q=>q.constraints)});K$(M,G)||(_(G),A.current.layout=G,L&&L(G),Uc(z,G,T.current))}}),[]),Cl(()=>{I.current.autoSaveId=e,I.current.direction=r,I.current.dragState=x,I.current.id=g,I.current.onLayout=i,I.current.storage=u}),Cve({committedValuesRef:I,eagerValuesRef:A,groupId:g,layout:w,panelDataArray:A.current.panelDataArray,setLayout:_,panelGroupElement:y.current}),v.useEffect(()=>{const{panelDataArray:$}=A.current;if(e){if(w.length===0||w.length!==$.length)return;let L=q$[e];L==null&&(L=Dve(Mve,jve),q$[e]=L);const M=[...$],z=new Map(R.current);L(e,M,z,w,u)}},[e,w,u]),v.useEffect(()=>{});const O=v.useCallback($=>{const{onLayout:L}=I.current,{layout:M,panelDataArray:z}=A.current;if($.constraints.collapsible){const G=z.map(X=>X.constraints),{collapsedSize:q=0,panelSize:ae,pivotIndices:ie}=gl(z,$,M);if(Ct(ae!=null,`Panel size not found for panel "${$.id}"`),!Ss(ae,q)){R.current.set($.id,ae);const Z=Yc(z,$)===z.length-1?ae-q:q-ae,se=Ff({delta:Z,initialLayout:M,panelConstraints:G,pivotIndices:ie,prevLayout:M,trigger:"imperative-api"});$g(M,se)||(_(se),A.current.layout=se,L&&L(se),Uc(z,se,T.current))}}},[]),j=v.useCallback(($,L)=>{const{onLayout:M}=I.current,{layout:z,panelDataArray:G}=A.current;if($.constraints.collapsible){const q=G.map(me=>me.constraints),{collapsedSize:ae=0,panelSize:ie=0,minSize:X=0,pivotIndices:Z}=gl(G,$,z),se=L??X;if(Ss(ie,ae)){const me=R.current.get($.id),le=me!=null&&me>=se?me:se,He=Yc(G,$)===G.length-1?ie-le:le-ie,xe=Ff({delta:He,initialLayout:z,panelConstraints:q,pivotIndices:Z,prevLayout:z,trigger:"imperative-api"});$g(z,xe)||(_(xe),A.current.layout=xe,M&&M(xe),Uc(G,xe,T.current))}}},[]),U=v.useCallback($=>{const{layout:L,panelDataArray:M}=A.current,{panelSize:z}=gl(M,$,L);return Ct(z!=null,`Panel size not found for panel "${$.id}"`),z},[]),B=v.useCallback(($,L)=>{const{panelDataArray:M}=A.current,z=Yc(M,$);return Ove({defaultSize:L,dragState:x,layout:w,panelData:M,panelIndex:z})},[x,w]),W=v.useCallback($=>{const{layout:L,panelDataArray:M}=A.current,{collapsedSize:z=0,collapsible:G,panelSize:q}=gl(M,$,L);return Ct(q!=null,`Panel size not found for panel "${$.id}"`),G===!0&&Ss(q,z)},[]),J=v.useCallback($=>{const{layout:L,panelDataArray:M}=A.current,{collapsedSize:z=0,collapsible:G,panelSize:q}=gl(M,$,L);return Ct(q!=null,`Panel size not found for panel "${$.id}"`),!G||$l(q,z)>0},[]),ee=v.useCallback($=>{const{panelDataArray:L}=A.current;L.push($),L.sort((M,z)=>{const G=M.order,q=z.order;return G==null&&q==null?0:G==null?-1:q==null?1:G-q}),A.current.panelDataArrayChanged=!0,S()},[S]);Cl(()=>{if(A.current.panelDataArrayChanged){A.current.panelDataArrayChanged=!1;const{autoSaveId:$,onLayout:L,storage:M}=I.current,{layout:z,panelDataArray:G}=A.current;let q=null;if($){const ie=Lve($,G,M);ie&&(R.current=new Map(Object.entries(ie.expandToSizes)),q=ie.layout)}q==null&&(q=Ive({panelDataArray:G}));const ae=Z$({layout:q,panelConstraints:G.map(ie=>ie.constraints)});K$(z,ae)||(_(ae),A.current.layout=ae,L&&L(ae),Uc(G,ae,T.current))}}),Cl(()=>{const $=A.current;return()=>{$.layout=[]}},[]);const re=v.useCallback($=>{let L=!1;const M=y.current;return M&&window.getComputedStyle(M,null).getPropertyValue("direction")==="rtl"&&(L=!0),function(G){G.preventDefault();const q=y.current;if(!q)return()=>null;const{direction:ae,dragState:ie,id:X,keyboardResizeBy:Z,onLayout:se}=I.current,{layout:me,panelDataArray:le}=A.current,{initialLayout:Ne}=ie??{},He=Z6(X,$,q);let xe=Ave(G,$,ae,ie,Z,q);const Te=ae==="horizontal";Te&&L&&(xe=-xe);const $e=le.map(Fe=>Fe.constraints),fe=Ff({delta:xe,initialLayout:Ne??me,panelConstraints:$e,pivotIndices:He,prevLayout:me,trigger:$6(G)?"keyboard":"mouse-or-touch"}),Ie=!$g(me,fe);(z6(G)||F6(G))&&C.current!=xe&&(C.current=xe,!Ie&&xe!==0?Te?ex($,xe<0?H6:V6):ex($,xe<0?G6:W6):ex($,0)),Ie&&(_(fe),A.current.layout=fe,se&&se(fe),Uc(le,fe,T.current))}},[]),F=v.useCallback(($,L)=>{const{onLayout:M}=I.current,{layout:z,panelDataArray:G}=A.current,q=G.map(me=>me.constraints),{panelSize:ae,pivotIndices:ie}=gl(G,$,z);Ct(ae!=null,`Panel size not found for panel "${$.id}"`);const Z=Yc(G,$)===G.length-1?ae-L:L-ae,se=Ff({delta:Z,initialLayout:z,panelConstraints:q,pivotIndices:ie,prevLayout:z,trigger:"imperative-api"});$g(z,se)||(_(se),A.current.layout=se,M&&M(se),Uc(G,se,T.current))},[]),K=v.useCallback(($,L)=>{const{layout:M,panelDataArray:z}=A.current,{collapsedSize:G=0,collapsible:q}=L,{collapsedSize:ae=0,collapsible:ie,maxSize:X=100,minSize:Z=0}=$.constraints,{panelSize:se}=gl(z,$,M);se!=null&&(q&&ie&&Ss(se,G)?Ss(G,ae)||F($,ae):se<Z?F($,Z):se>X&&F($,X))},[F]),V=v.useCallback(($,L)=>{const{direction:M}=I.current,{layout:z}=A.current;if(!y.current)return;const G=_v($,y.current);Ct(G,`Drag handle element not found for id "${$}"`);const q=X6(M,L);E({dragHandleId:$,dragHandleRect:G.getBoundingClientRect(),initialCursorPosition:q,initialLayout:z})},[]),ne=v.useCallback(()=>{E(null)},[]),te=v.useCallback($=>{const{panelDataArray:L}=A.current,M=Yc(L,$);M>=0&&(L.splice(M,1),delete T.current[$.id],A.current.panelDataArrayChanged=!0,S())},[S]),D=v.useMemo(()=>({collapsePanel:O,direction:r,dragState:x,expandPanel:j,getPanelSize:U,getPanelStyle:B,groupId:g,isPanelCollapsed:W,isPanelExpanded:J,reevaluatePanelConstraints:K,registerPanel:ee,registerResizeHandle:re,resizePanel:F,startDragging:V,stopDragging:ne,unregisterPanel:te,panelGroupElement:y.current}),[O,x,r,j,U,B,g,W,J,K,ee,re,F,V,ne,te]),H={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return v.createElement(wv.Provider,{value:D},v.createElement(m,{...h,children:t,className:n,id:s,ref:y,style:{...H,...f},[qn.group]:"",[qn.groupDirection]:r,[qn.groupId]:g}))}const n8=v.forwardRef((e,t)=>v.createElement(t8,{...e,forwardedRef:t}));t8.displayName="PanelGroup";n8.displayName="forwardRef(PanelGroup)";function Yc(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function gl(e,t,n){const r=Yc(e,t),s=r===e.length-1?[r-1,r]:[r,r+1],i=n[r];return{...t.constraints,panelSize:i,pivotIndices:s}}function Pve({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){v.useEffect(()=>{if(e||n==null||r==null)return;const a=_v(t,r);if(a==null)return;const s=i=>{if(!i.defaultPrevented)switch(i.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{i.preventDefault(),n(i);break}case"F6":{i.preventDefault();const c=a.getAttribute(qn.groupId);Ct(c,`No group element found for id "${c}"`);const u=Mp(c,r),f=Y6(c,t,r);Ct(f!==null,`No resize element found for id "${t}"`);const m=i.shiftKey?f>0?f-1:u.length-1:f+1<u.length?f+1:0;u[m].focus();break}}};return a.addEventListener("keydown",s),()=>{a.removeEventListener("keydown",s)}},[r,e,t,n])}function r8({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:a,onBlur:s,onClick:i,onDragging:c,onFocus:u,onPointerDown:f,onPointerUp:m,style:h={},tabIndex:g=0,tagName:y="div",...x}){var E,w;const _=v.useRef(null),S=v.useRef({onClick:i,onDragging:c,onPointerDown:f,onPointerUp:m});v.useEffect(()=>{S.current.onClick=i,S.current.onDragging=c,S.current.onPointerDown=f,S.current.onPointerUp=m});const T=v.useContext(wv);if(T===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:R,groupId:C,registerResizeHandle:I,startDragging:A,stopDragging:O,panelGroupElement:j}=T,U=U1(a),[B,W]=v.useState("inactive"),[J,ee]=v.useState(!1),[re,F]=v.useState(null),K=v.useRef({state:B});Cl(()=>{K.current.state=B}),v.useEffect(()=>{if(n)F(null);else{const D=I(U);F(()=>D)}},[n,U,I]);const V=(E=r?.coarse)!==null&&E!==void 0?E:15,ne=(w=r?.fine)!==null&&w!==void 0?w:5;v.useEffect(()=>{if(n||re==null)return;const D=_.current;Ct(D,"Element ref not attached");let H=!1;return Eve(U,D,R,{coarse:V,fine:ne},(L,M,z)=>{if(!M){W("inactive");return}switch(L){case"down":{W("drag"),H=!1,Ct(z,'Expected event to be defined for "down" action'),A(U,z);const{onDragging:G,onPointerDown:q}=S.current;G?.(!0),q?.();break}case"move":{const{state:G}=K.current;H=!0,G!=="drag"&&W("hover"),Ct(z,'Expected event to be defined for "move" action'),re(z);break}case"up":{W("hover"),O();const{onClick:G,onDragging:q,onPointerUp:ae}=S.current;q?.(!1),ae?.(),H||G?.();break}}})},[V,R,n,ne,I,U,re,A,O]),Pve({disabled:n,handleId:U,resizeHandler:re,panelGroupElement:j});const te={touchAction:"none",userSelect:"none"};return v.createElement(y,{...x,children:e,className:t,id:a,onBlur:()=>{ee(!1),s?.()},onFocus:()=>{ee(!0),u?.()},ref:_,role:"separator",style:{...te,...h},tabIndex:g,[qn.groupDirection]:R,[qn.groupId]:C,[qn.resizeHandle]:"",[qn.resizeHandleActive]:B==="drag"?"pointer":J?"keyboard":void 0,[qn.resizeHandleEnabled]:!n,[qn.resizeHandleId]:U,[qn.resizeHandleState]:B})}r8.displayName="PanelResizeHandle";function aa({className:e,...t}){return d.jsx(n8,{"data-slot":"resizable-panel-group",className:Oe("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t})}function Rn({...e}){return d.jsx(U6,{"data-slot":"resizable-panel",...e})}function wo({withHandle:e,className:t,...n}){return d.jsx(r8,{"data-slot":"resizable-handle",className:Oe("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&&d.jsx("div",{className:"bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border",children:d.jsx(Tie,{className:"size-2.5"})})})}function gm({className:e,...t}){return d.jsx("kbd",{"data-slot":"kbd",className:Oe("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 Uve({isSearchExpanded:e,searchQuery:t,filteredNotificationsCount:n,notificationsCount:r,onSearchExpand:a,onSearchChange:s,onSearchBlur:i,onClearAll:c,searchInputRef:u}){return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Tn,{ref:u,placeholder:"Search notifications...",value:t,onChange:f=>s(f.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Notifications"}),d.jsx(kr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:d.jsx(wd,{className:"h-4 w-4"})})}),d.jsxs(Mt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(gm,{children:"F"})]})]})]})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,disabled:r===0,className:"h-8 w-8 p-0",children:d.jsx(Mi,{className:"h-4 w-4"})})}),d.jsx(Mt,{side:"bottom",children:"Clear all"})]})})]})}function Wi({id:e,isSelected:t,isFocused:n,icon:r,title:a,description:s,metadata:i,onClick:c,className:u}){return d.jsx("button",{id:e,type:"button",onClick:c,className:Oe("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:d.jsxs("div",{className:"flex items-start gap-2 sm:gap-3",children:[r&&d.jsx("div",{className:"flex-shrink-0 mt-1",children:d.jsx("div",{className:Oe("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:r})}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("div",{className:"flex items-center gap-2 mb-1",children:d.jsx("h3",{className:Oe("font-medium truncate font-mono text-sm"),children:a})}),s&&d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 line-clamp-2",children:s})]})]})})}function $ve({notifications:e,selectedNotification:t,onNotificationSelect:n,focusedIndex:r,formatRelativeTime:a,listRef:s}){return e.length===0?d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx(vd,{vertical:!0,noBorder:!0,message:"No notifications yet"})}):d.jsx("div",{ref:s,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((i,c)=>d.jsx(Wi,{id:`notification-${i.id}`,isSelected:t?.id===i.id,isFocused:r===c,title:d.jsxs("span",{className:"flex items-center gap-3",children:[i.method,!i.read&&d.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const u=a(i.timestamp),f=i.params&&Object.keys(i.params).length>0?Object.keys(i.params).length:0,m=f>0?` | ${f} param${f>1?"s":""}`:"";return u+m})(),onClick:()=>n(i)},i.id))})}function zve({notification:e,previewMode:t,onTogglePreview:n,onCopy:r,onDownload:a,onFullscreen:s,isCopied:i=!1,onClose:c}){return e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.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:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(qu,{className:"h-3 w-3 text-gray-400"}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleTimeString()})]}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:e.formatRelativeTime(e.timestamp)})]}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsxs(Le,{variant:"ghost",size:"sm",onClick:n,className:t?"":"text-purple-600 dark:text-purple-400",children:[t?d.jsx(fT,{className:"h-4 w-4 mr-1"}):d.jsx(q3,{className:"h-4 w-4 mr-1"}),t?"JSON":"Formatted"]}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:r,children:i?d.jsx(oa,{className:"h-4 w-4"}):d.jsx(zr,{className:"h-4 w-4"})}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:a,children:d.jsx(Qp,{className:"h-4 w-4"})}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:s,children:d.jsx(hT,{className:"h-4 w-4"})}),c&&d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,children:d.jsx(qo,{className:"h-4 w-4"})})]})]}),d.jsx("div",{className:"flex-1 overflow-y-auto",children:d.jsx("div",{className:"px-4 pt-4",children:d.jsx(nr,{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`})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(uT,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a notification to view details"})]})}function uy(e){const n=Date.now()-e,r=Math.floor(n/1e3),a=Math.floor(r/60),s=Math.floor(a/60),i=Math.floor(s/24);return r<60?"just now":a<60?`${a}m ago`:s<24?`${s}h ago`:i<7?`${i}d ago`:new Date(e).toLocaleDateString()}function Fve({notifications:e,unreadCount:t,markNotificationRead:n,markAllNotificationsRead:r,clearNotifications:a,serverId:s,isConnected:i}){const[c,u]=v.useState(null),[f,m]=v.useState(""),[h,g]=v.useState(-1),[y,x]=v.useState(!0),[E,w]=v.useState(!1),[_,S]=v.useState(!0),[T,R]=v.useState(!1),C=v.useRef(null),I=v.useRef(null),A=v.useRef(null),O=v.useRef(!1);v.useEffect(()=>{y&&e.length>0&&C.current&&!O.current&&(C.current.scrollTop=0)},[e.length,y]),v.useEffect(()=>{const K=C.current;if(!K)return;const V=()=>{K.scrollTop>0&&(O.current=!0,x(!1))};return K.addEventListener("scroll",V),()=>K.removeEventListener("scroll",V)},[]),v.useEffect(()=>{e.length===0&&(O.current=!1,x(!0))},[e.length]),v.useEffect(()=>{c&&!c.read&&n(c.id)},[c,n]),v.useEffect(()=>{E&&A.current&&A.current.focus()},[E]);const j=v.useCallback(()=>{f.trim()||w(!1)},[f]),U=v.useMemo(()=>{if(!f.trim())return e;const K=f.toLowerCase();return e.filter(V=>V.method.toLowerCase().includes(K)||JSON.stringify(V.params||{}).toLowerCase().includes(K))},[e,f]);v.useEffect(()=>{g(-1)},[f]),v.useEffect(()=>{const K=V=>{const ne=V.target;if(ne.tagName==="INPUT"||ne.tagName==="TEXTAREA"||ne.contentEditable==="true"||V.metaKey||V.ctrlKey||V.altKey)return;const D=U;if(V.key==="ArrowDown")V.preventDefault(),g(H=>{const $=H+1;return $>=D.length?0:$});else if(V.key==="ArrowUp")V.preventDefault(),g(H=>{const $=H-1;return $<0?D.length-1:$});else if(V.key==="Enter"&&h>=0){V.preventDefault();const H=U[h];H&&B(H)}};return document.addEventListener("keydown",K),()=>document.removeEventListener("keydown",K)},[h,U]),v.useEffect(()=>{if(h>=0){const K=`notification-${U[h]?.id}`,V=document.getElementById(K);V&&V.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,U]);const B=v.useCallback(K=>{u(K)},[]),W=v.useCallback(()=>{window.confirm("Are you sure you want to clear all notifications? This cannot be undone.")&&(a(),u(null))},[a]),J=v.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)),R(!0),setTimeout(()=>R(!1),2e3)}catch(K){console.error("[NotificationsTab] Failed to copy notification:",K)}},[c]),ee=v.useCallback(()=>{if(c)try{const K=new globalThis.Blob([JSON.stringify({method:c.method,timestamp:c.timestamp,read:c.read,params:c.params},null,2)],{type:"application/json"}),V=URL.createObjectURL(K),ne=document.createElement("a");ne.href=V,ne.download=`notification-${Date.now()}.json`,document.body.appendChild(ne),ne.click(),document.body.removeChild(ne),URL.revokeObjectURL(V)}catch(K){console.error("[NotificationsTab] Failed to download notification:",K)}},[c]),re=v.useCallback(async()=>{if(I.current)try{document.fullscreenElement?await document.exitFullscreen():await I.current.requestFullscreen()}catch(K){console.error("[NotificationsTab] Failed to toggle fullscreen:",K)}},[]),F=c?{method:c.method,params:c.params,timestamp:c.timestamp,read:c.read,formatRelativeTime:uy}:null;return i?d.jsxs(aa,{direction:"horizontal",className:"h-full",children:[d.jsx(Rn,{defaultSize:40,minSize:30,children:d.jsx(aa,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:d.jsxs(Rn,{defaultSize:75,minSize:30,children:[d.jsx(Uve,{isSearchExpanded:E,searchQuery:f,filteredNotificationsCount:U.length,notificationsCount:e.length,onSearchExpand:()=>w(!0),onSearchChange:m,onSearchBlur:j,onClearAll:W,searchInputRef:A}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx($ve,{notifications:U,selectedNotification:c,onNotificationSelect:B,focusedIndex:h,formatRelativeTime:uy,listRef:C})})]})})}),d.jsx(wo,{}),d.jsx(Rn,{defaultSize:60,minSize:40,children:d.jsx("div",{ref:I,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(zve,{notification:F,previewMode:_,onTogglePreview:()=>S(!_),onCopy:J,onDownload:ee,onFullscreen:re,onClose:()=>u(null),isCopied:T})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(uT,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function a8({activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabTitle:r,secondaryTabTitle:a,primaryCount:s,secondaryCount:i,secondaryIcon:c,primaryIcon:u,searchPlaceholder:f="Search...",onSearchExpand:m,onSearchChange:h,onSearchBlur:g,onTabSwitch:y,searchInputRef:x,primaryTabName:E}){const w=e===E;return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:t?d.jsx(Tn,{ref:x,placeholder:f,value:n,onChange:_=>h(_.target.value),onBlur:g,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:w?r:a}),w&&d.jsxs(d.Fragment,{children:[d.jsx(kr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:s}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:m,className:"h-8 w-8 p-0",children:d.jsx(wd,{className:"h-4 w-4"})})}),d.jsxs(Mt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(gm,{children:"F"})]})]})]})]})}),d.jsxs(Le,{variant:"ghost",size:"sm",onClick:y,className:"gap-2 flex-shrink-0",children:[w?d.jsx(c,{}):d.jsx(u,{}),d.jsx("span",{className:"hidden sm:inline",children:w?a:r}),w&&i>0&&d.jsx(kr,{className:"bg-purple-500/20 text-purple-600 dark:text-purple-400 border-transparent",variant:"outline",children:i})]})]})}function X$({prompts:e,selectedPrompt:t,onPromptSelect:n,focusedIndex:r}){return e.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(yp,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No prompts available"})]}):d.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((a,s)=>d.jsx(Wi,{id:`prompt-${a.name}`,isSelected:t?.name===a.name,isFocused:r===s,icon:d.jsx(yp,{className:"h-4 w-4"}),title:a.name,description:a.description,metadata:a.arguments&&a.arguments.length>0&&d.jsxs(kr,{variant:"outline",className:"text-xs border-gray-300 dark:border-zinc-600 text-gray-600 dark:text-gray-400",children:[a.arguments.length," args"]}),onClick:()=>n(a)},a.name))})}function J$({activeTab:e,isSearchExpanded:t,searchQuery:n,filteredPromptsCount:r,savedPromptsCount:a,onSearchExpand:s,onSearchChange:i,onSearchBlur:c,onTabSwitch:u,searchInputRef:f}){return d.jsx(a8,{activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabName:"prompts",secondaryTabName:"saved",primaryTabTitle:"Prompts",secondaryTabTitle:"History",primaryCount:r,secondaryCount:a,primaryIcon:yp,secondaryIcon:qu,searchPlaceholder:"Search prompts...",onSearchExpand:s,onSearchChange:i,onSearchBlur:c,onTabSwitch:u,searchInputRef:f})}function Q$({savedPrompts:e,selectedPrompt:t,onLoadPrompt:n,onDeletePrompt:r,focusedIndex:a}){return e.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(qu,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No history"}),d.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500 mt-1",children:"Prompts you execute will appear here"})]}):d.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((s,i)=>d.jsx(Wi,{id:`saved-prompt-${s.id}`,isSelected:t?.id===s.id,isFocused:a===i,icon:d.jsx(qu,{className:"h-4 w-4"}),title:s.name,description:`${s.promptName} - ${new Date(s.savedAt).toLocaleString()}`,onClick:()=>n(s)},s.id))})}function Bve({selectedPrompt:e,promptArgs:t,onArgChange:n}){const r=e?.arguments||[];if(!(r.length>0))return d.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500 dark:text-gray-400 text-sm",children:"No arguments required"});const s=i=>{const c=i.name,u=t[c],f=typeof u=="string"?u:JSON.stringify(u);return i.type==="boolean"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:c,className:"text-sm font-medium",children:[c,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsxs("div",{className:"flex items-center space-x-2",children:[d.jsx("input",{id:c,type:"checkbox",checked:!!u,onChange:m=>n(c,m.target.checked),className:"rounded","aria-label":`Toggle ${c}`}),d.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:i.description})]})]},c):i.type==="number"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:c,className:"text-sm font-medium",children:[c,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(Tn,{id:c,type:"number",value:Number(u)||0,onChange:m=>n(c,Number(m.target.value)),placeholder:i.description||`Enter ${c}`}),i.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:i.description})]},c):i.type==="array"||i.type==="object"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:c,className:"text-sm font-medium",children:[c,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(Pl,{id:c,value:f,onChange:m=>{try{const h=JSON.parse(m.target.value);n(c,h)}catch{n(c,m.target.value)}},placeholder:i.description||`Enter ${c} as JSON`,className:"font-mono text-sm min-h-[100px]"}),i.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:i.description})]},c):d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:c,className:"text-sm font-medium",children:[c,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(Tn,{id:c,value:f,onChange:m=>n(c,m.target.value),placeholder:i.description||`Enter ${c}`}),i.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:i.description})]},c)};return d.jsx("div",{className:"space-y-4",children:r.map(i=>s(i))})}function ez({selectedPrompt:e,promptArgs:t,isExecuting:n,isConnected:r,onArgChange:a,onExecute:s,onSave:i}){return v.useEffect(()=>{const c=u=>{(u.metaKey||u.ctrlKey)&&u.key==="Enter"&&e&&!n&&r&&(u.preventDefault(),s())};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[e,n,r,s]),e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx("div",{className:"flex-shrink-0 p-3 sm:p-6 pt-3 pb-4 pr-3",children:d.jsxs("div",{children:[d.jsxs("div",{className:"flex flex-row items-center justify-between mb-0 gap-2",children:[d.jsx("h3",{className:"text-base sm:text-lg font-semibold",children:e.name}),d.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[d.jsx(Le,{onClick:s,disabled:n||!r,size:"sm",className:"lg:size-default pr-1! gap-0",children:n?d.jsxs(d.Fragment,{children:[d.jsx(_o,{className:"mr-2"}),d.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]}):d.jsxs(d.Fragment,{children:[d.jsx(eB,{className:"h-4 w-4 sm:mr-2"}),d.jsx("span",{className:"hidden sm:inline",children:"Execute"}),d.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:"⌘↵"})]})}),d.jsxs(Le,{variant:"outline",onClick:i,disabled:n,size:"sm",className:"lg:size-default gap-2",children:[d.jsx(gT,{className:"h-4 w-4"}),d.jsx("span",{className:"hidden sm:inline",children:"Save"})]})]})]}),e.description&&d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 leading-relaxed mt-2",children:e.description})]})}),d.jsx("div",{className:"flex-1 overflow-y-auto px-3 sm:px-6 pb-4 pr-3",children:d.jsx(Bve,{selectedPrompt:e,promptArgs:t,onArgChange:a})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a prompt to get started"}),d.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 Hve(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 tz({results:e,copiedResult:t,onCopy:n}){return d.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:d.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:e.length>0?d.jsx("div",{className:"space-y-4 flex-1 h-full",children:e.map((r,a)=>{const s=r.error||Hve(r.result);return d.jsxs("div",{className:"space-y-0 flex-1 h-full flex flex-col",children:[d.jsxs("div",{className:"flex items-center gap-2 px-4 pt-2 border-b border-gray-200 dark:border-zinc-600 pb-2",children:[d.jsx("h3",{className:"text-sm font-medium",children:"Response"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(qu,{className:"h-3 w-3 text-gray-400"}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(r.timestamp).toLocaleTimeString()})]}),r.duration!==void 0&&d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(vp,{className:"h-3 w-3 text-gray-400"}),d.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[r.duration,"ms"]})]}),d.jsx("div",{className:"flex gap-2 ml-auto",children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>n(a,r.result),className:"h-6 px-2",children:t===a?d.jsx(oa,{className:"h-4 w-4"}):d.jsx(zr,{className:"h-4 w-4"})})})]}),s?d.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:[d.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),d.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:s})]}):d.jsx("div",{className:"px-4 pt-4",children:d.jsx(nr,{data:r.result,filename:`prompt-result-${r.promptName}-${Date.now()}.json`})})]},a)})}):d.jsx("div",{className:"flex items-center justify-center h-full",children:d.jsx("div",{className:"text-center",children:d.jsx(vd,{vertical:!0,noBorder:!0,message:"No Results yet"})})})})})}function z1({serverIds:e,onCountChange:t,onClearRef:n}={}){const[r,a]=v.useState([]),s=v.useRef(null),[i,c]=v.useState(new Set),[u]=v.useState(""),f=y=>{c(x=>{const E=new Set(x);return E.has(y)?E.delete(y):E.add(y),E})},m=async()=>{a([]),c(new Set),t?.(0);try{const y=new URLSearchParams;e&&e.length>0&&y.set("serverIds",e.join(","));const x=await fetch(`/inspector/api/rpc/log?${y.toString()}`,{method:"DELETE"});x.ok||console.warn("[RPC Logger] Failed to clear server buffer:",x.status)}catch(y){console.warn("[RPC Logger] Error clearing server buffer:",y)}},h=v.useMemo(()=>!e||e.length===0?"":[...e].sort().join(","),[e]);v.useEffect(()=>(n&&(n.current=m),()=>{n&&(n.current=null)}),[n,m]),v.useEffect(()=>{t?.(r.length)},[r.length,t]),v.useEffect(()=>{let y=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 E=`/inspector/api/rpc/stream?${x.toString()}`;console.log("[RPC Logger] Connecting to SSE stream:",E),y=new globalThis.EventSource(E),y.onopen=()=>{console.log("[RPC Logger] SSE connection opened")},y.onmessage=w=>{try{const _=JSON.parse(w.data);if(!_||_.type!=="rpc")return;const{serverId:S,direction:T,message:R,timestamp:C}=_,I=R,A=typeof I?.method=="string"?I.method:I?.result!==void 0?"result":I?.error!==void 0?"error":"unknown",O={id:`${C??Date.now()}-${Math.random().toString(36).slice(2)}`,serverId:typeof S=="string"?S:"unknown",direction:typeof T=="string"?T.toUpperCase():"",method:A,timestamp:C??new Date().toISOString(),payload:R};console.log("[RPC Logger] Received RPC event:",{method:A,direction:T,serverId:S}),a(j=>{const U=[O,...j].slice(0,1e3);return t?.(U.length),U})}catch(_){console.error("[RPC Logger] Error parsing SSE message:",_)}},y.onerror=w=>{console.error("[RPC Logger] SSE connection error:",w);try{y?.close()}catch{}}}catch(x){console.error("[RPC Logger] Failed to create SSE connection:",x)}return()=>{try{y?.close(),console.log("[RPC Logger] SSE connection closed")}catch{}}},[h]);const g=v.useMemo(()=>{let y=r;if(e&&e.length>0){const x=new Set(e);y=y.filter(E=>x.has(E.serverId))}if(u.trim()){const x=u.toLowerCase();y=y.filter(E=>E.serverId.toLowerCase().includes(x)||E.method.toLowerCase().includes(x)||E.direction.toLowerCase().includes(x)||JSON.stringify(E.payload).toLowerCase().includes(x))}return y},[r,u,e]);return d.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:d.jsx("div",{ref:s,className:"flex-1 min-h-0 overflow-y-auto",children:g.length===0?d.jsxs("div",{className:"text-center py-8",children:[d.jsx("div",{className:"text-xs text-muted-foreground",children:"No messages yet"}),d.jsx("div",{className:"text-[10px] text-muted-foreground mt-1",children:"JSON-RPC messages will appear here"})]}):g.map(y=>{const x=i.has(y.id);return d.jsxs("div",{className:"group hover:bg-muted/50 transition-all duration-200 overflow-hidden",children:[d.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>f(y.id),children:[d.jsx("div",{className:"flex-shrink-0",children:x?d.jsx(Gl,{className:"h-3 w-3 text-muted-foreground transition-transform"}):d.jsx(Wse,{className:"h-3 w-3 text-muted-foreground transition-transform"})}),d.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[d.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:new Date(y.timestamp).toLocaleTimeString()}),d.jsx("span",{className:`flex items-center justify-center px-1 py-0.5 rounded ${y.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:y.direction==="RECEIVE"?"Incoming":"Outgoing",children:y.direction==="RECEIVE"?d.jsx(Lse,{className:"h-3 w-3"}):d.jsx(jse,{className:"h-3 w-3"})}),d.jsx("span",{className:"text-xs font-mono text-foreground truncate",children:y.method})]})]}),x&&d.jsx("div",{className:"border-t bg-muted/20",children:d.jsx("div",{className:"p-3",children:d.jsx("div",{className:"max-h-[40vh] overflow-auto rounded-sm bg-background/60 p-2",children:d.jsx(nr,{data:y.payload})})})})]},y.id)})})})}const nz="mcp-inspector-saved-prompts";function o8({ref:e,prompts:t,callPrompt:n,serverId:r,isConnected:a}){const[s,i]=v.useState(null),[c,u]=v.useState(null),{selectedPromptName:f,setSelectedPromptName:m}=Wl(),[h,g]=v.useState({}),[y,x]=v.useState([]),[E,w]=v.useState(!1),[_,S]=v.useState(null),[T,R]=v.useState(""),[C,I]=v.useState("prompts"),[A,O]=v.useState([]),[j,U]=v.useState(!1),[B,W]=v.useState(""),[J,ee]=v.useState(!1),[re,F]=v.useState(-1),K=v.useRef(null),[V,ne]=v.useState(!1),[te,D]=v.useState("list"),[H,$]=v.useState(0),[L,M]=v.useState(!0),z=v.useRef(null),G=v.useRef(null);v.useEffect(()=>{const xe=()=>{ne(window.innerWidth<1024)};return xe(),window.addEventListener("resize",xe),()=>window.removeEventListener("resize",xe)},[]),v.useEffect(()=>{D(s?"detail":"list")},[s]),v.useEffect(()=>{V&&y.length>0&&!E&&D("response")},[y,E,V]),v.useImperativeHandle(e,()=>({focusSearch:()=>{ee(!0),setTimeout(()=>{K.current&&K.current.focus()},0)},blurSearch:()=>{R(""),ee(!1),K.current&&K.current.blur()}})),v.useEffect(()=>{try{const xe=localStorage.getItem(nz);if(xe){const Te=JSON.parse(xe);O(Te)}}catch(xe){console.error("[PromptsTab] Failed to load saved prompts:",xe)}},[]);const q=v.useCallback(xe=>{try{localStorage.setItem(nz,JSON.stringify(xe))}catch(Te){console.error("[PromptsTab] Failed to save prompts:",Te)}},[]);v.useEffect(()=>{J&&K.current&&K.current.focus()},[J]);const ae=v.useCallback(()=>{T.trim()||ee(!1)},[T]),ie=v.useMemo(()=>{if(!T.trim())return t;const xe=T.toLowerCase();return t.filter(Te=>Te.name.toLowerCase().includes(xe)||Te.description?.toLowerCase().includes(xe))},[t,T]),X=v.useCallback(xe=>{i(xe);const Te={};xe.arguments&&xe.arguments.forEach($e=>{$e.default!==void 0?Te[$e.name]=$e.default:$e.type==="string"?Te[$e.name]="":$e.type==="number"?Te[$e.name]=0:$e.type==="boolean"?Te[$e.name]=!1:$e.type==="array"?Te[$e.name]=[]:$e.type==="object"&&(Te[$e.name]={})}),g(Te)},[]),Z=v.useCallback(xe=>{const Te=t.find($e=>$e.name===xe.promptName);Te&&(i(Te),g(xe.args),u(xe))},[t]);v.useEffect(()=>{F(-1)},[T,C]),v.useEffect(()=>{const xe=Te=>{const $e=Te.target;if($e.tagName==="INPUT"||$e.tagName==="TEXTAREA"||$e.contentEditable==="true"||Te.metaKey||Te.ctrlKey||Te.altKey)return;const Ie=C==="prompts"?ie:A;if(Te.key==="ArrowDown")Te.preventDefault(),F(Fe=>{const Ee=Fe+1;return Ee>=Ie.length?0:Ee});else if(Te.key==="ArrowUp")Te.preventDefault(),F(Fe=>{const Ee=Fe-1;return Ee<0?Ie.length-1:Ee});else if(Te.key==="Enter"&&re>=0)if(Te.preventDefault(),C==="prompts"){const Fe=ie[re];Fe&&X(Fe)}else{const Fe=A[re];Fe&&Z(Fe)}};return document.addEventListener("keydown",xe),()=>document.removeEventListener("keydown",xe)},[re,ie,A,C,X,Z]),v.useEffect(()=>{if(re>=0){const xe=C==="prompts"?`prompt-${ie[re]?.name}`:`saved-prompt-${A[re]?.id}`,Te=document.getElementById(xe);Te&&Te.scrollIntoView({behavior:"smooth",block:"nearest"})}},[re,ie,A,C]),v.useEffect(()=>{if(console.warn("[PromptsTab] Auto-selection effect triggered:",{selectedPromptName:f,promptsCount:t.length,currentSelectedPrompt:s?.name}),f&&t.length>0){const xe=t.find(Te=>Te.name===f);if(console.warn("[PromptsTab] Prompt lookup result:",{selectedPromptName:f,promptFound:!!xe,promptName:xe?.name,shouldSelect:xe&&s?.name!==xe.name}),xe&&s?.name!==xe.name){console.warn("[PromptsTab] Selecting prompt:",xe.name),m(null);const Te=setTimeout(()=>{X(xe);const $e=document.getElementById(`prompt-${xe.name}`);$e&&(console.warn("[PromptsTab] Scrolling to prompt element"),$e.scrollIntoView({behavior:"smooth",block:"nearest"}))},100);return()=>clearTimeout(Te)}}},[f,t,s,X,m]);const se=v.useCallback((xe,Te)=>{g($e=>({...$e,[xe]:Te}))},[]),me=v.useCallback(async()=>{if(!s||E)return;w(!0);const xe=Date.now();try{const Te=await n(s.name,h),$e=Date.now()-xe;Tr.getInstance().capture(new bP({promptName:s.name,serverId:r,success:!0})).catch(()=>{}),x(Ie=>[{promptName:s.name,args:h,result:Te,timestamp:xe,duration:$e},...Ie])}catch(Te){Tr.getInstance().capture(new bP({promptName:s.name,serverId:r,success:!1,error:Te instanceof Error?Te.message:"Unknown error"})).catch(()=>{});const fe={promptName:s.name,args:h,result:null,error:Te instanceof Error?Te.message:String(Te),timestamp:xe,duration:Date.now()-xe};x(Ie=>[fe,...Ie])}finally{w(!1)}},[s,h,E,n,r]),le=v.useCallback(async(xe,Te)=>{try{await navigator.clipboard.writeText(JSON.stringify(Te,null,2)),S(xe),setTimeout(()=>S(null),2e3)}catch($e){console.error("[PromptsTab] Failed to copy result:",$e)}},[]),Ne=v.useCallback(()=>{s&&(W(""),U(!0))},[s]),He=v.useCallback(xe=>{q(A.filter(Te=>Te.id!==xe)),c?.id===xe&&u(null)},[A,q,c]);return V?d.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[te!=="list"&&d.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[d.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>{te==="response"?D("detail"):(i(null),D("list"))},className:"p-0 h-8 w-8",children:d.jsx(dT,{className:"h-4 w-4"})}),d.jsxs("div",{className:"flex items-center text-sm font-medium",children:[d.jsx("button",{onClick:()=>{i(null),D("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Prompts"}),te!=="list"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("button",{onClick:()=>{te==="response"&&D("detail")},className:te==="detail"?"text-foreground hover:underline":te==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),te==="response"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),d.jsx("div",{className:"flex-1 relative overflow-hidden",children:d.jsxs(Jy,{initial:!1,mode:"popLayout",children:[te==="list"&&d.jsxs(wa.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:[d.jsx(J$,{activeTab:C,isSearchExpanded:J,searchQuery:T,filteredPromptsCount:ie.length,savedPromptsCount:A.length,onSearchExpand:()=>ee(!0),onSearchChange:R,onSearchBlur:ae,onTabSwitch:()=>I(C==="prompts"?"saved":"prompts"),searchInputRef:K}),C==="prompts"?d.jsx(X$,{prompts:ie,selectedPrompt:s,onPromptSelect:X,focusedIndex:re}):d.jsx(Q$,{savedPrompts:A,selectedPrompt:c,onLoadPrompt:Z,onDeletePrompt:He,focusedIndex:re})]},"list"),te==="detail"&&d.jsx(wa.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:d.jsx(ez,{selectedPrompt:s,promptArgs:h,isExecuting:E,isConnected:a,onArgChange:se,onExecute:me,onSave:Ne})},"detail"),te==="response"&&d.jsx(wa.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:d.jsx(tz,{results:y,copiedResult:_,onCopy:le})},"response")]})})]}):d.jsxs(aa,{direction:"horizontal",className:"h-full",children:[d.jsx(Rn,{defaultSize:33,className:"flex flex-col h-full relative",children:d.jsxs(aa,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[d.jsx(Rn,{defaultSize:75,minSize:30,children:d.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[d.jsx(J$,{activeTab:C,isSearchExpanded:J,searchQuery:T,filteredPromptsCount:ie.length,savedPromptsCount:A.length,onSearchExpand:()=>ee(!0),onSearchChange:R,onSearchBlur:ae,onTabSwitch:()=>I(C==="prompts"?"saved":"prompts"),searchInputRef:K}),C==="prompts"?d.jsx(X$,{prompts:ie,selectedPrompt:s,onPromptSelect:X,focusedIndex:re}):d.jsx(Q$,{savedPrompts:A,selectedPrompt:c,onLoadPrompt:Z,onDeletePrompt:He,focusedIndex:re})]})}),d.jsx(wo,{withHandle:!0}),d.jsxs(Rn,{ref:z,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>M(!0),onExpand:()=>M(!1),className:"flex flex-col border-t dark:border-zinc-700",children:[d.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),L?(z.current?.resize(25),M(!1)):(z.current?.resize(5),M(!0))},children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),H>0&&d.jsx(kr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:H}),H>0&&!L&&d.jsx(Le,{variant:"ghost",size:"sm",onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),G.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:d.jsx(Mi,{className:"h-3.5 w-3.5"})})]}),d.jsx(Gl,{className:`h-4 w-4 text-muted-foreground transition-transform ${L?"rotate-180":""}`})]}),!L&&d.jsx("div",{className:"flex-1 overflow-hidden min-h-0",children:d.jsx(z1,{serverIds:[r],onCountChange:$,onClearRef:G})})]})]})}),d.jsx(wo,{withHandle:!0}),d.jsx(Rn,{defaultSize:67,children:d.jsxs(aa,{direction:"vertical",children:[d.jsx(Rn,{defaultSize:40,children:d.jsx(ez,{selectedPrompt:s,promptArgs:h,isExecuting:E,isConnected:a,onArgChange:se,onExecute:me,onSave:Ne})}),d.jsx(wo,{withHandle:!0}),d.jsx(Rn,{defaultSize:50,children:d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(tz,{results:y,copiedResult:_,onCopy:le})})})]})})]})}o8.displayName="PromptsTab";function vu(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 Vve(e){return{uri:e.uri,mimeType:e.mimeType,text:e.text,blob:e.blob}}function s8({resource:e,onUIAction:t,className:n}){const r=async s=>t?.(s),a=Vve(e);return d.jsx("div",{className:n,children:d.jsx(j1,{resource:a,onUIAction:r,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:[tve,eve,nve,rve],library:M1}})})}function Gve(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(`
1658
+ `);T=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"){E+=O.content;const j=w[w.length-1];j&&j.type==="text"?j.text=E:w.push({type:"text",text:E}),console.log("[Parts after text]",w.length,"parts, text length:",E.length),s(U=>U.map(B=>B.id===x?{...B,parts:[...w]}:B))}else if(O.type==="tool-call")E&&(E=""),w.push({type:"tool-invocation",toolInvocation:{toolName:O.toolName,args:O.args,state:"pending"}}),console.log("[Parts after tool-call]",w.length,"parts, tool:",O.toolName),s(j=>j.map(U=>U.id===x?{...U,parts:[...w]}:U));else if(O.type==="tool-result"){const j=w.find(U=>U.type==="tool-invocation"&&U.toolInvocation?.toolName===O.toolName&&!U.toolInvocation?.result);j&&j.toolInvocation?(j.toolInvocation.result=O.result,j.toolInvocation.state="result",console.log("[Parts after tool-result]",w.length,"parts, updated:",O.toolName),s(U=>U.map(B=>B.id===x?{...B,parts:[...w]}:B))):console.warn("[tool-result] Could not find matching tool part for",O.toolName)}else if(O.type==="done")console.log("[Done] Final parts:",w.length),s(j=>j.map(U=>U.id===x?{...U,parts:[...w],content:""}:U));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 y="Unknown error occurred";if(g instanceof Error){y=g.message;const E=g;E.status&&(y=`HTTP ${E.status}: ${y}`),(E.code===401||y.includes("401")||y.includes("Unauthorized"))&&(y="Authentication failed (401). Check your Authorization header in the connection settings.")}const x={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${y}`,timestamp:Date.now()};s(E=>[...E,x])}finally{c(!1)}},[t,r,e,a,n]),f=v.useCallback(()=>{s([])},[]);return{messages:a,isLoading:i,sendMessage:u,clearMessages:f}}function lve({connection:e,llmConfig:t,isConnected:n,readResource:r}){const[a,s]=v.useState([]),[i,c]=v.useState(!1),u=v.useRef(null),f=v.useRef(null),m=v.useRef(null),h=v.useCallback(async y=>{if(!y.trim()||!t||!n)return;const x={id:`user-${Date.now()}`,role:"user",content:y.trim(),timestamp:Date.now()};s(_=>[..._,x]),c(!0),u.current=new AbortController;const E=Date.now();let w=0;try{const _=`assistant-${Date.now()}`;let S="";const T=[];if(s(R=>[...R,{id:_,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 R;if(t.provider==="openai"){const{ChatOpenAI:C}=await rr(async()=>{const{ChatOpenAI:I}=await import("./index-BNQethI5.js");return{ChatOpenAI:I}},__vite__mapDeps([5,6,7,3,8,9]));R=new C({model:t.model,apiKey:t.apiKey})}else if(t.provider==="anthropic"){const{ChatAnthropic:C}=await rr(async()=>{const{ChatAnthropic:I}=await import("./index-CZpbYyd9.js");return{ChatAnthropic:I}},__vite__mapDeps([10,7,6,3]));R=new C({model:t.model,apiKey:t.apiKey})}else if(t.provider==="google"){const{ChatGoogleGenerativeAI:C}=await rr(async()=>{const{ChatGoogleGenerativeAI:I}=await import("./index-BRUKWgxH.js");return{ChatGoogleGenerativeAI:I}},__vite__mapDeps([11,7,6,3,9]));R=new C({model:t.model,apiKey:t.apiKey})}else throw new Error(`Unsupported LLM provider: ${t.provider}`);m.current={instance:R,provider:t.provider,model:t.model,apiKey:t.apiKey}}if(!f.current||f.current.llm!==m.current.instance){const{MCPAgent:R}=await rr(async()=>{const{MCPAgent:C}=await import("./browser-C3nhYEaN.js");return{MCPAgent:C}},__vite__mapDeps([12,8,6,7,3,9]));f.current=new R({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 f.current.initialize()}else console.log("[useChatMessagesClientSide] Reusing existing agent. History length:",f.current.conversationHistory?.length);for await(const R of f.current.streamEvents(y,10,!1,void 0)){if(u.current?.signal.aborted)break;if(R.event==="on_chat_model_stream"&&R.data?.chunk?.text){const C=R.data.chunk.text;if(typeof C=="string"&&C.length>0){S+=C;const I=T[T.length-1];I&&I.type==="text"?I.text=S:T.push({type:"text",text:S}),s(A=>A.map(O=>O.id===_?{...O,parts:[...T]}:O))}}else if(R.event==="on_tool_start"){S&&(S="");let C={};R.data?.input?C=R.data.input:R.data?.tool_input?C=R.data.tool_input:R.data&&(C=R.data),console.log("[useChatMessagesClientSide] on_tool_start:",{toolName:R.name,eventData:R.data,extractedArgs:C}),w++,T.push({type:"tool-invocation",toolInvocation:{toolName:R.name||"unknown",args:C,state:"pending"}}),s(I=>I.map(A=>A.id===_?{...A,parts:[...T]}:A))}else if(R.event==="on_tool_end"){const C=T.find(I=>I.type==="tool-invocation"&&I.toolInvocation?.toolName===R.name&&!I.toolInvocation?.result);if(console.log("[useChatMessagesClientSide] on_tool_end event:",{toolName:R.name,hasToolPart:!!C,output:R.data?.output}),C&&C.toolInvocation){let I=R.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}C.toolInvocation.result=I,C.toolInvocation.state="result";const A=I?._meta?.["openai/outputTemplate"];if(console.log("[useChatMessagesClientSide] Tool result:",{toolName:R.name,hasMeta:!!I?._meta,hasStructuredContent:!!I?.structuredContent,appsSdkUri:A}),A&&typeof A=="string"&&r){console.log("[useChatMessagesClientSide] Detected Apps SDK component, fetching resource:",A);try{const O=await r(A);console.log("[useChatMessagesClientSide] Resource fetched:",O);const j=I?.structuredContent||null;if(O?.contents&&Array.isArray(O.contents)){const U=O.contents.map(W=>({type:"resource",resource:W}));console.log("[useChatMessagesClientSide] Created MCP resources:",U);const B={...I,content:[...I.content||[],...U],structuredContent:j};C.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)}}s(O=>O.map(j=>j.id===_?{...j,parts:[...T]}:j))}}}s(R=>R.map(C=>C.id===_?{...C,parts:[...T],content:""}:C)),t&&Tr.getInstance().capture(new yP({serverId:e.url,provider:t.provider,model:t.model,messageCount:a.length+1,toolCallsCount:w,success:!0,executionMode:"client-side",duration:Date.now()-E})).catch(()=>{})}catch(_){console.error("Client-side agent error:",_);let S="Unknown error occurred";if(_ instanceof Error){S=_.message;const R=_;R.status&&(S=`HTTP ${R.status}: ${S}`),(R.code===401||S.includes("401")||S.includes("Unauthorized"))&&(S="Authentication failed (401). Check your Authorization header in the connection settings.")}t&&Tr.getInstance().capture(new yP({serverId:e.url,provider:t.provider,model:t.model,messageCount:a.length+1,toolCallsCount:w,success:!1,executionMode:"client-side",duration:Date.now()-E,error:S})).catch(()=>{});const T={id:`error-${Date.now()}`,role:"assistant",content:`Error: ${S}`,timestamp:Date.now()};s(R=>[...R,T])}finally{c(!1),u.current=null}},[e,t,n,a,r]),g=v.useCallback(()=>{s([]),f.current&&f.current.clearConversationHistory()},[]);return{messages:a,isLoading:i,sendMessage:h,clearMessages:g}}const B$={openai:"gpt-4o",anthropic:"claude-haiku-4-5-20251001",google:"gemini-2.5-flash"};function j6({mcpServerUrl:e}){const[t,n]=v.useState(null),[r,a]=v.useState(null),[s,i]=v.useState(!1),[c,u]=v.useState("openai"),[f,m]=v.useState(""),[h,g]=v.useState(B$.openai),y=v.useCallback(()=>{const j=localStorage.getItem("mcp-inspector-api-keys");if(j)try{return JSON.parse(j)}catch(U){return console.error("Failed to load API keys:",U),{}}return{}},[]),x=v.useCallback(j=>{localStorage.setItem("mcp-inspector-api-keys",JSON.stringify(j))},[]),[E,w]=v.useState("none"),[_,S]=v.useState(""),[T,R]=v.useState(""),[C,I]=v.useState("");v.useEffect(()=>{const j=localStorage.getItem("mcp-inspector-llm-config"),U=y();if(j)try{const B=JSON.parse(j);n(B),u(B.provider),m(U[B.provider]||B.apiKey||""),g(B.model)}catch(B){console.error("Failed to load LLM config:",B)}},[y]),v.useEffect(()=>{const j=localStorage.getItem("mcp-inspector-auth-config");if(j)try{const U=JSON.parse(j);a(U),w(U.type),U.username&&S(U.username),U.password&&R(U.password),U.token&&I(U.token)}catch(U){console.error("Failed to load auth config:",U)}else try{const U="mcp:auth",B=M6(e),W=`${U}_${B}_tokens`;localStorage.getItem(W)&&(a({type:"oauth"}),w("oauth"))}catch(U){console.error("Failed to check for OAuth tokens:",U)}},[e]),v.useEffect(()=>{g(B$[c]);const j=y();m(j[c]||"")},[c,y]);const A=v.useCallback(()=>{if(!f.trim())return;const j=y();j[c]=f,x(j);const U={provider:c,apiKey:f,model:h},B={type:E,...E==="basic"&&{username:_.trim(),password:T.trim()},...E==="bearer"&&{token:C.trim()}};n(U),a(B),localStorage.setItem("mcp-inspector-llm-config",JSON.stringify(U)),localStorage.setItem("mcp-inspector-auth-config",JSON.stringify(B)),i(!1)},[c,f,h,E,_,T,C,y,x]),O=v.useCallback(()=>{n(null),a(null);const j=y();delete j[c],x(j),m(""),S(""),R(""),I(""),w("none"),localStorage.removeItem("mcp-inspector-llm-config"),localStorage.removeItem("mcp-inspector-auth-config")},[c,y,x]);return{llmConfig:t,authConfig:r,configDialogOpen:s,setConfigDialogOpen:i,tempProvider:c,setTempProvider:u,tempApiKey:f,setTempApiKey:m,tempModel:h,setTempModel:g,tempAuthType:E,saveLLMConfig:A,clearConfig:O}}function cve({connection:e,isConnected:t,useClientSide:n=!0,readResource:r}){const[a,s]=v.useState(""),i=v.useRef(null),{llmConfig:c,authConfig:u,configDialogOpen:f,setConfigDialogOpen:m,tempProvider:h,setTempProvider:g,tempApiKey:y,setTempApiKey:x,tempModel:E,setTempModel:w,saveLLMConfig:_,clearConfig:S}=j6({mcpServerUrl:e.url}),T={connection:e,llmConfig:c,isConnected:t,readResource:r},R=ive({mcpServerUrl:e.url,llmConfig:c,authConfig:u,isConnected:t}),C=lve(T),{messages:I,isLoading:A,sendMessage:O,clearMessages:j}=n?C:R;LH({onNewChat:j}),v.useEffect(()=>{c&&I.length===0&&i.current&&i.current.focus()},[c,I.length]),v.useEffect(()=>{!A&&I.length>0&&i.current&&i.current.focus()},[A,I.length]);const U=v.useCallback(()=>{a.trim()&&(O(a),s(""))},[a,O]),B=v.useCallback(J=>{J.key==="Enter"&&!J.shiftKey&&(J.preventDefault(),U())},[U]),W=v.useCallback(()=>{S(),j()},[S,j]);return c&&I.length===0?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx("div",{className:"absolute top-4 right-4 z-10",children:d.jsx(SS,{open:f,onOpenChange:m,tempProvider:h,tempModel:E,tempApiKey:y,onProviderChange:g,onModelChange:w,onApiKeyChange:x,onSave:_,onClear:W,showClearButton:!0,buttonLabel:"Change API Key"})}),d.jsx(xhe,{mcpServerUrl:e.url,inputValue:a,isConnected:t,isLoading:A,textareaRef:i,llmConfig:c,onInputChange:s,onKeyDown:B,onSubmit:J=>{J.preventDefault(),U()},onConfigDialogOpenChange:m})]}):d.jsxs("div",{className:"flex flex-col h-full relative",children:[d.jsx(vhe,{llmConfig:c,hasMessages:I.length>0,configDialogOpen:f,onConfigDialogOpenChange:m,onClearChat:j,tempProvider:h,tempModel:E,tempApiKey:y,onProviderChange:g,onModelChange:w,onApiKeyChange:x,onSaveConfig:_,onClearConfig:W}),d.jsx("div",{className:"flex-1 overflow-y-auto p-2 sm:p-4 pt-[80px] sm:pt-[100px]",children:c?d.jsx(sve,{messages:I,isLoading:A,serverId:e.url,readResource:r,tools:e.tools}):d.jsx(She,{onConfigureClick:()=>m(!0)})}),c&&d.jsx(whe,{inputValue:a,isConnected:t,isLoading:A,textareaRef:i,onInputChange:s,onKeyDown:B,onSendMessage:U})]})}const wv=v.createContext(null);wv.displayName="PanelGroupContext";const qn={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"},P1=10,Cl=v.useLayoutEffect,H$=id.useId,uve=typeof H$=="function"?H$:()=>null;let dve=0;function U1(e=null){const t=uve(),n=v.useRef(e||t||null);return n.current===null&&(n.current=""+dve++),e??n.current}function P6({children:e,className:t="",collapsedSize:n,collapsible:r,defaultSize:a,forwardedRef:s,id:i,maxSize:c,minSize:u,onCollapse:f,onExpand:m,onResize:h,order:g,style:y,tagName:x="div",...E}){const w=v.useContext(wv);if(w===null)throw Error("Panel components must be rendered within a PanelGroup container");const{collapsePanel:_,expandPanel:S,getPanelSize:T,getPanelStyle:R,groupId:C,isPanelCollapsed:I,reevaluatePanelConstraints:A,registerPanel:O,resizePanel:j,unregisterPanel:U}=w,B=U1(i),W=v.useRef({callbacks:{onCollapse:f,onExpand:m,onResize:h},constraints:{collapsedSize:n,collapsible:r,defaultSize:a,maxSize:c,minSize:u},id:B,idIsFromProps:i!==void 0,order:g});v.useRef({didLogMissingDefaultSizeWarning:!1}),Cl(()=>{const{callbacks:ee,constraints:re}=W.current,F={...re};W.current.id=B,W.current.idIsFromProps=i!==void 0,W.current.order=g,ee.onCollapse=f,ee.onExpand=m,ee.onResize=h,re.collapsedSize=n,re.collapsible=r,re.defaultSize=a,re.maxSize=c,re.minSize=u,(F.collapsedSize!==re.collapsedSize||F.collapsible!==re.collapsible||F.maxSize!==re.maxSize||F.minSize!==re.minSize)&&A(W.current,F)}),Cl(()=>{const ee=W.current;return O(ee),()=>{U(ee)}},[g,B,O,U]),v.useImperativeHandle(s,()=>({collapse:()=>{_(W.current)},expand:ee=>{S(W.current,ee)},getId(){return B},getSize(){return T(W.current)},isCollapsed(){return I(W.current)},isExpanded(){return!I(W.current)},resize:ee=>{j(W.current,ee)}}),[_,S,T,I,B,j]);const J=R(W.current,a);return v.createElement(x,{...E,children:e,className:t,id:B,style:{...J,...y},[qn.groupId]:C,[qn.panel]:"",[qn.panelCollapsible]:r||void 0,[qn.panelId]:B,[qn.panelSize]:parseFloat(""+J.flexGrow).toFixed(1)})}const U6=v.forwardRef((e,t)=>v.createElement(P6,{...e,forwardedRef:t}));P6.displayName="Panel";U6.displayName="forwardRef(Panel)";let JS=null,ub=-1,_i=null;function fve(e,t,n){const r=(t&H6)!==0,a=(t&V6)!==0,s=(t&G6)!==0,i=(t&W6)!==0;if(t){if(r)return s?"se-resize":i?"ne-resize":"e-resize";if(a)return s?"sw-resize":i?"nw-resize":"w-resize";if(s)return"s-resize";if(i)return"n-resize"}switch(e){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function pve(){_i!==null&&(document.head.removeChild(_i),JS=null,_i=null,ub=-1)}function XE(e,t,n){var r,a;const s=fve(e,t);if(JS!==s){if(JS=s,_i===null&&(_i=document.createElement("style"),document.head.appendChild(_i)),ub>=0){var i;(i=_i.sheet)===null||i===void 0||i.removeRule(ub)}ub=(r=(a=_i.sheet)===null||a===void 0?void 0:a.insertRule(`*{cursor: ${s} !important;}`))!==null&&r!==void 0?r:-1}}function $6(e){return e.type==="keydown"}function z6(e){return e.type.startsWith("pointer")}function F6(e){return e.type.startsWith("mouse")}function Ev(e){if(z6(e)){if(e.isPrimary)return{x:e.clientX,y:e.clientY}}else if(F6(e))return{x:e.clientX,y:e.clientY};return{x:1/0,y:1/0}}function mve(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function hve(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 gve(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:W$(e),b:W$(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)e=n.a.pop(),t=n.b.pop(),r=e;Ct(r,"Stacking order can only be calculated for elements with a common ancestor");const a={a:G$(V$(n.a)),b:G$(V$(n.b))};if(a.a===a.b){const s=r.childNodes,i={a:n.a.at(-1),b:n.b.at(-1)};let c=s.length;for(;c--;){const u=s[c];if(u===i.a)return 1;if(u===i.b)return-1}}return Math.sign(a.a-a.b)}const bve=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function yve(e){var t;const n=getComputedStyle((t=B6(e))!==null&&t!==void 0?t:e).display;return n==="flex"||n==="inline-flex"}function vve(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||yve(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"||bve.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function V$(e){let t=e.length;for(;t--;){const n=e[t];if(Ct(n,"Missing node"),vve(n))return n}return null}function G$(e){return e&&Number(getComputedStyle(e).zIndex)||0}function W$(e){const t=[];for(;e;)t.push(e),e=B6(e);return t}function B6(e){const{parentNode:t}=e;return t&&t instanceof ShadowRoot?t.host:t}const H6=1,V6=2,G6=4,W6=8,wve=mve()==="coarse";let vo=[],yu=!1,Ti=new Map,xv=new Map;const Lp=new Set;function Eve(e,t,n,r,a){var s;const{ownerDocument:i}=t,c={direction:n,element:t,hitAreaMargins:r,setResizeHandlerState:a},u=(s=Ti.get(i))!==null&&s!==void 0?s:0;return Ti.set(i,u+1),Lp.add(c),ly(),function(){var m;xv.delete(e),Lp.delete(c);const h=(m=Ti.get(i))!==null&&m!==void 0?m:1;if(Ti.set(i,h-1),ly(),h===1&&Ti.delete(i),vo.includes(c)){const g=vo.indexOf(c);g>=0&&vo.splice(g,1),Sv(),a("up",!0,null)}}}function xve(e){const{target:t}=e,{x:n,y:r}=Ev(e);yu=!0,$1({target:t,x:n,y:r}),ly(),vo.length>0&&(cy("down",e),Sv(),e.preventDefault(),K6(t)||e.stopImmediatePropagation())}function JE(e){const{x:t,y:n}=Ev(e);if(yu&&e.type!=="pointerleave"&&e.buttons===0&&(yu=!1,cy("up",e)),!yu){const{target:r}=e;$1({target:r,x:t,y:n})}cy("move",e),Sv(),vo.length>0&&e.preventDefault()}function QE(e){const{target:t}=e,{x:n,y:r}=Ev(e);xv.clear(),yu=!1,vo.length>0&&(e.preventDefault(),K6(t)||e.stopImmediatePropagation()),cy("up",e),$1({target:t,x:n,y:r}),Sv(),ly()}function K6(e){let t=e;for(;t;){if(t.hasAttribute(qn.resizeHandle))return!0;t=t.parentElement}return!1}function $1({target:e,x:t,y:n}){vo.splice(0);let r=null;(e instanceof HTMLElement||e instanceof SVGElement)&&(r=e),Lp.forEach(a=>{const{element:s,hitAreaMargins:i}=a,c=s.getBoundingClientRect(),{bottom:u,left:f,right:m,top:h}=c,g=wve?i.coarse:i.fine;if(t>=f-g&&t<=m+g&&n>=h-g&&n<=u+g){if(r!==null&&document.contains(r)&&s!==r&&!s.contains(r)&&!r.contains(s)&&gve(r,s)>0){let x=r,E=!1;for(;x&&!x.contains(s);){if(hve(x.getBoundingClientRect(),c)){E=!0;break}x=x.parentElement}if(E)return}vo.push(a)}})}function ex(e,t){xv.set(e,t)}function Sv(){let e=!1,t=!1;vo.forEach(r=>{const{direction:a}=r;a==="horizontal"?e=!0:t=!0});let n=0;xv.forEach(r=>{n|=r}),e&&t?XE("intersection",n):e?XE("horizontal",n):t?XE("vertical",n):pve()}let tx;function ly(){var e;(e=tx)===null||e===void 0||e.abort(),tx=new AbortController;const t={capture:!0,signal:tx.signal};Lp.size&&(yu?(vo.length>0&&Ti.forEach((n,r)=>{const{body:a}=r;n>0&&(a.addEventListener("contextmenu",QE,t),a.addEventListener("pointerleave",JE,t),a.addEventListener("pointermove",JE,t))}),Ti.forEach((n,r)=>{const{body:a}=r;a.addEventListener("pointerup",QE,t),a.addEventListener("pointercancel",QE,t)})):Ti.forEach((n,r)=>{const{body:a}=r;n>0&&(a.addEventListener("pointerdown",xve,t),a.addEventListener("pointermove",JE,t))}))}function cy(e,t){Lp.forEach(n=>{const{setResizeHandlerState:r}=n,a=vo.includes(n);r(e,a,t)})}function Sve(){const[e,t]=v.useState(0);return v.useCallback(()=>t(n=>n+1),[])}function Ct(e,t){if(!e)throw console.error(t),Error(t)}function $l(e,t,n=P1){return e.toFixed(n)===t.toFixed(n)?0:e>t?1:-1}function Ss(e,t,n=P1){return $l(e,t,n)===0}function Pa(e,t,n){return $l(e,t,n)===0}function _ve(e,t,n){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++){const a=e[r],s=t[r];if(!Pa(a,s,n))return!1}return!0}function cu({panelConstraints:e,panelIndex:t,size:n}){const r=e[t];Ct(r!=null,`Panel constraints not found for index ${t}`);let{collapsedSize:a=0,collapsible:s,maxSize:i=100,minSize:c=0}=r;if($l(n,c)<0)if(s){const u=(a+c)/2;$l(n,u)<0?n=a:n=c}else n=c;return n=Math.min(i,n),n=parseFloat(n.toFixed(P1)),n}function Ff({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:r,prevLayout:a,trigger:s}){if(Pa(e,0))return t;const i=[...t],[c,u]=r;Ct(c!=null,"Invalid first pivot index"),Ct(u!=null,"Invalid second pivot index");let f=0;if(s==="keyboard"){{const h=e<0?u:c,g=n[h];Ct(g,`Panel constraints not found for index ${h}`);const{collapsedSize:y=0,collapsible:x,minSize:E=0}=g;if(x){const w=t[h];if(Ct(w!=null,`Previous layout not found for panel index ${h}`),Pa(w,y)){const _=E-w;$l(_,Math.abs(e))>0&&(e=e<0?0-_:_)}}}{const h=e<0?c:u,g=n[h];Ct(g,`No panel constraints found for index ${h}`);const{collapsedSize:y=0,collapsible:x,minSize:E=0}=g;if(x){const w=t[h];if(Ct(w!=null,`Previous layout not found for panel index ${h}`),Pa(w,E)){const _=w-y;$l(_,Math.abs(e))>0&&(e=e<0?0-_:_)}}}}{const h=e<0?1:-1;let g=e<0?u:c,y=0;for(;;){const E=t[g];Ct(E!=null,`Previous layout not found for panel index ${g}`);const _=cu({panelConstraints:n,panelIndex:g,size:100})-E;if(y+=_,g+=h,g<0||g>=n.length)break}const x=Math.min(Math.abs(e),Math.abs(y));e=e<0?0-x:x}{let g=e<0?c:u;for(;g>=0&&g<n.length;){const y=Math.abs(e)-Math.abs(f),x=t[g];Ct(x!=null,`Previous layout not found for panel index ${g}`);const E=x-y,w=cu({panelConstraints:n,panelIndex:g,size:E});if(!Pa(x,w)&&(f+=x-w,i[g]=w,f.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?g--:g++}}if(_ve(a,i))return a;{const h=e<0?u:c,g=t[h];Ct(g!=null,`Previous layout not found for panel index ${h}`);const y=g+f,x=cu({panelConstraints:n,panelIndex:h,size:y});if(i[h]=x,!Pa(x,y)){let E=y-x,_=e<0?u:c;for(;_>=0&&_<n.length;){const S=i[_];Ct(S!=null,`Previous layout not found for panel index ${_}`);const T=S+E,R=cu({panelConstraints:n,panelIndex:_,size:T});if(Pa(S,R)||(E-=R-S,i[_]=R),Pa(E,0))break;e>0?_--:_++}}}const m=i.reduce((h,g)=>g+h,0);return Pa(m,100)?i:a}function Tve({layout:e,panelsArray:t,pivotIndices:n}){let r=0,a=100,s=0,i=0;const c=n[0];Ct(c!=null,"No pivot index found"),t.forEach((h,g)=>{const{constraints:y}=h,{maxSize:x=100,minSize:E=0}=y;g===c?(r=E,a=x):(s+=E,i+=x)});const u=Math.min(a,100-s),f=Math.max(r,100-i),m=e[c];return{valueMax:u,valueMin:f,valueNow:m}}function Mp(e,t=document){return Array.from(t.querySelectorAll(`[${qn.resizeHandleId}][data-panel-group-id="${e}"]`))}function Y6(e,t,n=document){const a=Mp(e,n).findIndex(s=>s.getAttribute(qn.resizeHandleId)===t);return a??null}function Z6(e,t,n){const r=Y6(e,t,n);return r!=null?[r,r+1]:[-1,-1]}function Nve(e){return e instanceof HTMLElement?!0:typeof e=="object"&&e!==null&&"tagName"in e&&"getAttribute"in e}function q6(e,t=document){if(Nve(t)&&t.dataset.panelGroupId==e)return t;const n=t.querySelector(`[data-panel-group][data-panel-group-id="${e}"]`);return n||null}function _v(e,t=document){const n=t.querySelector(`[${qn.resizeHandleId}="${e}"]`);return n||null}function kve(e,t,n,r=document){var a,s,i,c;const u=_v(t,r),f=Mp(e,r),m=u?f.indexOf(u):-1,h=(a=(s=n[m])===null||s===void 0?void 0:s.id)!==null&&a!==void 0?a:null,g=(i=(c=n[m+1])===null||c===void 0?void 0:c.id)!==null&&i!==void 0?i:null;return[h,g]}function Cve({committedValuesRef:e,eagerValuesRef:t,groupId:n,layout:r,panelDataArray:a,panelGroupElement:s,setLayout:i}){v.useRef({didWarnAboutMissingResizeHandle:!1}),Cl(()=>{if(!s)return;const c=Mp(n,s);for(let u=0;u<a.length-1;u++){const{valueMax:f,valueMin:m,valueNow:h}=Tve({layout:r,panelsArray:a,pivotIndices:[u,u+1]}),g=c[u];if(g!=null){const y=a[u];Ct(y,`No panel data found for index "${u}"`),g.setAttribute("aria-controls",y.id),g.setAttribute("aria-valuemax",""+Math.round(f)),g.setAttribute("aria-valuemin",""+Math.round(m)),g.setAttribute("aria-valuenow",h!=null?""+Math.round(h):"")}}return()=>{c.forEach((u,f)=>{u.removeAttribute("aria-controls"),u.removeAttribute("aria-valuemax"),u.removeAttribute("aria-valuemin"),u.removeAttribute("aria-valuenow")})}},[n,r,a,s]),v.useEffect(()=>{if(!s)return;const c=t.current;Ct(c,"Eager values not found");const{panelDataArray:u}=c,f=q6(n,s);Ct(f!=null,`No group found for id "${n}"`);const m=Mp(n,s);Ct(m,`No resize handles found for group id "${n}"`);const h=m.map(g=>{const y=g.getAttribute(qn.resizeHandleId);Ct(y,"Resize handle element has no handle id attribute");const[x,E]=kve(n,y,u,s);if(x==null||E==null)return()=>{};const w=_=>{if(!_.defaultPrevented)switch(_.key){case"Enter":{_.preventDefault();const S=u.findIndex(T=>T.id===x);if(S>=0){const T=u[S];Ct(T,`No panel data found for index ${S}`);const R=r[S],{collapsedSize:C=0,collapsible:I,minSize:A=0}=T.constraints;if(R!=null&&I){const O=Ff({delta:Pa(R,C)?A-C:C-R,initialLayout:r,panelConstraints:u.map(j=>j.constraints),pivotIndices:Z6(n,y,s),prevLayout:r,trigger:"keyboard"});r!==O&&i(O)}}break}}};return g.addEventListener("keydown",w),()=>{g.removeEventListener("keydown",w)}});return()=>{h.forEach(g=>g())}},[s,e,t,n,r,a,i])}function K$(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 X6(e,t){const n=e==="horizontal",{x:r,y:a}=Ev(t);return n?r:a}function Rve(e,t,n,r,a){const s=n==="horizontal",i=_v(t,a);Ct(i,`No resize handle element found for id "${t}"`);const c=i.getAttribute(qn.groupId);Ct(c,"Resize handle element has no group id attribute");let{initialCursorPosition:u}=r;const f=X6(n,e),m=q6(c,a);Ct(m,`No group element found for id "${c}"`);const h=m.getBoundingClientRect(),g=s?h.width:h.height;return(f-u)/g*100}function Ave(e,t,n,r,a,s){if($6(e)){const i=n==="horizontal";let c=0;e.shiftKey?c=100:a!=null?c=a:c=10;let u=0;switch(e.key){case"ArrowDown":u=i?0:c;break;case"ArrowLeft":u=i?-c:0;break;case"ArrowRight":u=i?c:0;break;case"ArrowUp":u=i?0:-c;break;case"End":u=100;break;case"Home":u=-100;break}return u}else return r==null?0:Rve(e,t,n,r,s)}function Ive({panelDataArray:e}){const t=Array(e.length),n=e.map(s=>s.constraints);let r=0,a=100;for(let s=0;s<e.length;s++){const i=n[s];Ct(i,`Panel constraints not found for index ${s}`);const{defaultSize:c}=i;c!=null&&(r++,t[s]=c,a-=c)}for(let s=0;s<e.length;s++){const i=n[s];Ct(i,`Panel constraints not found for index ${s}`);const{defaultSize:c}=i;if(c!=null)continue;const u=e.length-r,f=a/u;r++,t[s]=f,a-=f}return t}function Uc(e,t,n){t.forEach((r,a)=>{const s=e[a];Ct(s,`Panel data not found for index ${a}`);const{callbacks:i,constraints:c,id:u}=s,{collapsedSize:f=0,collapsible:m}=c,h=n[u];if(h==null||r!==h){n[u]=r;const{onCollapse:g,onExpand:y,onResize:x}=i;x&&x(r,h),m&&(g||y)&&(y&&(h==null||Ss(h,f))&&!Ss(r,f)&&y(),g&&(h==null||!Ss(h,f))&&Ss(r,f)&&g())}})}function $g(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 Ove({defaultSize:e,dragState:t,layout:n,panelData:r,panelIndex:a,precision:s=3}){const i=n[a];let c;return i==null?c=e!=null?e.toFixed(s):"1":r.length===1?c="1":c=i.toFixed(s),{flexBasis:0,flexGrow:c,flexShrink:1,overflow:"hidden",pointerEvents:t!==null?"none":void 0}}function Dve(e,t=10){let n=null;return(...a)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{e(...a)},t)}}function Y$(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 J6(e){return`react-resizable-panels:${e}`}function Q6(e){return e.map(t=>{const{constraints:n,id:r,idIsFromProps:a,order:s}=t;return a?r:s?`${s}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((t,n)=>t.localeCompare(n)).join(",")}function e8(e,t){try{const n=J6(e),r=t.getItem(n);if(r){const a=JSON.parse(r);if(typeof a=="object"&&a!=null)return a}}catch{}return null}function Lve(e,t,n){var r,a;const s=(r=e8(e,n))!==null&&r!==void 0?r:{},i=Q6(t);return(a=s[i])!==null&&a!==void 0?a:null}function Mve(e,t,n,r,a){var s;const i=J6(e),c=Q6(t),u=(s=e8(e,a))!==null&&s!==void 0?s:{};u[c]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{a.setItem(i,JSON.stringify(u))}catch(f){console.error(f)}}function Z$({layout:e,panelConstraints:t}){const n=[...e],r=n.reduce((s,i)=>s+i,0);if(n.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${n.map(s=>`${s}%`).join(", ")}`);if(!Pa(r,100)&&n.length>0)for(let s=0;s<t.length;s++){const i=n[s];Ct(i!=null,`No layout data found for index ${s}`);const c=100/r*i;n[s]=c}let a=0;for(let s=0;s<t.length;s++){const i=n[s];Ct(i!=null,`No layout data found for index ${s}`);const c=cu({panelConstraints:t,panelIndex:s,size:i});i!=c&&(a+=i-c,n[s]=c)}if(!Pa(a,0))for(let s=0;s<t.length;s++){const i=n[s];Ct(i!=null,`No layout data found for index ${s}`);const c=i+a,u=cu({panelConstraints:t,panelIndex:s,size:c});if(i!==u&&(a-=u-i,n[s]=u,Pa(a,0)))break}return n}const jve=100,Bf={getItem:e=>(Y$(Bf),Bf.getItem(e)),setItem:(e,t)=>{Y$(Bf),Bf.setItem(e,t)}},q$={};function t8({autoSaveId:e=null,children:t,className:n="",direction:r,forwardedRef:a,id:s=null,onLayout:i=null,keyboardResizeBy:c=null,storage:u=Bf,style:f,tagName:m="div",...h}){const g=U1(s),y=v.useRef(null),[x,E]=v.useState(null),[w,_]=v.useState([]),S=Sve(),T=v.useRef({}),R=v.useRef(new Map),C=v.useRef(0),I=v.useRef({autoSaveId:e,direction:r,dragState:x,id:g,keyboardResizeBy:c,onLayout:i,storage:u}),A=v.useRef({layout:w,panelDataArray:[],panelDataArrayChanged:!1});v.useRef({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),v.useImperativeHandle(a,()=>({getId:()=>I.current.id,getLayout:()=>{const{layout:$}=A.current;return $},setLayout:$=>{const{onLayout:L}=I.current,{layout:M,panelDataArray:z}=A.current,G=Z$({layout:$,panelConstraints:z.map(q=>q.constraints)});K$(M,G)||(_(G),A.current.layout=G,L&&L(G),Uc(z,G,T.current))}}),[]),Cl(()=>{I.current.autoSaveId=e,I.current.direction=r,I.current.dragState=x,I.current.id=g,I.current.onLayout=i,I.current.storage=u}),Cve({committedValuesRef:I,eagerValuesRef:A,groupId:g,layout:w,panelDataArray:A.current.panelDataArray,setLayout:_,panelGroupElement:y.current}),v.useEffect(()=>{const{panelDataArray:$}=A.current;if(e){if(w.length===0||w.length!==$.length)return;let L=q$[e];L==null&&(L=Dve(Mve,jve),q$[e]=L);const M=[...$],z=new Map(R.current);L(e,M,z,w,u)}},[e,w,u]),v.useEffect(()=>{});const O=v.useCallback($=>{const{onLayout:L}=I.current,{layout:M,panelDataArray:z}=A.current;if($.constraints.collapsible){const G=z.map(X=>X.constraints),{collapsedSize:q=0,panelSize:ae,pivotIndices:ie}=gl(z,$,M);if(Ct(ae!=null,`Panel size not found for panel "${$.id}"`),!Ss(ae,q)){R.current.set($.id,ae);const Z=Yc(z,$)===z.length-1?ae-q:q-ae,se=Ff({delta:Z,initialLayout:M,panelConstraints:G,pivotIndices:ie,prevLayout:M,trigger:"imperative-api"});$g(M,se)||(_(se),A.current.layout=se,L&&L(se),Uc(z,se,T.current))}}},[]),j=v.useCallback(($,L)=>{const{onLayout:M}=I.current,{layout:z,panelDataArray:G}=A.current;if($.constraints.collapsible){const q=G.map(me=>me.constraints),{collapsedSize:ae=0,panelSize:ie=0,minSize:X=0,pivotIndices:Z}=gl(G,$,z),se=L??X;if(Ss(ie,ae)){const me=R.current.get($.id),le=me!=null&&me>=se?me:se,He=Yc(G,$)===G.length-1?ie-le:le-ie,xe=Ff({delta:He,initialLayout:z,panelConstraints:q,pivotIndices:Z,prevLayout:z,trigger:"imperative-api"});$g(z,xe)||(_(xe),A.current.layout=xe,M&&M(xe),Uc(G,xe,T.current))}}},[]),U=v.useCallback($=>{const{layout:L,panelDataArray:M}=A.current,{panelSize:z}=gl(M,$,L);return Ct(z!=null,`Panel size not found for panel "${$.id}"`),z},[]),B=v.useCallback(($,L)=>{const{panelDataArray:M}=A.current,z=Yc(M,$);return Ove({defaultSize:L,dragState:x,layout:w,panelData:M,panelIndex:z})},[x,w]),W=v.useCallback($=>{const{layout:L,panelDataArray:M}=A.current,{collapsedSize:z=0,collapsible:G,panelSize:q}=gl(M,$,L);return Ct(q!=null,`Panel size not found for panel "${$.id}"`),G===!0&&Ss(q,z)},[]),J=v.useCallback($=>{const{layout:L,panelDataArray:M}=A.current,{collapsedSize:z=0,collapsible:G,panelSize:q}=gl(M,$,L);return Ct(q!=null,`Panel size not found for panel "${$.id}"`),!G||$l(q,z)>0},[]),ee=v.useCallback($=>{const{panelDataArray:L}=A.current;L.push($),L.sort((M,z)=>{const G=M.order,q=z.order;return G==null&&q==null?0:G==null?-1:q==null?1:G-q}),A.current.panelDataArrayChanged=!0,S()},[S]);Cl(()=>{if(A.current.panelDataArrayChanged){A.current.panelDataArrayChanged=!1;const{autoSaveId:$,onLayout:L,storage:M}=I.current,{layout:z,panelDataArray:G}=A.current;let q=null;if($){const ie=Lve($,G,M);ie&&(R.current=new Map(Object.entries(ie.expandToSizes)),q=ie.layout)}q==null&&(q=Ive({panelDataArray:G}));const ae=Z$({layout:q,panelConstraints:G.map(ie=>ie.constraints)});K$(z,ae)||(_(ae),A.current.layout=ae,L&&L(ae),Uc(G,ae,T.current))}}),Cl(()=>{const $=A.current;return()=>{$.layout=[]}},[]);const re=v.useCallback($=>{let L=!1;const M=y.current;return M&&window.getComputedStyle(M,null).getPropertyValue("direction")==="rtl"&&(L=!0),function(G){G.preventDefault();const q=y.current;if(!q)return()=>null;const{direction:ae,dragState:ie,id:X,keyboardResizeBy:Z,onLayout:se}=I.current,{layout:me,panelDataArray:le}=A.current,{initialLayout:Ne}=ie??{},He=Z6(X,$,q);let xe=Ave(G,$,ae,ie,Z,q);const Te=ae==="horizontal";Te&&L&&(xe=-xe);const $e=le.map(Fe=>Fe.constraints),fe=Ff({delta:xe,initialLayout:Ne??me,panelConstraints:$e,pivotIndices:He,prevLayout:me,trigger:$6(G)?"keyboard":"mouse-or-touch"}),Ie=!$g(me,fe);(z6(G)||F6(G))&&C.current!=xe&&(C.current=xe,!Ie&&xe!==0?Te?ex($,xe<0?H6:V6):ex($,xe<0?G6:W6):ex($,0)),Ie&&(_(fe),A.current.layout=fe,se&&se(fe),Uc(le,fe,T.current))}},[]),F=v.useCallback(($,L)=>{const{onLayout:M}=I.current,{layout:z,panelDataArray:G}=A.current,q=G.map(me=>me.constraints),{panelSize:ae,pivotIndices:ie}=gl(G,$,z);Ct(ae!=null,`Panel size not found for panel "${$.id}"`);const Z=Yc(G,$)===G.length-1?ae-L:L-ae,se=Ff({delta:Z,initialLayout:z,panelConstraints:q,pivotIndices:ie,prevLayout:z,trigger:"imperative-api"});$g(z,se)||(_(se),A.current.layout=se,M&&M(se),Uc(G,se,T.current))},[]),K=v.useCallback(($,L)=>{const{layout:M,panelDataArray:z}=A.current,{collapsedSize:G=0,collapsible:q}=L,{collapsedSize:ae=0,collapsible:ie,maxSize:X=100,minSize:Z=0}=$.constraints,{panelSize:se}=gl(z,$,M);se!=null&&(q&&ie&&Ss(se,G)?Ss(G,ae)||F($,ae):se<Z?F($,Z):se>X&&F($,X))},[F]),V=v.useCallback(($,L)=>{const{direction:M}=I.current,{layout:z}=A.current;if(!y.current)return;const G=_v($,y.current);Ct(G,`Drag handle element not found for id "${$}"`);const q=X6(M,L);E({dragHandleId:$,dragHandleRect:G.getBoundingClientRect(),initialCursorPosition:q,initialLayout:z})},[]),ne=v.useCallback(()=>{E(null)},[]),te=v.useCallback($=>{const{panelDataArray:L}=A.current,M=Yc(L,$);M>=0&&(L.splice(M,1),delete T.current[$.id],A.current.panelDataArrayChanged=!0,S())},[S]),D=v.useMemo(()=>({collapsePanel:O,direction:r,dragState:x,expandPanel:j,getPanelSize:U,getPanelStyle:B,groupId:g,isPanelCollapsed:W,isPanelExpanded:J,reevaluatePanelConstraints:K,registerPanel:ee,registerResizeHandle:re,resizePanel:F,startDragging:V,stopDragging:ne,unregisterPanel:te,panelGroupElement:y.current}),[O,x,r,j,U,B,g,W,J,K,ee,re,F,V,ne,te]),H={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return v.createElement(wv.Provider,{value:D},v.createElement(m,{...h,children:t,className:n,id:s,ref:y,style:{...H,...f},[qn.group]:"",[qn.groupDirection]:r,[qn.groupId]:g}))}const n8=v.forwardRef((e,t)=>v.createElement(t8,{...e,forwardedRef:t}));t8.displayName="PanelGroup";n8.displayName="forwardRef(PanelGroup)";function Yc(e,t){return e.findIndex(n=>n===t||n.id===t.id)}function gl(e,t,n){const r=Yc(e,t),s=r===e.length-1?[r-1,r]:[r,r+1],i=n[r];return{...t.constraints,panelSize:i,pivotIndices:s}}function Pve({disabled:e,handleId:t,resizeHandler:n,panelGroupElement:r}){v.useEffect(()=>{if(e||n==null||r==null)return;const a=_v(t,r);if(a==null)return;const s=i=>{if(!i.defaultPrevented)switch(i.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{i.preventDefault(),n(i);break}case"F6":{i.preventDefault();const c=a.getAttribute(qn.groupId);Ct(c,`No group element found for id "${c}"`);const u=Mp(c,r),f=Y6(c,t,r);Ct(f!==null,`No resize element found for id "${t}"`);const m=i.shiftKey?f>0?f-1:u.length-1:f+1<u.length?f+1:0;u[m].focus();break}}};return a.addEventListener("keydown",s),()=>{a.removeEventListener("keydown",s)}},[r,e,t,n])}function r8({children:e=null,className:t="",disabled:n=!1,hitAreaMargins:r,id:a,onBlur:s,onClick:i,onDragging:c,onFocus:u,onPointerDown:f,onPointerUp:m,style:h={},tabIndex:g=0,tagName:y="div",...x}){var E,w;const _=v.useRef(null),S=v.useRef({onClick:i,onDragging:c,onPointerDown:f,onPointerUp:m});v.useEffect(()=>{S.current.onClick=i,S.current.onDragging=c,S.current.onPointerDown=f,S.current.onPointerUp=m});const T=v.useContext(wv);if(T===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");const{direction:R,groupId:C,registerResizeHandle:I,startDragging:A,stopDragging:O,panelGroupElement:j}=T,U=U1(a),[B,W]=v.useState("inactive"),[J,ee]=v.useState(!1),[re,F]=v.useState(null),K=v.useRef({state:B});Cl(()=>{K.current.state=B}),v.useEffect(()=>{if(n)F(null);else{const D=I(U);F(()=>D)}},[n,U,I]);const V=(E=r?.coarse)!==null&&E!==void 0?E:15,ne=(w=r?.fine)!==null&&w!==void 0?w:5;v.useEffect(()=>{if(n||re==null)return;const D=_.current;Ct(D,"Element ref not attached");let H=!1;return Eve(U,D,R,{coarse:V,fine:ne},(L,M,z)=>{if(!M){W("inactive");return}switch(L){case"down":{W("drag"),H=!1,Ct(z,'Expected event to be defined for "down" action'),A(U,z);const{onDragging:G,onPointerDown:q}=S.current;G?.(!0),q?.();break}case"move":{const{state:G}=K.current;H=!0,G!=="drag"&&W("hover"),Ct(z,'Expected event to be defined for "move" action'),re(z);break}case"up":{W("hover"),O();const{onClick:G,onDragging:q,onPointerUp:ae}=S.current;q?.(!1),ae?.(),H||G?.();break}}})},[V,R,n,ne,I,U,re,A,O]),Pve({disabled:n,handleId:U,resizeHandler:re,panelGroupElement:j});const te={touchAction:"none",userSelect:"none"};return v.createElement(y,{...x,children:e,className:t,id:a,onBlur:()=>{ee(!1),s?.()},onFocus:()=>{ee(!0),u?.()},ref:_,role:"separator",style:{...te,...h},tabIndex:g,[qn.groupDirection]:R,[qn.groupId]:C,[qn.resizeHandle]:"",[qn.resizeHandleActive]:B==="drag"?"pointer":J?"keyboard":void 0,[qn.resizeHandleEnabled]:!n,[qn.resizeHandleId]:U,[qn.resizeHandleState]:B})}r8.displayName="PanelResizeHandle";function aa({className:e,...t}){return d.jsx(n8,{"data-slot":"resizable-panel-group",className:Oe("flex h-full w-full data-[panel-group-direction=vertical]:flex-col",e),...t})}function Rn({...e}){return d.jsx(U6,{"data-slot":"resizable-panel",...e})}function wo({withHandle:e,className:t,...n}){return d.jsx(r8,{"data-slot":"resizable-handle",className:Oe("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&&d.jsx("div",{className:"bg-border z-10 flex h-4 w-3 items-center justify-center rounded-xs border",children:d.jsx(Tie,{className:"size-2.5"})})})}function gm({className:e,...t}){return d.jsx("kbd",{"data-slot":"kbd",className:Oe("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 Uve({isSearchExpanded:e,searchQuery:t,filteredNotificationsCount:n,notificationsCount:r,onSearchExpand:a,onSearchChange:s,onSearchBlur:i,onClearAll:c,searchInputRef:u}){return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Tn,{ref:u,placeholder:"Search notifications...",value:t,onChange:f=>s(f.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Notifications"}),d.jsx(kr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:d.jsx(wd,{className:"h-4 w-4"})})}),d.jsxs(Mt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(gm,{children:"F"})]})]})]})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,disabled:r===0,className:"h-8 w-8 p-0",children:d.jsx(Mi,{className:"h-4 w-4"})})}),d.jsx(Mt,{side:"bottom",children:"Clear all"})]})})]})}function Wi({id:e,isSelected:t,isFocused:n,icon:r,title:a,description:s,metadata:i,onClick:c,className:u}){return d.jsx("button",{id:e,type:"button",onClick:c,className:Oe("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:d.jsxs("div",{className:"flex items-start gap-2 sm:gap-3",children:[r&&d.jsx("div",{className:"flex-shrink-0 mt-1",children:d.jsx("div",{className:Oe("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:r})}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("div",{className:"flex items-center gap-2 mb-1",children:d.jsx("h3",{className:Oe("font-medium truncate font-mono text-sm"),children:a})}),s&&d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 line-clamp-2",children:s})]})]})})}function $ve({notifications:e,selectedNotification:t,onNotificationSelect:n,focusedIndex:r,formatRelativeTime:a,listRef:s}){return e.length===0?d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx(vd,{vertical:!0,noBorder:!0,message:"No notifications yet"})}):d.jsx("div",{ref:s,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((i,c)=>d.jsx(Wi,{id:`notification-${i.id}`,isSelected:t?.id===i.id,isFocused:r===c,title:d.jsxs("span",{className:"flex items-center gap-3",children:[i.method,!i.read&&d.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const u=a(i.timestamp),f=i.params&&Object.keys(i.params).length>0?Object.keys(i.params).length:0,m=f>0?` | ${f} param${f>1?"s":""}`:"";return u+m})(),onClick:()=>n(i)},i.id))})}function zve({notification:e,previewMode:t,onTogglePreview:n,onCopy:r,onDownload:a,onFullscreen:s,isCopied:i=!1,onClose:c}){return e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.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:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(qu,{className:"h-3 w-3 text-gray-400"}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleTimeString()})]}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:e.formatRelativeTime(e.timestamp)})]}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsxs(Le,{variant:"ghost",size:"sm",onClick:n,className:t?"":"text-purple-600 dark:text-purple-400",children:[t?d.jsx(fT,{className:"h-4 w-4 mr-1"}):d.jsx(q3,{className:"h-4 w-4 mr-1"}),t?"JSON":"Formatted"]}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:r,children:i?d.jsx(oa,{className:"h-4 w-4"}):d.jsx(zr,{className:"h-4 w-4"})}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:a,children:d.jsx(Qp,{className:"h-4 w-4"})}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:s,children:d.jsx(hT,{className:"h-4 w-4"})}),c&&d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,children:d.jsx(qo,{className:"h-4 w-4"})})]})]}),d.jsx("div",{className:"flex-1 overflow-y-auto",children:d.jsx("div",{className:"px-4 pt-4",children:d.jsx(nr,{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`})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(uT,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a notification to view details"})]})}function uy(e){const n=Date.now()-e,r=Math.floor(n/1e3),a=Math.floor(r/60),s=Math.floor(a/60),i=Math.floor(s/24);return r<60?"just now":a<60?`${a}m ago`:s<24?`${s}h ago`:i<7?`${i}d ago`:new Date(e).toLocaleDateString()}function Fve({notifications:e,unreadCount:t,markNotificationRead:n,markAllNotificationsRead:r,clearNotifications:a,serverId:s,isConnected:i}){const[c,u]=v.useState(null),[f,m]=v.useState(""),[h,g]=v.useState(-1),[y,x]=v.useState(!0),[E,w]=v.useState(!1),[_,S]=v.useState(!0),[T,R]=v.useState(!1),C=v.useRef(null),I=v.useRef(null),A=v.useRef(null),O=v.useRef(!1);v.useEffect(()=>{y&&e.length>0&&C.current&&!O.current&&(C.current.scrollTop=0)},[e.length,y]),v.useEffect(()=>{const K=C.current;if(!K)return;const V=()=>{K.scrollTop>0&&(O.current=!0,x(!1))};return K.addEventListener("scroll",V),()=>K.removeEventListener("scroll",V)},[]),v.useEffect(()=>{e.length===0&&(O.current=!1,x(!0))},[e.length]),v.useEffect(()=>{c&&!c.read&&n(c.id)},[c,n]),v.useEffect(()=>{E&&A.current&&A.current.focus()},[E]);const j=v.useCallback(()=>{f.trim()||w(!1)},[f]),U=v.useMemo(()=>{if(!f.trim())return e;const K=f.toLowerCase();return e.filter(V=>V.method.toLowerCase().includes(K)||JSON.stringify(V.params||{}).toLowerCase().includes(K))},[e,f]);v.useEffect(()=>{g(-1)},[f]),v.useEffect(()=>{const K=V=>{const ne=V.target;if(ne.tagName==="INPUT"||ne.tagName==="TEXTAREA"||ne.contentEditable==="true"||V.metaKey||V.ctrlKey||V.altKey)return;const D=U;if(V.key==="ArrowDown")V.preventDefault(),g(H=>{const $=H+1;return $>=D.length?0:$});else if(V.key==="ArrowUp")V.preventDefault(),g(H=>{const $=H-1;return $<0?D.length-1:$});else if(V.key==="Enter"&&h>=0){V.preventDefault();const H=U[h];H&&B(H)}};return document.addEventListener("keydown",K),()=>document.removeEventListener("keydown",K)},[h,U]),v.useEffect(()=>{if(h>=0){const K=`notification-${U[h]?.id}`,V=document.getElementById(K);V&&V.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,U]);const B=v.useCallback(K=>{u(K)},[]),W=v.useCallback(()=>{window.confirm("Are you sure you want to clear all notifications? This cannot be undone.")&&(a(),u(null))},[a]),J=v.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)),R(!0),setTimeout(()=>R(!1),2e3)}catch(K){console.error("[NotificationsTab] Failed to copy notification:",K)}},[c]),ee=v.useCallback(()=>{if(c)try{const K=new globalThis.Blob([JSON.stringify({method:c.method,timestamp:c.timestamp,read:c.read,params:c.params},null,2)],{type:"application/json"}),V=URL.createObjectURL(K),ne=document.createElement("a");ne.href=V,ne.download=`notification-${Date.now()}.json`,document.body.appendChild(ne),ne.click(),document.body.removeChild(ne),URL.revokeObjectURL(V)}catch(K){console.error("[NotificationsTab] Failed to download notification:",K)}},[c]),re=v.useCallback(async()=>{if(I.current)try{document.fullscreenElement?await document.exitFullscreen():await I.current.requestFullscreen()}catch(K){console.error("[NotificationsTab] Failed to toggle fullscreen:",K)}},[]),F=c?{method:c.method,params:c.params,timestamp:c.timestamp,read:c.read,formatRelativeTime:uy}:null;return i?d.jsxs(aa,{direction:"horizontal",className:"h-full",children:[d.jsx(Rn,{defaultSize:40,minSize:30,children:d.jsx(aa,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:d.jsxs(Rn,{defaultSize:75,minSize:30,children:[d.jsx(Uve,{isSearchExpanded:E,searchQuery:f,filteredNotificationsCount:U.length,notificationsCount:e.length,onSearchExpand:()=>w(!0),onSearchChange:m,onSearchBlur:j,onClearAll:W,searchInputRef:A}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx($ve,{notifications:U,selectedNotification:c,onNotificationSelect:B,focusedIndex:h,formatRelativeTime:uy,listRef:C})})]})})}),d.jsx(wo,{}),d.jsx(Rn,{defaultSize:60,minSize:40,children:d.jsx("div",{ref:I,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(zve,{notification:F,previewMode:_,onTogglePreview:()=>S(!_),onCopy:J,onDownload:ee,onFullscreen:re,onClose:()=>u(null),isCopied:T})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(uT,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function a8({activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabTitle:r,secondaryTabTitle:a,primaryCount:s,secondaryCount:i,secondaryIcon:c,primaryIcon:u,searchPlaceholder:f="Search...",onSearchExpand:m,onSearchChange:h,onSearchBlur:g,onTabSwitch:y,searchInputRef:x,primaryTabName:E}){const w=e===E;return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:t?d.jsx(Tn,{ref:x,placeholder:f,value:n,onChange:_=>h(_.target.value),onBlur:g,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:w?r:a}),w&&d.jsxs(d.Fragment,{children:[d.jsx(kr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:s}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:m,className:"h-8 w-8 p-0",children:d.jsx(wd,{className:"h-4 w-4"})})}),d.jsxs(Mt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(gm,{children:"F"})]})]})]})]})}),d.jsxs(Le,{variant:"ghost",size:"sm",onClick:y,className:"gap-2 flex-shrink-0",children:[w?d.jsx(c,{}):d.jsx(u,{}),d.jsx("span",{className:"hidden sm:inline",children:w?a:r}),w&&i>0&&d.jsx(kr,{className:"bg-purple-500/20 text-purple-600 dark:text-purple-400 border-transparent",variant:"outline",children:i})]})]})}function X$({prompts:e,selectedPrompt:t,onPromptSelect:n,focusedIndex:r}){return e.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(yp,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No prompts available"})]}):d.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((a,s)=>d.jsx(Wi,{id:`prompt-${a.name}`,isSelected:t?.name===a.name,isFocused:r===s,icon:d.jsx(yp,{className:"h-4 w-4"}),title:a.name,description:a.description,metadata:a.arguments&&a.arguments.length>0&&d.jsxs(kr,{variant:"outline",className:"text-xs border-gray-300 dark:border-zinc-600 text-gray-600 dark:text-gray-400",children:[a.arguments.length," args"]}),onClick:()=>n(a)},a.name))})}function J$({activeTab:e,isSearchExpanded:t,searchQuery:n,filteredPromptsCount:r,savedPromptsCount:a,onSearchExpand:s,onSearchChange:i,onSearchBlur:c,onTabSwitch:u,searchInputRef:f}){return d.jsx(a8,{activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabName:"prompts",secondaryTabName:"saved",primaryTabTitle:"Prompts",secondaryTabTitle:"History",primaryCount:r,secondaryCount:a,primaryIcon:yp,secondaryIcon:qu,searchPlaceholder:"Search prompts...",onSearchExpand:s,onSearchChange:i,onSearchBlur:c,onTabSwitch:u,searchInputRef:f})}function Q$({savedPrompts:e,selectedPrompt:t,onLoadPrompt:n,onDeletePrompt:r,focusedIndex:a}){return e.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(qu,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No history"}),d.jsx("p",{className:"text-sm text-gray-400 dark:text-gray-500 mt-1",children:"Prompts you execute will appear here"})]}):d.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((s,i)=>d.jsx(Wi,{id:`saved-prompt-${s.id}`,isSelected:t?.id===s.id,isFocused:a===i,icon:d.jsx(qu,{className:"h-4 w-4"}),title:s.name,description:`${s.promptName} - ${new Date(s.savedAt).toLocaleString()}`,onClick:()=>n(s)},s.id))})}function Bve({selectedPrompt:e,promptArgs:t,onArgChange:n}){const r=e?.arguments||[];if(!(r.length>0))return d.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500 dark:text-gray-400 text-sm",children:"No arguments required"});const s=i=>{const c=i.name,u=t[c],f=typeof u=="string"?u:JSON.stringify(u);return i.type==="boolean"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:c,className:"text-sm font-medium",children:[c,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsxs("div",{className:"flex items-center space-x-2",children:[d.jsx("input",{id:c,type:"checkbox",checked:!!u,onChange:m=>n(c,m.target.checked),className:"rounded","aria-label":`Toggle ${c}`}),d.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:i.description})]})]},c):i.type==="number"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:c,className:"text-sm font-medium",children:[c,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(Tn,{id:c,type:"number",value:Number(u)||0,onChange:m=>n(c,Number(m.target.value)),placeholder:i.description||`Enter ${c}`}),i.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:i.description})]},c):i.type==="array"||i.type==="object"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:c,className:"text-sm font-medium",children:[c,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(Pl,{id:c,value:f,onChange:m=>{try{const h=JSON.parse(m.target.value);n(c,h)}catch{n(c,m.target.value)}},placeholder:i.description||`Enter ${c} as JSON`,className:"font-mono text-sm min-h-[100px]"}),i.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:i.description})]},c):d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:c,className:"text-sm font-medium",children:[c,i.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(Tn,{id:c,value:f,onChange:m=>n(c,m.target.value),placeholder:i.description||`Enter ${c}`}),i.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:i.description})]},c)};return d.jsx("div",{className:"space-y-4",children:r.map(i=>s(i))})}function ez({selectedPrompt:e,promptArgs:t,isExecuting:n,isConnected:r,onArgChange:a,onExecute:s,onSave:i}){return v.useEffect(()=>{const c=u=>{(u.metaKey||u.ctrlKey)&&u.key==="Enter"&&e&&!n&&r&&(u.preventDefault(),s())};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[e,n,r,s]),e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx("div",{className:"flex-shrink-0 p-3 sm:p-6 pt-3 pb-4 pr-3",children:d.jsxs("div",{children:[d.jsxs("div",{className:"flex flex-row items-center justify-between mb-0 gap-2",children:[d.jsx("h3",{className:"text-base sm:text-lg font-semibold",children:e.name}),d.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[d.jsx(Le,{onClick:s,disabled:n||!r,size:"sm",className:"lg:size-default pr-1! gap-0",children:n?d.jsxs(d.Fragment,{children:[d.jsx(_o,{className:"mr-2"}),d.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]}):d.jsxs(d.Fragment,{children:[d.jsx(eB,{className:"h-4 w-4 sm:mr-2"}),d.jsx("span",{className:"hidden sm:inline",children:"Execute"}),d.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:"⌘↵"})]})}),d.jsxs(Le,{variant:"outline",onClick:i,disabled:n,size:"sm",className:"lg:size-default gap-2",children:[d.jsx(gT,{className:"h-4 w-4"}),d.jsx("span",{className:"hidden sm:inline",children:"Save"})]})]})]}),e.description&&d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 leading-relaxed mt-2",children:e.description})]})}),d.jsx("div",{className:"flex-1 overflow-y-auto px-3 sm:px-6 pb-4 pr-3",children:d.jsx(Bve,{selectedPrompt:e,promptArgs:t,onArgChange:a})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a prompt to get started"}),d.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 Hve(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 tz({results:e,copiedResult:t,onCopy:n}){return d.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:d.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:e.length>0?d.jsx("div",{className:"space-y-4 flex-1 h-full",children:e.map((r,a)=>{const s=r.error||Hve(r.result);return d.jsxs("div",{className:"space-y-0 flex-1 h-full flex flex-col",children:[d.jsxs("div",{className:"flex items-center gap-2 px-4 pt-2 border-b border-gray-200 dark:border-zinc-600 pb-2",children:[d.jsx("h3",{className:"text-sm font-medium",children:"Response"}),d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(qu,{className:"h-3 w-3 text-gray-400"}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(r.timestamp).toLocaleTimeString()})]}),r.duration!==void 0&&d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(vp,{className:"h-3 w-3 text-gray-400"}),d.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[r.duration,"ms"]})]}),d.jsx("div",{className:"flex gap-2 ml-auto",children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>n(a,r.result),className:"h-6 px-2",children:t===a?d.jsx(oa,{className:"h-4 w-4"}):d.jsx(zr,{className:"h-4 w-4"})})})]}),s?d.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:[d.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),d.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:s})]}):d.jsx("div",{className:"px-4 pt-4",children:d.jsx(nr,{data:r.result,filename:`prompt-result-${r.promptName}-${Date.now()}.json`})})]},a)})}):d.jsx("div",{className:"flex items-center justify-center h-full",children:d.jsx("div",{className:"text-center",children:d.jsx(vd,{vertical:!0,noBorder:!0,message:"No Results yet"})})})})})}function z1({serverIds:e,onCountChange:t,onClearRef:n}={}){const[r,a]=v.useState([]),s=v.useRef(null),[i,c]=v.useState(new Set),[u]=v.useState(""),f=y=>{c(x=>{const E=new Set(x);return E.has(y)?E.delete(y):E.add(y),E})},m=async()=>{a([]),c(new Set),t?.(0);try{const y=new URLSearchParams;e&&e.length>0&&y.set("serverIds",e.join(","));const x=await fetch(`/inspector/api/rpc/log?${y.toString()}`,{method:"DELETE"});x.ok||console.warn("[RPC Logger] Failed to clear server buffer:",x.status)}catch(y){console.warn("[RPC Logger] Error clearing server buffer:",y)}},h=v.useMemo(()=>!e||e.length===0?"":[...e].sort().join(","),[e]);v.useEffect(()=>(n&&(n.current=m),()=>{n&&(n.current=null)}),[n,m]),v.useEffect(()=>{t?.(r.length)},[r.length,t]),v.useEffect(()=>{let y=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 E=`/inspector/api/rpc/stream?${x.toString()}`;console.log("[RPC Logger] Connecting to SSE stream:",E),y=new globalThis.EventSource(E),y.onopen=()=>{console.log("[RPC Logger] SSE connection opened")},y.onmessage=w=>{try{const _=JSON.parse(w.data);if(!_||_.type!=="rpc")return;const{serverId:S,direction:T,message:R,timestamp:C}=_,I=R,A=typeof I?.method=="string"?I.method:I?.result!==void 0?"result":I?.error!==void 0?"error":"unknown",O={id:`${C??Date.now()}-${Math.random().toString(36).slice(2)}`,serverId:typeof S=="string"?S:"unknown",direction:typeof T=="string"?T.toUpperCase():"",method:A,timestamp:C??new Date().toISOString(),payload:R};console.log("[RPC Logger] Received RPC event:",{method:A,direction:T,serverId:S}),a(j=>{const U=[O,...j].slice(0,1e3);return t?.(U.length),U})}catch(_){console.error("[RPC Logger] Error parsing SSE message:",_)}},y.onerror=w=>{console.error("[RPC Logger] SSE connection error:",w);try{y?.close()}catch{}}}catch(x){console.error("[RPC Logger] Failed to create SSE connection:",x)}return()=>{try{y?.close(),console.log("[RPC Logger] SSE connection closed")}catch{}}},[h]);const g=v.useMemo(()=>{let y=r;if(e&&e.length>0){const x=new Set(e);y=y.filter(E=>x.has(E.serverId))}if(u.trim()){const x=u.toLowerCase();y=y.filter(E=>E.serverId.toLowerCase().includes(x)||E.method.toLowerCase().includes(x)||E.direction.toLowerCase().includes(x)||JSON.stringify(E.payload).toLowerCase().includes(x))}return y},[r,u,e]);return d.jsx("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:d.jsx("div",{ref:s,className:"flex-1 min-h-0 overflow-y-auto",children:g.length===0?d.jsxs("div",{className:"text-center py-8",children:[d.jsx("div",{className:"text-xs text-muted-foreground",children:"No messages yet"}),d.jsx("div",{className:"text-[10px] text-muted-foreground mt-1",children:"JSON-RPC messages will appear here"})]}):g.map(y=>{const x=i.has(y.id);return d.jsxs("div",{className:"group hover:bg-muted/50 transition-all duration-200 overflow-hidden",children:[d.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>f(y.id),children:[d.jsx("div",{className:"flex-shrink-0",children:x?d.jsx(Gl,{className:"h-3 w-3 text-muted-foreground transition-transform"}):d.jsx(Wse,{className:"h-3 w-3 text-muted-foreground transition-transform"})}),d.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[d.jsx("span",{className:"text-muted-foreground font-mono text-xs",children:new Date(y.timestamp).toLocaleTimeString()}),d.jsx("span",{className:`flex items-center justify-center px-1 py-0.5 rounded ${y.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:y.direction==="RECEIVE"?"Incoming":"Outgoing",children:y.direction==="RECEIVE"?d.jsx(Lse,{className:"h-3 w-3"}):d.jsx(jse,{className:"h-3 w-3"})}),d.jsx("span",{className:"text-xs font-mono text-foreground truncate",children:y.method})]})]}),x&&d.jsx("div",{className:"border-t bg-muted/20",children:d.jsx("div",{className:"p-3",children:d.jsx("div",{className:"max-h-[40vh] overflow-auto rounded-sm bg-background/60 p-2",children:d.jsx(nr,{data:y.payload})})})})]},y.id)})})})}const nz="mcp-inspector-saved-prompts";function o8({ref:e,prompts:t,callPrompt:n,serverId:r,isConnected:a}){const[s,i]=v.useState(null),[c,u]=v.useState(null),{selectedPromptName:f,setSelectedPromptName:m}=Wl(),[h,g]=v.useState({}),[y,x]=v.useState([]),[E,w]=v.useState(!1),[_,S]=v.useState(null),[T,R]=v.useState(""),[C,I]=v.useState("prompts"),[A,O]=v.useState([]),[j,U]=v.useState(!1),[B,W]=v.useState(""),[J,ee]=v.useState(!1),[re,F]=v.useState(-1),K=v.useRef(null),[V,ne]=v.useState(!1),[te,D]=v.useState("list"),[H,$]=v.useState(0),[L,M]=v.useState(!0),z=v.useRef(null),G=v.useRef(null);v.useEffect(()=>{const xe=()=>{ne(window.innerWidth<1024)};return xe(),window.addEventListener("resize",xe),()=>window.removeEventListener("resize",xe)},[]),v.useEffect(()=>{D(s?"detail":"list")},[s]),v.useEffect(()=>{V&&y.length>0&&!E&&D("response")},[y,E,V]),v.useImperativeHandle(e,()=>({focusSearch:()=>{ee(!0),setTimeout(()=>{K.current&&K.current.focus()},0)},blurSearch:()=>{R(""),ee(!1),K.current&&K.current.blur()}})),v.useEffect(()=>{try{const xe=localStorage.getItem(nz);if(xe){const Te=JSON.parse(xe);O(Te)}}catch(xe){console.error("[PromptsTab] Failed to load saved prompts:",xe)}},[]);const q=v.useCallback(xe=>{try{localStorage.setItem(nz,JSON.stringify(xe))}catch(Te){console.error("[PromptsTab] Failed to save prompts:",Te)}},[]);v.useEffect(()=>{J&&K.current&&K.current.focus()},[J]);const ae=v.useCallback(()=>{T.trim()||ee(!1)},[T]),ie=v.useMemo(()=>{if(!T.trim())return t;const xe=T.toLowerCase();return t.filter(Te=>Te.name.toLowerCase().includes(xe)||Te.description?.toLowerCase().includes(xe))},[t,T]),X=v.useCallback(xe=>{i(xe);const Te={};xe.arguments&&xe.arguments.forEach($e=>{$e.default!==void 0?Te[$e.name]=$e.default:$e.type==="string"?Te[$e.name]="":$e.type==="number"?Te[$e.name]=0:$e.type==="boolean"?Te[$e.name]=!1:$e.type==="array"?Te[$e.name]=[]:$e.type==="object"&&(Te[$e.name]={})}),g(Te)},[]),Z=v.useCallback(xe=>{const Te=t.find($e=>$e.name===xe.promptName);Te&&(i(Te),g(xe.args),u(xe))},[t]);v.useEffect(()=>{F(-1)},[T,C]),v.useEffect(()=>{const xe=Te=>{const $e=Te.target;if($e.tagName==="INPUT"||$e.tagName==="TEXTAREA"||$e.contentEditable==="true"||Te.metaKey||Te.ctrlKey||Te.altKey)return;const Ie=C==="prompts"?ie:A;if(Te.key==="ArrowDown")Te.preventDefault(),F(Fe=>{const Ee=Fe+1;return Ee>=Ie.length?0:Ee});else if(Te.key==="ArrowUp")Te.preventDefault(),F(Fe=>{const Ee=Fe-1;return Ee<0?Ie.length-1:Ee});else if(Te.key==="Enter"&&re>=0)if(Te.preventDefault(),C==="prompts"){const Fe=ie[re];Fe&&X(Fe)}else{const Fe=A[re];Fe&&Z(Fe)}};return document.addEventListener("keydown",xe),()=>document.removeEventListener("keydown",xe)},[re,ie,A,C,X,Z]),v.useEffect(()=>{if(re>=0){const xe=C==="prompts"?`prompt-${ie[re]?.name}`:`saved-prompt-${A[re]?.id}`,Te=document.getElementById(xe);Te&&Te.scrollIntoView({behavior:"smooth",block:"nearest"})}},[re,ie,A,C]),v.useEffect(()=>{if(console.warn("[PromptsTab] Auto-selection effect triggered:",{selectedPromptName:f,promptsCount:t.length,currentSelectedPrompt:s?.name}),f&&t.length>0){const xe=t.find(Te=>Te.name===f);if(console.warn("[PromptsTab] Prompt lookup result:",{selectedPromptName:f,promptFound:!!xe,promptName:xe?.name,shouldSelect:xe&&s?.name!==xe.name}),xe&&s?.name!==xe.name){console.warn("[PromptsTab] Selecting prompt:",xe.name),m(null);const Te=setTimeout(()=>{X(xe);const $e=document.getElementById(`prompt-${xe.name}`);$e&&(console.warn("[PromptsTab] Scrolling to prompt element"),$e.scrollIntoView({behavior:"smooth",block:"nearest"}))},100);return()=>clearTimeout(Te)}}},[f,t,s,X,m]);const se=v.useCallback((xe,Te)=>{g($e=>({...$e,[xe]:Te}))},[]),me=v.useCallback(async()=>{if(!s||E)return;w(!0);const xe=Date.now();try{const Te=await n(s.name,h),$e=Date.now()-xe;Tr.getInstance().capture(new bP({promptName:s.name,serverId:r,success:!0})).catch(()=>{}),x(Ie=>[{promptName:s.name,args:h,result:Te,timestamp:xe,duration:$e},...Ie])}catch(Te){Tr.getInstance().capture(new bP({promptName:s.name,serverId:r,success:!1,error:Te instanceof Error?Te.message:"Unknown error"})).catch(()=>{});const fe={promptName:s.name,args:h,result:null,error:Te instanceof Error?Te.message:String(Te),timestamp:xe,duration:Date.now()-xe};x(Ie=>[fe,...Ie])}finally{w(!1)}},[s,h,E,n,r]),le=v.useCallback(async(xe,Te)=>{try{await navigator.clipboard.writeText(JSON.stringify(Te,null,2)),S(xe),setTimeout(()=>S(null),2e3)}catch($e){console.error("[PromptsTab] Failed to copy result:",$e)}},[]),Ne=v.useCallback(()=>{s&&(W(""),U(!0))},[s]),He=v.useCallback(xe=>{q(A.filter(Te=>Te.id!==xe)),c?.id===xe&&u(null)},[A,q,c]);return V?d.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[te!=="list"&&d.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[d.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>{te==="response"?D("detail"):(i(null),D("list"))},className:"p-0 h-8 w-8",children:d.jsx(dT,{className:"h-4 w-4"})}),d.jsxs("div",{className:"flex items-center text-sm font-medium",children:[d.jsx("button",{onClick:()=>{i(null),D("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Prompts"}),te!=="list"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("button",{onClick:()=>{te==="response"&&D("detail")},className:te==="detail"?"text-foreground hover:underline":te==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),te==="response"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),d.jsx("div",{className:"flex-1 relative overflow-hidden",children:d.jsxs(Jy,{initial:!1,mode:"popLayout",children:[te==="list"&&d.jsxs(wa.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:[d.jsx(J$,{activeTab:C,isSearchExpanded:J,searchQuery:T,filteredPromptsCount:ie.length,savedPromptsCount:A.length,onSearchExpand:()=>ee(!0),onSearchChange:R,onSearchBlur:ae,onTabSwitch:()=>I(C==="prompts"?"saved":"prompts"),searchInputRef:K}),C==="prompts"?d.jsx(X$,{prompts:ie,selectedPrompt:s,onPromptSelect:X,focusedIndex:re}):d.jsx(Q$,{savedPrompts:A,selectedPrompt:c,onLoadPrompt:Z,onDeletePrompt:He,focusedIndex:re})]},"list"),te==="detail"&&d.jsx(wa.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:d.jsx(ez,{selectedPrompt:s,promptArgs:h,isExecuting:E,isConnected:a,onArgChange:se,onExecute:me,onSave:Ne})},"detail"),te==="response"&&d.jsx(wa.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:d.jsx(tz,{results:y,copiedResult:_,onCopy:le})},"response")]})})]}):d.jsxs(aa,{direction:"horizontal",className:"h-full",children:[d.jsx(Rn,{defaultSize:33,className:"flex flex-col h-full relative",children:d.jsxs(aa,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[d.jsx(Rn,{defaultSize:75,minSize:30,children:d.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[d.jsx(J$,{activeTab:C,isSearchExpanded:J,searchQuery:T,filteredPromptsCount:ie.length,savedPromptsCount:A.length,onSearchExpand:()=>ee(!0),onSearchChange:R,onSearchBlur:ae,onTabSwitch:()=>I(C==="prompts"?"saved":"prompts"),searchInputRef:K}),C==="prompts"?d.jsx(X$,{prompts:ie,selectedPrompt:s,onPromptSelect:X,focusedIndex:re}):d.jsx(Q$,{savedPrompts:A,selectedPrompt:c,onLoadPrompt:Z,onDeletePrompt:He,focusedIndex:re})]})}),d.jsx(wo,{withHandle:!0}),d.jsxs(Rn,{ref:z,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>M(!0),onExpand:()=>M(!1),className:"flex flex-col border-t dark:border-zinc-700",children:[d.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),L?(z.current?.resize(25),M(!1)):(z.current?.resize(5),M(!0))},children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),H>0&&d.jsx(kr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:H}),H>0&&!L&&d.jsx(Le,{variant:"ghost",size:"sm",onClick:xe=>{xe.preventDefault(),xe.stopPropagation(),G.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:d.jsx(Mi,{className:"h-3.5 w-3.5"})})]}),d.jsx(Gl,{className:`h-4 w-4 text-muted-foreground transition-transform ${L?"rotate-180":""}`})]}),!L&&d.jsx("div",{className:"flex-1 overflow-hidden min-h-0",children:d.jsx(z1,{serverIds:[r],onCountChange:$,onClearRef:G})})]})]})}),d.jsx(wo,{withHandle:!0}),d.jsx(Rn,{defaultSize:67,children:d.jsxs(aa,{direction:"vertical",children:[d.jsx(Rn,{defaultSize:40,children:d.jsx(ez,{selectedPrompt:s,promptArgs:h,isExecuting:E,isConnected:a,onArgChange:se,onExecute:me,onSave:Ne})}),d.jsx(wo,{withHandle:!0}),d.jsx(Rn,{defaultSize:50,children:d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(tz,{results:y,copiedResult:_,onCopy:le})})})]})})]})}o8.displayName="PromptsTab";function vu(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 Vve(e){return{uri:e.uri,mimeType:e.mimeType,text:e.text,blob:e.blob}}function s8({resource:e,onUIAction:t,className:n}){const r=async s=>t?.(s),a=Vve(e);return d.jsx("div",{className:n,children:d.jsx(j1,{resource:a,onUIAction:r,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:[tve,eve,nve,rve],library:M1}})})}function Gve(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(`
1659
1659
  `)}return"An error occurred"}function rz({result:e,isLoading:t,previewMode:n,serverId:r,readResource:a,onTogglePreview:s,onCopy:i,onDownload:c,onFullscreen:u,isCopied:f=!1}){let m=[],h;if(e?.resourceAnnotations&&(m=Object.keys(e.resourceAnnotations).filter(w=>w.startsWith("openai/")),h=e.resourceAnnotations["openai/outputTemplate"]),e?.result?.contents?.[0]?._meta){const w=e.result.contents[0]._meta,_=Object.keys(w).filter(S=>S.startsWith("openai/"));_.length>0&&(m=[...m,..._]),!h&&w["openai/outputTemplate"]&&(h=w["openai/outputTemplate"]),!h&&e.uri&&e.uri.startsWith("ui://widget/")&&(h=e.uri)}const g=!!(m.length>0&&h&&typeof h=="string"&&r&&a);if(t)return d.jsx("div",{className:"flex absolute left-0 top-0 items-center justify-center w-full h-full",children:d.jsx(_o,{className:"size-5"})});if(!e)return d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a resource to view its contents"}),d.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Choose a resource from the list to see its data"})]});const y=e.error||Gve(e.result);if(y)return d.jsx("div",{className:"p-4",children:d.jsxs("div",{className:"bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded p-3",children:[d.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),d.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:y})]})});const x=e?.result?.contents&&Array.isArray(e.result.contents)&&e.result.contents.some(w=>w.mimeType&&vu(w)),E=x?e.result.contents.filter(w=>w.mimeType&&vu(w)):[];return d.jsxs("div",{className:"flex flex-col h-full",children:[d.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:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(qu,{className:"h-3 w-3 text-gray-400"}),d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleTimeString()})]}),(()=>{const w=e?.duration??e.result?.duration??e.result?.metrics?.durationMs;return w!==void 0?d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(vp,{className:"h-3 w-3 text-gray-400"}),d.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[w,"ms"]})]}):null})(),x&&d.jsx(kr,{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&&d.jsx(kr,{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"})]}),d.jsxs("div",{className:"flex items-center gap-1",children:[(x||g)&&d.jsxs(Le,{variant:"ghost",size:"sm",onClick:s,className:n?"":"text-purple-600 dark:text-purple-400",children:[n?d.jsx(fT,{className:"h-4 w-4 mr-1"}):d.jsx(q3,{className:"h-4 w-4 mr-1"}),n?"JSON":g?"Component":"Preview"]}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:i,children:f?d.jsx(oa,{className:"h-4 w-4"}):d.jsx(zr,{className:"h-4 w-4"})}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,children:d.jsx(Qp,{className:"h-4 w-4"})}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:u,children:d.jsx(hT,{className:"h-4 w-4"})})]})]}),d.jsx("div",{className:"flex-1 overflow-y-auto",children:g&&r&&a&&h?n?d.jsx("div",{className:"flex-1 h-full",children:d.jsx(A1,{componentUrl:h,toolName:e.uri,toolArgs:{},toolResult:e.result,serverId:r,readResource:a,className:"w-full h-full relative flex p-4"})}):d.jsx("div",{className:"px-4 pt-4",children:d.jsx(nr,{data:e.result,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})}):x?n?d.jsxs("div",{className:"space-y-0 h-full",children:[E.map((w,_)=>d.jsx("div",{className:"mx-0 size-full",children:d.jsx("div",{className:"w-full h-full",children:d.jsx(s8,{resource:w,className:"w-full h-full"})})},`mcp-ui-${w.uri||`resource-${Date.now()}-${Math.random()}`}`)),(()=>{if(e.result.contents&&Array.isArray(e.result.contents)){const w=e.result.contents.filter(_=>!(_.mimeType&&vu(_)));if(w.length>0)return d.jsx("div",{className:"px-4",children:d.jsx(nr,{data:w,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-non-ui-${Date.now()}.json`})})}return null})()]}):d.jsx("div",{className:"px-4 pt-4",children:d.jsx(nr,{data:e.result,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-mcp-ui-${Date.now()}.json`})}):d.jsx("div",{className:"px-4 pt-4",children:d.jsx(nr,{data:e.result,filename:`resource-${e.uri.replace(/[^a-zA-Z0-9]/g,"-")}-${Date.now()}.json`})})})]})}function Wve(e,t){if(!e&&!t)return d.jsx(vie,{className:"h-5 w-5"});const n=(e||t||"").toLowerCase();return n.includes("image")?d.jsx(gie,{className:"h-5 w-5"}):n.includes("json")||n.includes("javascript")||n.includes("typescript")?d.jsx(mie,{className:"h-5 w-5"}):n.includes("html")||n.includes("xml")?d.jsx(Sie,{className:"h-5 w-5"}):n.includes("database")||n.includes("sql")?d.jsx(Wy,{className:"h-5 w-5"}):d.jsx(pT,{className:"h-5 w-5"})}function az({resources:e,selectedResource:t,onResourceSelect:n,focusedIndex:r}){return e.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(Wy,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No resources available"})]}):d.jsx("div",{className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((a,s)=>{const i=Wve(a.mimeType,a.uri),c=[a.description,a.mimeType&&d.jsx("span",{className:"font-mono",children:a.mimeType},"mime")].filter(Boolean);return d.jsx(Wi,{id:`resource-${a.uri}`,isSelected:t?.uri===a.uri,isFocused:r===s,icon:i,title:a.name,description:c.length>0?d.jsxs("span",{className:"flex flex-col gap-1",children:[a.description&&d.jsx("span",{children:a.description}),a.mimeType&&d.jsx("span",{className:"text-xs text-gray-500 dark:text-gray-500 font-mono",children:a.mimeType})]}):void 0,onClick:()=>n(a)},a.uri)})})}function oz({isSearchExpanded:e,searchQuery:t,filteredResourcesCount:n,onSearchExpand:r,onSearchChange:a,onSearchBlur:s,searchInputRef:i}){return d.jsx("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Tn,{ref:i,placeholder:"Search resources...",value:t,onChange:c=>a(c.target.value),onBlur:s,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Resources"}),d.jsx(kr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:d.jsx(wd,{className:"h-4 w-4"})})}),d.jsxs(Mt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(gm,{children:"F"})]})]})]})})})}function i8({ref:e,resources:t,readResource:n,serverId:r,isConnected:a}){const[s,i]=v.useState(null),{selectedResourceUri:c,setSelectedResourceUri:u}=Wl(),[f,m]=v.useState(null),[h,g]=v.useState(!1),[y,x]=v.useState(""),[E]=v.useState("resources"),[w,_]=v.useState(!0),[S,T]=v.useState(!1),[R,C]=v.useState(-1),[I,A]=v.useState(!1),O=v.useRef(null),j=v.useRef(null),[U,B]=v.useState(!1),[W,J]=v.useState("list"),[ee,re]=v.useState(0),[F,K]=v.useState(!0),V=v.useRef(null),ne=v.useRef(null);v.useEffect(()=>{const z=()=>{B(window.innerWidth<1024)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),v.useEffect(()=>{J(s?"detail":"list")},[s]),v.useImperativeHandle(e,()=>({focusSearch:()=>{T(!0),setTimeout(()=>{O.current&&O.current.focus()},0)},blurSearch:()=>{x(""),T(!1),O.current&&O.current.blur()}})),v.useEffect(()=>{S&&O.current&&O.current.focus()},[S]);const te=v.useCallback(()=>{y.trim()||T(!1)},[y]),D=v.useMemo(()=>{if(!y)return t;const z=y.toLowerCase();return t.filter(G=>G.name.toLowerCase().includes(z)||G.description?.toLowerCase().includes(z)||G.uri.toLowerCase().includes(z))},[t,y]),H=v.useCallback(async z=>{if(i(z),a){g(!0);const G=Date.now();try{const q=await n(z.uri);Tr.getInstance().capture(new gP({resourceUri:z.uri,serverId:r,success:!0})).catch(()=>{}),m({uri:z.uri,result:q,timestamp:G,resourceAnnotations:z.annotations})}catch(q){Tr.getInstance().capture(new gP({resourceUri:z.uri,serverId:r,success:!1,error:q instanceof Error?q.message:"Unknown error"})).catch(()=>{}),m({uri:z.uri,result:null,error:q instanceof Error?q.message:"Unknown error",timestamp:G,resourceAnnotations:z.annotations})}finally{g(!1)}}},[n,r,a]);v.useEffect(()=>{C(-1)},[y,E]),v.useEffect(()=>{const z=G=>{const q=G.target;if(q.tagName==="INPUT"||q.tagName==="TEXTAREA"||q.contentEditable==="true"||G.metaKey||G.ctrlKey||G.altKey)return;const ie=D;if(G.key==="ArrowDown")G.preventDefault(),C(X=>{const Z=X+1;return Z>=ie.length?0:Z});else if(G.key==="ArrowUp")G.preventDefault(),C(X=>{const Z=X-1;return Z<0?ie.length-1:Z});else if(G.key==="Enter"&&R>=0){G.preventDefault();const X=D[R];X&&H(X)}};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[R,D,H]),v.useEffect(()=>{if(R>=0){const z=`resource-${D[R]?.uri}`,G=document.getElementById(z);G&&G.scrollIntoView({behavior:"smooth",block:"nearest"})}},[R,D]),v.useEffect(()=>{if(c&&t.length>0){const z=t.find(G=>G.uri===c);z&&s?.uri!==z.uri&&(u(null),setTimeout(()=>{H(z);const G=document.getElementById(`resource-${z.uri}`);G&&G.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[c,t,s,H,u]);const $=v.useCallback(async()=>{if(f)try{await navigator.clipboard.writeText(JSON.stringify(f.result,null,2)),A(!0),setTimeout(()=>A(!1),2e3)}catch(z){console.error("[ResourcesTab] Failed to copy result:",z)}},[f]),L=v.useCallback(()=>{if(f)try{const z=new globalThis.Blob([JSON.stringify(f.result,null,2)],{type:"application/json"}),G=URL.createObjectURL(z),q=document.createElement("a");q.href=G,q.download=`resource-${Date.now()}.json`,document.body.appendChild(q),q.click(),document.body.removeChild(q),URL.revokeObjectURL(G)}catch(z){console.error("[ResourcesTab] Failed to download result:",z)}},[f]),M=v.useCallback(async()=>{if(j.current)try{document.fullscreenElement?await document.exitFullscreen():await j.current.requestFullscreen()}catch(z){console.error("[ResourcesTab] Failed to toggle fullscreen:",z)}},[]);return U?d.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[W!=="list"&&d.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[d.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>{i(null),J("list")},className:"p-0 h-8 w-8",children:d.jsx(dT,{className:"h-4 w-4"})}),d.jsxs("div",{className:"flex items-center text-sm font-medium",children:[d.jsx("button",{onClick:()=>{i(null),J("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Resources"}),W==="detail"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("span",{className:"text-foreground",children:"Content"})]})]})]}),d.jsx("div",{className:"flex-1 relative overflow-hidden",children:d.jsxs(Jy,{initial:!1,mode:"popLayout",children:[W==="list"&&d.jsxs(wa.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:[d.jsx(oz,{activeTab:E,isSearchExpanded:S,searchQuery:y,filteredResourcesCount:D.length,onSearchExpand:()=>T(!0),onSearchChange:x,onSearchBlur:te,onTabSwitch:()=>{},searchInputRef:O}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(az,{resources:D,selectedResource:s,onResourceSelect:H,focusedIndex:R})})]},"list"),W==="detail"&&d.jsx(wa.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:d.jsx("div",{ref:j,className:"h-full",children:d.jsx(rz,{result:f,isLoading:h,previewMode:w,serverId:r,readResource:n,onTogglePreview:()=>_(!w),onCopy:$,onDownload:L,onFullscreen:M,isCopied:I})})},"detail")]})})]}):d.jsxs(aa,{direction:"horizontal",className:"h-full",children:[d.jsx(Rn,{defaultSize:25,children:d.jsxs(aa,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[d.jsx(Rn,{defaultSize:75,minSize:30,children:d.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[d.jsx(oz,{activeTab:E,isSearchExpanded:S,searchQuery:y,filteredResourcesCount:D.length,onSearchExpand:()=>T(!0),onSearchChange:x,onSearchBlur:te,onTabSwitch:()=>{},searchInputRef:O}),d.jsx(az,{resources:D,selectedResource:s,onResourceSelect:H,focusedIndex:R})]})}),d.jsx(wo,{withHandle:!0}),d.jsxs(Rn,{ref:V,defaultSize:0,collapsible:!0,minSize:5,collapsedSize:5,onCollapse:()=>K(!0),onExpand:()=>K(!1),className:"flex flex-col border-t dark:border-zinc-700",children:[d.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:z=>{z.preventDefault(),z.stopPropagation(),F?(V.current?.resize(25),K(!1)):(V.current?.resize(5),K(!0))},children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),ee>0&&d.jsx(kr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:ee}),ee>0&&!F&&d.jsx(Le,{variant:"ghost",size:"sm",onClick:z=>{z.preventDefault(),z.stopPropagation(),ne.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:d.jsx(Mi,{className:"h-3.5 w-3.5"})})]}),d.jsx(Gl,{className:`h-4 w-4 text-muted-foreground transition-transform ${F?"":"rotate-180"}`})]}),!F&&d.jsx("div",{className:"flex-1 overflow-hidden min-h-0",children:d.jsx(z1,{serverIds:[r],onCountChange:re,onClearRef:ne})})]})]})}),d.jsx(wo,{}),d.jsx(Rn,{defaultSize:50,children:d.jsx(aa,{direction:"vertical",children:d.jsx(Rn,{defaultSize:70,children:d.jsx("div",{ref:j,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(rz,{result:f,isLoading:h,previewMode:w,serverId:r,readResource:n,onTogglePreview:()=>_(!w),onCopy:$,onDownload:L,onFullscreen:M,isCopied:I})})})})})]})}i8.displayName="ResourcesTab";function sz({savedRequests:e,selectedRequest:t,onLoadRequest:n,onDeleteRequest:r,focusedIndex:a}){if(e.length===0)return d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(Wy,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"No saved requests yet"}),d.jsx("p",{className:"text-xs text-gray-400 dark:text-gray-500",children:"Execute a tool and click Save to store requests"})]});const s=(i,c)=>{i.stopPropagation(),c()};return d.jsx("div",{className:"overflow-y-auto flex-1 border-r dark:border-zinc-700 overscroll-contain",children:e.map((i,c)=>d.jsxs("div",{className:"relative group",children:[d.jsx(Wi,{id:`saved-${i.id}`,isSelected:t?.id===i.id,isFocused:a===c,icon:d.jsx(Mb,{className:"h-4 w-4"}),title:i.name,description:i.toolName,metadata:d.jsx("div",{className:"flex flex-col gap-1",children:d.jsx("span",{className:"text-xs text-gray-400 dark:text-gray-500",children:new Date(i.savedAt).toLocaleString()})}),onClick:()=>n(i)}),d.jsx("div",{className:"absolute top-1/2 right-2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity z-10",children:d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"secondary",size:"sm",onClick:u=>s(u,()=>r(i.id)),className:"h-8 w-8 p-0",children:d.jsx(Mi,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:d.jsx("p",{children:"Delete saved request"})})]})})]},i.id))})}function iz({isOpen:e,requestName:t,defaultPlaceholder:n,onRequestNameChange:r,onSave:a,onCancel:s}){return e?d.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:s,children:d.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:i=>i.stopPropagation(),children:[d.jsx("h3",{className:"text-lg font-semibold mb-4 text-gray-900 dark:text-gray-100",children:"Save Request"}),d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{children:[d.jsx(Wt,{htmlFor:"request-name",children:"Request Name (optional)"}),d.jsx(Tn,{id:"request-name",value:t,onChange:i=>r(i.target.value),placeholder:n,className:"mt-2",onKeyDown:i=>{i.key==="Enter"&&a()},autoFocus:!0})]}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx(Le,{variant:"outline",onClick:s,children:"Cancel"}),d.jsxs(Le,{onClick:a,children:[d.jsx(gT,{className:"h-4 w-4 mr-2"}),"Save"]})]})]})]})}):null}function l8(e,t){if(!e?.$ref)return e;const n=e.$ref;if(n.startsWith("#/")){const r=n.substring(2).split("/");let a=t;for(const s of r)if(a&&typeof a=="object"&&s in a)a=a[s];else return console.warn(`Could not resolve $ref: ${n}`),e;return a}return e}function Kve(e,t){if(e.anyOf&&Array.isArray(e.anyOf)){const n=e.anyOf.find(r=>r.type!=="null");if(n)return{...l8(n,t),nullable:!0}}return e}function Yve(e){return Array.isArray(e.enum)?e.enum:null}function lz({selectedTool:e,toolArgs:t,onArgChange:n}){const r=e?.inputSchema?.properties||{},a=e?.inputSchema?.required||[];return Object.keys(r).length>0?d.jsx("div",{className:"space-y-4",children:Object.entries(r).map(([i,c])=>{const u=e?.inputSchema||{};let f=Kve(c,u);f=l8(f,u);const m=Yve(f),h=f.type==="string"&&m!==null,g=f;g.required=a.includes(i);const y=t[i];let x="";return y!=null&&(typeof y=="string"?x=y:typeof y=="object"&&y!==null?x=JSON.stringify(y,null,2):x=String(y)),g.type==="object"||g.type==="array"?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:i,className:"text-sm font-medium",children:[i,g?.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(Pl,{id:i,value:x,onChange:w=>n(i,w.target.value),placeholder:g?.description||`Enter ${i}`,className:"min-h-[100px]"}),g?.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g.description})]},i):h&&m?d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:i,className:"text-sm font-medium",children:[i,g.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsxs(ks,{value:String(t[i]||""),onValueChange:w=>n(i,w),children:[d.jsx(Rs,{id:i,className:"w-full",children:d.jsx(Cs,{placeholder:g.description||"Select an option"})}),d.jsx(As,{children:m.map((w,_)=>d.jsx(Pr,{value:w,children:g.enumNames?.[_]||w},w))})]}),g.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g.description})]},i):d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:i,className:"text-sm font-medium",children:[i,g?.required&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),d.jsx(Tn,{id:i,value:x,onChange:w=>n(i,w.target.value),placeholder:g?.description||`Enter ${i}`}),g?.description&&d.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400",children:g.description})]},i)})}):d.jsx("div",{className:"flex items-center justify-center h-32 text-gray-500 dark:text-gray-400 text-sm",children:"No parameters required"})}function cz({selectedTool:e,toolArgs:t,isExecuting:n,isConnected:r,onArgChange:a,onExecute:s,onSave:i,onCancel:c}){const[u,f]=v.useState(!1),[m,h]=v.useState(()=>{if(typeof window<"u"){const E=localStorage.getItem("mcp-inspector-show-tool-metadata");return E?JSON.parse(E):!1}return!1}),[g,y]=v.useState(!1);v.useEffect(()=>{typeof window<"u"&&localStorage.setItem("mcp-inspector-show-tool-metadata",JSON.stringify(m))},[m]);const x=()=>{if(!e)return;const E={name:e.name,description:e.description||"",_meta:e._meta};navigator.clipboard.writeText(JSON.stringify(E,null,2)),y(!0),setTimeout(()=>y(!1),2e3)};return v.useEffect(()=>{const E=w=>{(w.metaKey||w.ctrlKey)&&w.key==="Enter"&&e&&!n&&r&&(w.preventDefault(),s()),w.key==="Escape"&&n&&c&&(w.preventDefault(),c())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[e,n,r,s,c]),e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx("div",{className:"flex-shrink-0 p-3 sm:p-5 pt-3 sm:pt-4 pb-4 sm:pr-4",children:d.jsxs("div",{children:[d.jsxs("div",{className:"flex flex-row items-center justify-between mb-0 gap-2",children:[d.jsx("h3",{className:"text-base sm:text-lg font-semibold",children:e.name}),d.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsxs(Le,{variant:m?"default":"outline",onClick:()=>h(!m),disabled:n,size:"sm",className:"lg:size-default gap-2",title:"Toggle tool metadata",children:[d.jsx(fT,{className:"h-4 w-4"}),d.jsx("span",{className:"hidden sm:inline",children:"Metadata"})]})}),d.jsx(Mt,{children:d.jsx("p",{children:"Show tool definition metadata"})})]}),d.jsxs(Le,{variant:"outline",onClick:i,disabled:n,size:"sm",className:"lg:size-default gap-2",children:[d.jsx(gT,{className:"h-4 w-4"}),d.jsx("span",{className:"hidden sm:inline",children:"Save"})]}),n&&c?d.jsxs(Dt,{open:u?void 0:!1,children:[d.jsx(Lt,{asChild:!0,children:d.jsx("div",{onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),className:"relative",children:d.jsx(Le,{onClick:c,variant:u?"destructive":"default",size:"sm",className:"lg:size-default gap-2 transition-all",children:u?d.jsxs(d.Fragment,{children:[d.jsx(qo,{className:"h-4 w-4"}),d.jsx("span",{className:"hidden sm:inline",children:"Cancel"}),d.jsx("span",{className:"hidden sm:inline text-[12px] border border-current p-1 rounded-full ml-2",children:"Esc"})]}):d.jsxs(d.Fragment,{children:[d.jsx(_o,{className:"mr-2"}),d.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]})})})}),d.jsx(Mt,{children:d.jsx("p",{children:"Hover to cancel (or press Esc)"})})]}):d.jsx(Le,{onClick:s,disabled:n||!r,size:"sm",className:"lg:size-default pr-1! gap-0",children:n?d.jsxs(d.Fragment,{children:[d.jsx(_o,{className:"mr-2"}),d.jsx("span",{className:"hidden sm:inline",children:"Executing..."})]}):d.jsxs(d.Fragment,{children:[d.jsx(eB,{className:"h-4 w-4 sm:mr-2"}),d.jsx("span",{className:"hidden sm:inline",children:"Execute"}),d.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&&d.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 leading-relaxed mt-2",children:e.description})]})}),m?d.jsxs("div",{className:"flex-1 overflow-hidden flex gap-4 px-3 sm:px-6 pb-4",children:[d.jsx("div",{className:"flex-1 min-w-0 overflow-y-auto",children:d.jsx(lz,{selectedTool:e,toolArgs:t,onArgChange:a})}),d.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:[d.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-zinc-200 dark:border-zinc-800 flex-shrink-0",children:[d.jsx("h4",{className:"text-sm font-medium",children:"Tool Definition"}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:x,className:"h-7 w-7 p-0",title:"Copy metadata",children:g?d.jsx(oa,{className:"h-3.5 w-3.5 text-green-600"}):d.jsx(zr,{className:"h-3.5 w-3.5"})})]}),d.jsx("div",{className:"flex-1 overflow-y-auto p-3",children:d.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)})})]})]}):d.jsx("div",{className:"flex-1 overflow-y-auto px-3 sm:px-6 pb-4 pr-3",children:d.jsx(lz,{selectedTool:e,toolArgs:t,onArgChange:a})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx("p",{className:"text-gray-500 dark:text-gray-400 mb-2",children:"Select a tool to get started"}),d.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 uz(e){const n=Date.now()-e,r=Math.floor(n/1e3),a=Math.floor(r/60),s=Math.floor(a/60),i=Math.floor(s/24);return r<10?"now":r<60?`${r}s ago`:a<60?`${a}m ago`:s<24?`${s}h ago`:`${i}d ago`}function Zve(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
1660
  `)}return"An error occurred"}function qve(e){try{return JSON.parse(e),!0}catch{return!1}}function Xve({content:e}){return!Array.isArray(e)||e.length===0?d.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No content"}):d.jsx("div",{className:"space-y-4",children:e.map((t,n)=>{if(t.type==="text"){const r=t.text||"";if(qve(r))try{const a=JSON.parse(r);return d.jsxs("div",{className:"space-y-2",children:[d.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Text Content (JSON)"}),d.jsx(nr,{data:a,filename:`content-${n}.json`})]},n)}catch{}return d.jsxs("div",{className:"space-y-2",children:[d.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Text Content"}),d.jsx("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3 font-mono text-sm whitespace-pre-wrap break-words",children:r})]},n)}if(t.type==="image")return d.jsxs("div",{className:"space-y-2",children:[d.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Image Content"}),d.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3",children:[d.jsx("img",{src:`data:${t.mimeType||"image/png"};base64,${t.data}`,alt:"Result",className:"max-w-full rounded"}),t.annotations&&d.jsx("div",{className:"mt-2 text-xs text-gray-500 dark:text-gray-400",children:d.jsx(nr,{data:t.annotations,filename:`image-annotations-${n}.json`})})]})]},n);if(t.type==="audio")return d.jsxs("div",{className:"space-y-2",children:[d.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Audio Content"}),d.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3",children:[d.jsx("audio",{controls:!0,src:`data:${t.mimeType||"audio/wav"};base64,${t.data}`,className:"w-full"}),t.annotations&&d.jsx("div",{className:"mt-2 text-xs text-gray-500 dark:text-gray-400",children:d.jsx(nr,{data:t.annotations,filename:`audio-annotations-${n}.json`})})]})]},n);if(t.type==="resource_link")return d.jsxs("div",{className:"space-y-2",children:[d.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Resource Link"}),d.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3 space-y-2",children:[d.jsxs("div",{className:"font-mono text-sm break-all",children:[d.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"URI:"})," ",t.uri]}),t.name&&d.jsxs("div",{className:"text-sm",children:[d.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"Name:"})," ",t.name]}),t.description&&d.jsxs("div",{className:"text-sm",children:[d.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"Description:"})," ",t.description]}),t.mimeType&&d.jsxs("div",{className:"text-sm",children:[d.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"MIME Type:"})," ",t.mimeType]}),t.annotations&&d.jsxs("div",{className:"mt-2",children:[d.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"Annotations:"}),d.jsx(nr,{data:t.annotations,filename:`resource-link-annotations-${n}.json`})]})]})]},n);if(t.type==="resource"){const r=t.resource||{};return d.jsxs("div",{className:"space-y-2",children:[d.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Embedded Resource"}),d.jsxs("div",{className:"bg-gray-50 dark:bg-zinc-900 rounded-lg p-3 space-y-2",children:[d.jsxs("div",{className:"font-mono text-sm break-all",children:[d.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"URI:"})," ",r.uri]}),r.mimeType&&d.jsxs("div",{className:"text-sm",children:[d.jsx("span",{className:"text-gray-600 dark:text-gray-400",children:"MIME Type:"})," ",r.mimeType]}),r.text&&d.jsxs("div",{children:[d.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"Content:"}),d.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:r.text})]}),r.blob&&d.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:["[Binary content: ",r.blob.length||0," bytes]"]}),r.annotations&&d.jsxs("div",{className:"mt-2",children:[d.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400 mb-1",children:"Annotations:"}),d.jsx(nr,{data:r.annotations,filename:`resource-annotations-${n}.json`})]})]})]},n)}return d.jsxs("div",{className:"space-y-2",children:[d.jsxs("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:["Unknown Content Type: ",t.type||"N/A"]}),d.jsx(nr,{data:t,filename:`content-${n}.json`})]},n)})})}function dz({results:e,copiedResult:t,previewMode:n,serverId:r,readResource:a,onCopy:s,onTogglePreview:i,onMaximize:c,isMaximized:u=!1}){const[f,m]=v.useState(0),[h,g]=v.useState(""),[y,x]=v.useState(!0),E=e[0],w=E?e.filter(ee=>ee.toolName===E.toolName):[],_=w[f]||w[0],S=e.findIndex(ee=>ee===_);v.useEffect(()=>{w.length>0&&f>=w.length&&m(0)},[w.length,f]),v.useEffect(()=>{const ee=()=>{_&&g(uz(_.timestamp))};ee();const re=setInterval(ee,1e3);return()=>clearInterval(re)},[_]);const T=v.useMemo(()=>_?.args,[_?.timestamp,f]),R=v.useMemo(()=>_?.result,[_?.timestamp,f]),C=v.useCallback(ee=>a(ee),[a]);if(e.length===0)return d.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:d.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:d.jsx("div",{className:"flex items-center justify-center h-full",children:d.jsx("div",{className:"text-center",children:d.jsx(vd,{vertical:!0,noBorder:!0,message:"No Results yet"})})})})});const I=_.toolMeta?.["openai/outputTemplate"],A=!!(I&&typeof I=="string"&&_.appsSdkResource),O=I,j=_.result?.content||[],U=j.filter(ee=>ee.type==="resource"&&vu(ee.resource)),B=U.length>0,W=!!(j&&j.length>0||_.result?.structuredContent),J=!B&&!A&&W;return d.jsx("div",{className:"flex flex-col h-full bg-white dark:bg-black border-t dark:border-zinc-700",children:d.jsx("div",{className:"flex-1 overflow-y-auto h-full",children:d.jsxs("div",{className:"space-y-0 flex-1 h-full flex flex-col",children:[d.jsxs("div",{className:`flex items-center gap-2 px-4 pt-2 ${B||A||J?"border-b border-gray-200 dark:border-zinc-600 pb-2":""}`,children:[d.jsx("h3",{className:"text-sm font-medium hidden sm:block",children:"Response"}),_.duration!==void 0&&d.jsxs("div",{className:"hidden sm:flex items-center gap-1",children:[d.jsx(vp,{className:"h-3 w-3 text-gray-400"}),d.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:[_.duration,"ms"]})]}),A&&d.jsxs("div",{className:"flex items-center gap-4 sm:ml-4",children:[d.jsxs("span",{className:"hidden sm:inline text-xs text-gray-500 dark:text-gray-400",children:["URI: ",O||"No URI"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>i(),className:`text-xs font-medium ${n?"text-black dark:text-white":"text-zinc-500 dark:text-zinc-400"}`,children:"Component"}),d.jsx("span",{className:"text-xs text-zinc-400",children:"|"}),d.jsx("button",{onClick:()=>i(),className:`text-xs font-medium ${n?"text-zinc-500 dark:text-zinc-400":"text-black dark:text-white"}`,children:"Raw JSON"})]})]}),B&&!A&&d.jsxs("div",{className:"flex items-center gap-4 sm:ml-4",children:[d.jsxs("span",{className:"hidden sm:inline text-xs text-gray-500 dark:text-gray-400",children:["URI: ",U[0]?.resource?.uri||"No URI"]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("button",{onClick:()=>i(),className:`text-xs font-medium ${n?"text-black dark:text-white":"text-zinc-500 dark:text-zinc-400"}`,children:"Preview"}),d.jsx("span",{className:"text-xs text-zinc-400",children:"|"}),d.jsx("button",{onClick:()=>i(),className:`text-xs font-medium ${n?"text-zinc-500 dark:text-zinc-400":"text-black dark:text-white"}`,children:"JSON"})]})]}),J&&d.jsxs("div",{className:"flex items-center gap-2 sm:ml-4",children:[d.jsx("button",{onClick:()=>x(!0),className:`text-xs font-medium ${y?"text-black dark:text-white":"text-zinc-500 dark:text-zinc-400"}`,children:"Formatted"}),d.jsx("span",{className:"text-xs text-zinc-400",children:"|"}),d.jsx("button",{onClick:()=>x(!1),className:`text-xs font-medium ${y?"text-zinc-500 dark:text-zinc-400":"text-black dark:text-white"}`,children:"Raw"})]}),d.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[(A||B)&&c&&d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,title:u?"Restore":"Maximize",children:u?d.jsx(jie,{className:"h-4 w-4"}):d.jsx(hT,{className:"h-4 w-4"})}),w.length>1&&d.jsxs(ks,{value:f.toString(),onValueChange:ee=>m(parseInt(ee)),children:[d.jsx(Rs,{size:"sm",className:"w-[140px] h-8 text-xs",children:d.jsx(Cs,{children:d.jsxs("div",{className:"flex items-center gap-1",children:[d.jsx(Mb,{className:"h-3 w-3"}),d.jsx("span",{children:h})]})})}),d.jsx(As,{children:w.map((ee,re)=>d.jsx(Pr,{value:re.toString(),children:d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(Mb,{className:"h-3 w-3"}),d.jsx("span",{children:uz(ee.timestamp)}),d.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",new Date(ee.timestamp).toLocaleTimeString(),")"]})]})},re))})]}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>s(S,_.result),children:t===S?d.jsx(oa,{className:"h-4 w-4"}):d.jsx(zr,{className:"h-4 w-4"})})]})]}),(()=>{const ee=_.error||Zve(_.result);return ee?d.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:[d.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Error:"}),d.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:ee})]}):(()=>{if(A){const re=_.appsSdkResource;return re.isLoading?d.jsx(d.Fragment,{}):re.error?d.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:[d.jsx("p",{className:"text-red-800 dark:text-red-300 font-medium",children:"Resource Error:"}),d.jsx("p",{className:"text-red-700 dark:text-red-400 text-sm",children:re.error})]}):n?d.jsx("div",{className:"flex-1",children:d.jsx(A1,{componentUrl:O,toolName:_.toolName,toolArgs:T,toolResult:R,serverId:r,readResource:C,className:"w-full h-full relative p-4"})}):d.jsx("div",{className:"px-4 pt-4",children:d.jsx(nr,{data:_.result,filename:`tool-result-${_.toolName}-${Date.now()}.json`})})}if(B)return n?d.jsxs("div",{className:"space-y-0 h-full",children:[U.map((re,F)=>d.jsx("div",{className:"mx-0 size-full",children:d.jsx(s8,{resource:re.resource,onUIAction:K=>{},className:"w-full h-full relative"})},F)),j.filter(re=>!(re.type==="resource"&&vu(re.resource))).length>0&&d.jsx("div",{className:"px-4",children:d.jsx(nr,{data:j.filter(re=>!(re.type==="resource"&&vu(re.resource))),filename:`tool-result-${_.toolName}-non-ui-${Date.now()}.json`})})]}):d.jsx("div",{className:"px-4 pt-4",children:d.jsx(nr,{data:_.result,filename:`tool-result-${_.toolName}-mcp-ui-${Date.now()}.json`})});if(J&&y){const re=_.result?.structuredContent;return d.jsxs("div",{className:"px-4 pt-4 space-y-4",children:[re&&d.jsxs("div",{className:"space-y-2",children:[d.jsx("div",{className:"text-xs font-medium text-gray-500 dark:text-gray-400",children:"Structured Content"}),d.jsx(nr,{data:re,filename:`structured-content-${_.toolName}-${Date.now()}.json`})]}),j&&j.length>0&&d.jsx(Xve,{content:j}),!re&&(!j||j.length===0)&&d.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No content to display"})]})}return d.jsx("div",{className:"px-4 pt-4",children:d.jsx(nr,{data:_.result,filename:`tool-result-${_.toolName}-${Date.now()}.json`})})})()})()]})})})}function fz({tools:e,selectedTool:t,onToolSelect:n,focusedIndex:r}){return e.length===0?d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(Ol,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"No tools available"})]}):d.jsx("div",{className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((a,s)=>d.jsx(Wi,{id:`tool-${a.name}`,isSelected:t?.name===a.name,isFocused:r===s,icon:d.jsx(Ol,{className:"h-4 w-4"}),title:a.name,description:a.description,metadata:a.inputSchema?.properties&&d.jsxs(kr,{variant:"outline",className:"text-xs border-gray-300 dark:border-zinc-600 text-gray-600 dark:text-gray-400",children:[Object.keys(a.inputSchema.properties).length," params"]}),onClick:()=>n(a)},a.name))})}function pz({activeTab:e,isSearchExpanded:t,searchQuery:n,filteredToolsCount:r,savedRequestsCount:a,onSearchExpand:s,onSearchChange:i,onSearchBlur:c,onTabSwitch:u,searchInputRef:f}){return d.jsx(a8,{activeTab:e,isSearchExpanded:t,searchQuery:n,primaryTabName:"tools",secondaryTabName:"saved",primaryTabTitle:"Tools",secondaryTabTitle:"Saved",primaryCount:r,secondaryCount:a,primaryIcon:Ol,secondaryIcon:Wy,searchPlaceholder:"Search tools...",onSearchExpand:s,onSearchChange:i,onSearchBlur:c,onTabSwitch:u,searchInputRef:f})}const mz="mcp-inspector-saved-requests";function c8({ref:e,tools:t,callTool:n,readResource:r,serverId:a,isConnected:s}){const[i,c]=v.useState(null),[u,f]=v.useState(null),{selectedToolName:m,setSelectedToolName:h}=Wl(),[g,y]=v.useState({}),[x,E]=v.useState([]),[w,_]=v.useState(!1),[S,T]=v.useState(null),[R,C]=v.useState(null),[I,A]=v.useState(""),[O,j]=v.useState("tools"),[U,B]=v.useState([]),[W,J]=v.useState(!1),[ee,re]=v.useState(""),[F,K]=v.useState(!0),[V,ne]=v.useState(!1),[te,D]=v.useState(-1),H=v.useRef(null),[$,L]=v.useState(!1),[M,z]=v.useState("list"),[G,q]=v.useState(!1),[ae,ie]=v.useState(0),[X,Z]=v.useState(!0),[se,me]=v.useState(void 0),le=v.useRef(null),Ne=v.useRef(null),He=v.useRef(null),xe=v.useRef(null),Te=v.useRef(null);v.useEffect(()=>{const Ae=()=>{L(window.innerWidth<1024)};return Ae(),window.addEventListener("resize",Ae),()=>window.removeEventListener("resize",Ae)},[]),v.useEffect(()=>{z(i?"detail":"list")},[i]),v.useEffect(()=>{$&&x.length>0&&!w&&z("response")},[x,w,$]),v.useImperativeHandle(e,()=>({focusSearch:()=>{ne(!0),setTimeout(()=>{H.current&&H.current.focus()},0)},blurSearch:()=>{A(""),ne(!1),H.current&&H.current.blur()}})),v.useEffect(()=>{try{const Ae=localStorage.getItem(mz);Ae&&B(JSON.parse(Ae))}catch(Ae){console.error("[ToolsTab] Failed to load saved requests:",Ae)}},[]);const $e=v.useCallback(Ae=>{try{localStorage.setItem(mz,JSON.stringify(Ae)),B(Ae)}catch(Me){console.error("[ToolsTab] Failed to save requests:",Me)}},[]),fe=v.useMemo(()=>{if(!I.trim())return t;const Ae=I.toLowerCase();return t.filter(Me=>Me.name.toLowerCase().includes(Ae)||Me.description?.toLowerCase().includes(Ae))},[t,I]),Ie=v.useCallback(Ae=>{c(Ae);const Me={};Ae.inputSchema?.properties&&Object.entries(Ae.inputSchema.properties).forEach(([Ve,it])=>{const pt=it;pt.default!==void 0?Me[Ve]=pt.default:pt.type==="string"?Me[Ve]="":pt.type==="number"?Me[Ve]=0:pt.type==="boolean"?Me[Ve]=!1:pt.type==="array"?Me[Ve]="[]":pt.type==="object"&&(Me[Ve]="{}")}),y(Me)},[]),Fe=v.useCallback(Ae=>{const Me=t.find(Ve=>Ve.name===Ae.toolName);Me&&(c(Me),y(Ae.args),f(Ae))},[t]);v.useEffect(()=>{V&&H.current&&H.current.focus()},[V]);const Ee=v.useCallback(()=>{I.trim()||ne(!1)},[I]);v.useEffect(()=>{O!=="tools"&&ne(!1)},[O]),v.useEffect(()=>{D(-1)},[I,O]),v.useEffect(()=>{const Ae=Me=>{const Ve=Me.target;if(Ve.tagName==="INPUT"||Ve.tagName==="TEXTAREA"||Ve.contentEditable==="true"||Me.metaKey||Me.ctrlKey||Me.altKey)return;const pt=O==="tools"?fe:U;if(Me.key==="ArrowDown")Me.preventDefault(),D(Et=>{const xt=Et+1;return xt>=pt.length?0:xt});else if(Me.key==="ArrowUp")Me.preventDefault(),D(Et=>{const xt=Et-1;return xt<0?pt.length-1:xt});else if(Me.key==="Enter"&&te>=0)if(Me.preventDefault(),O==="tools"){const Et=fe[te];Et&&Ie(Et)}else{const Et=U[te];Et&&Fe(Et)}};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[te,fe,U,O,Ie,Fe]),v.useEffect(()=>{if(te>=0){const Ae=O==="tools"?`tool-${fe[te]?.name}`:`saved-${U[te]?.id}`,Me=document.getElementById(Ae);Me&&Me.scrollIntoView({behavior:"smooth",block:"nearest"})}},[te,fe,U,O]),v.useEffect(()=>{if(m&&t.length>0){const Ae=t.find(Me=>Me.name===m);if(Ae&&i?.name!==Ae.name){h(null);const Me=setTimeout(()=>{Ie(Ae);const Ve=document.getElementById(`tool-${Ae.name}`);Ve&&Ve.scrollIntoView({behavior:"smooth",block:"nearest"})},100);return()=>clearTimeout(Me)}}},[m,t,i,Ie,h]);const at=v.useCallback((Ae,Me)=>{y(Ve=>{const it={...Ve};if(i?.inputSchema?.properties?.[Ae]){const Et=i.inputSchema.properties[Ae].type;if(Et==="object"||Et==="array")it[Ae]=Me;else if(Et==="string")it[Ae]=Me;else try{it[Ae]=JSON.parse(Me)}catch{it[Ae]=Me}}else it[Ae]=Me;return it})},[i]),lt=v.useCallback(async()=>{if(!i||w)return;const Ae=new AbortController;C(Ae),_(!0);const Me=Date.now();try{const Ve={...g};i.inputSchema?.properties&&Object.entries(i.inputSchema.properties).forEach(([Ze,vt])=>{const Ut=vt.type,yr=Ve[Ze];if((Ut==="object"||Ut==="array")&&typeof yr=="string")try{Ve[Ze]=JSON.parse(yr)}catch{}});const it=await n(i.name,Ve,{timeout:6e5,resetTimeoutOnProgress:!0,signal:Ae.signal}),pt=Date.now()-Me;Tr.getInstance().capture(new hP({toolName:i.name,serverId:a,success:!0,duration:pt})).catch(()=>{});const xt=i?._meta||i?.metadata,un=xt?.["openai/outputTemplate"];let mn;if(un&&typeof un=="string"){const Ze={toolName:i.name,args:g,result:it,timestamp:Me,duration:pt,toolMeta:xt,appsSdkResource:{uri:un,resourceData:null,isLoading:!0}};E([Ze]);try{const vt=await r(un);let Pt=null;if(it?.structuredContent)Pt=it.structuredContent;else if(Array.isArray(it)&&it[0]){const Ut=it[0];Ut.output?.value?.structuredContent?Pt=Ut.output.value.structuredContent:Ut.structuredContent?Pt=Ut.structuredContent:Ut.output?.value&&(Pt=Ut.output.value)}Pt||(Pt=it),mn={uri:un,resourceData:{...vt,structuredContent:Pt},isLoading:!1}}catch(vt){mn={uri:un,resourceData:null,isLoading:!1,error:vt instanceof Error?vt.message:String(vt)}}E(vt=>vt.map((Pt,Ut)=>Ut===0?{...Pt,appsSdkResource:mn}:Pt))}else E(Ze=>[{toolName:i.name,args:g,result:it,timestamp:Me,duration:pt,toolMeta:xt},...Ze])}catch(Ve){const it=Date.now()-Me;Tr.getInstance().capture(new hP({toolName:i.name,serverId:a,success:!1,duration:it,error:Ve instanceof Error?Ve.message:String(Ve)})).catch(()=>{});const Et=i?._meta||i?.metadata,xt={toolName:i.name,args:g,result:null,error:Ve instanceof Error?Ve.message:String(Ve),timestamp:Me,duration:it,toolMeta:Et},un=Et?.["openai/outputTemplate"];E(un?[xt]:mn=>[xt,...mn])}finally{_(!1)}},[i,g,w,n,r,a]),bt=v.useCallback(async(Ae,Me)=>{try{await navigator.clipboard.writeText(JSON.stringify(Me,null,2)),T(Ae),setTimeout(()=>T(null),2e3)}catch(Ve){console.error("[ToolsTab] Failed to copy result:",Ve)}},[]),Rt=v.useCallback(Ae=>{E(Me=>Me.filter((Ve,it)=>it!==Ae))},[]),De=v.useMemo(()=>i?x.filter(Ae=>Ae.toolName===i.name):[],[x,i]),ze=v.useCallback(Ae=>{const Me=De[Ae];if(Me){const Ve=window.open("","_blank","width=800,height=600");Ve&&(Ve.document.write(`
1661
1661
  <html>
@@ -1671,4 +1671,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1671
1671
  <pre>${JSON.stringify(Me.result,null,2)}</pre>
1672
1672
  </body>
1673
1673
  </html>
1674
- `),Ve.document.close())}},[x]),ht=v.useCallback(()=>{G?(le.current&&le.current.expand(),Ne.current&&Ne.current.expand(),q(!1)):(le.current&&le.current.collapse(),Ne.current&&Ne.current.collapse(),q(!0))},[G]),nt=v.useCallback(()=>{i&&(re(""),J(!0))},[i]),kt=v.useCallback(()=>{if(!i)return;const Ae={id:`${Date.now()}-${Math.random()}`,name:ee.trim()||`${i.name} - ${new Date().toLocaleString()}`,toolName:i.name,args:g,savedAt:Date.now(),serverId:i._serverId,serverName:i._serverName};$e([...U,Ae]),Tr.getInstance().capture(new Ese({toolName:i.name,serverId:a})).catch(()=>{}),J(!1),re("")},[i,ee,g,U,$e,a]),ot=v.useCallback(Ae=>{$e(U.filter(Me=>Me.id!==Ae)),u?.id===Ae&&f(null)},[U,$e,u]);return $?d.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[M!=="list"&&d.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[d.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>{M==="response"?z("detail"):(c(null),z("list"))},className:"p-0 h-8 w-8",children:d.jsx(dT,{className:"h-4 w-4"})}),d.jsxs("div",{className:"flex items-center text-sm font-medium",children:[d.jsx("button",{onClick:()=>{c(null),z("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Tools"}),M==="detail"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("button",{onClick:()=>{z("response")},className:M==="detail"?"text-foreground hover:underline":M==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),M==="response"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),d.jsx("div",{className:"flex-1 relative overflow-hidden",children:d.jsxs(Jy,{initial:!1,mode:"popLayout",children:[M==="list"&&d.jsxs(wa.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:[d.jsx(pz,{activeTab:O,isSearchExpanded:V,searchQuery:I,filteredToolsCount:fe.length,savedRequestsCount:U.length,onSearchExpand:()=>ne(!0),onSearchChange:A,onSearchBlur:Ee,onTabSwitch:()=>j(O==="tools"?"saved":"tools"),searchInputRef:H}),O==="tools"?d.jsx(fz,{tools:fe,selectedTool:i,onToolSelect:Ie,focusedIndex:te}):d.jsx(sz,{savedRequests:U,selectedRequest:u,onLoadRequest:Fe,onDeleteRequest:ot,focusedIndex:te})]},"list"),M==="detail"&&d.jsx(wa.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:d.jsx(cz,{selectedTool:i,toolArgs:g,isExecuting:w,isConnected:s,onArgChange:at,onExecute:lt,onSave:nt})},"detail"),M==="response"&&d.jsx(wa.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:d.jsx(dz,{results:De,copiedResult:S,previewMode:F,serverId:a,readResource:r,onCopy:bt,onDelete:Rt,onFullscreen:ze,onTogglePreview:()=>K(!F)})},"response")]})}),d.jsx(iz,{isOpen:W,requestName:ee,defaultPlaceholder:`${i?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:re,onSave:kt,onCancel:()=>J(!1)})]}):d.jsxs(aa,{direction:"horizontal",className:"h-full",children:[d.jsx(Rn,{ref:le,defaultSize:33,collapsible:!0,className:"flex flex-col h-full relative",children:d.jsxs(aa,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[d.jsx(Rn,{defaultSize:75,minSize:30,children:d.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[d.jsx(pz,{activeTab:O,isSearchExpanded:V,searchQuery:I,filteredToolsCount:fe.length,savedRequestsCount:U.length,onSearchExpand:()=>ne(!0),onSearchChange:A,onSearchBlur:Ee,onTabSwitch:()=>j(O==="tools"?"saved":"tools"),searchInputRef:H}),O==="tools"?d.jsx(fz,{tools:fe,selectedTool:i,onToolSelect:Ie,focusedIndex:te}):d.jsx(sz,{savedRequests:U,selectedRequest:u,onLoadRequest:Fe,onDeleteRequest:ot,focusedIndex:te})]})}),d.jsx(wo,{withHandle:!0}),d.jsxs(Rn,{ref:xe,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:[d.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:Ae=>{Ae.preventDefault(),Ae.stopPropagation(),X?(xe.current?.resize(25),Z(!1)):(xe.current?.resize(5),Z(!0))},children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),ae>0&&d.jsx(kr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:ae}),ae>0&&!X&&d.jsx(Le,{variant:"ghost",size:"sm",onClick:Ae=>{Ae.preventDefault(),Ae.stopPropagation(),Te.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:d.jsx(Mi,{className:"h-3.5 w-3.5"})})]}),d.jsx(Gl,{className:`h-4 w-4 text-muted-foreground transition-transform ${X?"":"rotate-180"}`})]}),!X&&d.jsx("div",{className:"flex-1 overflow-hidden min-h-0",children:d.jsx(z1,{serverIds:[a],onCountChange:ie,onClearRef:Te})})]})]})}),d.jsx(wo,{withHandle:!0}),d.jsx(Rn,{defaultSize:67,children:d.jsxs(aa,{direction:"vertical",children:[d.jsx(Rn,{ref:Ne,defaultSize:40,collapsible:!0,children:d.jsx(cz,{selectedTool:i,toolArgs:g,isExecuting:w,isConnected:s,onArgChange:at,onExecute:lt,onSave:nt,onCancel:()=>{R&&R.abort()}})}),d.jsx(wo,{withHandle:!0}),d.jsx(Rn,{ref:He,defaultSize:60,children:d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(dz,{results:De,copiedResult:S,previewMode:F,serverId:a,readResource:r,onCopy:bt,onDelete:Rt,onFullscreen:ze,onTogglePreview:()=>K(!F),onMaximize:ht,isMaximized:G})})})]})}),d.jsx(iz,{isOpen:W,requestName:ee,defaultPlaceholder:`${i?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:re,onSave:kt,onCancel:()=>J(!1)})]})}c8.displayName="ToolsTab";function Jve({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:r,onSearchExpand:a,onSearchChange:s,onSearchBlur:i,onRejectAll:c,searchInputRef:u}){return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Tn,{ref:u,placeholder:"Search requests...",value:t,onChange:f=>s(f.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Sampling"}),d.jsx(kr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:d.jsx(wd,{className:"h-4 w-4"})})}),d.jsxs(Mt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(gm,{children:"F"})]})]})]})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,disabled:r===0,className:"h-8 w-8 p-0",children:d.jsx(Mi,{className:"h-4 w-4"})})}),d.jsx(Mt,{side:"bottom",children:"Reject all"})]})})]})}function Qve({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:r,formatRelativeTime:a,listRef:s}){return e.length===0?d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx(vd,{vertical:!0,noBorder:!0,message:"No sampling requests"})}):d.jsx("div",{ref:s,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((i,c)=>{const u=i.request.params?.messages?.length||0,f=i.request.params?.maxTokens;return d.jsx(Wi,{id:`sampling-request-${i.id}`,isSelected:t?.id===i.id,isFocused:r===c,title:d.jsxs("span",{className:"flex items-center gap-3",children:[i.serverName,d.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const m=a(i.timestamp),h=[];u>0&&h.push(`${u} message${u>1?"s":""}`),f&&h.push(`max ${f} tokens`);const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(i)},i.id)})})}function e0e({llmConfig:e}){const t=v.useRef(null);return{generateResponse:v.useCallback(async({request:r})=>{if(!e)throw new Error("LLM config is not available");const a=r.params||{},s=a.maxTokens,i=a.temperature;a.modelPreferences;const c=a.messages||[];if(console.log("[useSamplingLLM] Request structure:",{hasParams:!!a,messagesCount:c.length,messages:c,params:a}),c.length===0)throw new Error("No messages found in sampling request");const u=[],{HumanMessage:f,AIMessage:m}=await rr(async()=>{const{HumanMessage:x,AIMessage:E}=await import("./index-D4BJ-4dv.js").then(w=>w.bE);return{HumanMessage:x,AIMessage:E}},[]);for(const x of c){if(!x||!x.role){console.warn("Skipping invalid message:",x);continue}const E=Array.isArray(x.content)?x.content[0]:x.content;if(!E){console.warn("Skipping message with no content:",x);continue}E.type==="text"&&E.text?x.role==="user"?u.push(new f(E.text)):x.role==="assistant"&&u.push(new m(E.text)):console.warn("Skipping message with unsupported content type:",E)}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 E={model:e.model,apiKey:e.apiKey};if(s!==void 0&&(E.maxTokens=s),i!==void 0?E.temperature=i:e.temperature!==void 0&&(E.temperature=e.temperature),e.provider==="openai"){const{ChatOpenAI:w}=await rr(async()=>{const{ChatOpenAI:_}=await import("./index-D3h9OtLD.js");return{ChatOpenAI:_}},__vite__mapDeps([5,6,7,3,8,9]));x=new w(E)}else if(e.provider==="anthropic"){const{ChatAnthropic:w}=await rr(async()=>{const{ChatAnthropic:_}=await import("./index-B-y3tpvd.js");return{ChatAnthropic:_}},__vite__mapDeps([10,7,6,3]));x=new w(E)}else if(e.provider==="google"){const{ChatGoogleGenerativeAI:w}=await rr(async()=>{const{ChatGoogleGenerativeAI:_}=await import("./index-DVE3PVDT.js");return{ChatGoogleGenerativeAI:_}},__vite__mapDeps([11,7,6,3,9]));x=new w(E)}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 t0e({request:e,onApprove:t,onReject:n,onClose:r,previewMode:a,onTogglePreview:s,isCopied:i,onCopy:c,onDownload:u,onFullscreen:f,llmConfig:m}){const[h,g]=v.useState("manual"),[y,x]=v.useState("stub-model"),[E,w]=v.useState("endTurn"),[_,S]=v.useState("assistant"),[T,R]=v.useState("text"),[C,I]=v.useState("positive"),[A,O]=v.useState(""),[j,U]=v.useState("image/png"),[B,W]=v.useState(!1),[J,ee]=v.useState(null),{generateResponse:re,isAvailable:F}=e0e({llmConfig:m});v.useEffect(()=>{e&&(x("stub-model"),w("endTurn"),S("assistant"),R("text"),I("positive"),O(""),U("image/png"),ee(null))},[e?.id]);const K=async()=>{if(!(!e||!F)){W(!0),ee(null);try{const D=await re({request:e.request});x(D.model||m?.model||"stub-model"),w(D.stopReason||"endTurn"),S(D.role||"assistant");const H=Array.isArray(D.content)?D.content[0]:D.content;H.type==="text"?(R("text"),I(H.text||"")):H.type==="image"&&(R("image"),O(H.data||""),U(H.mimeType||"image/png"))}catch(D){const H=D instanceof Error?D.message:"Failed to generate response";ee(H),Xt.error("LLM Generation Failed",{description:H})}finally{W(!1)}}},V=v.useMemo(()=>{const D={model:y,stopReason:E,role:_,content:{type:T}};return T==="text"?D.content.text=C:T==="image"&&(D.content.data=A,D.content.mimeType=j),D},[y,E,_,T,C,A,j]),ne=()=>{if(!e)return;const D=__.safeParse(V);if(!D.success){Xt.error("Invalid response",{description:`Validation failed: ${D.error.message}`});return}t(e.id,D.data),r(),rr(()=>Promise.resolve().then(()=>id),void 0).then(H=>{const $=Xt(H.createElement("div",{className:"space-y-3"},H.createElement("div",null,H.createElement("strong",null,"Sampling Response Sent"),H.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),H.createElement("div",{className:"flex gap-2"},H.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 L=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:e.toolName}});window.dispatchEvent(L),Xt.dismiss($)}},"View Tool Result"))),{duration:5e3})})},te=()=>{e&&(n(e.id,"User rejected sampling request"),r())};return e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),d.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,className:"h-8 w-8 p-0",children:i?d.jsx(oa,{className:"h-4 w-4 text-green-600"}):d.jsx(zr,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:"Copy request"})]}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:d.jsx(Qp,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:"Download request"})]}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:f,className:"h-8 w-8 p-0",children:d.jsx(mT,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:"Fullscreen"})]}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:d.jsx(qo,{className:"h-4 w-4"})})]})]}),d.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Request"}),d.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:d.jsx(nr,{data:e.request})})]}),d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Response"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(Wt,{htmlFor:`responseMode-${e.id}`,className:"text-xs text-gray-500 dark:text-gray-400",children:"Mode:"}),d.jsxs(ks,{value:h,onValueChange:D=>g(D),children:[d.jsx(Rs,{id:`responseMode-${e.id}`,className:"w-32 h-8 text-xs",children:d.jsx(Cs,{})}),d.jsxs(As,{children:[d.jsx(Pr,{value:"manual",children:"Manual"}),d.jsx(Pr,{value:"llm",children:"LLM"})]})]})]})]}),h==="llm"&&d.jsxs("div",{className:"space-y-2 p-3 bg-muted rounded-lg",children:[F?d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(Le,{onClick:K,disabled:B,size:"sm",className:"flex items-center gap-2",children:B?d.jsxs(d.Fragment,{children:[d.jsx(Li,{className:"h-4 w-4 animate-spin"}),"Generating..."]}):d.jsxs(d.Fragment,{children:[d.jsx(tle,{className:"h-4 w-4"}),"Generate with LLM"]})}),d.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["Using ",m?.provider," (",m?.model,")"]})]}):d.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:"LLM not configured. Please configure LLM in the Chat tab."}),J&&d.jsx("div",{className:"text-xs text-red-600 dark:text-red-400",children:J})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`model-${e.id}`,children:"Model"}),d.jsx(Tn,{id:`model-${e.id}`,value:y,onChange:D=>x(D.target.value),placeholder:"stub-model",disabled:h==="llm"&&B})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`stopReason-${e.id}`,children:"Stop Reason"}),d.jsx(Tn,{id:`stopReason-${e.id}`,value:E,onChange:D=>w(D.target.value),placeholder:"endTurn",disabled:h==="llm"&&B})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`role-${e.id}`,children:"Role"}),d.jsxs(ks,{value:_,onValueChange:D=>S(D),disabled:h==="llm"&&B,children:[d.jsx(Rs,{id:`role-${e.id}`,children:d.jsx(Cs,{})}),d.jsxs(As,{children:[d.jsx(Pr,{value:"assistant",children:"assistant"}),d.jsx(Pr,{value:"user",children:"user"})]})]})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`contentType-${e.id}`,children:"Content Type"}),d.jsxs(ks,{value:T,onValueChange:D=>R(D),disabled:h==="llm"&&B,children:[d.jsx(Rs,{id:`contentType-${e.id}`,children:d.jsx(Cs,{})}),d.jsxs(As,{children:[d.jsx(Pr,{value:"text",children:"text"}),d.jsx(Pr,{value:"image",children:"image"})]})]})]}),T==="text"&&d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`text-${e.id}`,children:"Text Content"}),d.jsx(Pl,{id:`text-${e.id}`,value:C,onChange:D=>I(D.target.value),placeholder:"Enter response text...",rows:6,disabled:h==="llm"&&B})]}),T==="image"&&d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`imageData-${e.id}`,children:"Base64 Image Data"}),d.jsx(Pl,{id:`imageData-${e.id}`,value:A,onChange:D=>O(D.target.value),placeholder:"Base64 encoded image data...",rows:4,disabled:h==="llm"&&B})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`mimeType-${e.id}`,children:"MIME Type"}),d.jsx(Tn,{id:`mimeType-${e.id}`,value:j,onChange:D=>U(D.target.value),placeholder:"image/png",disabled:h==="llm"&&B})]})]})]})]}),d.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[d.jsx(Le,{onClick:ne,className:"flex-1",disabled:h==="llm"&&B,children:"Approve"}),d.jsx(Le,{onClick:te,variant:"outline",className:"flex-1",disabled:h==="llm"&&B,children:"Reject"})]})]}):d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a sampling request to view details"})})}function n0e({pendingRequests:e,onApprove:t,onReject:n,serverId:r,isConnected:a,mcpServerUrl:s}){const{selectedSamplingRequestId:i,setSelectedSamplingRequestId:c}=Wl(),{llmConfig:u}=j6({mcpServerUrl:s}),[f,m]=v.useState(null),[h,g]=v.useState(""),[y,x]=v.useState(-1),[E,w]=v.useState(!0),[_,S]=v.useState(!1),[T,R]=v.useState(!0),[C,I]=v.useState(!1),A=v.useRef(null),O=v.useRef(null),j=v.useRef(null),U=v.useRef(!1);v.useEffect(()=>{if(console.log("[SamplingTab] Auto-selection check:",{selectedSamplingRequestId:i,pendingRequestsCount:e.length,currentSelectedId:f?.id}),i&&e.length>0){const V=e.find(ne=>ne.id===i);console.log("[SamplingTab] Found request for auto-selection:",!!V,V?.id),V&&(console.log("[SamplingTab] Auto-selecting request:",V.id),c(null),m(V),setTimeout(()=>{const ne=document.getElementById(`sampling-request-${V.id}`);console.log("[SamplingTab] Scrolling to element:",!!ne),ne&&ne.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[i,e,c]),v.useEffect(()=>{const V=ne=>{const D=ne.detail.requestId;console.log("[SamplingTab] Custom navigate event received:",D);const H=e.find($=>$.id===D);H&&(console.log("[SamplingTab] Selecting request from event:",D),m(H),setTimeout(()=>{const $=document.getElementById(`sampling-request-${D}`);$&&$.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-sampling",V),()=>window.removeEventListener("navigate-to-sampling",V)},[e]),v.useEffect(()=>{E&&e.length>0&&A.current&&!U.current&&(A.current.scrollTop=0)},[e.length,E]),v.useEffect(()=>{const V=A.current;if(!V)return;const ne=()=>{V.scrollTop>0&&(U.current=!0,w(!1))};return V.addEventListener("scroll",ne),()=>V.removeEventListener("scroll",ne)},[]),v.useEffect(()=>{e.length===0&&(U.current=!1,w(!0))},[e.length]),v.useEffect(()=>{_&&j.current&&j.current.focus()},[_]);const B=v.useCallback(()=>{h.trim()||S(!1)},[h]),W=v.useMemo(()=>{if(!h.trim())return e;const V=h.toLowerCase();return e.filter(ne=>ne.serverName.toLowerCase().includes(V)||JSON.stringify(ne.request||{}).toLowerCase().includes(V))},[e,h]);v.useEffect(()=>{x(-1)},[h]),v.useEffect(()=>{const V=ne=>{const te=ne.target;if(te.tagName==="INPUT"||te.tagName==="TEXTAREA"||te.contentEditable==="true"||ne.metaKey||ne.ctrlKey||ne.altKey)return;const H=W;if(ne.key==="ArrowDown")ne.preventDefault(),x($=>{const L=$+1;return L>=H.length?0:L});else if(ne.key==="ArrowUp")ne.preventDefault(),x($=>{const L=$-1;return L<0?H.length-1:L});else if(ne.key==="Enter"&&y>=0){ne.preventDefault();const $=W[y];$&&J($)}};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[y,W]),v.useEffect(()=>{if(y>=0){const V=`sampling-request-${W[y]?.id}`,ne=document.getElementById(V);ne&&ne.scrollIntoView({behavior:"smooth",block:"nearest"})}},[y,W]);const J=v.useCallback(V=>{m(V)},[]),ee=v.useCallback(()=>{window.confirm("Are you sure you want to reject all sampling requests? This cannot be undone.")&&(e.forEach(V=>{n(V.id,"User rejected all requests")}),m(null))},[e,n]),re=v.useCallback(async()=>{if(f)try{await navigator.clipboard.writeText(JSON.stringify({id:f.id,serverName:f.serverName,timestamp:f.timestamp,request:f.request},null,2)),I(!0),setTimeout(()=>I(!1),2e3)}catch(V){console.error("[SamplingTab] Failed to copy request:",V)}},[f]),F=v.useCallback(()=>{if(f)try{const V=new globalThis.Blob([JSON.stringify({id:f.id,serverName:f.serverName,timestamp:f.timestamp,request:f.request},null,2)],{type:"application/json"}),ne=URL.createObjectURL(V),te=document.createElement("a");te.href=ne,te.download=`sampling-request-${Date.now()}.json`,document.body.appendChild(te),te.click(),document.body.removeChild(te),URL.revokeObjectURL(ne)}catch(V){console.error("[SamplingTab] Failed to download request:",V)}},[f]),K=v.useCallback(async()=>{if(O.current)try{document.fullscreenElement?await document.exitFullscreen():await O.current.requestFullscreen()}catch(V){console.error("[SamplingTab] Failed to toggle fullscreen:",V)}},[]);return a?d.jsxs(aa,{direction:"horizontal",className:"h-full",children:[d.jsx(Rn,{defaultSize:40,minSize:30,children:d.jsx(aa,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:d.jsxs(Rn,{defaultSize:75,minSize:30,children:[d.jsx(Jve,{isSearchExpanded:_,searchQuery:h,filteredRequestsCount:W.length,requestsCount:e.length,onSearchExpand:()=>S(!0),onSearchChange:g,onSearchBlur:B,onRejectAll:ee,searchInputRef:j}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(Qve,{requests:W,selectedRequest:f,onRequestSelect:J,focusedIndex:y,formatRelativeTime:uy,listRef:A})})]})})}),d.jsx(wo,{}),d.jsx(Rn,{defaultSize:60,minSize:40,children:d.jsx("div",{ref:O,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(t0e,{request:f,onApprove:t,onReject:n,onClose:()=>m(null),previewMode:T,onTogglePreview:()=>R(!T),isCopied:C,onCopy:re,onDownload:F,onFullscreen:K,llmConfig:u})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(J3,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function r0e({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:r,onSearchExpand:a,onSearchChange:s,onSearchBlur:i,onCancelAll:c,searchInputRef:u}){return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Tn,{ref:u,placeholder:"Search requests...",value:t,onChange:f=>s(f.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Elicitation"}),d.jsx(kr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:d.jsx(wd,{className:"h-4 w-4"})})}),d.jsxs(Mt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(gm,{children:"F"})]})]})]})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,disabled:r===0,className:"h-8 w-8 p-0",children:d.jsx(qo,{className:"h-4 w-4"})})}),d.jsx(Mt,{side:"bottom",children:"Cancel all"})]})})]})}function a0e({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:r,formatRelativeTime:a,listRef:s}){return e.length===0?d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx(vd,{vertical:!0,noBorder:!0,message:"No elicitation requests"})}):d.jsx("div",{ref:s,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((i,c)=>{const u=i.request.mode||"form",f=u==="form"&&"requestedSchema"in i.request&&i.request.requestedSchema;return d.jsx(Wi,{id:`elicitation-request-${i.id}`,isSelected:t?.id===i.id,isFocused:r===c,title:d.jsxs("span",{className:"flex items-center gap-3",children:[i.serverName,d.jsx(kr,{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=a(i.timestamp),h=[];f&&h.push("with schema"),u==="url"&&h.push("external action");const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(i)},i.id)})})}function o0e({request:e,onApprove:t,onReject:n,onClose:r,previewMode:a,onTogglePreview:s,isCopied:i,onCopy:c,onDownload:u,onFullscreen:f}){const[m,h]=v.useState({}),[g,y]=v.useState(!1),x=e?.request.mode||"form",E=x==="form",w=x==="url";v.useEffect(()=>{if(e&&E&&"requestedSchema"in e.request){const A=e.request.requestedSchema,O={};if(A?.type==="object"&&A.properties)for(const[j,U]of Object.entries(A.properties)){const B=U;B.default!==void 0?O[j]=B.default:B.type==="boolean"?O[j]=!1:B.type==="number"||B.type==="integer"?O[j]=0:O[j]=""}h(O)}y(!1)},[e?.id,E]);const _=(A,O)=>{h(j=>({...j,[A]:O}))},S=()=>{if(e){if(E){if("requestedSchema"in e.request){const A=e.request.requestedSchema;if(A?.required){const O=A.required.filter(j=>m[j]===void 0||m[j]===""||m[j]===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 w&&t(e.id,{action:"accept"});r(),rr(()=>Promise.resolve().then(()=>id),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 j=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:null}});window.dispatchEvent(j),Xt.dismiss(O)}},"View Tool Result"))),{duration:5e3})})}},T=()=>{e&&(t(e.id,{action:"decline"}),r())},R=()=>{e&&(n(e.id,"User cancelled elicitation request"),r())},C=()=>{e&&w&&"url"in e.request&&(window.open(e.request.url,"_blank"),y(!0))},I=v.useMemo(()=>{if(!e||!E||!("requestedSchema"in e.request))return null;const A=e.request.requestedSchema;if(!A||A.type!=="object"||!A.properties)return d.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No form schema available"});const O=A.properties,j=A.required||[];return d.jsx("div",{className:"space-y-4",children:Object.entries(O).map(([U,B])=>{const W=B,J=j.includes(U),ee=W.type||"string",re=W.title||U,F=W.description;return d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:`field-${U}`,children:[re,J&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),F&&d.jsx("p",{className:"text-xs text-muted-foreground",children:F}),ee==="boolean"?d.jsxs("div",{className:"flex items-center space-x-2",children:[d.jsx(Op,{id:`field-${U}`,checked:m[U]||!1,onCheckedChange:K=>_(U,K)}),d.jsx(Wt,{htmlFor:`field-${U}`,className:"text-sm font-normal cursor-pointer",children:W.title||U})]}):ee==="number"||ee==="integer"?d.jsx(Tn,{id:`field-${U}`,type:"number",value:m[U]||"",onChange:K=>_(U,ee==="integer"?parseInt(K.target.value,10):parseFloat(K.target.value)),placeholder:W.default?.toString()||""}):W.enum?d.jsxs("select",{id:`field-${U}`,value:m[U]||"",onChange:K=>_(U,K.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:[d.jsx("option",{value:"",children:"Select..."}),W.enum.map(K=>d.jsx("option",{value:K,children:K},K))]}):ee==="string"&&(W.format==="textarea"||W.maxLength>100)?d.jsx(Pl,{id:`field-${U}`,value:m[U]||"",onChange:K=>_(U,K.target.value),placeholder:W.default||"",rows:4}):d.jsx(Tn,{id:`field-${U}`,type:"text",value:m[U]||"",onChange:K=>_(U,K.target.value),placeholder:W.default||""})]},U)})})},[e,m,E]);return e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),d.jsx(kr,{variant:"outline",className:w?"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}),d.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,className:"h-8 w-8 p-0",children:i?d.jsx(oa,{className:"h-4 w-4 text-green-600"}):d.jsx(zr,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:"Copy request"})]}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:d.jsx(Qp,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:"Download request"})]}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:f,className:"h-8 w-8 p-0",children:d.jsx(mT,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:"Fullscreen"})]}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:d.jsx(qo,{className:"h-4 w-4"})})]})]}),d.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Message"}),d.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:e.request.message})]}),w&&"url"in e.request&&d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"External Action Required"}),d.jsxs("div",{className:"bg-muted rounded-lg p-4 space-y-3",children:[d.jsx("p",{className:"text-sm text-muted-foreground",children:"This request requires you to complete an action at an external URL:"}),d.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background rounded border",children:[d.jsx("code",{className:"flex-1 text-xs font-mono break-all",children:e.request.url}),d.jsxs(Le,{size:"sm",variant:"outline",onClick:C,className:"flex items-center gap-2",children:[d.jsx(Wx,{className:"h-4 w-4"}),"Open URL"]})]}),d.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[d.jsx(Op,{id:"url-completed",checked:g,onCheckedChange:A=>y(!!A)}),d.jsx(Wt,{htmlFor:"url-completed",className:"text-sm font-normal cursor-pointer",children:"I have completed the required action"})]})]})]}),E&&d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Form Data"}),I]}),E&&"requestedSchema"in e.request&&e.request.requestedSchema&&d.jsxs("details",{className:"space-y-2",children:[d.jsx("summary",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 cursor-pointer",children:"Schema (for reference)"}),d.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:d.jsx(nr,{data:e.request.requestedSchema})})]})]}),d.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[d.jsx(Le,{onClick:S,className:"flex-1",children:"Accept"}),d.jsx(Le,{onClick:T,variant:"outline",className:"flex-1",children:"Decline"}),d.jsx(Le,{onClick:R,variant:"outline",className:"flex-1",children:"Cancel"})]})]}):d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select an elicitation request to view details"})})}function s0e({pendingRequests:e=[],onApprove:t,onReject:n,serverId:r,isConnected:a}){const{selectedElicitationRequestId:s,setSelectedElicitationRequestId:i}=Wl(),[c,u]=v.useState(null),[f,m]=v.useState(""),[h,g]=v.useState(-1),[y,x]=v.useState(!0),[E,w]=v.useState(!1),[_,S]=v.useState(!0),[T,R]=v.useState(!1),C=v.useRef(null),I=v.useRef(null),A=v.useRef(null),O=v.useRef(!1);v.useEffect(()=>{if(console.log("[ElicitationTab] Auto-selection check:",{selectedElicitationRequestId:s,pendingRequestsCount:e.length,currentSelectedId:c?.id}),s&&e.length>0){const F=e.find(K=>K.id===s);console.log("[ElicitationTab] Found request for auto-selection:",!!F,F?.id),F&&(console.log("[ElicitationTab] Auto-selecting request:",F.id),i(null),u(F),setTimeout(()=>{const K=document.getElementById(`elicitation-request-${F.id}`);console.log("[ElicitationTab] Scrolling to element:",!!K),K&&K.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[s,e,i]),v.useEffect(()=>{const F=K=>{const ne=K.detail.requestId;console.log("[ElicitationTab] Custom navigate event received:",ne);const te=e.find(D=>D.id===ne);te&&(console.log("[ElicitationTab] Selecting request from event:",ne),u(te),setTimeout(()=>{const D=document.getElementById(`elicitation-request-${ne}`);D&&D.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-elicitation",F),()=>window.removeEventListener("navigate-to-elicitation",F)},[e]),v.useEffect(()=>{y&&e.length>0&&C.current&&!O.current&&(C.current.scrollTop=0)},[e.length,y]),v.useEffect(()=>{const F=C.current;if(!F)return;const K=()=>{F.scrollTop>0&&(O.current=!0,x(!1))};return F.addEventListener("scroll",K),()=>F.removeEventListener("scroll",K)},[]),v.useEffect(()=>{e.length===0&&(O.current=!1,x(!0))},[e.length]),v.useEffect(()=>{E&&A.current&&A.current.focus()},[E]);const j=v.useCallback(()=>{f.trim()||w(!1)},[f]),U=v.useMemo(()=>{if(!f.trim())return e;const F=f.toLowerCase();return e.filter(K=>K.serverName.toLowerCase().includes(F)||K.request.message.toLowerCase().includes(F)||JSON.stringify(K.request||{}).toLowerCase().includes(F))},[e,f]);v.useEffect(()=>{g(-1)},[f]),v.useEffect(()=>{const F=K=>{const V=K.target;if(V.tagName==="INPUT"||V.tagName==="TEXTAREA"||V.contentEditable==="true"||K.metaKey||K.ctrlKey||K.altKey)return;const te=U;if(K.key==="ArrowDown")K.preventDefault(),g(D=>{const H=D+1;return H>=te.length?0:H});else if(K.key==="ArrowUp")K.preventDefault(),g(D=>{const H=D-1;return H<0?te.length-1:H});else if(K.key==="Enter"&&h>=0){K.preventDefault();const D=U[h];D&&B(D)}};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[h,U]),v.useEffect(()=>{if(h>=0){const F=`elicitation-request-${U[h]?.id}`,K=document.getElementById(F);K&&K.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,U]);const B=v.useCallback(F=>{u(F)},[]),W=v.useCallback(()=>{window.confirm("Are you sure you want to cancel all elicitation requests? This cannot be undone.")&&(e.forEach(F=>{n(F.id,"User cancelled all requests")}),u(null))},[e,n]),J=v.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)),R(!0),setTimeout(()=>R(!1),2e3)}catch(F){console.error("[ElicitationTab] Failed to copy request:",F)}},[c]),ee=v.useCallback(()=>{if(c)try{const F=new globalThis.Blob([JSON.stringify({id:c.id,serverName:c.serverName,timestamp:c.timestamp,request:c.request},null,2)],{type:"application/json"}),K=URL.createObjectURL(F),V=document.createElement("a");V.href=K,V.download=`elicitation-request-${Date.now()}.json`,document.body.appendChild(V),V.click(),document.body.removeChild(V),URL.revokeObjectURL(K)}catch(F){console.error("[ElicitationTab] Failed to download request:",F)}},[c]),re=v.useCallback(async()=>{if(I.current)try{document.fullscreenElement?await document.exitFullscreen():await I.current.requestFullscreen()}catch(F){console.error("[ElicitationTab] Failed to toggle fullscreen:",F)}},[]);return a?d.jsxs(aa,{direction:"horizontal",className:"h-full",children:[d.jsx(Rn,{defaultSize:40,minSize:30,children:d.jsx(aa,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:d.jsxs(Rn,{defaultSize:75,minSize:30,children:[d.jsx(r0e,{isSearchExpanded:E,searchQuery:f,filteredRequestsCount:U.length,requestsCount:e.length,onSearchExpand:()=>w(!0),onSearchChange:m,onSearchBlur:j,onCancelAll:W,searchInputRef:A}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(a0e,{requests:U,selectedRequest:c,onRequestSelect:B,focusedIndex:h,formatRelativeTime:uy,listRef:C})})]})})}),d.jsx(wo,{}),d.jsx(Rn,{defaultSize:60,minSize:40,children:d.jsx("div",{ref:I,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(o0e,{request:c,onApprove:t,onReject:n,onClose:()=>u(null),previewMode:_,onTogglePreview:()=>S(!_),isCopied:T,onCopy:J,onDownload:ee,onFullscreen:re})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(nB,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function i0e({selectedServer:e,activeTab:t,toolsSearchRef:n,promptsSearchRef:r,resourcesSearchRef:a,children:s}){return e?d.jsxs(d.Fragment,{children:[d.jsx("div",{style:{display:t==="tools"?"block":"none"},className:"h-full",children:d.jsx(c8,{ref:n,tools:e.tools,callTool:e.callTool,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="prompts"?"block":"none"},className:"h-full",children:d.jsx(o8,{ref:r,prompts:e.prompts,callPrompt:e.getPrompt,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="resources"?"block":"none"},className:"h-full",children:d.jsx(i8,{ref:a,resources:e.resources,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="chat"?"block":"none"},className:"h-full",children:d.jsx(cve,{connection:e,isConnected:e.state==="ready",readResource:e.readResource},e.id)}),d.jsx("div",{style:{display:t==="sampling"?"block":"none"},className:"h-full",children:d.jsx(n0e,{pendingRequests:e.pendingSamplingRequests,onApprove:e.approveSampling,onReject:e.rejectSampling,serverId:e.id,isConnected:e.state==="ready",mcpServerUrl:e.url})}),d.jsx("div",{style:{display:t==="elicitation"?"block":"none"},className:"h-full",children:d.jsx(s0e,{pendingRequests:e.pendingElicitationRequests,onApprove:e.approveElicitation,onReject:e.rejectElicitation,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="notifications"?"block":"none"},className:"h-full",children:d.jsx(Fve,{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"&&d.jsx(d.Fragment,{children:s})]}):d.jsx(d.Fragment,{children:s})}function hz({className:e}){return d.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentcolor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",className:e,children:[d.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"}),d.jsx("path",{d:"M9 18c-4.51 2-5-2-7-2"})]})}const u8=v.createContext(void 0);function d8(){const e=v.use(u8);if(!e)throw new Error("useTabs must be used within a TabsProvider");return e}const f8=v.createContext(void 0);function l0e(){return v.use(f8)}function QS({ref:e,children:t,defaultValue:n,value:r,onValueChange:a,className:s,...i}){const[c,u]=v.useState(n||""),f=r!==void 0,m=v.useCallback(g=>{f||u(g),a?.(g)},[f,a]),h=f?r:c;return d.jsx(u8,{value:{activeValue:h,handleValueChange:m},children:d.jsx("div",{ref:e,className:Oe("flex flex-col gap-2",s),...i,children:t})})}QS.displayName="Tabs";function e_({ref:e,children:t,className:n,variant:r="default",...a}){const{activeValue:s}=d8(),[i,c]=v.useState({width:0,left:0}),u=v.useRef(null),f=v.useRef(null),m=v.useRef(null),g=v.Children.toArray(t).findIndex(E=>v.isValidElement(E)&&E.props.value===s),y=v.useCallback(()=>{const E=u.current;if(!E)return;const _=E.querySelectorAll("button")[g];if(_){const S=E.getBoundingClientRect(),T=_.getBoundingClientRect();c({width:T.width,left:T.left-S.left})}},[g]),x=v.useCallback(()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(y,16)},[y]);return v.useEffect(()=>{const E=setTimeout(y,10);return()=>clearTimeout(E)},[y]),v.useEffect(()=>{const E=u.current;return E?(f.current=new ResizeObserver(()=>{x()}),f.current.observe(E),E.querySelectorAll("button").forEach(_=>{f.current&&f.current.observe(_)}),()=>{f.current&&f.current.disconnect(),m.current&&clearTimeout(m.current)}):void 0},[x]),v.useEffect(()=>{const E=()=>{x()};return window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[x]),v.useEffect(()=>{const E=u.current;if(!E)return;const w=E.querySelector("[data-width]");w&&(w.style.width=`${i.width}px`,w.style.left=`${i.left}px`)},[i]),d.jsx(f8,{value:{variant:r},children:d.jsxs("div",{ref:u,className:Oe("relative flex bg-none",r==="default"&&"p-1 rounded-full border border-zinc-300 dark:border-zinc-600",r==="underline"&&"border-b border-zinc-200 dark:border-zinc-700",n),...a,children:[t,d.jsx("span",{className:Oe("absolute transition-all duration-200 ease-out z-0",r==="default"&&"bg-white dark:bg-zinc-700 rounded-full h-[calc(100%-8px)] top-1 border border-zinc-300 dark:border-zinc-600",r==="underline"&&"bottom-0 h-0.5 bg-black dark:bg-white"),"data-width":i.width,"data-left":i.left})]})})}e_.displayName="TabsList";function t_({ref:e,children:t,value:n,className:r,disabled:a,icon:s,...i}){const{activeValue:c,handleValueChange:u}=d8(),m=l0e()?.variant||"default",h=c===n;return d.jsxs("button",{ref:e,disabled:a,onClick:()=>u(n),className:Oe("relative z-10 flex-1 inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-colors 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",m==="default"&&"rounded-md px-4 py-2.5",m==="underline"&&"px-6 py-3 border-b-2 border-transparent",h&&"text-foreground",!h&&"text-muted-foreground hover:text-foreground",r),...i,children:[s&&d.jsx(s,{className:"mr-2 h-4 w-4"}),t]})}t_.displayName="TabsTrigger";function gz({className:e}){const{theme:t,setTheme:n}=yv(),r=v.useRef(null),[a,s]=v.useState(!1);v.useEffect(()=>{s(!0)},[]);const i=()=>t==="system"?"light":t==="light"?"dark":"system",c=()=>t==="system"?d.jsx(xP,{className:"size-4"}):t==="light"?d.jsx(sle,{className:"size-5"}):d.jsx($ie,{className:"size-4"}),u=()=>t==="system"?"Switch to light mode":t==="light"?"Switch to dark mode":"Switch to system mode",f=async()=>{if(!r.current)return;const m=i();if(typeof document<"u"&&"startViewTransition"in document){await document.startViewTransition(()=>{fd.flushSync(()=>{n(m)})}).ready;const{top:h,left:g,width:y,height:x}=r.current.getBoundingClientRect(),E=h+x/2,w=g+y/2,_=window.innerWidth-g,S=window.innerHeight-h,T=Math.hypot(Math.max(g,_),Math.max(h,S));document.documentElement.animate({clipPath:[`circle(0px at ${w}px ${E}px)`,`circle(${T}px at ${w}px ${E}px)`]},{duration:700,easing:"ease-in-out",pseudoElement:"::view-transition-new(root)"})}else n(m)};return a?d.jsx("button",{ref:r,onClick:f,className:Oe(e),"aria-label":u(),title:`Current: ${t==="system"?"Auto":t==="light"?"Light":"Dark"}`,children:c()}):d.jsx("button",{ref:r,className:Oe(e),"aria-label":"Toggle theme",children:d.jsx(xP,{className:"size-4"})})}function bz({className:e,state:t="collapsed",href:n="https://mcp-use.com"}){const[r,a]=v.useState(!1),s=.2,i=.7,c=.6,u=4,f=s+i+c,m=0,h=s/f,g=(s+i)/f,y=1;return d.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:Oe("flex items-center transition-opacity -my-3",t==="expanded"?"space-x-2":"",e),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[d.jsx("div",{className:"relative",children:d.jsxs(wa.svg,{viewBox:"0 0 303 303",initial:"rest",animate:r?"hover":"rest",className:Oe("text-foreground",t==="expanded"?"size-[40px]":"size-[20px]"),children:[d.jsxs(wa.g,{variants:{rest:{opacity:1},hover:{opacity:[1,0,0,1],transition:{duration:f,times:[m,h,g,y],ease:"easeInOut"}}},fill:"currentColor",fillRule:"nonzero",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[d.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"}),d.jsx("circle",{cx:"70.3",cy:"232.3",r:"50"}),d.jsx("circle",{cx:"232.3",cy:"70.3",r:"50"})]}),d.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx(c0e,{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:y},total:f}),d.jsx(yz,{cx:70.3,cy:232.3,r:50,times:{T0:m,T1:h,T2:g,T3:y},total:f}),d.jsx(yz,{cx:232.3,cy:70.3,r:50,times:{T0:m,T1:h,T2:g,T3:y},total:f})]})]})}),t==="expanded"&&d.jsxs("div",{className:"font-ubuntu flex flex-col items-start -space-y-1 mr-3",children:[d.jsx("h1",{className:"text-xl font-medium",children:"mcp-use"}),d.jsx("span",{className:"text-lg text-muted-foreground tracking-wide font-sans font-light",children:"Inspector"})]})]})}function c0e({d:e,times:t,total:n}){const{T0:r,T1:a,T2:s,T3:i}=t;return d.jsx(wa.path,{d:e,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:n,times:[r,a,s,i],ease:"easeInOut"}}}})}function yz({cx:e,cy:t,r:n,times:r,total:a}){const{T0:s,T1:i,T2:c,T3:u}=r;return d.jsx(wa.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:a,times:[s,i,c,u],ease:"easeInOut"}}}})}function p8({ref:e,shimmerColor:t,shimmerSize:n="0.05em",shimmerDuration:r="3s",borderRadius:a="100px",background:s,className:i,children:c,...u}){const{resolvedTheme:f}=yv(),m=f==="dark"?"#000000":"#ffffff",h=f==="dark"?"rgba(255, 255, 255, 1)":"rgba(0, 0, 0, 1)",g=t||m,y=s||h;return d.jsxs("button",{style:{"--spread":"90deg","--shimmer-color":g,"--radius":a,"--speed":r,"--cut":n,"--bg":y},className:Oe("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",f==="dark"?"border-black/10 text-black":"border-white/10 text-white",i),ref:e,...u,children:[d.jsx("div",{className:Oe("-z-30 blur-[2px]","[container-type:size] absolute inset-0 overflow-visible"),children:d.jsx("div",{className:"animate-shimmer-slide absolute inset-0 [aspect-ratio:1] h-[100cqh] [border-radius:0] [mask:none]",children:d.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,d.jsx("div",{className:Oe("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",f==="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]")}),d.jsx("div",{className:Oe("absolute [inset:var(--cut)] -z-20 [border-radius:var(--radius)] [background:var(--bg)]")})]})}p8.displayName="ShimmerButton";function vz({status:e}){const t=s=>{switch(s){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:s}}},{color:n,ringColor:r,tooltip:a}=t(e);return d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:`absolute w-2 h-2 rounded-full ${r} animate-ping`}),d.jsx("div",{className:`relative w-2 h-2 rounded-full ${n}`})]})}),d.jsx(Mt,{children:d.jsx("p",{children:a})})]})}function wz({connections:e,selectedServer:t,onServerSelect:n,onOpenConnectionOptions:r,mobileMode:a=!1}){const s=dd(),i=c=>{const u=e.find(f=>f.id===c);if(!u||u.state!=="ready"){Xt.error("Server is not connected and cannot be inspected");return}n(c)};return a?d.jsx("div",{className:"flex items-center gap-2",children:d.jsx("div",{className:"relative",children:d.jsxs(Fx,{children:[d.jsx(Bx,{asChild:!0,children:d.jsxs(Le,{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?d.jsx(Sl,{serverUrl:t.url,serverName:t.name,size:"md"}):d.jsx(qie,{className:"h-5 w-5"}),d.jsx(Gl,{className:"h-4 w-4"})]})}),d.jsxs(Lb,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[d.jsx(Hx,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>s("/"),children:"MCP Servers"}),d.jsx(Mf,{}),e.length===0?d.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=>d.jsxs(Ts,{onClick:()=>i(c.id),className:"flex items-center gap-3",children:[d.jsx(Sl,{serverUrl:c.url,serverName:c.name,size:"sm"}),d.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[d.jsx("div",{className:"font-medium",children:c.name}),d.jsx(vz,{status:c.state})]}),d.jsx(Le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:u=>{u.stopPropagation(),r(c.id)},children:d.jsx(mu,{className:"h-3 w-3"})})]},c.id)),d.jsx(Mf,{}),d.jsx(Ts,{onClick:()=>s("/"),children:d.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})})}):d.jsx("div",{className:"flex items-center gap-2",children:d.jsx("div",{className:"relative",children:d.jsxs(Fx,{children:[d.jsx(Bx,{asChild:!0,children:d.jsxs(p8,{className:Oe("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&&d.jsx(Sl,{serverUrl:t.url,serverName:t.name,size:"md",className:"mr-2"}),d.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[d.jsx("span",{className:"truncate",children:t?t.name:"Select server to inspect"}),t&&d.jsx("div",{className:"flex items-center gap-2",children:t.error&&t.state!=="ready"?d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.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"})}),d.jsx(Mt,{children:d.jsx("p",{className:"max-w-xs",children:t.error})})]}):d.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&&d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx("button",{type:"button",onClick:()=>{r(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:d.jsx(mu,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:d.jsx("p",{children:"Edit connection settings"})})]}),d.jsxs(Lb,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[d.jsx(Hx,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>s("/"),children:"MCP Servers"}),d.jsx(Mf,{}),e.length===0?d.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=>d.jsxs(Ts,{onClick:()=>i(c.id),className:"flex items-center gap-3",children:[d.jsx(Sl,{serverUrl:c.url,serverName:c.name,size:"sm"}),d.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[d.jsx("div",{className:"font-medium",children:c.name}),d.jsx(vz,{status:c.state})]}),d.jsx(Le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:u=>{u.stopPropagation(),r(c.id)},children:d.jsx(mu,{className:"h-3 w-3"})})]},c.id)),d.jsx(Mf,{}),d.jsx(Ts,{onClick:()=>s("/"),children:d.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})})})}const Ez=[{id:"tools",label:"Tools",icon:Ol},{id:"prompts",label:"Prompts",icon:yp},{id:"resources",label:"Resources",icon:Eie},{id:"sampling",label:"Sampling",icon:J3},{id:"elicitation",label:"Elicitation",icon:nB},{id:"notifications",label:"Notifications",icon:uT},{id:"chat",label:"Chat",icon:Die}];function xz(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 u0e({connections:e,selectedServer:t,activeTab:n,onServerSelect:r,onTabChange:a,onCommandPaletteOpen:s,onOpenConnectionOptions:i}){const{tunnelUrl:c}=Wl(),u=t&&c,[f,m]=v.useState(!1),h=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 d.jsxs("header",{className:"w-full mx-auto",children:[d.jsxs("div",{className:"flex lg:hidden flex-col gap-3",children:[d.jsxs("div",{className:"flex items-center justify-between w-full",children:[d.jsx("div",{className:"flex-1 flex justify-start",children:d.jsx(wz,{connections:e,selectedServer:t,onServerSelect:r,onOpenConnectionOptions:i,mobileMode:!0})}),d.jsx("div",{className:"flex-shrink-0 flex justify-center",children:d.jsx("div",{className:"scale-150",children:d.jsx(bz,{state:"collapsed"})})}),d.jsxs("div",{className:"flex-1 flex justify-end items-center gap-2",children:[d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",asChild:!0,children:d.jsx("a",{href:"https://github.com/mcp-use/mcp-use",target:"_blank",rel:"noopener noreferrer",className:"p-2","aria-label":"GitHub",children:d.jsx(hz,{className:"h-4 w-4"})})})}),d.jsx(Mt,{children:d.jsx("p",{children:"Give us a star ⭐"})})]}),d.jsx(gz,{className:"p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors cursor-pointer"})]})]}),t&&d.jsx("div",{className:"w-full",children:d.jsx(QS,{value:n,onValueChange:g=>a(g),children:d.jsx(e_,{className:"w-full justify-center",children:Ez.map(g=>{const y=xz(g.id,t);return d.jsxs(t_,{value:g.id,icon:g.icon,className:"[&>svg]:mr-0 flex-1 flex-row gap-2 relative",children:[y>0&&d.jsx("span",{className:Oe(n===g.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:y}),d.jsx("span",{className:"sr-only",children:g.label})]},g.id)})})})})]}),d.jsxs("div",{className:"hidden lg:flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"flex items-center flex-wrap gap-2 md:space-x-6 space-x-2",children:[d.jsx(wz,{connections:e,selectedServer:t,onServerSelect:r,onOpenConnectionOptions:i}),t&&d.jsx(QS,{value:n,onValueChange:g=>a(g),children:d.jsx(e_,{className:"overflow-x-auto",children:Ez.map(g=>{const y=xz(g.id,t);return d.jsx(t_,{value:g.id,icon:g.icon,className:"[&>svg]:mr-0 lg:[&>svg]:mr-2 relative",children:d.jsxs("div",{className:"items-center gap-2 hidden lg:flex",children:[g.label,y>0&&d.jsx("span",{className:Oe(n===g.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:y})]})},g.id)})})}),u&&d.jsxs(sV,{children:[d.jsx(iV,{asChild:!0,children:d.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:[d.jsx(vp,{className:"size-4 text-purple-600 dark:text-purple-400 animate-pulse"}),d.jsx("span",{className:"text-xs font-medium text-purple-700 dark:text-purple-300 hidden lg:inline",children:"Tunnel"})]})}),d.jsx(lN,{className:"w-[calc(100vw-2rem)] sm:w-96",align:"start",children:d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{children:[d.jsxs("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:[d.jsx(vp,{className:"size-4 text-purple-600 dark:text-purple-400"}),"Tunnel URL"]}),d.jsxs("div",{className:"flex items-center gap-2 p-2 py-0 bg-muted rounded-full",children:[d.jsxs("code",{className:"flex-1 text-[10px] font-mono",children:[c,"/mcp"]}),d.jsx(Le,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:h,children:f?d.jsx(oa,{className:"size-3.5 text-green-600"}):d.jsx(zr,{className:"size-3.5"})})]})]}),d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Use in ChatGPT"}),d.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"1."}),d.jsxs("span",{children:["Enable"," ",d.jsx("span",{className:"font-medium text-foreground",children:"dev mode"})," ","from settings"]})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"2."}),d.jsxs("span",{children:["In"," ",d.jsx("span",{className:"font-medium text-foreground",children:"App & Connectors"})," ","click on"," ",d.jsx("span",{className:"font-medium text-foreground",children:"create"})]})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"3."}),d.jsx("span",{children:"Use the tunnel URL in the input"})]})]})]})]})})]})]}),d.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-shrink-0",children:[d.jsxs(Dt,{children:[d.jsx(Lt,{children:d.jsx(gz,{className:"p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors cursor-pointer"})}),d.jsx(Mt,{children:d.jsx("p",{children:"Toggle theme"})})]}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsxs(Le,{variant:"ghost",className:"hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full px-1 -mx-3 flex gap-1",onClick:s,children:[d.jsx(aie,{className:"size-4"}),d.jsx("span",{className:"text-base font-mono hidden sm:inline",children:"K"})]})}),d.jsx(Mt,{children:d.jsx("p",{children:"Command Palette"})})]}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",asChild:!0,children:d.jsxs("a",{href:"https://github.com/mcp-use/mcp-use",className:"flex items-center gap-2",target:"_blank",rel:"noopener noreferrer",children:[d.jsx(hz,{className:"h-4 w-4"}),d.jsx("span",{className:"hidden sm:inline",children:"Github"})]})})}),d.jsx(Mt,{children:d.jsx("p",{children:"Give us a star ⭐"})})]}),d.jsx(bz,{state:"expanded"})]})]})]})}function d0e({children:e}){const t=dd(),n=$s(),{connections:r,addConnection:a,removeConnection:s,updateConnectionConfig:i,configLoaded:c}=cT(),{selectedServerId:u,setSelectedServerId:f,activeTab:m,setActiveTab:h,navigateToItem:g,setTunnelUrl:y}=Wl(),[x,E]=v.useState(!1),[w,_]=v.useState(null),S=Nme();v.useEffect(()=>{const K=new URLSearchParams(n.search).get("tunnelUrl");y(K)},[n.search,y]),v.useEffect(()=>{const F=ne=>{const D=ne.detail.requestId;u&&g(u,"sampling",D)},K=ne=>{const D=ne.detail.requestId;u&&g(u,"elicitation",D)},V=ne=>{const D=ne.detail.toolName;u&&D?g(u,"tools",D):u&&h("tools")};return window.addEventListener("navigate-to-sampling",F),window.addEventListener("navigate-to-elicitation",K),window.addEventListener("navigate-to-tool-result",V),()=>{window.removeEventListener("navigate-to-sampling",F),window.removeEventListener("navigate-to-elicitation",K),window.removeEventListener("navigate-to-tool-result",V)}},[u,h,g]);const T=v.useRef(null),R=v.useRef(null),C=v.useRef(null),{isAutoConnecting:I}=Tme({connections:r,addConnection:a,removeConnection:s,configLoaded:c}),A=v.useCallback(F=>{Tr.getInstance().capture(new wse({trigger:F})).catch(()=>{}),E(!0)},[]),O=F=>{const K=r.find(D=>D.id===F);if(!K||K.state!=="ready"){Xt.error("Server is not connected and cannot be inspected");return}f(F);const ne=new URLSearchParams(n.search).get("tunnelUrl"),te=ne?`/?server=${encodeURIComponent(F)}&tunnelUrl=${encodeURIComponent(ne)}`:`/?server=${encodeURIComponent(F)}`;t(te)},j=v.useCallback(F=>{_(F)},[]),U=v.useCallback(F=>{w&&(F.url!==w?(s(w),a(F.url,F.name,F.proxyConfig,F.transportType)):i(w,{name:F.name,proxyConfig:F.proxyConfig,transportType:F.transportType}),_(null),Xt.success("Connection settings updated"))},[w,s,a,i]),B=(F,K,V)=>{if(console.warn("[Layout] handleCommandPaletteNavigate called:",{tab:F,itemName:K,serverId:V}),V){const ne=r.find($=>$.id===V);if(console.warn("[Layout] Server lookup:",{serverId:V,serverFound:!!ne,serverState:ne?.state}),!ne||ne.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:V,tab:F,itemName:K}),g(V,F,K);const D=new URLSearchParams(n.search).get("tunnelUrl"),H=D?`/?server=${encodeURIComponent(V)}&tunnelUrl=${encodeURIComponent(D)}`:`/?server=${encodeURIComponent(V)}`;console.warn("[Layout] Navigating to:",H),t(H)}else console.warn("[Layout] No serverId, just updating tab to:",F),h(F)},W=r.find(F=>F.id===u),J=W?W.tools.map(F=>({...F,_serverId:W.id})):r.flatMap(F=>F.state==="ready"?F.tools.map(K=>({...K,_serverId:F.id,_serverName:F.name})):[]),ee=W?W.prompts.map(F=>({...F,_serverId:W.id})):r.flatMap(F=>F.state==="ready"?F.prompts.map(K=>({...K,_serverId:F.id,_serverName:F.name})):[]),re=W?W.resources.map(F=>({...F,_serverId:W.id})):r.flatMap(F=>F.state==="ready"?F.resources.map(K=>({...K,_serverId:F.id,_serverName:F.name})):[]);return v.useEffect(()=>{const K=new URLSearchParams(n.search).get("server"),V=K?decodeURIComponent(K):null;V!==u&&f(V)},[n.search,u,f]),v.useEffect(()=>{const K=new URLSearchParams(n.search).get("server");if(!K)return;const V=decodeURIComponent(K),ne=r.find(te=>te.id===V);if(!ne){const te=setTimeout(()=>t("/"),3e3);return()=>clearTimeout(te)}if(ne.state==="failed"){const te=setTimeout(()=>t("/"),2e3);return()=>clearTimeout(te)}},[n.search,t,r]),LH({onCommandPalette:()=>A("keyboard"),onToolsTab:()=>{W&&h("tools")},onPromptsTab:()=>{W&&h("prompts")},onResourcesTab:()=>{W&&h("resources")},onChatTab:()=>{W&&h("chat")},onHome:()=>{t("/")},onFocusSearch:()=>{m==="tools"&&T.current?T.current.focusSearch():m==="prompts"&&R.current?R.current.focusSearch():m==="resources"&&C.current&&C.current.focusSearch()},onBlurSearch:()=>{m==="tools"&&T.current?T.current.blurSearch():m==="prompts"&&R.current?R.current.blurSearch():m==="resources"&&C.current&&C.current.blurSearch()}}),I?d.jsx("div",{className:"h-screen bg-white dark:bg-zinc-900 flex items-center justify-center",children:d.jsxs("div",{className:"flex flex-col items-center gap-4",children:[d.jsx(_o,{className:"h-8 w-8 text-zinc-600 dark:text-zinc-400"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Connecting to MCP server..."})]})}):d.jsx(K3,{children:d.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:[d.jsx(u0e,{connections:r,selectedServer:W,activeTab:m,onServerSelect:O,onTabChange:h,onCommandPaletteOpen:()=>A("button"),onOpenConnectionOptions:j}),d.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:d.jsx(i0e,{selectedServer:W,activeTab:m,toolsSearchRef:T,promptsSearchRef:R,resourcesSearchRef:C,children:e})}),d.jsx(Qme,{isOpen:x,onOpenChange:E,tools:J,prompts:ee,resources:re,savedRequests:S,connections:r,onNavigate:B,onServerSelect:O}),d.jsx(XB,{connection:w&&r.find(F=>F.id===w)||null,open:w!==null,onOpenChange:F=>{F||_(null)},onConnect:U})]})})}function f0e(){const[e,t]=v.useState("processing"),[n,r]=v.useState("");return v.useEffect(()=>{console.log("[OAuthCallback] Component mounted, handling authorization..."),console.log("[OAuthCallback] Current URL:",window.location.href),D_().then(()=>{console.log("[OAuthCallback] Authorization successful"),t("success")}).catch(a=>{console.error("[OAuthCallback] Authorization failed:",a),t("error"),r(a instanceof Error?a.message:String(a))})},[]),e==="processing"?d.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:d.jsxs("div",{className:"flex flex-col items-center gap-4",children:[d.jsx(Li,{className:"h-8 w-8 animate-spin text-zinc-600 dark:text-zinc-400"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Completing authentication..."})]})}):e==="error"?d.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:d.jsxs("div",{className:"max-w-md p-6",children:[d.jsx("h1",{className:"text-xl font-semibold text-red-600 dark:text-red-400 mb-2",children:"Authentication Error"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400 mb-4",children:n}),d.jsx("p",{className:"text-xs text-zinc-500 dark:text-zinc-500",children:"You can close this window and try again."})]})}):d.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:d.jsxs("div",{className:"max-w-md p-6",children:[d.jsx("h1",{className:"text-xl font-semibold text-green-600 dark:text-green-400 mb-2",children:"Authentication Successful!"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Redirecting you back..."})]})})}var p0e=(e,t,n,r,a,s,i,c)=>{let u=document.documentElement,f=["light","dark"];function m(y){(Array.isArray(e)?e:[e]).forEach(x=>{let E=x==="class",w=E&&s?a.map(_=>s[_]||_):a;E?(u.classList.remove(...w),u.classList.add(s&&s[y]?s[y]:y)):u.setAttribute(x,y)}),h(y)}function h(y){c&&f.includes(y)&&(u.style.colorScheme=y)}function g(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let y=localStorage.getItem(t)||n,x=i&&y==="system"?g():y;m(x)}catch{}},m0e=v.createContext(void 0),h0e={setTheme:e=>{},themes:[]},g0e=()=>{var e;return(e=v.useContext(m0e))!=null?e:h0e};v.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:a,defaultTheme:s,value:i,themes:c,nonce:u,scriptProps:f})=>{let m=JSON.stringify([n,t,s,e,c,i,r,a]).slice(1,-1);return v.createElement("script",{...f,suppressHydrationWarning:!0,nonce:typeof window>"u"?u:"",dangerouslySetInnerHTML:{__html:`(${p0e.toString()})(${m})`}})});function b0e({...e}){const{theme:t="system"}=g0e();return d.jsx(rB,{theme:t,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...e})}function y0e(){return d.jsx(Bbe,{children:d.jsx(kse,{children:d.jsxs(_me,{children:[d.jsx(Tee,{basename:"/inspector",children:d.jsxs(nee,{children:[d.jsx(Ix,{path:"/oauth/callback",element:d.jsx(f0e,{})}),d.jsx(Ix,{path:"/",element:d.jsx(d0e,{children:d.jsx(Sme,{})})})]})}),d.jsx(b0e,{position:"top-center"})]})})})}const Sz=new URLSearchParams(window.location.search);if(Sz.has("code")||Sz.has("error"))try{D_()}catch(e){console.error("[inspector] OAuth callback error:",e)}const _z=document.getElementById("root");_z?dQ.createRoot(_z).render(d.jsx(y0e,{})):console.error("[inspector] Root element not found");export{tK as $,Ue as A,de as B,uZ as C,Bn as D,Dn as E,vn as F,Be as G,s2 as H,B2 as I,Wg as J,Uo as K,Ej as L,Cz as M,YJ as N,HJ as O,D_ as P,VG as Q,ce as R,jz as T,AG as V,WJ as W,Fn as Z,Pe as _,rr as a,id as b,fd as c,S0e as d,w0e as e,Rh as f,jp as g,WG as h,_0e as i,$i as j,MK as k,jW as l,WW as m,n7 as n,o7 as o,x0e as p,LK as q,v as r,MW as s,E0e as t,XG as u,Ai as v,zY as w,fb as x,BG as y,ve as z};
1674
+ `),Ve.document.close())}},[x]),ht=v.useCallback(()=>{G?(le.current&&le.current.expand(),Ne.current&&Ne.current.expand(),q(!1)):(le.current&&le.current.collapse(),Ne.current&&Ne.current.collapse(),q(!0))},[G]),nt=v.useCallback(()=>{i&&(re(""),J(!0))},[i]),kt=v.useCallback(()=>{if(!i)return;const Ae={id:`${Date.now()}-${Math.random()}`,name:ee.trim()||`${i.name} - ${new Date().toLocaleString()}`,toolName:i.name,args:g,savedAt:Date.now(),serverId:i._serverId,serverName:i._serverName};$e([...U,Ae]),Tr.getInstance().capture(new Ese({toolName:i.name,serverId:a})).catch(()=>{}),J(!1),re("")},[i,ee,g,U,$e,a]),ot=v.useCallback(Ae=>{$e(U.filter(Me=>Me.id!==Ae)),u?.id===Ae&&f(null)},[U,$e,u]);return $?d.jsxs("div",{className:"h-full flex flex-col overflow-hidden relative bg-background",children:[M!=="list"&&d.jsxs("div",{className:"flex items-center gap-2 p-2 border-b shrink-0 bg-background z-10",children:[d.jsx(Le,{variant:"ghost",size:"sm",onClick:()=>{M==="response"?z("detail"):(c(null),z("list"))},className:"p-0 h-8 w-8",children:d.jsx(dT,{className:"h-4 w-4"})}),d.jsxs("div",{className:"flex items-center text-sm font-medium",children:[d.jsx("button",{onClick:()=>{c(null),z("list")},className:"text-muted-foreground hover:text-foreground hover:underline cursor-pointer",children:"Tools"}),M==="detail"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("button",{onClick:()=>{z("response")},className:M==="detail"?"text-foreground hover:underline":M==="response"?"text-muted-foreground hover:text-foreground hover:underline cursor-pointer":"text-muted-foreground",children:"Execute"})]}),M==="response"&&d.jsxs(d.Fragment,{children:[d.jsx("span",{className:"mx-2 text-muted-foreground",children:"/"}),d.jsx("span",{className:"text-foreground",children:"Response"})]})]})]}),d.jsx("div",{className:"flex-1 relative overflow-hidden",children:d.jsxs(Jy,{initial:!1,mode:"popLayout",children:[M==="list"&&d.jsxs(wa.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:[d.jsx(pz,{activeTab:O,isSearchExpanded:V,searchQuery:I,filteredToolsCount:fe.length,savedRequestsCount:U.length,onSearchExpand:()=>ne(!0),onSearchChange:A,onSearchBlur:Ee,onTabSwitch:()=>j(O==="tools"?"saved":"tools"),searchInputRef:H}),O==="tools"?d.jsx(fz,{tools:fe,selectedTool:i,onToolSelect:Ie,focusedIndex:te}):d.jsx(sz,{savedRequests:U,selectedRequest:u,onLoadRequest:Fe,onDeleteRequest:ot,focusedIndex:te})]},"list"),M==="detail"&&d.jsx(wa.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:d.jsx(cz,{selectedTool:i,toolArgs:g,isExecuting:w,isConnected:s,onArgChange:at,onExecute:lt,onSave:nt})},"detail"),M==="response"&&d.jsx(wa.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:d.jsx(dz,{results:De,copiedResult:S,previewMode:F,serverId:a,readResource:r,onCopy:bt,onDelete:Rt,onFullscreen:ze,onTogglePreview:()=>K(!F)})},"response")]})}),d.jsx(iz,{isOpen:W,requestName:ee,defaultPlaceholder:`${i?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:re,onSave:kt,onCancel:()=>J(!1)})]}):d.jsxs(aa,{direction:"horizontal",className:"h-full",children:[d.jsx(Rn,{ref:le,defaultSize:33,collapsible:!0,className:"flex flex-col h-full relative",children:d.jsxs(aa,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:[d.jsx(Rn,{defaultSize:75,minSize:30,children:d.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[d.jsx(pz,{activeTab:O,isSearchExpanded:V,searchQuery:I,filteredToolsCount:fe.length,savedRequestsCount:U.length,onSearchExpand:()=>ne(!0),onSearchChange:A,onSearchBlur:Ee,onTabSwitch:()=>j(O==="tools"?"saved":"tools"),searchInputRef:H}),O==="tools"?d.jsx(fz,{tools:fe,selectedTool:i,onToolSelect:Ie,focusedIndex:te}):d.jsx(sz,{savedRequests:U,selectedRequest:u,onLoadRequest:Fe,onDeleteRequest:ot,focusedIndex:te})]})}),d.jsx(wo,{withHandle:!0}),d.jsxs(Rn,{ref:xe,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:[d.jsxs("div",{className:"group flex items-center justify-between p-3 shrink-0 cursor-pointer hover:bg-muted/50 transition-colors",onClick:Ae=>{Ae.preventDefault(),Ae.stopPropagation(),X?(xe.current?.resize(25),Z(!1)):(xe.current?.resize(5),Z(!0))},children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"text-sm font-medium",children:"RPC Messages"}),ae>0&&d.jsx(kr,{variant:"secondary",className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",children:ae}),ae>0&&!X&&d.jsx(Le,{variant:"ghost",size:"sm",onClick:Ae=>{Ae.preventDefault(),Ae.stopPropagation(),Te.current?.()},className:"h-6 w-6 p-0",title:"Clear all messages",children:d.jsx(Mi,{className:"h-3.5 w-3.5"})})]}),d.jsx(Gl,{className:`h-4 w-4 text-muted-foreground transition-transform ${X?"":"rotate-180"}`})]}),!X&&d.jsx("div",{className:"flex-1 overflow-hidden min-h-0",children:d.jsx(z1,{serverIds:[a],onCountChange:ie,onClearRef:Te})})]})]})}),d.jsx(wo,{withHandle:!0}),d.jsx(Rn,{defaultSize:67,children:d.jsxs(aa,{direction:"vertical",children:[d.jsx(Rn,{ref:Ne,defaultSize:40,collapsible:!0,children:d.jsx(cz,{selectedTool:i,toolArgs:g,isExecuting:w,isConnected:s,onArgChange:at,onExecute:lt,onSave:nt,onCancel:()=>{R&&R.abort()}})}),d.jsx(wo,{withHandle:!0}),d.jsx(Rn,{ref:He,defaultSize:60,children:d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(dz,{results:De,copiedResult:S,previewMode:F,serverId:a,readResource:r,onCopy:bt,onDelete:Rt,onFullscreen:ze,onTogglePreview:()=>K(!F),onMaximize:ht,isMaximized:G})})})]})}),d.jsx(iz,{isOpen:W,requestName:ee,defaultPlaceholder:`${i?.name} - ${new Date().toLocaleString()}`,onRequestNameChange:re,onSave:kt,onCancel:()=>J(!1)})]})}c8.displayName="ToolsTab";function Jve({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:r,onSearchExpand:a,onSearchChange:s,onSearchBlur:i,onRejectAll:c,searchInputRef:u}){return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Tn,{ref:u,placeholder:"Search requests...",value:t,onChange:f=>s(f.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Sampling"}),d.jsx(kr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:d.jsx(wd,{className:"h-4 w-4"})})}),d.jsxs(Mt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(gm,{children:"F"})]})]})]})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,disabled:r===0,className:"h-8 w-8 p-0",children:d.jsx(Mi,{className:"h-4 w-4"})})}),d.jsx(Mt,{side:"bottom",children:"Reject all"})]})})]})}function Qve({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:r,formatRelativeTime:a,listRef:s}){return e.length===0?d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx(vd,{vertical:!0,noBorder:!0,message:"No sampling requests"})}):d.jsx("div",{ref:s,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((i,c)=>{const u=i.request.params?.messages?.length||0,f=i.request.params?.maxTokens;return d.jsx(Wi,{id:`sampling-request-${i.id}`,isSelected:t?.id===i.id,isFocused:r===c,title:d.jsxs("span",{className:"flex items-center gap-3",children:[i.serverName,d.jsx("span",{className:"size-1.5 block rounded-full bg-orange-500"})]}),description:(()=>{const m=a(i.timestamp),h=[];u>0&&h.push(`${u} message${u>1?"s":""}`),f&&h.push(`max ${f} tokens`);const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(i)},i.id)})})}function e0e({llmConfig:e}){const t=v.useRef(null);return{generateResponse:v.useCallback(async({request:r})=>{if(!e)throw new Error("LLM config is not available");const a=r.params||{},s=a.maxTokens,i=a.temperature;a.modelPreferences;const c=a.messages||[];if(console.log("[useSamplingLLM] Request structure:",{hasParams:!!a,messagesCount:c.length,messages:c,params:a}),c.length===0)throw new Error("No messages found in sampling request");const u=[],{HumanMessage:f,AIMessage:m}=await rr(async()=>{const{HumanMessage:x,AIMessage:E}=await import("./index-DTNvsjCH.js").then(w=>w.bE);return{HumanMessage:x,AIMessage:E}},[]);for(const x of c){if(!x||!x.role){console.warn("Skipping invalid message:",x);continue}const E=Array.isArray(x.content)?x.content[0]:x.content;if(!E){console.warn("Skipping message with no content:",x);continue}E.type==="text"&&E.text?x.role==="user"?u.push(new f(E.text)):x.role==="assistant"&&u.push(new m(E.text)):console.warn("Skipping message with unsupported content type:",E)}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 E={model:e.model,apiKey:e.apiKey};if(s!==void 0&&(E.maxTokens=s),i!==void 0?E.temperature=i:e.temperature!==void 0&&(E.temperature=e.temperature),e.provider==="openai"){const{ChatOpenAI:w}=await rr(async()=>{const{ChatOpenAI:_}=await import("./index-BNQethI5.js");return{ChatOpenAI:_}},__vite__mapDeps([5,6,7,3,8,9]));x=new w(E)}else if(e.provider==="anthropic"){const{ChatAnthropic:w}=await rr(async()=>{const{ChatAnthropic:_}=await import("./index-CZpbYyd9.js");return{ChatAnthropic:_}},__vite__mapDeps([10,7,6,3]));x=new w(E)}else if(e.provider==="google"){const{ChatGoogleGenerativeAI:w}=await rr(async()=>{const{ChatGoogleGenerativeAI:_}=await import("./index-BRUKWgxH.js");return{ChatGoogleGenerativeAI:_}},__vite__mapDeps([11,7,6,3,9]));x=new w(E)}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 t0e({request:e,onApprove:t,onReject:n,onClose:r,previewMode:a,onTogglePreview:s,isCopied:i,onCopy:c,onDownload:u,onFullscreen:f,llmConfig:m}){const[h,g]=v.useState("manual"),[y,x]=v.useState("stub-model"),[E,w]=v.useState("endTurn"),[_,S]=v.useState("assistant"),[T,R]=v.useState("text"),[C,I]=v.useState("positive"),[A,O]=v.useState(""),[j,U]=v.useState("image/png"),[B,W]=v.useState(!1),[J,ee]=v.useState(null),{generateResponse:re,isAvailable:F}=e0e({llmConfig:m});v.useEffect(()=>{e&&(x("stub-model"),w("endTurn"),S("assistant"),R("text"),I("positive"),O(""),U("image/png"),ee(null))},[e?.id]);const K=async()=>{if(!(!e||!F)){W(!0),ee(null);try{const D=await re({request:e.request});x(D.model||m?.model||"stub-model"),w(D.stopReason||"endTurn"),S(D.role||"assistant");const H=Array.isArray(D.content)?D.content[0]:D.content;H.type==="text"?(R("text"),I(H.text||"")):H.type==="image"&&(R("image"),O(H.data||""),U(H.mimeType||"image/png"))}catch(D){const H=D instanceof Error?D.message:"Failed to generate response";ee(H),Xt.error("LLM Generation Failed",{description:H})}finally{W(!1)}}},V=v.useMemo(()=>{const D={model:y,stopReason:E,role:_,content:{type:T}};return T==="text"?D.content.text=C:T==="image"&&(D.content.data=A,D.content.mimeType=j),D},[y,E,_,T,C,A,j]),ne=()=>{if(!e)return;const D=__.safeParse(V);if(!D.success){Xt.error("Invalid response",{description:`Validation failed: ${D.error.message}`});return}t(e.id,D.data),r(),rr(()=>Promise.resolve().then(()=>id),void 0).then(H=>{const $=Xt(H.createElement("div",{className:"space-y-3"},H.createElement("div",null,H.createElement("strong",null,"Sampling Response Sent"),H.createElement("p",{className:"text-sm text-muted-foreground mt-1"},"The tool will continue executing.")),H.createElement("div",{className:"flex gap-2"},H.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 L=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:e.toolName}});window.dispatchEvent(L),Xt.dismiss($)}},"View Tool Result"))),{duration:5e3})})},te=()=>{e&&(n(e.id,"User rejected sampling request"),r())};return e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),d.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,className:"h-8 w-8 p-0",children:i?d.jsx(oa,{className:"h-4 w-4 text-green-600"}):d.jsx(zr,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:"Copy request"})]}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:d.jsx(Qp,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:"Download request"})]}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:f,className:"h-8 w-8 p-0",children:d.jsx(mT,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:"Fullscreen"})]}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:d.jsx(qo,{className:"h-4 w-4"})})]})]}),d.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Request"}),d.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:d.jsx(nr,{data:e.request})})]}),d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Response"}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(Wt,{htmlFor:`responseMode-${e.id}`,className:"text-xs text-gray-500 dark:text-gray-400",children:"Mode:"}),d.jsxs(ks,{value:h,onValueChange:D=>g(D),children:[d.jsx(Rs,{id:`responseMode-${e.id}`,className:"w-32 h-8 text-xs",children:d.jsx(Cs,{})}),d.jsxs(As,{children:[d.jsx(Pr,{value:"manual",children:"Manual"}),d.jsx(Pr,{value:"llm",children:"LLM"})]})]})]})]}),h==="llm"&&d.jsxs("div",{className:"space-y-2 p-3 bg-muted rounded-lg",children:[F?d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx(Le,{onClick:K,disabled:B,size:"sm",className:"flex items-center gap-2",children:B?d.jsxs(d.Fragment,{children:[d.jsx(Li,{className:"h-4 w-4 animate-spin"}),"Generating..."]}):d.jsxs(d.Fragment,{children:[d.jsx(tle,{className:"h-4 w-4"}),"Generate with LLM"]})}),d.jsxs("span",{className:"text-xs text-gray-500 dark:text-gray-400",children:["Using ",m?.provider," (",m?.model,")"]})]}):d.jsx("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:"LLM not configured. Please configure LLM in the Chat tab."}),J&&d.jsx("div",{className:"text-xs text-red-600 dark:text-red-400",children:J})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`model-${e.id}`,children:"Model"}),d.jsx(Tn,{id:`model-${e.id}`,value:y,onChange:D=>x(D.target.value),placeholder:"stub-model",disabled:h==="llm"&&B})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`stopReason-${e.id}`,children:"Stop Reason"}),d.jsx(Tn,{id:`stopReason-${e.id}`,value:E,onChange:D=>w(D.target.value),placeholder:"endTurn",disabled:h==="llm"&&B})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`role-${e.id}`,children:"Role"}),d.jsxs(ks,{value:_,onValueChange:D=>S(D),disabled:h==="llm"&&B,children:[d.jsx(Rs,{id:`role-${e.id}`,children:d.jsx(Cs,{})}),d.jsxs(As,{children:[d.jsx(Pr,{value:"assistant",children:"assistant"}),d.jsx(Pr,{value:"user",children:"user"})]})]})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`contentType-${e.id}`,children:"Content Type"}),d.jsxs(ks,{value:T,onValueChange:D=>R(D),disabled:h==="llm"&&B,children:[d.jsx(Rs,{id:`contentType-${e.id}`,children:d.jsx(Cs,{})}),d.jsxs(As,{children:[d.jsx(Pr,{value:"text",children:"text"}),d.jsx(Pr,{value:"image",children:"image"})]})]})]}),T==="text"&&d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`text-${e.id}`,children:"Text Content"}),d.jsx(Pl,{id:`text-${e.id}`,value:C,onChange:D=>I(D.target.value),placeholder:"Enter response text...",rows:6,disabled:h==="llm"&&B})]}),T==="image"&&d.jsxs(d.Fragment,{children:[d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`imageData-${e.id}`,children:"Base64 Image Data"}),d.jsx(Pl,{id:`imageData-${e.id}`,value:A,onChange:D=>O(D.target.value),placeholder:"Base64 encoded image data...",rows:4,disabled:h==="llm"&&B})]}),d.jsxs("div",{className:"space-y-2",children:[d.jsx(Wt,{htmlFor:`mimeType-${e.id}`,children:"MIME Type"}),d.jsx(Tn,{id:`mimeType-${e.id}`,value:j,onChange:D=>U(D.target.value),placeholder:"image/png",disabled:h==="llm"&&B})]})]})]})]}),d.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[d.jsx(Le,{onClick:ne,className:"flex-1",disabled:h==="llm"&&B,children:"Approve"}),d.jsx(Le,{onClick:te,variant:"outline",className:"flex-1",disabled:h==="llm"&&B,children:"Reject"})]})]}):d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select a sampling request to view details"})})}function n0e({pendingRequests:e,onApprove:t,onReject:n,serverId:r,isConnected:a,mcpServerUrl:s}){const{selectedSamplingRequestId:i,setSelectedSamplingRequestId:c}=Wl(),{llmConfig:u}=j6({mcpServerUrl:s}),[f,m]=v.useState(null),[h,g]=v.useState(""),[y,x]=v.useState(-1),[E,w]=v.useState(!0),[_,S]=v.useState(!1),[T,R]=v.useState(!0),[C,I]=v.useState(!1),A=v.useRef(null),O=v.useRef(null),j=v.useRef(null),U=v.useRef(!1);v.useEffect(()=>{if(console.log("[SamplingTab] Auto-selection check:",{selectedSamplingRequestId:i,pendingRequestsCount:e.length,currentSelectedId:f?.id}),i&&e.length>0){const V=e.find(ne=>ne.id===i);console.log("[SamplingTab] Found request for auto-selection:",!!V,V?.id),V&&(console.log("[SamplingTab] Auto-selecting request:",V.id),c(null),m(V),setTimeout(()=>{const ne=document.getElementById(`sampling-request-${V.id}`);console.log("[SamplingTab] Scrolling to element:",!!ne),ne&&ne.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[i,e,c]),v.useEffect(()=>{const V=ne=>{const D=ne.detail.requestId;console.log("[SamplingTab] Custom navigate event received:",D);const H=e.find($=>$.id===D);H&&(console.log("[SamplingTab] Selecting request from event:",D),m(H),setTimeout(()=>{const $=document.getElementById(`sampling-request-${D}`);$&&$.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-sampling",V),()=>window.removeEventListener("navigate-to-sampling",V)},[e]),v.useEffect(()=>{E&&e.length>0&&A.current&&!U.current&&(A.current.scrollTop=0)},[e.length,E]),v.useEffect(()=>{const V=A.current;if(!V)return;const ne=()=>{V.scrollTop>0&&(U.current=!0,w(!1))};return V.addEventListener("scroll",ne),()=>V.removeEventListener("scroll",ne)},[]),v.useEffect(()=>{e.length===0&&(U.current=!1,w(!0))},[e.length]),v.useEffect(()=>{_&&j.current&&j.current.focus()},[_]);const B=v.useCallback(()=>{h.trim()||S(!1)},[h]),W=v.useMemo(()=>{if(!h.trim())return e;const V=h.toLowerCase();return e.filter(ne=>ne.serverName.toLowerCase().includes(V)||JSON.stringify(ne.request||{}).toLowerCase().includes(V))},[e,h]);v.useEffect(()=>{x(-1)},[h]),v.useEffect(()=>{const V=ne=>{const te=ne.target;if(te.tagName==="INPUT"||te.tagName==="TEXTAREA"||te.contentEditable==="true"||ne.metaKey||ne.ctrlKey||ne.altKey)return;const H=W;if(ne.key==="ArrowDown")ne.preventDefault(),x($=>{const L=$+1;return L>=H.length?0:L});else if(ne.key==="ArrowUp")ne.preventDefault(),x($=>{const L=$-1;return L<0?H.length-1:L});else if(ne.key==="Enter"&&y>=0){ne.preventDefault();const $=W[y];$&&J($)}};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[y,W]),v.useEffect(()=>{if(y>=0){const V=`sampling-request-${W[y]?.id}`,ne=document.getElementById(V);ne&&ne.scrollIntoView({behavior:"smooth",block:"nearest"})}},[y,W]);const J=v.useCallback(V=>{m(V)},[]),ee=v.useCallback(()=>{window.confirm("Are you sure you want to reject all sampling requests? This cannot be undone.")&&(e.forEach(V=>{n(V.id,"User rejected all requests")}),m(null))},[e,n]),re=v.useCallback(async()=>{if(f)try{await navigator.clipboard.writeText(JSON.stringify({id:f.id,serverName:f.serverName,timestamp:f.timestamp,request:f.request},null,2)),I(!0),setTimeout(()=>I(!1),2e3)}catch(V){console.error("[SamplingTab] Failed to copy request:",V)}},[f]),F=v.useCallback(()=>{if(f)try{const V=new globalThis.Blob([JSON.stringify({id:f.id,serverName:f.serverName,timestamp:f.timestamp,request:f.request},null,2)],{type:"application/json"}),ne=URL.createObjectURL(V),te=document.createElement("a");te.href=ne,te.download=`sampling-request-${Date.now()}.json`,document.body.appendChild(te),te.click(),document.body.removeChild(te),URL.revokeObjectURL(ne)}catch(V){console.error("[SamplingTab] Failed to download request:",V)}},[f]),K=v.useCallback(async()=>{if(O.current)try{document.fullscreenElement?await document.exitFullscreen():await O.current.requestFullscreen()}catch(V){console.error("[SamplingTab] Failed to toggle fullscreen:",V)}},[]);return a?d.jsxs(aa,{direction:"horizontal",className:"h-full",children:[d.jsx(Rn,{defaultSize:40,minSize:30,children:d.jsx(aa,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:d.jsxs(Rn,{defaultSize:75,minSize:30,children:[d.jsx(Jve,{isSearchExpanded:_,searchQuery:h,filteredRequestsCount:W.length,requestsCount:e.length,onSearchExpand:()=>S(!0),onSearchChange:g,onSearchBlur:B,onRejectAll:ee,searchInputRef:j}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(Qve,{requests:W,selectedRequest:f,onRequestSelect:J,focusedIndex:y,formatRelativeTime:uy,listRef:A})})]})})}),d.jsx(wo,{}),d.jsx(Rn,{defaultSize:60,minSize:40,children:d.jsx("div",{ref:O,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(t0e,{request:f,onApprove:t,onReject:n,onClose:()=>m(null),previewMode:T,onTogglePreview:()=>R(!T),isCopied:C,onCopy:re,onDownload:F,onFullscreen:K,llmConfig:u})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(J3,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function r0e({isSearchExpanded:e,searchQuery:t,filteredRequestsCount:n,requestsCount:r,onSearchExpand:a,onSearchChange:s,onSearchBlur:i,onCancelAll:c,searchInputRef:u}){return d.jsxs("div",{className:"flex flex-row items-center justify-between p-4 sm:p-4 py-3 gap-2",children:[d.jsx("div",{className:"flex items-center gap-2 flex-1",children:e?d.jsx(Tn,{ref:u,placeholder:"Search requests...",value:t,onChange:f=>s(f.target.value),onBlur:i,className:"h-8 border-gray-300 dark:border-zinc-600"}):d.jsxs(d.Fragment,{children:[d.jsx("h2",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:"Elicitation"}),d.jsx(kr,{className:"bg-zinc-500/20 text-zinc-600 dark:text-zinc-400 border-transparent",variant:"outline",children:n}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:a,className:"h-8 w-8 p-0",children:d.jsx(wd,{className:"h-4 w-4"})})}),d.jsxs(Mt,{side:"bottom",className:"flex gap-2",children:["Search",d.jsx(gm,{children:"F"})]})]})]})}),d.jsx("div",{className:"flex items-center gap-2",children:d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,disabled:r===0,className:"h-8 w-8 p-0",children:d.jsx(qo,{className:"h-4 w-4"})})}),d.jsx(Mt,{side:"bottom",children:"Cancel all"})]})})]})}function a0e({requests:e,selectedRequest:t,onRequestSelect:n,focusedIndex:r,formatRelativeTime:a,listRef:s}){return e.length===0?d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx(vd,{vertical:!0,noBorder:!0,message:"No elicitation requests"})}):d.jsx("div",{ref:s,className:"overflow-y-auto flex-1 overscroll-contain",children:e.map((i,c)=>{const u=i.request.mode||"form",f=u==="form"&&"requestedSchema"in i.request&&i.request.requestedSchema;return d.jsx(Wi,{id:`elicitation-request-${i.id}`,isSelected:t?.id===i.id,isFocused:r===c,title:d.jsxs("span",{className:"flex items-center gap-3",children:[i.serverName,d.jsx(kr,{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=a(i.timestamp),h=[];f&&h.push("with schema"),u==="url"&&h.push("external action");const g=h.length>0?` | ${h.join(", ")}`:"";return m+g})(),onClick:()=>n(i)},i.id)})})}function o0e({request:e,onApprove:t,onReject:n,onClose:r,previewMode:a,onTogglePreview:s,isCopied:i,onCopy:c,onDownload:u,onFullscreen:f}){const[m,h]=v.useState({}),[g,y]=v.useState(!1),x=e?.request.mode||"form",E=x==="form",w=x==="url";v.useEffect(()=>{if(e&&E&&"requestedSchema"in e.request){const A=e.request.requestedSchema,O={};if(A?.type==="object"&&A.properties)for(const[j,U]of Object.entries(A.properties)){const B=U;B.default!==void 0?O[j]=B.default:B.type==="boolean"?O[j]=!1:B.type==="number"||B.type==="integer"?O[j]=0:O[j]=""}h(O)}y(!1)},[e?.id,E]);const _=(A,O)=>{h(j=>({...j,[A]:O}))},S=()=>{if(e){if(E){if("requestedSchema"in e.request){const A=e.request.requestedSchema;if(A?.required){const O=A.required.filter(j=>m[j]===void 0||m[j]===""||m[j]===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 w&&t(e.id,{action:"accept"});r(),rr(()=>Promise.resolve().then(()=>id),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 j=new globalThis.CustomEvent("navigate-to-tool-result",{detail:{toolName:null}});window.dispatchEvent(j),Xt.dismiss(O)}},"View Tool Result"))),{duration:5e3})})}},T=()=>{e&&(t(e.id,{action:"decline"}),r())},R=()=>{e&&(n(e.id,"User cancelled elicitation request"),r())},C=()=>{e&&w&&"url"in e.request&&(window.open(e.request.url,"_blank"),y(!0))},I=v.useMemo(()=>{if(!e||!E||!("requestedSchema"in e.request))return null;const A=e.request.requestedSchema;if(!A||A.type!=="object"||!A.properties)return d.jsx("div",{className:"text-sm text-gray-500 dark:text-gray-400",children:"No form schema available"});const O=A.properties,j=A.required||[];return d.jsx("div",{className:"space-y-4",children:Object.entries(O).map(([U,B])=>{const W=B,J=j.includes(U),ee=W.type||"string",re=W.title||U,F=W.description;return d.jsxs("div",{className:"space-y-2",children:[d.jsxs(Wt,{htmlFor:`field-${U}`,children:[re,J&&d.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),F&&d.jsx("p",{className:"text-xs text-muted-foreground",children:F}),ee==="boolean"?d.jsxs("div",{className:"flex items-center space-x-2",children:[d.jsx(Op,{id:`field-${U}`,checked:m[U]||!1,onCheckedChange:K=>_(U,K)}),d.jsx(Wt,{htmlFor:`field-${U}`,className:"text-sm font-normal cursor-pointer",children:W.title||U})]}):ee==="number"||ee==="integer"?d.jsx(Tn,{id:`field-${U}`,type:"number",value:m[U]||"",onChange:K=>_(U,ee==="integer"?parseInt(K.target.value,10):parseFloat(K.target.value)),placeholder:W.default?.toString()||""}):W.enum?d.jsxs("select",{id:`field-${U}`,value:m[U]||"",onChange:K=>_(U,K.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:[d.jsx("option",{value:"",children:"Select..."}),W.enum.map(K=>d.jsx("option",{value:K,children:K},K))]}):ee==="string"&&(W.format==="textarea"||W.maxLength>100)?d.jsx(Pl,{id:`field-${U}`,value:m[U]||"",onChange:K=>_(U,K.target.value),placeholder:W.default||"",rows:4}):d.jsx(Tn,{id:`field-${U}`,type:"text",value:m[U]||"",onChange:K=>_(U,K.target.value),placeholder:W.default||""})]},U)})})},[e,m,E]);return e?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsxs("div",{className:"flex items-center justify-between p-4 border-b dark:border-zinc-700",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("h3",{className:"font-medium text-gray-900 dark:text-gray-100",children:e.serverName}),d.jsx(kr,{variant:"outline",className:w?"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}),d.jsx("span",{className:"text-sm text-gray-500 dark:text-gray-400",children:new Date(e.timestamp).toLocaleString()})]}),d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:c,className:"h-8 w-8 p-0",children:i?d.jsx(oa,{className:"h-4 w-4 text-green-600"}):d.jsx(zr,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:"Copy request"})]}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:u,className:"h-8 w-8 p-0",children:d.jsx(Qp,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:"Download request"})]}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",onClick:f,className:"h-8 w-8 p-0",children:d.jsx(mT,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:"Fullscreen"})]}),d.jsx(Le,{variant:"ghost",size:"sm",onClick:r,className:"h-8 w-8 p-0",children:d.jsx(qo,{className:"h-4 w-4"})})]})]}),d.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-6",children:[d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Message"}),d.jsx("p",{className:"text-sm text-gray-700 dark:text-gray-300",children:e.request.message})]}),w&&"url"in e.request&&d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"External Action Required"}),d.jsxs("div",{className:"bg-muted rounded-lg p-4 space-y-3",children:[d.jsx("p",{className:"text-sm text-muted-foreground",children:"This request requires you to complete an action at an external URL:"}),d.jsxs("div",{className:"flex items-center gap-2 p-2 bg-background rounded border",children:[d.jsx("code",{className:"flex-1 text-xs font-mono break-all",children:e.request.url}),d.jsxs(Le,{size:"sm",variant:"outline",onClick:C,className:"flex items-center gap-2",children:[d.jsx(Wx,{className:"h-4 w-4"}),"Open URL"]})]}),d.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[d.jsx(Op,{id:"url-completed",checked:g,onCheckedChange:A=>y(!!A)}),d.jsx(Wt,{htmlFor:"url-completed",className:"text-sm font-normal cursor-pointer",children:"I have completed the required action"})]})]})]}),E&&d.jsxs("div",{className:"space-y-2",children:[d.jsx("h4",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100",children:"Form Data"}),I]}),E&&"requestedSchema"in e.request&&e.request.requestedSchema&&d.jsxs("details",{className:"space-y-2",children:[d.jsx("summary",{className:"text-sm font-semibold text-gray-900 dark:text-gray-100 cursor-pointer",children:"Schema (for reference)"}),d.jsx("div",{className:"bg-muted rounded-lg p-3 max-h-64 overflow-auto",children:d.jsx(nr,{data:e.request.requestedSchema})})]})]}),d.jsxs("div",{className:"flex gap-2 p-4 border-t dark:border-zinc-700",children:[d.jsx(Le,{onClick:S,className:"flex-1",children:"Accept"}),d.jsx(Le,{onClick:T,variant:"outline",className:"flex-1",children:"Decline"}),d.jsx(Le,{onClick:R,variant:"outline",className:"flex-1",children:"Cancel"})]})]}):d.jsx("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Select an elicitation request to view details"})})}function s0e({pendingRequests:e=[],onApprove:t,onReject:n,serverId:r,isConnected:a}){const{selectedElicitationRequestId:s,setSelectedElicitationRequestId:i}=Wl(),[c,u]=v.useState(null),[f,m]=v.useState(""),[h,g]=v.useState(-1),[y,x]=v.useState(!0),[E,w]=v.useState(!1),[_,S]=v.useState(!0),[T,R]=v.useState(!1),C=v.useRef(null),I=v.useRef(null),A=v.useRef(null),O=v.useRef(!1);v.useEffect(()=>{if(console.log("[ElicitationTab] Auto-selection check:",{selectedElicitationRequestId:s,pendingRequestsCount:e.length,currentSelectedId:c?.id}),s&&e.length>0){const F=e.find(K=>K.id===s);console.log("[ElicitationTab] Found request for auto-selection:",!!F,F?.id),F&&(console.log("[ElicitationTab] Auto-selecting request:",F.id),i(null),u(F),setTimeout(()=>{const K=document.getElementById(`elicitation-request-${F.id}`);console.log("[ElicitationTab] Scrolling to element:",!!K),K&&K.scrollIntoView({behavior:"smooth",block:"nearest"})},100))}},[s,e,i]),v.useEffect(()=>{const F=K=>{const ne=K.detail.requestId;console.log("[ElicitationTab] Custom navigate event received:",ne);const te=e.find(D=>D.id===ne);te&&(console.log("[ElicitationTab] Selecting request from event:",ne),u(te),setTimeout(()=>{const D=document.getElementById(`elicitation-request-${ne}`);D&&D.scrollIntoView({behavior:"smooth",block:"nearest"})},200))};return window.addEventListener("navigate-to-elicitation",F),()=>window.removeEventListener("navigate-to-elicitation",F)},[e]),v.useEffect(()=>{y&&e.length>0&&C.current&&!O.current&&(C.current.scrollTop=0)},[e.length,y]),v.useEffect(()=>{const F=C.current;if(!F)return;const K=()=>{F.scrollTop>0&&(O.current=!0,x(!1))};return F.addEventListener("scroll",K),()=>F.removeEventListener("scroll",K)},[]),v.useEffect(()=>{e.length===0&&(O.current=!1,x(!0))},[e.length]),v.useEffect(()=>{E&&A.current&&A.current.focus()},[E]);const j=v.useCallback(()=>{f.trim()||w(!1)},[f]),U=v.useMemo(()=>{if(!f.trim())return e;const F=f.toLowerCase();return e.filter(K=>K.serverName.toLowerCase().includes(F)||K.request.message.toLowerCase().includes(F)||JSON.stringify(K.request||{}).toLowerCase().includes(F))},[e,f]);v.useEffect(()=>{g(-1)},[f]),v.useEffect(()=>{const F=K=>{const V=K.target;if(V.tagName==="INPUT"||V.tagName==="TEXTAREA"||V.contentEditable==="true"||K.metaKey||K.ctrlKey||K.altKey)return;const te=U;if(K.key==="ArrowDown")K.preventDefault(),g(D=>{const H=D+1;return H>=te.length?0:H});else if(K.key==="ArrowUp")K.preventDefault(),g(D=>{const H=D-1;return H<0?te.length-1:H});else if(K.key==="Enter"&&h>=0){K.preventDefault();const D=U[h];D&&B(D)}};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[h,U]),v.useEffect(()=>{if(h>=0){const F=`elicitation-request-${U[h]?.id}`,K=document.getElementById(F);K&&K.scrollIntoView({behavior:"smooth",block:"nearest"})}},[h,U]);const B=v.useCallback(F=>{u(F)},[]),W=v.useCallback(()=>{window.confirm("Are you sure you want to cancel all elicitation requests? This cannot be undone.")&&(e.forEach(F=>{n(F.id,"User cancelled all requests")}),u(null))},[e,n]),J=v.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)),R(!0),setTimeout(()=>R(!1),2e3)}catch(F){console.error("[ElicitationTab] Failed to copy request:",F)}},[c]),ee=v.useCallback(()=>{if(c)try{const F=new globalThis.Blob([JSON.stringify({id:c.id,serverName:c.serverName,timestamp:c.timestamp,request:c.request},null,2)],{type:"application/json"}),K=URL.createObjectURL(F),V=document.createElement("a");V.href=K,V.download=`elicitation-request-${Date.now()}.json`,document.body.appendChild(V),V.click(),document.body.removeChild(V),URL.revokeObjectURL(K)}catch(F){console.error("[ElicitationTab] Failed to download request:",F)}},[c]),re=v.useCallback(async()=>{if(I.current)try{document.fullscreenElement?await document.exitFullscreen():await I.current.requestFullscreen()}catch(F){console.error("[ElicitationTab] Failed to toggle fullscreen:",F)}},[]);return a?d.jsxs(aa,{direction:"horizontal",className:"h-full",children:[d.jsx(Rn,{defaultSize:40,minSize:30,children:d.jsx(aa,{direction:"vertical",className:"h-full border-r dark:border-zinc-700",children:d.jsxs(Rn,{defaultSize:75,minSize:30,children:[d.jsx(r0e,{isSearchExpanded:E,searchQuery:f,filteredRequestsCount:U.length,requestsCount:e.length,onSearchExpand:()=>w(!0),onSearchChange:m,onSearchBlur:j,onCancelAll:W,searchInputRef:A}),d.jsx("div",{className:"flex flex-col h-full",children:d.jsx(a0e,{requests:U,selectedRequest:c,onRequestSelect:B,focusedIndex:h,formatRelativeTime:uy,listRef:C})})]})})}),d.jsx(wo,{}),d.jsx(Rn,{defaultSize:60,minSize:40,children:d.jsx("div",{ref:I,className:"h-full bg-white dark:bg-zinc-900",children:d.jsx(o0e,{request:c,onApprove:t,onReject:n,onClose:()=>u(null),previewMode:_,onTogglePreview:()=>S(!_),isCopied:T,onCopy:J,onDownload:ee,onFullscreen:re})})})]}):d.jsxs("div",{className:"flex flex-col items-center justify-center h-full p-4 text-center",children:[d.jsx(nB,{className:"h-12 w-12 text-gray-400 dark:text-gray-600 mb-3"}),d.jsx("p",{className:"text-gray-500 dark:text-gray-400",children:"Not connected to server"})]})}function i0e({selectedServer:e,activeTab:t,toolsSearchRef:n,promptsSearchRef:r,resourcesSearchRef:a,children:s}){return e?d.jsxs(d.Fragment,{children:[d.jsx("div",{style:{display:t==="tools"?"block":"none"},className:"h-full",children:d.jsx(c8,{ref:n,tools:e.tools,callTool:e.callTool,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="prompts"?"block":"none"},className:"h-full",children:d.jsx(o8,{ref:r,prompts:e.prompts,callPrompt:e.getPrompt,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="resources"?"block":"none"},className:"h-full",children:d.jsx(i8,{ref:a,resources:e.resources,readResource:e.readResource,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="chat"?"block":"none"},className:"h-full",children:d.jsx(cve,{connection:e,isConnected:e.state==="ready",readResource:e.readResource},e.id)}),d.jsx("div",{style:{display:t==="sampling"?"block":"none"},className:"h-full",children:d.jsx(n0e,{pendingRequests:e.pendingSamplingRequests,onApprove:e.approveSampling,onReject:e.rejectSampling,serverId:e.id,isConnected:e.state==="ready",mcpServerUrl:e.url})}),d.jsx("div",{style:{display:t==="elicitation"?"block":"none"},className:"h-full",children:d.jsx(s0e,{pendingRequests:e.pendingElicitationRequests,onApprove:e.approveElicitation,onReject:e.rejectElicitation,serverId:e.id,isConnected:e.state==="ready"})}),d.jsx("div",{style:{display:t==="notifications"?"block":"none"},className:"h-full",children:d.jsx(Fve,{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"&&d.jsx(d.Fragment,{children:s})]}):d.jsx(d.Fragment,{children:s})}function hz({className:e}){return d.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentcolor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round",className:e,children:[d.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"}),d.jsx("path",{d:"M9 18c-4.51 2-5-2-7-2"})]})}const u8=v.createContext(void 0);function d8(){const e=v.use(u8);if(!e)throw new Error("useTabs must be used within a TabsProvider");return e}const f8=v.createContext(void 0);function l0e(){return v.use(f8)}function QS({ref:e,children:t,defaultValue:n,value:r,onValueChange:a,className:s,...i}){const[c,u]=v.useState(n||""),f=r!==void 0,m=v.useCallback(g=>{f||u(g),a?.(g)},[f,a]),h=f?r:c;return d.jsx(u8,{value:{activeValue:h,handleValueChange:m},children:d.jsx("div",{ref:e,className:Oe("flex flex-col gap-2",s),...i,children:t})})}QS.displayName="Tabs";function e_({ref:e,children:t,className:n,variant:r="default",...a}){const{activeValue:s}=d8(),[i,c]=v.useState({width:0,left:0}),u=v.useRef(null),f=v.useRef(null),m=v.useRef(null),g=v.Children.toArray(t).findIndex(E=>v.isValidElement(E)&&E.props.value===s),y=v.useCallback(()=>{const E=u.current;if(!E)return;const _=E.querySelectorAll("button")[g];if(_){const S=E.getBoundingClientRect(),T=_.getBoundingClientRect();c({width:T.width,left:T.left-S.left})}},[g]),x=v.useCallback(()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(y,16)},[y]);return v.useEffect(()=>{const E=setTimeout(y,10);return()=>clearTimeout(E)},[y]),v.useEffect(()=>{const E=u.current;return E?(f.current=new ResizeObserver(()=>{x()}),f.current.observe(E),E.querySelectorAll("button").forEach(_=>{f.current&&f.current.observe(_)}),()=>{f.current&&f.current.disconnect(),m.current&&clearTimeout(m.current)}):void 0},[x]),v.useEffect(()=>{const E=()=>{x()};return window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[x]),v.useEffect(()=>{const E=u.current;if(!E)return;const w=E.querySelector("[data-width]");w&&(w.style.width=`${i.width}px`,w.style.left=`${i.left}px`)},[i]),d.jsx(f8,{value:{variant:r},children:d.jsxs("div",{ref:u,className:Oe("relative flex bg-none",r==="default"&&"p-1 rounded-full border border-zinc-300 dark:border-zinc-600",r==="underline"&&"border-b border-zinc-200 dark:border-zinc-700",n),...a,children:[t,d.jsx("span",{className:Oe("absolute transition-all duration-200 ease-out z-0",r==="default"&&"bg-white dark:bg-zinc-700 rounded-full h-[calc(100%-8px)] top-1 border border-zinc-300 dark:border-zinc-600",r==="underline"&&"bottom-0 h-0.5 bg-black dark:bg-white"),"data-width":i.width,"data-left":i.left})]})})}e_.displayName="TabsList";function t_({ref:e,children:t,value:n,className:r,disabled:a,icon:s,...i}){const{activeValue:c,handleValueChange:u}=d8(),m=l0e()?.variant||"default",h=c===n;return d.jsxs("button",{ref:e,disabled:a,onClick:()=>u(n),className:Oe("relative z-10 flex-1 inline-flex items-center justify-center whitespace-nowrap text-sm font-medium ring-offset-background transition-colors 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",m==="default"&&"rounded-md px-4 py-2.5",m==="underline"&&"px-6 py-3 border-b-2 border-transparent",h&&"text-foreground",!h&&"text-muted-foreground hover:text-foreground",r),...i,children:[s&&d.jsx(s,{className:"mr-2 h-4 w-4"}),t]})}t_.displayName="TabsTrigger";function gz({className:e}){const{theme:t,setTheme:n}=yv(),r=v.useRef(null),[a,s]=v.useState(!1);v.useEffect(()=>{s(!0)},[]);const i=()=>t==="system"?"light":t==="light"?"dark":"system",c=()=>t==="system"?d.jsx(xP,{className:"size-4"}):t==="light"?d.jsx(sle,{className:"size-5"}):d.jsx($ie,{className:"size-4"}),u=()=>t==="system"?"Switch to light mode":t==="light"?"Switch to dark mode":"Switch to system mode",f=async()=>{if(!r.current)return;const m=i();if(typeof document<"u"&&"startViewTransition"in document){await document.startViewTransition(()=>{fd.flushSync(()=>{n(m)})}).ready;const{top:h,left:g,width:y,height:x}=r.current.getBoundingClientRect(),E=h+x/2,w=g+y/2,_=window.innerWidth-g,S=window.innerHeight-h,T=Math.hypot(Math.max(g,_),Math.max(h,S));document.documentElement.animate({clipPath:[`circle(0px at ${w}px ${E}px)`,`circle(${T}px at ${w}px ${E}px)`]},{duration:700,easing:"ease-in-out",pseudoElement:"::view-transition-new(root)"})}else n(m)};return a?d.jsx("button",{ref:r,onClick:f,className:Oe(e),"aria-label":u(),title:`Current: ${t==="system"?"Auto":t==="light"?"Light":"Dark"}`,children:c()}):d.jsx("button",{ref:r,className:Oe(e),"aria-label":"Toggle theme",children:d.jsx(xP,{className:"size-4"})})}function bz({className:e,state:t="collapsed",href:n="https://mcp-use.com"}){const[r,a]=v.useState(!1),s=.2,i=.7,c=.6,u=4,f=s+i+c,m=0,h=s/f,g=(s+i)/f,y=1;return d.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:Oe("flex items-center transition-opacity -my-3",t==="expanded"?"space-x-2":"",e),onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[d.jsx("div",{className:"relative",children:d.jsxs(wa.svg,{viewBox:"0 0 303 303",initial:"rest",animate:r?"hover":"rest",className:Oe("text-foreground",t==="expanded"?"size-[40px]":"size-[20px]"),children:[d.jsxs(wa.g,{variants:{rest:{opacity:1},hover:{opacity:[1,0,0,1],transition:{duration:f,times:[m,h,g,y],ease:"easeInOut"}}},fill:"currentColor",fillRule:"nonzero",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[d.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"}),d.jsx("circle",{cx:"70.3",cy:"232.3",r:"50"}),d.jsx("circle",{cx:"232.3",cy:"70.3",r:"50"})]}),d.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:u,strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx(c0e,{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:y},total:f}),d.jsx(yz,{cx:70.3,cy:232.3,r:50,times:{T0:m,T1:h,T2:g,T3:y},total:f}),d.jsx(yz,{cx:232.3,cy:70.3,r:50,times:{T0:m,T1:h,T2:g,T3:y},total:f})]})]})}),t==="expanded"&&d.jsxs("div",{className:"font-ubuntu flex flex-col items-start -space-y-1 mr-3",children:[d.jsx("h1",{className:"text-xl font-medium",children:"mcp-use"}),d.jsx("span",{className:"text-lg text-muted-foreground tracking-wide font-sans font-light",children:"Inspector"})]})]})}function c0e({d:e,times:t,total:n}){const{T0:r,T1:a,T2:s,T3:i}=t;return d.jsx(wa.path,{d:e,variants:{rest:{pathLength:0,opacity:0},hover:{pathLength:[0,0,1,1],opacity:[0,0,1,1],transition:{duration:n,times:[r,a,s,i],ease:"easeInOut"}}}})}function yz({cx:e,cy:t,r:n,times:r,total:a}){const{T0:s,T1:i,T2:c,T3:u}=r;return d.jsx(wa.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:a,times:[s,i,c,u],ease:"easeInOut"}}}})}function p8({ref:e,shimmerColor:t,shimmerSize:n="0.05em",shimmerDuration:r="3s",borderRadius:a="100px",background:s,className:i,children:c,...u}){const{resolvedTheme:f}=yv(),m=f==="dark"?"#000000":"#ffffff",h=f==="dark"?"rgba(255, 255, 255, 1)":"rgba(0, 0, 0, 1)",g=t||m,y=s||h;return d.jsxs("button",{style:{"--spread":"90deg","--shimmer-color":g,"--radius":a,"--speed":r,"--cut":n,"--bg":y},className:Oe("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",f==="dark"?"border-black/10 text-black":"border-white/10 text-white",i),ref:e,...u,children:[d.jsx("div",{className:Oe("-z-30 blur-[2px]","[container-type:size] absolute inset-0 overflow-visible"),children:d.jsx("div",{className:"animate-shimmer-slide absolute inset-0 [aspect-ratio:1] h-[100cqh] [border-radius:0] [mask:none]",children:d.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,d.jsx("div",{className:Oe("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",f==="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]")}),d.jsx("div",{className:Oe("absolute [inset:var(--cut)] -z-20 [border-radius:var(--radius)] [background:var(--bg)]")})]})}p8.displayName="ShimmerButton";function vz({status:e}){const t=s=>{switch(s){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:s}}},{color:n,ringColor:r,tooltip:a}=t(e);return d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsxs("div",{className:"relative",children:[d.jsx("div",{className:`absolute w-2 h-2 rounded-full ${r} animate-ping`}),d.jsx("div",{className:`relative w-2 h-2 rounded-full ${n}`})]})}),d.jsx(Mt,{children:d.jsx("p",{children:a})})]})}function wz({connections:e,selectedServer:t,onServerSelect:n,onOpenConnectionOptions:r,mobileMode:a=!1}){const s=dd(),i=c=>{const u=e.find(f=>f.id===c);if(!u||u.state!=="ready"){Xt.error("Server is not connected and cannot be inspected");return}n(c)};return a?d.jsx("div",{className:"flex items-center gap-2",children:d.jsx("div",{className:"relative",children:d.jsxs(Fx,{children:[d.jsx(Bx,{asChild:!0,children:d.jsxs(Le,{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?d.jsx(Sl,{serverUrl:t.url,serverName:t.name,size:"md"}):d.jsx(qie,{className:"h-5 w-5"}),d.jsx(Gl,{className:"h-4 w-4"})]})}),d.jsxs(Lb,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[d.jsx(Hx,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>s("/"),children:"MCP Servers"}),d.jsx(Mf,{}),e.length===0?d.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=>d.jsxs(Ts,{onClick:()=>i(c.id),className:"flex items-center gap-3",children:[d.jsx(Sl,{serverUrl:c.url,serverName:c.name,size:"sm"}),d.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[d.jsx("div",{className:"font-medium",children:c.name}),d.jsx(vz,{status:c.state})]}),d.jsx(Le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:u=>{u.stopPropagation(),r(c.id)},children:d.jsx(mu,{className:"h-3 w-3"})})]},c.id)),d.jsx(Mf,{}),d.jsx(Ts,{onClick:()=>s("/"),children:d.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})})}):d.jsx("div",{className:"flex items-center gap-2",children:d.jsx("div",{className:"relative",children:d.jsxs(Fx,{children:[d.jsx(Bx,{asChild:!0,children:d.jsxs(p8,{className:Oe("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&&d.jsx(Sl,{serverUrl:t.url,serverName:t.name,size:"md",className:"mr-2"}),d.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[d.jsx("span",{className:"truncate",children:t?t.name:"Select server to inspect"}),t&&d.jsx("div",{className:"flex items-center gap-2",children:t.error&&t.state!=="ready"?d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.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"})}),d.jsx(Mt,{children:d.jsx("p",{className:"max-w-xs",children:t.error})})]}):d.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&&d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx("button",{type:"button",onClick:()=>{r(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:d.jsx(mu,{className:"h-4 w-4"})})}),d.jsx(Mt,{children:d.jsx("p",{children:"Edit connection settings"})})]}),d.jsxs(Lb,{className:"w-[calc(100vw-2rem)] sm:w-[300px]",align:"start",children:[d.jsx(Hx,{className:"cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:()=>s("/"),children:"MCP Servers"}),d.jsx(Mf,{}),e.length===0?d.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=>d.jsxs(Ts,{onClick:()=>i(c.id),className:"flex items-center gap-3",children:[d.jsx(Sl,{serverUrl:c.url,serverName:c.name,size:"sm"}),d.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[d.jsx("div",{className:"font-medium",children:c.name}),d.jsx(vz,{status:c.state})]}),d.jsx(Le,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 hover:bg-zinc-100 dark:hover:bg-zinc-800",onClick:u=>{u.stopPropagation(),r(c.id)},children:d.jsx(mu,{className:"h-3 w-3"})})]},c.id)),d.jsx(Mf,{}),d.jsx(Ts,{onClick:()=>s("/"),children:d.jsx("span",{className:"text-blue-600 dark:text-blue-400",children:"+ Add new server"})})]})]})})})}const Ez=[{id:"tools",label:"Tools",icon:Ol},{id:"prompts",label:"Prompts",icon:yp},{id:"resources",label:"Resources",icon:Eie},{id:"sampling",label:"Sampling",icon:J3},{id:"elicitation",label:"Elicitation",icon:nB},{id:"notifications",label:"Notifications",icon:uT},{id:"chat",label:"Chat",icon:Die}];function xz(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 u0e({connections:e,selectedServer:t,activeTab:n,onServerSelect:r,onTabChange:a,onCommandPaletteOpen:s,onOpenConnectionOptions:i}){const{tunnelUrl:c}=Wl(),u=t&&c,[f,m]=v.useState(!1),h=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 d.jsxs("header",{className:"w-full mx-auto",children:[d.jsxs("div",{className:"flex lg:hidden flex-col gap-3",children:[d.jsxs("div",{className:"flex items-center justify-between w-full",children:[d.jsx("div",{className:"flex-1 flex justify-start",children:d.jsx(wz,{connections:e,selectedServer:t,onServerSelect:r,onOpenConnectionOptions:i,mobileMode:!0})}),d.jsx("div",{className:"flex-shrink-0 flex justify-center",children:d.jsx("div",{className:"scale-150",children:d.jsx(bz,{state:"collapsed"})})}),d.jsxs("div",{className:"flex-1 flex justify-end items-center gap-2",children:[d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",asChild:!0,children:d.jsx("a",{href:"https://github.com/mcp-use/mcp-use",target:"_blank",rel:"noopener noreferrer",className:"p-2","aria-label":"GitHub",children:d.jsx(hz,{className:"h-4 w-4"})})})}),d.jsx(Mt,{children:d.jsx("p",{children:"Give us a star ⭐"})})]}),d.jsx(gz,{className:"p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors cursor-pointer"})]})]}),t&&d.jsx("div",{className:"w-full",children:d.jsx(QS,{value:n,onValueChange:g=>a(g),children:d.jsx(e_,{className:"w-full justify-center",children:Ez.map(g=>{const y=xz(g.id,t);return d.jsxs(t_,{value:g.id,icon:g.icon,className:"[&>svg]:mr-0 flex-1 flex-row gap-2 relative",children:[y>0&&d.jsx("span",{className:Oe(n===g.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:y}),d.jsx("span",{className:"sr-only",children:g.label})]},g.id)})})})})]}),d.jsxs("div",{className:"hidden lg:flex items-center justify-between gap-3",children:[d.jsxs("div",{className:"flex items-center flex-wrap gap-2 md:space-x-6 space-x-2",children:[d.jsx(wz,{connections:e,selectedServer:t,onServerSelect:r,onOpenConnectionOptions:i}),t&&d.jsx(QS,{value:n,onValueChange:g=>a(g),children:d.jsx(e_,{className:"overflow-x-auto",children:Ez.map(g=>{const y=xz(g.id,t);return d.jsx(t_,{value:g.id,icon:g.icon,className:"[&>svg]:mr-0 lg:[&>svg]:mr-2 relative",children:d.jsxs("div",{className:"items-center gap-2 hidden lg:flex",children:[g.label,y>0&&d.jsx("span",{className:Oe(n===g.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:y})]})},g.id)})})}),u&&d.jsxs(sV,{children:[d.jsx(iV,{asChild:!0,children:d.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:[d.jsx(vp,{className:"size-4 text-purple-600 dark:text-purple-400 animate-pulse"}),d.jsx("span",{className:"text-xs font-medium text-purple-700 dark:text-purple-300 hidden lg:inline",children:"Tunnel"})]})}),d.jsx(lN,{className:"w-[calc(100vw-2rem)] sm:w-96",align:"start",children:d.jsxs("div",{className:"space-y-4",children:[d.jsxs("div",{children:[d.jsxs("h4",{className:"font-semibold text-sm mb-2 flex items-center gap-2",children:[d.jsx(vp,{className:"size-4 text-purple-600 dark:text-purple-400"}),"Tunnel URL"]}),d.jsxs("div",{className:"flex items-center gap-2 p-2 py-0 bg-muted rounded-full",children:[d.jsxs("code",{className:"flex-1 text-[10px] font-mono",children:[c,"/mcp"]}),d.jsx(Le,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:h,children:f?d.jsx(oa,{className:"size-3.5 text-green-600"}):d.jsx(zr,{className:"size-3.5"})})]})]}),d.jsxs("div",{children:[d.jsx("h5",{className:"font-semibold text-sm mb-2",children:"Use in ChatGPT"}),d.jsxs("ol",{className:"space-y-2 text-xs text-muted-foreground",children:[d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"1."}),d.jsxs("span",{children:["Enable"," ",d.jsx("span",{className:"font-medium text-foreground",children:"dev mode"})," ","from settings"]})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"2."}),d.jsxs("span",{children:["In"," ",d.jsx("span",{className:"font-medium text-foreground",children:"App & Connectors"})," ","click on"," ",d.jsx("span",{className:"font-medium text-foreground",children:"create"})]})]}),d.jsxs("li",{className:"flex gap-2",children:[d.jsx("span",{className:"font-semibold text-foreground",children:"3."}),d.jsx("span",{children:"Use the tunnel URL in the input"})]})]})]})]})})]})]}),d.jsxs("div",{className:"flex items-center gap-2 sm:gap-4 flex-shrink-0",children:[d.jsxs(Dt,{children:[d.jsx(Lt,{children:d.jsx(gz,{className:"p-2 hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full transition-colors cursor-pointer"})}),d.jsx(Mt,{children:d.jsx("p",{children:"Toggle theme"})})]}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsxs(Le,{variant:"ghost",className:"hover:bg-zinc-200 dark:hover:bg-zinc-800 rounded-full px-1 -mx-3 flex gap-1",onClick:s,children:[d.jsx(aie,{className:"size-4"}),d.jsx("span",{className:"text-base font-mono hidden sm:inline",children:"K"})]})}),d.jsx(Mt,{children:d.jsx("p",{children:"Command Palette"})})]}),d.jsxs(Dt,{children:[d.jsx(Lt,{asChild:!0,children:d.jsx(Le,{variant:"ghost",size:"sm",asChild:!0,children:d.jsxs("a",{href:"https://github.com/mcp-use/mcp-use",className:"flex items-center gap-2",target:"_blank",rel:"noopener noreferrer",children:[d.jsx(hz,{className:"h-4 w-4"}),d.jsx("span",{className:"hidden sm:inline",children:"Github"})]})})}),d.jsx(Mt,{children:d.jsx("p",{children:"Give us a star ⭐"})})]}),d.jsx(bz,{state:"expanded"})]})]})]})}function d0e({children:e}){const t=dd(),n=$s(),{connections:r,addConnection:a,removeConnection:s,updateConnectionConfig:i,configLoaded:c}=cT(),{selectedServerId:u,setSelectedServerId:f,activeTab:m,setActiveTab:h,navigateToItem:g,setTunnelUrl:y}=Wl(),[x,E]=v.useState(!1),[w,_]=v.useState(null),S=Nme();v.useEffect(()=>{const K=new URLSearchParams(n.search).get("tunnelUrl");y(K)},[n.search,y]),v.useEffect(()=>{const F=ne=>{const D=ne.detail.requestId;u&&g(u,"sampling",D)},K=ne=>{const D=ne.detail.requestId;u&&g(u,"elicitation",D)},V=ne=>{const D=ne.detail.toolName;u&&D?g(u,"tools",D):u&&h("tools")};return window.addEventListener("navigate-to-sampling",F),window.addEventListener("navigate-to-elicitation",K),window.addEventListener("navigate-to-tool-result",V),()=>{window.removeEventListener("navigate-to-sampling",F),window.removeEventListener("navigate-to-elicitation",K),window.removeEventListener("navigate-to-tool-result",V)}},[u,h,g]);const T=v.useRef(null),R=v.useRef(null),C=v.useRef(null),{isAutoConnecting:I}=Tme({connections:r,addConnection:a,removeConnection:s,configLoaded:c}),A=v.useCallback(F=>{Tr.getInstance().capture(new wse({trigger:F})).catch(()=>{}),E(!0)},[]),O=F=>{const K=r.find(D=>D.id===F);if(!K||K.state!=="ready"){Xt.error("Server is not connected and cannot be inspected");return}f(F);const ne=new URLSearchParams(n.search).get("tunnelUrl"),te=ne?`/?server=${encodeURIComponent(F)}&tunnelUrl=${encodeURIComponent(ne)}`:`/?server=${encodeURIComponent(F)}`;t(te)},j=v.useCallback(F=>{_(F)},[]),U=v.useCallback(F=>{w&&(F.url!==w?(s(w),a(F.url,F.name,F.proxyConfig,F.transportType)):i(w,{name:F.name,proxyConfig:F.proxyConfig,transportType:F.transportType}),_(null),Xt.success("Connection settings updated"))},[w,s,a,i]),B=(F,K,V)=>{if(console.warn("[Layout] handleCommandPaletteNavigate called:",{tab:F,itemName:K,serverId:V}),V){const ne=r.find($=>$.id===V);if(console.warn("[Layout] Server lookup:",{serverId:V,serverFound:!!ne,serverState:ne?.state}),!ne||ne.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:V,tab:F,itemName:K}),g(V,F,K);const D=new URLSearchParams(n.search).get("tunnelUrl"),H=D?`/?server=${encodeURIComponent(V)}&tunnelUrl=${encodeURIComponent(D)}`:`/?server=${encodeURIComponent(V)}`;console.warn("[Layout] Navigating to:",H),t(H)}else console.warn("[Layout] No serverId, just updating tab to:",F),h(F)},W=r.find(F=>F.id===u),J=W?W.tools.map(F=>({...F,_serverId:W.id})):r.flatMap(F=>F.state==="ready"?F.tools.map(K=>({...K,_serverId:F.id,_serverName:F.name})):[]),ee=W?W.prompts.map(F=>({...F,_serverId:W.id})):r.flatMap(F=>F.state==="ready"?F.prompts.map(K=>({...K,_serverId:F.id,_serverName:F.name})):[]),re=W?W.resources.map(F=>({...F,_serverId:W.id})):r.flatMap(F=>F.state==="ready"?F.resources.map(K=>({...K,_serverId:F.id,_serverName:F.name})):[]);return v.useEffect(()=>{const K=new URLSearchParams(n.search).get("server"),V=K?decodeURIComponent(K):null;V!==u&&f(V)},[n.search,u,f]),v.useEffect(()=>{const K=new URLSearchParams(n.search).get("server");if(!K)return;const V=decodeURIComponent(K),ne=r.find(te=>te.id===V);if(!ne){const te=setTimeout(()=>t("/"),3e3);return()=>clearTimeout(te)}if(ne.state==="failed"){const te=setTimeout(()=>t("/"),2e3);return()=>clearTimeout(te)}},[n.search,t,r]),LH({onCommandPalette:()=>A("keyboard"),onToolsTab:()=>{W&&h("tools")},onPromptsTab:()=>{W&&h("prompts")},onResourcesTab:()=>{W&&h("resources")},onChatTab:()=>{W&&h("chat")},onHome:()=>{t("/")},onFocusSearch:()=>{m==="tools"&&T.current?T.current.focusSearch():m==="prompts"&&R.current?R.current.focusSearch():m==="resources"&&C.current&&C.current.focusSearch()},onBlurSearch:()=>{m==="tools"&&T.current?T.current.blurSearch():m==="prompts"&&R.current?R.current.blurSearch():m==="resources"&&C.current&&C.current.blurSearch()}}),I?d.jsx("div",{className:"h-screen bg-white dark:bg-zinc-900 flex items-center justify-center",children:d.jsxs("div",{className:"flex flex-col items-center gap-4",children:[d.jsx(_o,{className:"h-8 w-8 text-zinc-600 dark:text-zinc-400"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Connecting to MCP server..."})]})}):d.jsx(K3,{children:d.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:[d.jsx(u0e,{connections:r,selectedServer:W,activeTab:m,onServerSelect:O,onTabChange:h,onCommandPaletteOpen:()=>A("button"),onOpenConnectionOptions:j}),d.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:d.jsx(i0e,{selectedServer:W,activeTab:m,toolsSearchRef:T,promptsSearchRef:R,resourcesSearchRef:C,children:e})}),d.jsx(Qme,{isOpen:x,onOpenChange:E,tools:J,prompts:ee,resources:re,savedRequests:S,connections:r,onNavigate:B,onServerSelect:O}),d.jsx(XB,{connection:w&&r.find(F=>F.id===w)||null,open:w!==null,onOpenChange:F=>{F||_(null)},onConnect:U})]})})}function f0e(){const[e,t]=v.useState("processing"),[n,r]=v.useState("");return v.useEffect(()=>{console.log("[OAuthCallback] Component mounted, handling authorization..."),console.log("[OAuthCallback] Current URL:",window.location.href),D_().then(()=>{console.log("[OAuthCallback] Authorization successful"),t("success")}).catch(a=>{console.error("[OAuthCallback] Authorization failed:",a),t("error"),r(a instanceof Error?a.message:String(a))})},[]),e==="processing"?d.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:d.jsxs("div",{className:"flex flex-col items-center gap-4",children:[d.jsx(Li,{className:"h-8 w-8 animate-spin text-zinc-600 dark:text-zinc-400"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Completing authentication..."})]})}):e==="error"?d.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:d.jsxs("div",{className:"max-w-md p-6",children:[d.jsx("h1",{className:"text-xl font-semibold text-red-600 dark:text-red-400 mb-2",children:"Authentication Error"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400 mb-4",children:n}),d.jsx("p",{className:"text-xs text-zinc-500 dark:text-zinc-500",children:"You can close this window and try again."})]})}):d.jsx("div",{className:"h-screen w-full flex items-center justify-center bg-white dark:bg-zinc-900",children:d.jsxs("div",{className:"max-w-md p-6",children:[d.jsx("h1",{className:"text-xl font-semibold text-green-600 dark:text-green-400 mb-2",children:"Authentication Successful!"}),d.jsx("p",{className:"text-sm text-zinc-600 dark:text-zinc-400",children:"Redirecting you back..."})]})})}var p0e=(e,t,n,r,a,s,i,c)=>{let u=document.documentElement,f=["light","dark"];function m(y){(Array.isArray(e)?e:[e]).forEach(x=>{let E=x==="class",w=E&&s?a.map(_=>s[_]||_):a;E?(u.classList.remove(...w),u.classList.add(s&&s[y]?s[y]:y)):u.setAttribute(x,y)}),h(y)}function h(y){c&&f.includes(y)&&(u.style.colorScheme=y)}function g(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)m(r);else try{let y=localStorage.getItem(t)||n,x=i&&y==="system"?g():y;m(x)}catch{}},m0e=v.createContext(void 0),h0e={setTheme:e=>{},themes:[]},g0e=()=>{var e;return(e=v.useContext(m0e))!=null?e:h0e};v.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:a,defaultTheme:s,value:i,themes:c,nonce:u,scriptProps:f})=>{let m=JSON.stringify([n,t,s,e,c,i,r,a]).slice(1,-1);return v.createElement("script",{...f,suppressHydrationWarning:!0,nonce:typeof window>"u"?u:"",dangerouslySetInnerHTML:{__html:`(${p0e.toString()})(${m})`}})});function b0e({...e}){const{theme:t="system"}=g0e();return d.jsx(rB,{theme:t,className:"toaster group",style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)"},...e})}function y0e(){return d.jsx(Bbe,{children:d.jsx(kse,{children:d.jsxs(_me,{children:[d.jsx(Tee,{basename:"/inspector",children:d.jsxs(nee,{children:[d.jsx(Ix,{path:"/oauth/callback",element:d.jsx(f0e,{})}),d.jsx(Ix,{path:"/",element:d.jsx(d0e,{children:d.jsx(Sme,{})})})]})}),d.jsx(b0e,{position:"top-center"})]})})})}const Sz=new URLSearchParams(window.location.search);if(Sz.has("code")||Sz.has("error"))try{D_()}catch(e){console.error("[inspector] OAuth callback error:",e)}const _z=document.getElementById("root");_z?dQ.createRoot(_z).render(d.jsx(y0e,{})):console.error("[inspector] Root element not found");export{tK as $,Ue as A,de as B,uZ as C,Bn as D,Dn as E,vn as F,Be as G,s2 as H,B2 as I,Wg as J,Uo as K,Ej as L,Cz as M,YJ as N,HJ as O,D_ as P,VG as Q,ce as R,jz as T,AG as V,WJ as W,Fn as Z,Pe as _,rr as a,id as b,fd as c,S0e as d,w0e as e,Rh as f,jp as g,WG as h,_0e as i,$i as j,MK as k,jW as l,WW as m,n7 as n,o7 as o,x0e as p,LK as q,v as r,MW as s,E0e as t,XG as u,Ai as v,zY as w,fb as x,BG as y,ve as z};