@mcp-use/inspector 20.3.15-canary.0 → 20.3.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app/inspector.css.gz +0 -0
- package/dist/app/inspector.js.gz +0 -0
- package/dist/cli.js +12 -12
- package/dist/client/index.js +1 -1
- package/dist/server/index.js +9 -9
- package/package.json +6 -6
package/dist/client/index.js
CHANGED
|
@@ -198,7 +198,7 @@ void main(){
|
|
|
198
198
|
color=mix(color,grainOC,.35*grainOS);
|
|
199
199
|
opacity+=.5*grainOS;
|
|
200
200
|
fragColor=vec4(color,clamp(opacity,0.,1.));
|
|
201
|
-
}`;function MT(e){return[parseInt(e.slice(1,3),16)/255,parseInt(e.slice(3,5),16)/255,parseInt(e.slice(5,7),16)/255,1]}function Yl({className:e,colors:t=["#e0eaff","#f9ffbd","#dedede","#ffffff"],distortion:n=.8,swirl:o=.1,grainMixer:r=0,grainOverlay:s=.2,speed:a=1}){let i=Au(null),c=Au(null),l=Au({colors:t,distortion:n,swirl:o,grainMixer:r,grainOverlay:s,speed:a});return l.current={colors:t,distortion:n,swirl:o,grainMixer:r,grainOverlay:s,speed:a},kT(()=>{let u=i.current,p=c.current;if(!u||!p)return;let d=u.getContext("webgl2");if(!d)return;let h=(H,Y)=>{let U=d.createShader(H);return U?(d.shaderSource(U,Y),d.compileShader(U),d.getShaderParameter(U,d.COMPILE_STATUS)?U:(console.error(d.getShaderInfoLog(U)),null)):null},m=h(d.VERTEX_SHADER,PT),b=h(d.FRAGMENT_SHADER,RT);if(!m||!b)return;let f=d.createProgram();if(!f)return;if(d.attachShader(f,m),d.attachShader(f,b),d.linkProgram(f),!d.getProgramParameter(f,d.LINK_STATUS)){console.error(d.getProgramInfoLog(f));return}d.useProgram(f);let v=d.getAttribLocation(f,"a_position"),x=d.createBuffer();d.bindBuffer(d.ARRAY_BUFFER,x),d.bufferData(d.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),d.STATIC_DRAW),d.enableVertexAttribArray(v),d.vertexAttribPointer(v,2,d.FLOAT,!1,0,0);let y=d.getUniformLocation(f,"u_time"),g=d.getUniformLocation(f,"u_resolution"),C=[0,1,2,3].map(H=>d.getUniformLocation(f,`u_colors[${H}]`)),k=d.getUniformLocation(f,"u_colorsCount"),I=d.getUniformLocation(f,"u_distortion"),M=d.getUniformLocation(f,"u_swirl"),N=d.getUniformLocation(f,"u_grainMixer"),E=d.getUniformLocation(f,"u_grainOverlay"),T=0,S=performance.now(),P=0,A=()=>{let H=Math.min(2,window.devicePixelRatio||1);u.width=Math.floor(p.clientWidth*H),u.height=Math.floor(p.clientHeight*H),d.viewport(0,0,u.width,u.height)},R=H=>{if(document.hidden){S=H,P=requestAnimationFrame(R);return}let{colors:Y,distortion:U,swirl:V,grainMixer:K,grainOverlay:$,speed:G}=l.current,te=H-S;S=H,T+=te*G;let Z=Y.map(MT);d.uniform1f(y,T*.001),d.uniform2f(g,u.width,u.height);for(let z=0;z<4;z++){let F=C[z];F&&d.uniform4fv(F,Z[z]??[1,1,1,1])}d.uniform1f(k,Z.length),d.uniform1f(I,U),d.uniform1f(M,V),d.uniform1f(N,K),d.uniform1f(E,$),d.drawArrays(d.TRIANGLES,0,6),P=requestAnimationFrame(R)};A();let W=new ResizeObserver(A);return W.observe(p),P=requestAnimationFrame(R),()=>{cancelAnimationFrame(P),W.disconnect()}},[]),Wh("div",{ref:c,className:e,children:Wh("canvas",{ref:i,className:"h-full w-full","aria-hidden":!0})})}var IT=["#e0eaff","#f9ffbd","#dedede","#ffffff"],ET=["#27272a","#9a9448","#3f3f46","#18181b"];function Xl(e){return e==="dark"?ET:IT}import{useCallback as AT,useState as LT}from"react";import{Play as DT,Square as _T}from"lucide-react";import{jsx as Bs,jsxs as BT}from"react/jsx-runtime";var Kh="mcp-inspector-chat-mesh-animation-paused";function OT(e){try{return localStorage.getItem(e)==="true"}catch{return!1}}function Jh(e){let[t,n]=LT(()=>OT(e)),o=AT(()=>{n(r=>{let s=!r;try{localStorage.setItem(e,s?"true":"false")}catch{}return s})},[e]);return{paused:t,toggle:o}}var zT="z-50 flex h-7 w-7 cursor-pointer items-center justify-center rounded-full border border-zinc-500/60 bg-transparent text-zinc-600 transition-colors hover:border-zinc-500 hover:text-zinc-800 dark:border-zinc-500/50 dark:text-zinc-400 dark:hover:border-zinc-400 dark:hover:text-zinc-200";function Gh({paused:e,onToggle:t,className:n}){return BT(Ie,{children:[Bs(Re,{render:Bs("button",{type:"button",onClick:t,"aria-label":e?"Resume animation":"Pause animation",className:w(zT,n),children:e?Bs(DT,{className:"ml-px h-3 w-3",fill:"currentColor"}):Bs(_T,{className:"h-2.5 w-2.5",fill:"currentColor"})}),nativeButton:!0}),Bs(Me,{side:"left",children:Bs("p",{children:e?"Resume animation":"Pause animation"})})]})}import{jsx as Ya,jsxs as Qh}from"react/jsx-runtime";var FT=.54,$T=.4,Xh="linear-gradient(to top, black 0%, black 12%, rgba(0,0,0,0.55) 38%, transparent 100%)";function Zh({className:e,children:t,shaderPhase:n="hidden",onShaderFadeComplete:o,meshAnimationPaused:r=!1,...s}){let a=HT(null),[i,c]=UT(!1),{resolvedTheme:l}=go(),u=Xl(l),p=l==="dark",{paused:d,toggle:h}=Jh(Kh),m=d||r;Yh(()=>{let x=window.requestAnimationFrame(()=>c(!0));return()=>window.cancelAnimationFrame(x)},[]),Yh(()=>{n==="fading"&&!i&&o?.()},[n,i,o]);let b=n!=="hidden",f=n==="visible"&&i,v=x=>{x.propertyName==="opacity"&&n==="fading"&&o?.()};return Qh("div",{ref:a,className:w("relative flex min-h-0 flex-1 flex-col overflow-hidden bg-background",e),...s,children:[b&&Ya("div",{className:w("pointer-events-none absolute inset-x-0 bottom-0 z-0 transition-opacity duration-500",f?"opacity-100":"opacity-0"),style:{height:`${FT*100}%`},"aria-hidden":!0,onTransitionEnd:v,children:Qh("div",{className:w("absolute inset-0",i?p?"opacity-90":"opacity-75":"opacity-0"),style:{maskImage:Xh,WebkitMaskImage:Xh},children:[Ya("div",{className:"absolute inset-0 bg-[#edf2ff] dark:hidden"}),Ya(Yl,{className:"absolute inset-0 h-full w-full",colors:[...u],distortion:.8,swirl:.1,grainMixer:0,grainOverlay:p?.12:.3,speed:m?0:$T})]})}),b&&Ya(Gh,{paused:d,onToggle:h,className:"absolute bottom-3 right-3 sm:bottom-5 sm:right-5"}),Ya("div",{className:"relative z-10 flex min-h-0 flex-1 flex-col",children:t})]})}function ev(e){return e?e.apiKey==="server-managed"||e.baseUrl?.includes("/inspector/llm")===!0:!1}function Xa(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes("failed to fetch")||t.includes("networkerror")||t.includes("network request failed")||t.includes("load failed")}function Lu(e,t){if(!t)return e>=502&&e<=504?{kind:"cloud_unavailable"}:null;if(e===402)return{kind:"credits_exhausted",billingUrl:typeof t.upgradeUrl=="string"?t.upgradeUrl:typeof t.billingUrl=="string"?t.billingUrl:void 0,message:typeof t.message=="string"?t.message:"You've used your included free plan credits."};if(e===429){if(t.loginRequired&&t.loginUrl)return{kind:"login_required",loginUrl:String(t.loginUrl)};if(t.creditsExhausted)return{kind:"credits_exhausted",billingUrl:typeof t.billingUrl=="string"?t.billingUrl:void 0,message:typeof t.message=="string"?t.message:"You've used your included free plan credits."};if(t.error==="free_org_rate_limited"||typeof t.reason=="string")return{kind:"credits_exhausted",message:typeof t.message=="string"?t.message:"You've reached your included chat quota for this workspace."}}return e>=502&&e<=504?{kind:"cloud_unavailable"}:null}function VT(e){let t=e.match(/^OpenAI request failed \((\d+) /);if(!t)return null;let n=Number(t[1]),o=e.indexOf("{");if(o===-1)return null;try{let r=JSON.parse(e.slice(o));if(r&&typeof r=="object"&&!Array.isArray(r))return{status:n,body:r}}catch{}return null}function tv(e){if(e instanceof Error&&e.name==="LlmRequestError"){let t=e.status??0,n=e.body,o=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return Lu(t,o)}if(e instanceof Error){let t=VT(e.message);if(t)return Lu(t.status,t.body)}return Xa(e)?{kind:"cloud_unavailable"}:null}function nv(e,t){return Lu(e,t)}import{useCallback as Ql,useEffect as jT,useSyncExternalStore as qT}from"react";var Hu="openid profile email offline_access",rv="mcp-inspector:manufact-auth",WT="manufact:session-changed",Qa={loaded:!0,authorizing:!1,accessToken:null,user:null,mode:null},Zr=new Map,zu=new Set,Du=new Map,_u=new Map,sv=null,Ou=!1;typeof window<"u"&&window.addEventListener("message",e=>{if(e.data?.type!=="manufact:invalidate-oauth-client")return;for(let n of Zr.keys())Gn()?.removeItem(Pn(n,"client"));let t=sv;!t||Ou||(Ou=!0,uv(t,{isRetry:!0}).finally(()=>{Ou=!1}))});function KT(e){let t=Zr.get(e);if(t)return t;let n={...Qa,loaded:!1};return Zr.set(e,n),n}function Gn(){return typeof window>"u"?null:window.localStorage}function tc(e){return new URL(e).origin}function JT(e,t){let n=new URL(e),o=new URL(t),r=new Set(["localhost","127.0.0.1"]);return r.has(n.hostname)&&r.has(o.hostname)?n.origin===o.origin:(n.hostname==="manufact.com"||n.hostname.endsWith(".manufact.com"))&&(o.hostname==="manufact.com"||o.hostname.endsWith(".manufact.com"))}function av(e){let t=window.__MANUFACT_LOGIN_URL__;if(t)return new URL(t).origin;let n=new URL(e);return n.hostname==="localhost"||n.hostname==="127.0.0.1"?`${n.protocol}//${n.hostname}:3000`:`${n.protocol}//manufact.com`}function GT(e){return`${av(e)}/auth/embedded-sign-out`}function Pn(e,t){return`${rv}:${t}:${e}`}function YT(e){return Gn()?.getItem(Pn(e,"skip-session"))==="1"}function ec(e,t){let n=Pn(e,"skip-session");t?Gn()?.setItem(n,"1"):Gn()?.removeItem(n)}function XT(e){return`${rv}:state:${e}`}function Hs(e){let t=Gn()?.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return Gn()?.removeItem(e),null}}function Uu(e,t){Gn()?.setItem(e,JSON.stringify(t))}function xo(e,t){Zr.set(e,{...Zr.get(e)??Qa,...t}),zu.forEach(n=>n()),window.dispatchEvent(new CustomEvent(WT))}function iv(e){let t="";return e.forEach(n=>{t+=String.fromCharCode(n)}),btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Bu(e=32){let t=new Uint8Array(e);return crypto.getRandomValues(t),iv(t)}async function lv(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return iv(new Uint8Array(t))}async function nc(e){let t=await fetch(`${e}/api/auth/.well-known/openid-configuration`);if(!t.ok)throw new Error("Manufact OAuth discovery failed");return await t.json()}function cv(){return`${window.location.origin}${Yo()}/auth/callback`}function ov(e){return e==="localhost"||e==="127.0.0.1"}function QT(e){try{let t=new URL(e).hostname,n=typeof window<"u"?new URL(window.location.href).hostname:"";return ov(t)&&ov(n)}catch{return!1}}async function ZT(e,t,n){let o=new URL(`${e}/api/auth/oauth2/authorize`);o.searchParams.set("response_type","code"),o.searchParams.set("client_id",t),o.searchParams.set("redirect_uri",n),o.searchParams.set("scope",Hu),o.searchParams.set("code_challenge",await lv(Bu(32))),o.searchParams.set("code_challenge_method","S256"),o.searchParams.set("state","client-probe"),o.searchParams.set("prompt","none");try{let r=await fetch(o.toString(),{method:"GET",redirect:"manual",credentials:"include"}),s=r.headers.get("location")??"";return s.includes("/auth/error")&&s.includes("invalid_client")?!1:r.status>=300&&r.status<400||r.type==="opaqueredirect"?!!s&&!s.includes("/auth/error"):!0}catch{return!1}}async function ek(e,t){let n=cv(),o=Pn(e,"client"),r=Hs(o),s=QT(e);if(!s&&r?.client_id&&r.redirect_uri===n){if(await ZT(e,r.client_id,n))return r;Gn()?.removeItem(o)}else s&&r?.client_id&&Gn()?.removeItem(o);if(!t.registration_endpoint)throw new Error("Manufact OAuth registration is unavailable");let a=await fetch(t.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"mcp-use Inspector",redirect_uris:[n],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",scope:Hu})});if(!a.ok)throw new Error("Could not register Inspector with Manufact");let i=await a.json();if(!i.client_id)throw new Error("Manufact returned no OAuth client ID");let c={...i,redirect_uri:n};return Uu(o,c),c}async function tk(e,t){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t)}),o=await n.json().catch(()=>({}));if(!n.ok||!o.access_token)throw new Error(o.error_description??"Manufact token exchange failed");return{access_token:o.access_token,refresh_token:o.refresh_token,token_type:o.token_type,expires_at:Date.now()+(o.expires_in??3600)*1e3}}async function nk(e,t){if(!t.refresh_token)return null;let n=_u.get(e);if(n)return n;let o=(async()=>{try{let r=await nc(e),s=Hs(Pn(e,"client"));if(!s?.client_id)return null;let a=await tk(r.token_endpoint,{grant_type:"refresh_token",refresh_token:t.refresh_token,client_id:s.client_id}),i={...a,refresh_token:a.refresh_token??t.refresh_token};return Uu(Pn(e,"tokens"),i),i}catch{return Gn()?.removeItem(Pn(e,"tokens")),null}finally{_u.delete(e)}})();return _u.set(e,o),o}async function ok(e){let t=Hs(Pn(e,"tokens"));return t?.access_token?t.expires_at>Date.now()+3e4?t:nk(e,t):null}async function rk(e,t){let n=await nc(e);if(!n.userinfo_endpoint)return null;let o=await fetch(n.userinfo_endpoint,{headers:{Authorization:`Bearer ${t}`}});if(!o.ok)return null;let r=await o.json();return r.sub?{id:r.sub,name:r.name,email:r.email,image:r.picture}:null}async function dv(e){try{let t=await fetch(`${e}/api/auth/get-session`,{credentials:"include"});return t.ok?(await t.json())?.user??null:null}catch{return null}}async function Zl(e){let t=Du.get(e);if(t)return t;Zr.set(e,{...Zr.get(e)??Qa,loaded:!1});let n=(async()=>{try{let o=typeof window<"u"?window.location.href:e,r=JT(o,e),s=YT(e),a=await ok(e),i=a?await rk(e,a.access_token):null;if(i&&a){ec(e,!1),xo(e,{loaded:!0,accessToken:a.access_token,user:i,mode:"oauth"});return}a&&!i&&Gn()?.removeItem(Pn(e,"tokens"));let c=r&&!s?await dv(e):null;if(c){xo(e,{loaded:!0,accessToken:null,user:c,mode:"session"});return}xo(e,{loaded:!0,accessToken:null,user:null,mode:null})}catch{xo(e,{loaded:!0,accessToken:null,user:null,mode:null})}})().finally(()=>Du.delete(e));return Du.set(e,n),n}async function uv(e,t){let n=tc(e);sv=e,ec(n,!1);let o=window.open("","manufact-oauth","width=600,height=700,resizable=yes,scrollbars=yes");if(!o)throw new Error("Allow popups to sign in with Manufact");xo(n,{authorizing:!0});try{let r=await nc(n),s=await ek(n,r),a=Bu(64),i=Bu(),c=cv();Uu(XT(i),{authOrigin:n,clientId:s.client_id,redirectUri:c,codeVerifier:a,expiresAt:Date.now()+600*1e3});let l=new URL(r.authorization_endpoint);l.searchParams.set("response_type","code"),l.searchParams.set("client_id",s.client_id),l.searchParams.set("redirect_uri",c),l.searchParams.set("scope",Hu),l.searchParams.set("state",i),l.searchParams.set("code_challenge",await lv(a)),l.searchParams.set("code_challenge_method","S256"),l.searchParams.set("prompt","consent"),o.location.href=l.toString();let u=window.setInterval(()=>{o.closed&&(window.clearInterval(u),Zl(n).finally(()=>xo(n,{authorizing:!1})))},500)}catch(r){throw o.close(),xo(n,{authorizing:!1}),r}}function sk(e){let t=tc(e);Gn()?.removeItem(Pn(t,"tokens")),xo(t,{loaded:!0,authorizing:!1,accessToken:null,user:null,mode:null})}async function ak(e){let t=Hs(Pn(e,"tokens")),n=Hs(Pn(e,"client")),o=t?.refresh_token??t?.access_token;if(!n?.client_id||!o)return null;try{let s=(await nc(e)).revocation_endpoint??`${e}/api/auth/oauth2/revoke`;return(await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n.client_id,token:o,token_type_hint:t?.refresh_token?"refresh_token":"access_token"})})).status}catch{return-1}}async function ik(e){let t=av(e),n=window.open(GT(e),"manufact-sign-out","width=420,height=320");return n?new Promise(o=>{let r=!1,s=l=>{r||(r=!0,window.clearTimeout(a),window.clearInterval(c),window.removeEventListener("message",i),o(l))},a=window.setTimeout(()=>{s({attempted:!0,signOutOk:!1,signOutStatus:null})},3e4),i=l=>{l.origin===t&&l.data?.type==="manufact:sign-out-complete"&&s({attempted:!0,signOutOk:!0,signOutStatus:200})},c=window.setInterval(()=>{n.closed&&dv(e).then(l=>{s({attempted:!0,signOutOk:!l,signOutStatus:l?401:200})})},500);window.addEventListener("message",i)}):{attempted:!0,signOutOk:!1,signOutStatus:null}}async function lk(e,t){let n=tc(e),o=!!Hs(Pn(n,"tokens"))?.access_token;t==="oauth"||o?(await ak(n),ec(n,!0)):t==="session"&&(await ik(n),ec(n,!1)),sk(e)}function mv(e){let t=e?tc(e):null,n=Ql(s=>(zu.add(s),()=>zu.delete(s)),[]),o=Ql(()=>t?KT(t):Qa,[t]),r=qT(n,o,()=>Qa);return jT(()=>{if(!t)return;Zl(t);let s=i=>{i.origin===window.location.origin&&i.data?.type==="manufact:oauth-complete"&&i.data.authOrigin===t&&Zl(t).finally(()=>xo(t,{authorizing:!1}))},a=i=>{i.key!==Pn(t,"tokens")||!i.newValue||Zl(t).finally(()=>xo(t,{authorizing:!1}))};return window.addEventListener("message",s),window.addEventListener("storage",a),()=>{window.removeEventListener("message",s),window.removeEventListener("storage",a)}},[t]),{...r,authorize:Ql(async()=>{e&&await uv(e)},[e]),logout:Ql(async()=>{e&&await lk(e,r.mode)},[e,r.mode])}}function pv(e){return mv(e)}import{useEffect as ck}from"react";function fv(e){ck(()=>{let t=n=>{let o=n.target,r=o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.contentEditable==="true";if((n.metaKey||n.ctrlKey)&&n.key==="k"){n.preventDefault(),e.onCommandPalette?.();return}if((n.metaKey||n.ctrlKey)&&n.key==="o"&&e.onNewChat){n.preventDefault(),e.onNewChat();return}if(n.key==="Escape"){n.preventDefault(),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),e.onBlurSearch?.();return}if(!r&&!(n.metaKey||n.ctrlKey||n.altKey||n.shiftKey))switch(n.key.toLowerCase()){case"t":n.preventDefault(),e.onToolsTab?.();break;case"p":n.preventDefault(),e.onPromptsTab?.();break;case"r":n.preventDefault(),e.onResourcesTab?.();break;case"c":n.preventDefault(),e.onChatTab?.();break;case"h":n.preventDefault(),e.onHome?.();break;case"f":n.preventDefault(),e.onFocusSearch?.();break;default:break}};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[e])}import{Copy as Wk,Download as Kk,SquarePen as Jk}from"lucide-react";import{Check as Sv,ChevronsUpDown as Nv,Eye as Pk,EyeOff as Rk,Key as Mk,Loader2 as Tv}from"lucide-react";import{useEffect as Yu,useRef as Ik,useState as ts}from"react";import{Tabs as Vu}from"@base-ui/react/tabs";import{AnimatePresence as ju,motion as oc}from"motion/react";import{createContext as pk,forwardRef as Ku,useCallback as $u,useContext as fk,useEffect as qu,useRef as rc,useState as gk}from"react";import{useCallback as Us,useEffect as Fu,useRef as Fs,useState as gv}from"react";function hv(e,t){let n=e.getBoundingClientRect(),o=t==="x"?e.offsetWidth:e.offsetHeight,r=t==="x"?n.width:n.height;return o>0?r/o:1}function dk(e,t){let n=e.getBoundingClientRect(),o=hv(e,"x"),r=hv(e,"y"),s=[];return t.forEach((a,i)=>{let c=a.getBoundingClientRect();s[i]={top:(c.top-n.top)/r+e.scrollTop,left:(c.left-n.left)/o+e.scrollLeft,width:a.offsetWidth,height:a.offsetHeight}}),s}function uk(e,t,n,o){let r=o==="x"?t:n,s=null,a=1/0,i=null;return e.forEach((c,l)=>{let u=c.getBoundingClientRect(),p=o==="x"?u.left:u.top,d=o==="x"?u.right:u.bottom;r>=p&&r<=d&&(i=l);let h=(p+d)/2,m=Math.abs(r-h);m<a&&(a=m,s=l)}),i??s}function mk(e,t){if(e.length!==t.length)return!0;for(let n=0;n<t.length;n++){let o=e[n],r=t[n];if(o!==r&&(!o||!r||o.top!==r.top||o.left!==r.left||o.width!==r.width||o.height!==r.height))return!0}return!1}function vv(e,t={}){let{axis:n="y"}=t,o=Fs(new Map),[r,s]=gv(null),[a,i]=gv([]),c=Fs([]),l=Fs(0),u=Fs(null),p=Fs(null),d=Fs(null),h=Us(()=>{let y=e.current;if(!y)return;let g=dk(y,o.current);mk(c.current,g)&&(c.current=g,i(g))},[e]),m=Us((y,g)=>{s(uk(o.current,y,g,n))},[n]),b=Us((y,g)=>{g?o.current.set(y,g):o.current.delete(y),p.current!==null&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{p.current=null,h()})},[h]),f=Us(y=>{d.current={x:y.clientX,y:y.clientY},u.current!==null&&cancelAnimationFrame(u.current),u.current=requestAnimationFrame(()=>{u.current=null,h(),m(y.clientX,y.clientY)})},[h,m]),v=Us(()=>{l.current+=1},[]),x=Us(()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),d.current=null,s(null)},[]);return Fu(()=>{let y=e.current;if(!y||typeof ResizeObserver>"u")return;let g=new ResizeObserver(()=>{p.current!==null&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{p.current=null,h()})});return g.observe(y),()=>g.disconnect()},[e,h]),Fu(()=>{let y=e.current;if(!y)return;let g=()=>{h();let C=d.current;C&&m(C.x,C.y)};return y.addEventListener("scroll",g,{capture:!0,passive:!0}),()=>y.removeEventListener("scroll",g,{capture:!0})},[e,h,m]),Fu(()=>()=>{u.current!==null&&cancelAnimationFrame(u.current),p.current!==null&&cancelAnimationFrame(p.current)},[]),{activeIndex:r,setActiveIndex:s,itemRects:a,sessionRef:l,handlers:{onMouseMove:f,onMouseEnter:v,onMouseLeave:x},registerItem:b,measureItems:h}}import{jsx as On,jsxs as Wu}from"react/jsx-runtime";var bv=pk(null);function hk(){let e=fk(bv);if(!e)throw new Error("useTabsSubtle must be used within a TabsSubtle");return e}var Za=Ku(({children:e,selectedIndex:t,onSelect:n,idPrefix:o,activeLabel:r=!1,className:s,...a},i)=>{let c=rc(null),l=rc(!1),u=kt(),{activeIndex:p,setActiveIndex:d,itemRects:h,handlers:m,registerItem:b,measureItems:f}=vv(c,{axis:"x"}),v=rc(new Map),x=$u((S,P)=>{b(S,P),P?v.current.set(S,P):v.current.delete(S)},[b]);qu(()=>{f()},[f,e]),qu(()=>{let S=v.current;if(S.size===0)return;let P=new ResizeObserver(()=>f());return S.forEach(A=>P.observe(A)),()=>P.disconnect()},[f,e]);let y=$u(S=>{l.current=!0,m.onMouseMove(S)},[m]),g=$u(()=>{l.current=!1,m.onMouseLeave()},[m]),[C,k]=gk(null),I=h[t],M=p!==null?h[p]:null,N=C!==null?h[C]:null,E=p===t,T=p!==null&&!E;return On(bv.Provider,{value:{registerTab:x,hoveredIndex:p,selectedIndex:t,idPrefix:o,activeLabel:r},children:On(Vu.Root,{value:t,onValueChange:S=>{typeof S=="number"&&n(S)},render:Wu(Vu.List,{activateOnFocus:!1,ref:S=>{c.current=S,typeof i=="function"?i(S):i&&(i.current=S)},onMouseMove:y,onMouseLeave:g,onFocus:S=>{let P=S.target.closest("[data-proximity-index]")?.getAttribute("data-proximity-index");if(P!=null){let A=Number(P);d(A),k(S.target.matches(":focus-visible")?A:null)}},onBlur:S=>{c.current?.contains(S.relatedTarget)||(k(null),!l.current&&d(null))},className:w("relative flex items-center gap-0.5 select-none overflow-x-auto max-w-full -mx-1 px-1 -my-1 py-1",s),...a,children:[I&&On(oc.div,{className:w("absolute bg-accent pointer-events-none",u.bg),initial:!1,animate:{left:I.left,width:I.width,top:I.top,height:I.height,opacity:T?.8:1},transition:{...ce.moderate,opacity:{duration:.08}}}),On(ju,{children:M&&!E&&I&&On(oc.div,{className:w("absolute bg-accent pointer-events-none",u.bg),initial:{left:I.left,width:I.width,top:I.top,height:I.height,opacity:0},animate:{left:M.left,width:M.width,top:M.top,height:M.height,opacity:.4},exit:!l.current&&I?{left:I.left,width:I.width,top:I.top,height:I.height,opacity:0,transition:{...ce.moderate,opacity:{duration:.06}}}:{opacity:0,transition:ce.fast.exit},transition:{...ce.fast,opacity:{duration:.08}}})}),On(ju,{children:N&&On(oc.div,{className:w("absolute pointer-events-none z-20 border border-[color:var(--focus-ring,#6B97FF)]",u.focusRing),initial:!1,animate:{left:N.left-2,top:N.top-2,width:N.width+4,height:N.height+4},exit:{opacity:0,transition:ce.fast.exit},transition:{...ce.fast,opacity:{duration:.08}}})}),e]})})})});Za.displayName="TabsSubtle";var es=Ku(({icon:e,label:t,index:n,className:o,...r},s)=>{let a=rc(null),i=kt(),{registerTab:c,hoveredIndex:l,selectedIndex:u,idPrefix:p,activeLabel:d}=hk();qu(()=>(c(n,a.current),()=>c(n,null)),[n,c]);let h=u===n,m=l===n||h,b=d&&!!e,f=!b||h,v=Wu("span",{className:"inline-grid",children:[On("span",{className:"col-start-1 row-start-1 invisible [text-box:trim-both_cap_alphabetic]",style:{fontVariationSettings:At.semibold},"aria-hidden":"true",children:t}),On("span",{className:w("col-start-1 row-start-1 transition-[color,font-variation-settings] duration-80 [text-box:trim-both_cap_alphabetic]",m?"text-foreground":"text-muted-foreground"),style:{fontVariationSettings:h?At.semibold:At.normal},children:t})]});return Wu(Vu.Tab,{ref:x=>{let y=x;a.current=y,typeof s=="function"?s(y):s&&(s.current=y)},value:n,"data-proximity-index":n,id:p?`${p}-tab-${n}`:void 0,"aria-controls":p?`${p}-panel-${n}`:void 0,"aria-label":b&&!f?t:void 0,className:w("relative z-10 flex items-center px-2 cursor-pointer bg-transparent border-none outline-none text-xs",b?"h-7":"h-7 gap-1.5",i.bg,o),...r,children:[e&&On(e,{size:14,strokeWidth:m?2:1.5,className:w("shrink-0 transition-[color,stroke-width] duration-80",m?"text-foreground":"text-muted-foreground")}),b?On(ju,{children:f&&On(oc.span,{className:"overflow-hidden",initial:{width:0,opacity:0,marginLeft:0},animate:{width:"auto",opacity:1,marginLeft:6},exit:{width:0,opacity:0,marginLeft:0},transition:{...ce.fast,opacity:{duration:.06}},children:v},"label")}):v]})});es.displayName="TabsSubtleItem";var vk=Ku(({index:e,selectedIndex:t,idPrefix:n,children:o,className:r,...s},a)=>{let i=t===e;return On("div",{ref:a,id:`${n}-panel-${e}`,role:"tabpanel","aria-labelledby":`${n}-tab-${e}`,hidden:!i,tabIndex:-1,className:w("outline-none",r),...s,children:i&&o})});vk.displayName="TabsSubtlePanel";import*as Ut from"react";import{jsx as hr,jsxs as yk}from"react/jsx-runtime";var yv=Ut.createContext(null);function Ju(){let e=Ut.useContext(yv);if(!e)throw new Error("Command components must be used within <Command>");return e}function bk(e,t){return t?e.toLowerCase().includes(t.toLowerCase()):!0}var sc=Ut.forwardRef(({className:e,...t},n)=>{let[o,r]=Ut.useState(""),[s,a]=Ut.useState(null),[i,c]=Ut.useState(0),l=Ut.useCallback(()=>(c(u=>u+1),()=>c(u=>Math.max(0,u-1))),[]);return hr(yv.Provider,{value:{search:o,setSearch:r,activeValue:s,setActiveValue:a,visibleCount:i,registerVisible:l},children:hr("div",{ref:n,className:w("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})})});sc.displayName="Command";var ac=Ut.forwardRef(({className:e,...t},n)=>{let{search:o,setSearch:r}=Ju();return hr("div",{className:"flex items-center border-b px-3",children:hr("input",{ref:n,value:o,onChange:s=>r(s.target.value),className:w("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})})});ac.displayName="CommandInput";var ic=Ut.forwardRef(({className:e,...t},n)=>hr("div",{ref:n,className:w("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));ic.displayName="CommandList";var lc=Ut.forwardRef(({className:e,...t},n)=>{let{visibleCount:o}=Ju();return o>0?null:hr("div",{ref:n,className:w("py-6 text-center text-sm",e),...t})});lc.displayName="CommandEmpty";var cc=Ut.forwardRef(({className:e,heading:t,children:n,...o},r)=>yk("div",{ref:r,className:w("overflow-hidden p-1 text-foreground [&_[data-command-group-heading]]:px-2 [&_[data-command-group-heading]]:py-1.5 [&_[data-command-group-heading]]:text-xs [&_[data-command-group-heading]]:font-medium [&_[data-command-group-heading]]:text-muted-foreground",e),...o,children:[t?hr("div",{"data-command-group-heading":"",children:t}):null,n]}));cc.displayName="CommandGroup";var dc=Ut.forwardRef(({className:e,value:t,keywords:n,onSelect:o,disabled:r,onClick:s,...a},i)=>{let{search:c,activeValue:l,setActiveValue:u,registerVisible:p}=Ju(),d=Array.isArray(n)?n.join(" "):n,h=d?`${t} ${d}`:t,m=bk(h,c),b=l===t;return Ut.useLayoutEffect(()=>{if(m)return p()},[m,p]),Ut.useEffect(()=>{m&&l===null&&!r&&u(t)},[m,l,r,u,t]),m?hr("div",{ref:i,role:"option","aria-selected":b,"data-selected":b,"data-disabled":r,className:w("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",e),onMouseEnter:()=>!r&&u(t),onClick:f=>{s?.(f),r||o?.(t)},...a}):null});dc.displayName="CommandItem";import{buildOllamaApiUrl as Ek,normalizeOllamaBaseUrl as Ak,OllamaCorsError as Lk}from"@mcp-use/agent";import{ChevronDown as xk,Key as wk}from"lucide-react";import{jsx as Yn,jsxs as Gu}from"react/jsx-runtime";var Ck="https://cdn.mcp-use.com/mcpuse_logo_circle_dark.svg";function xv({symbolSize:e=14,className:t,textClassName:n}){return Gu("span",{className:w("inline-flex items-center gap-1.5 text-black dark:text-white",t),children:[Yn(Sk,{size:e}),Yn("span",{className:w("font-medium leading-none text-current [font-family:var(--font-family-outfit)]",n),children:"Manufact"})]})}function Sk({size:e=14,className:t}){return Gu("svg",{width:e,height:e,viewBox:"0 0 480 480","aria-hidden":!0,className:w("block shrink-0",t),children:[Yn("path",{d:"M101.7 0 C157.9 0 203.4 45.7 203.4 102.1 C203.4 126.6 202.1 152.1 212.2 174.3 L219.8 191 C233.8 221.8 258.5 246.4 289.2 260.5 L303.5 267 C326.5 277.5 353 275.8 378.3 275.8 C434.5 275.8 480 321.5 480 377.9 C480 434.3 434.5 480 378.3 480 C322.1 480 276.6 434.3 276.6 377.9 C276.6 354.2 277.7 329.6 267.8 308 L259.8 290.3 C245.7 259.5 221 234.8 190.2 220.7 L173 212.9 C151 202.9 125.8 204.2 101.7 204.2 C45.5 204.2 0 158.5 0 102.1 C0 45.7 45.5 0 101.7 0 Z",fill:"currentColor"}),Yn("circle",{cx:"96.4",cy:"383.6",r:"96.4",fill:"currentColor"}),Yn("circle",{cx:"383.6",cy:"96.4",r:"96.4",fill:"currentColor"})]})}var Nk='<svg width="512" height="512" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg" fill="#94A3B8" stroke="#94A3B8"><g><path fill="none" d="M3 248.945C18 248.945 76 236 106 219C136 202 136 202 198 158C276.497 102.293 332 120.945 423 120.945" stroke-width="90"/><path d="M511 121.5L357.25 210.268L357.25 32.7324L511 121.5Z"/><path fill="none" d="M0 249C15 249 73 261.945 103 278.945C133 295.945 133 295.945 195 339.945C273.497 395.652 329 377 420 377" stroke-width="90"/><path d="M508 376.445L354.25 287.678L354.25 465.213L508 376.445Z"/></g></svg>',Tk=`data:image/svg+xml,${encodeURIComponent(Nk)}`,wv={openai:"OpenAI",anthropic:"Anthropic",google:"Google",deepseek:"DeepSeek","z-ai":"Z.AI",nvidia:"NVIDIA",minimax:"MiniMax",moonshotai:"Moonshot AI",inclusionai:"InclusionAI","nex-agi":"Nex AGI","x-ai":"xAI",thinkingmachines:"Thinking Machines",mistralai:"Mistral AI",stepfun:"StepFun","aion-labs":"Aion Labs","bytedance-seed":"ByteDance Seed","ibm-granite":"IBM Granite","arcee-ai":"Arcee AI",rekaai:"Reka AI",kwaipilot:"KwaiPilot"};function uc(e,t){let n=e.trim(),o=wv[t];if(o){let s=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${s}\\s*:\\s*`,"i"),i=n.replace(a,"").trim();if(i.length>0)return i}let r=n.indexOf(": ");return r>0&&r<48?n.slice(r+2).trim():n}function Cv({provider:e,model:t,displayName:n,managedModel:o,mode:r="byok",className:s,...a}){let i=r==="managed"?o:null,c=i?uc(i.name,i.provider):n??t,l=i?i.provider:r==="managed"&&e==="openai-compatible"&&t.split("/")[0]||e;return Gu("button",{type:"button",className:w("inline-flex items-center gap-1.5 min-w-0 border-0 bg-transparent p-1","font-mono text-[11px] text-muted-foreground cursor-pointer","hover:text-foreground transition-colors","rounded-md outline-none focus-visible:ring-1 focus-visible:ring-ring",s),...a,children:[r==="managed"?Yn("img",{src:Ck,alt:"Manufact",className:"h-3.5 w-3.5 shrink-0 rounded-full object-cover"}):Yn(wk,{className:"size-3 shrink-0 opacity-70","aria-hidden":!0}),Yn(so,{provider:l,className:"shrink-0"}),Yn("span",{className:"whitespace-nowrap",children:c}),Yn(xk,{className:"size-3 shrink-0 opacity-60","aria-hidden":!0})]})}function qt(e){let t=wv[e];if(t)return t;switch(e){case"openai":return"OpenAI";case"openai-compatible":return"OpenAI Compatible";case"anthropic":return"Anthropic";case"google":return"Google";case"openrouter":return"OpenRouter";case"ollama":return"Ollama";default:return e.split(/[-_]/).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}}function kk(e,t){switch(e){case"openai":case"anthropic":case"google":return ma(`${e}.png`);case"ollama":return ma(`${t==="dark"?"ollama_dark":"ollama_light"}.png`);case"openrouter":return Tk;case"openai-compatible":return null;default:return null}}function so({provider:e,className:t}){let{resolvedTheme:n}=go();if(e==="openai-compatible")return null;let o=kk(e,n);if(o){let r=e==="ollama"?"h-3.5 w-3.5 object-contain":"h-4 w-4 rounded-full object-cover";return Yn("img",{src:o,alt:qt(e),className:w(r,t)})}return Yn("div",{"aria-label":qt(e),className:w("flex h-4 w-4 items-center justify-center rounded-full bg-neutral-900 text-[9px] font-semibold text-white dark:bg-neutral-100 dark:text-neutral-900",t),children:qt(e).charAt(0)})}import{Fragment as qk,jsx as ee,jsxs as $e}from"react/jsx-runtime";var Xu="mcp-inspector-models-cache",Dk=1440*60*1e3;function Pv(){try{let e=localStorage.getItem(Xu);if(e)return JSON.parse(e)}catch(e){console.error("Failed to load models cache:",e)}return{}}function _k(e,t){try{let n=Pv();n[e]={models:t,timestamp:Date.now()},localStorage.setItem(Xu,JSON.stringify(n))}catch(n){console.error("Failed to save models cache:",n)}}function Ok(e){try{let t=Pv(),n=t[e];if(n){if(Date.now()-n.timestamp<Dk)return n.models;delete t[e],localStorage.setItem(Xu,JSON.stringify(t))}}catch(t){console.error("Failed to get cached models:",t)}return null}function zk(e,t){if(!_o(e)||!t?.trim())return e;let n=e==="ollama"?Ak(t):t.trim().toLowerCase();return`${e}:${n}`}var Bk="chat-config-source",kv=["openai","anthropic","google"];async function Hk(e,t){let n={};t&&(n.Authorization=`Bearer ${t}`);let o;try{o=await fetch(`${e}/models`,{headers:n})}catch{throw new Error("Failed to reach the server. Check the URL is correct and that CORS is enabled on the server.")}if(!o.ok)throw new Error(`Failed to fetch models: ${o.statusText}`);if(!(o.headers.get("content-type")??"").includes("application/json"))throw new Error("Invalid URL \u2014 response was not JSON");let s=await o.json();if(!Array.isArray(s?.data))throw new Error("Unexpected response format \u2014 expected { data: [...] } from the OpenAI-compatible endpoint");return s.data.map(a=>({id:a.id}))}async function Uk(e){let t=await fetch("https://api.openai.com/v1/models",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw new Error(`Failed to fetch OpenAI models: ${t.statusText}`);return(await t.json()).data.map(o=>({id:o.id}))}async function Fk(e){let t=await fetch("https://api.anthropic.com/v1/models",{headers:{"x-api-key":e,"anthropic-version":"2023-06-01","anthropic-dangerous-direct-browser-access":"true"}});if(!t.ok)throw new Error(`Failed to fetch Anthropic models: ${t.statusText}`);return(await t.json()).data.map(o=>({id:o.id,displayName:o.display_name}))}async function $k(e){let t=await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${e}`);if(!t.ok)throw new Error(`Failed to fetch Google models: ${t.statusText}`);return((await t.json()).models||[]).map(o=>({id:o.name,displayName:o.displayName}))}async function Vk(e){let t=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw new Error(`Failed to fetch OpenRouter models: ${t.statusText}`);return(await t.json()).data.map(o=>({id:o.id,displayName:o.name}))}async function jk(e,t){let n;try{n=await fetch(Ek(e,"/api/tags"),{headers:{...t.trim()?{Authorization:`Bearer ${t.trim()}`}:{}}})}catch(r){throw new Lk(r)}if(!n.ok)throw new Error(`Failed to fetch Ollama models: ${n.statusText}`);return((await n.json()).models||[]).map(r=>({id:r.model||r.name||""}))}function ei({open:e,onOpenChange:t,tempProvider:n,tempModel:o,tempApiKey:r,tempBaseUrl:s,onProviderChange:a,onModelChange:i,onApiKeyChange:c,onBaseUrlChange:l,onSave:u,onClear:p,showClearButton:d=!1,buttonLabel:h="Configure API Key",hostedInspector:m=!1,freeTierInfo:b,managedCloudInfo:f,useManagedCloud:v=!1,onSaveManagedCloud:x}){let{resolvedTheme:y}=go(),g=Xl(y),C=y==="dark",[k,I]=ts([]),[M,N]=ts(!1),[E,T]=ts(null),[S,P]=ts(!1),[A,R]=ts(!1),[W,H]=ts(!1),[Y,U]=ts(v?0:1),V=zk(n,s),K=!!(m||b||f),$=!!(f&&Y===0);Yu(()=>{e&&U(v?0:1)},[e,v]),Yu(()=>{let D=Kr(n),_=_o(n);if($||!e||!n||D&&!r.trim()||_&&!s.trim()){I([]),T(null);return}let Le=setTimeout(async()=>{let Oe=Ok(V);if(Oe){I(Oe),T(null);return}N(!0),T(null);try{let He=[];n==="openai-compatible"?He=await Hk(s,r):n==="openai"?He=await Uk(r):n==="anthropic"?He=await Fk(r):n==="google"?He=await $k(r):n==="openrouter"?He=await Vk(r):n==="ollama"&&(He=await jk(s,r)),_k(V,He),I(He)}catch(He){T(He instanceof Error?He.message:"Failed to fetch models. Please check your API key."),I([])}finally{N(!1)}},500);return()=>clearTimeout(Le)},[r,s,n,e,V,$]);let G=Ik(null);Yu(()=>{if(!e||$){e||(G.current=null);return}let D=G.current;D!==null&&D!==n&&i(""),G.current=n},[n,e,i,$]);let te=_o(n),Z=!Kr(n),z=e&&(!Kr(n)||!!r.trim())&&(!te||!!s.trim()),F=Z?"API Key (optional)":"API Key",ie=Z?n==="ollama"?"Leave empty for local Ollama":"Enter your API key (optional)":"Enter your API key",le=n==="openai-compatible"?"http://localhost:11434/v1":dr(n),Ne=n==="openai-compatible"?"Base URL of your OpenAI-compatible API. Local servers must have CORS enabled.":null,de=n==="ollama"?"Optional for local Ollama. Stored locally and never sent to our servers.":"Your API key is stored locally and never sent to our servers.",re=f?f.models.reduce((D,_)=>(D[_.provider]||(D[_.provider]=[]),D[_.provider].push(_),D),{}):{},me=f?.models.find(D=>D.id===f.selectedModelId),be=kv.filter(D=>re[D]?.length),pe=me?.provider??be[0]??"",We=!!me&&!kv.includes(me.provider),Ke=pe?re[pe]??[]:[],Ve=!!p&&d&&(!f||Y===1),pt=()=>{if($&&x){x();return}u()},lt=$?!!(f?.isLoading||!f?.selectedModelId||f?.models.length===0):Kr(n)&&!r.trim()||te&&!s.trim()||!o.trim();return ee(on,{open:e,onOpenChange:t,children:$e(Xt,{className:"max-w-md","data-testid":"chat-config-dialog",children:[$e(Gt,{children:[ee($t,{children:K?"Configure Chat":"LLM Provider Configuration"}),ee(To,{children:f?"Pick a Manufact cloud model or bring your own API key.":b?"Chat requires an LLM. You can chat for free if you have a Manufact account, or you can use your own API key (not sent to Manufact).":"Configure your LLM provider and API key to start chatting with the MCP server"})]}),$e("div",{className:"space-y-4",children:[b&&$e("button",{type:"button",onClick:b.onLoginClick,"data-testid":"chat-config-sign-in-card",className:"relative w-full cursor-pointer overflow-hidden rounded-2xl border-0 text-left transition-opacity hover:opacity-95 active:opacity-90",children:[ee("div",{className:"absolute inset-0 bg-[#edf2ff] dark:bg-background","aria-hidden":!0}),ee("div",{className:"absolute inset-0 dark:opacity-90",children:ee(Yl,{className:"absolute inset-0 h-full w-full",colors:[...g],grainOverlay:C?.1:.15})}),$e("div",{className:"relative flex items-center justify-between gap-4 px-4 py-3.5",children:[$e("div",{className:"text-sm font-medium text-foreground",children:[ee("p",{children:"Chat for free with a"}),$e("p",{className:"mt-1 flex items-center gap-1.5",children:[ee(xv,{symbolSize:14,textClassName:"text-sm"}),"account"]})]}),ee(L,{size:"sm",render:ee("span",{"aria-hidden":"true"}),nativeButton:!1,tabIndex:-1,className:"pointer-events-none shrink-0",children:"Sign in"})]})]}),f&&ee("div",{className:"flex justify-center",children:$e(Za,{selectedIndex:Y,onSelect:U,idPrefix:Bk,className:"w-fit",children:[ee(es,{index:0,label:"Manufact cloud"}),ee(es,{index:1,label:"API key"})]})}),$e("div",{className:w("space-y-2",f&&"!mt-2"),children:[ee(Be,{children:"Provider"}),$?$e(un,{value:pe,onValueChange:D=>{let _=f?.models.find(j=>j.provider===D);_&&f?.onModelChange(_.id)},children:[ee(hn,{className:"rounded-md",leading:pe?ee(so,{provider:pe,className:"shrink-0"}):void 0,children:ee(fn,{})}),$e(gn,{children:[We&&$e(ht,{value:pe,label:qt(pe),disabled:!0,children:[qt(pe)," (current)"]}),be.map(D=>ee(ht,{value:D,label:qt(D),children:$e("div",{className:"flex items-center gap-2",children:[ee(so,{provider:D}),ee("span",{children:qt(D)})]})},D))]})]}):$e(un,{value:n,onValueChange:D=>a(D),children:[ee(hn,{className:"rounded-md",leading:ee(so,{provider:n,className:"shrink-0"}),children:ee(fn,{})}),$e(gn,{children:[ee(ht,{value:"openai",label:qt("openai"),children:$e("div",{className:"flex items-center gap-2",children:[ee(so,{provider:"openai"}),ee("span",{children:qt("openai")})]})}),ee(ht,{value:"anthropic",label:qt("anthropic"),children:$e("div",{className:"flex items-center gap-2",children:[ee(so,{provider:"anthropic"}),ee("span",{children:qt("anthropic")})]})}),ee(ht,{value:"google",label:qt("google"),children:$e("div",{className:"flex items-center gap-2",children:[ee(so,{provider:"google"}),ee("span",{children:qt("google")})]})}),ee(ht,{value:"ollama",label:qt("ollama"),children:$e("div",{className:"flex items-center gap-2",children:[ee(so,{provider:"ollama"}),ee("span",{children:qt("ollama")})]})}),ee(ht,{value:"openrouter",label:qt("openrouter"),children:$e("div",{className:"flex items-center gap-2",children:[ee(so,{provider:"openrouter"}),ee("span",{children:qt("openrouter")})]})}),ee(ht,{value:"openai-compatible",label:qt("openai-compatible"),children:ee("div",{className:"flex items-center gap-2",children:ee("span",{children:qt("openai-compatible")})})})]})]})]}),!$&&te&&$e("div",{className:"space-y-2",children:[ee(Be,{children:"Base URL"}),ee(Ae,{value:s,onChange:D=>l(D.target.value),placeholder:le,"data-testid":"chat-config-base-url-input"}),Ne&&ee("p",{className:"text-xs text-muted-foreground",children:Ne})]}),!$&&$e("div",{className:"space-y-2",children:[ee(Be,{children:F}),$e("div",{className:"relative",children:[ee(Ae,{type:W?"text":"password",value:r,onChange:D=>c(D.target.value),placeholder:ie,className:"pr-10","data-testid":"chat-config-api-key-input"}),ee(L,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>H(!W),children:W?ee(Rk,{className:"h-4 w-4 text-muted-foreground"}):ee(Pk,{className:"h-4 w-4 text-muted-foreground"})})]}),ee("p",{className:"text-xs text-muted-foreground",children:de})]}),$?$e("div",{className:"space-y-2",children:[ee(Be,{children:"Model"}),f?.isLoading?$e("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[ee(Tv,{className:"h-4 w-4 animate-spin"}),ee("span",{children:"Loading models\u2026"})]}):Ke.length>0?$e(rr,{open:A,modal:!0,onOpenChange:R,children:[ee(sr,{render:$e(L,{variant:"outline",role:"combobox","aria-expanded":A,className:"w-full justify-between rounded-md","data-testid":"chat-config-cloud-model-select",disabled:We,children:[ee("span",{className:"inline-flex min-w-0 items-center gap-2 truncate",children:me?$e(qk,{children:[ee(so,{provider:me.provider,className:"shrink-0"}),ee("span",{className:"truncate",children:uc(me.name,me.provider)})]}):"Select a model\u2026"}),ee(Nv,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]}),nativeButton:!0}),ee(ar,{className:"w-full p-0",align:"start",children:$e(sc,{children:[ee(ac,{placeholder:"Search models\u2026",className:"h-9"}),$e(ic,{children:[ee(lc,{children:"No model found."}),ee(cc,{children:Ke.map(D=>$e(dc,{value:D.id,keywords:[D.name,D.id,D.provider],onSelect:_=>{f?.onModelChange(_),R(!1)},children:[uc(D.name,D.provider),ee(Sv,{className:w("ml-auto h-4 w-4",f?.selectedModelId===D.id?"opacity-100":"opacity-0")})]},D.id))})]})]})})]}):ee("p",{className:"text-sm text-muted-foreground",children:"Cloud models unavailable \u2014 try again or use your own key."})]}):z&&$e("div",{className:"space-y-2",children:[ee(Be,{children:"Model"}),M?$e("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[ee(Tv,{className:"h-4 w-4 animate-spin"}),ee("span",{children:"Loading models..."})]}):E?ee("div",{className:"text-sm text-destructive",children:E}):k.length>0?$e(rr,{open:S,modal:!0,onOpenChange:P,children:[ee(sr,{render:$e(L,{variant:"outline",role:"combobox","aria-expanded":S,className:"w-full justify-between rounded-md","data-testid":"chat-config-model-select",children:[ee("span",{className:"truncate",children:o&&(k.find(D=>D.id===o)?.displayName||k.find(D=>D.id===o)?.id)||"Select a model..."}),ee(Nv,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]}),nativeButton:!0}),ee(ar,{className:"w-full p-0",align:"start",children:$e(sc,{children:[ee(ac,{placeholder:"Search models...",className:"h-9"}),$e(ic,{children:[ee(lc,{children:"No model found."}),ee(cc,{children:k.map(D=>$e(dc,{value:D.id,keywords:D.displayName,onSelect:_=>{i(_===o?"":_),P(!1)},children:[D.displayName||D.id,ee(Sv,{className:w("ml-auto h-4 w-4",o===D.id?"opacity-100":"opacity-0")})]},D.id))})]})]})})]}):ee(Ae,{value:o,onChange:D=>i(D.target.value),placeholder:"Enter model name manually","data-testid":"chat-config-model-input"})]}),$e("div",{className:"flex justify-between",children:[Ve&&ee(L,{variant:"outline",onClick:p,children:"Clear Config"}),$e(L,{onClick:pt,disabled:lt,className:Ve?"ml-auto":"","data-testid":"chat-config-save-button",children:[ee(Mk,{className:"h-4 w-4 mr-2"}),"Save Configuration"]})]})]})]})})}var Qu="rounded-full bg-background/80 backdrop-blur-md supports-[backdrop-filter]:bg-background/60 dark:bg-zinc-950/75 dark:supports-[backdrop-filter]:bg-zinc-950/55",Zu=w(Qu,"w-fit"),mc=w(Qu,"h-9 gap-1.5 px-3");import{jsx as Ft,jsxs as wo}from"react/jsx-runtime";var Gk="chat-view";function em({llmConfig:e,hasMessages:t,configDialogOpen:n,onConfigDialogOpenChange:o,onClearChat:r,tempProvider:s,tempModel:a,tempApiKey:i,tempBaseUrl:c,onProviderChange:l,onModelChange:u,onApiKeyChange:p,onBaseUrlChange:d,onSaveConfig:h,onClearConfig:m,hideConfigButton:b,hostedInspector:f,freeTierInfo:v,managedCloudInfo:x,useManagedCloud:y,onSaveManagedCloud:g,showClearButton:C,clearButtonLabel:k,hideTitle:I,clearButtonHideIcon:M,clearButtonHideShortcut:N,clearButtonVariant:E,hideClearButton:T,onCopyChat:S,onExportChat:P,activeChatId:A,chatTitle:R,showViewToggle:W,viewIndex:H=0,onViewIndexChange:Y,elevatedHeader:U}){return wo("div",{className:w("relative flex w-full items-center gap-2 overflow-visible",jo,U?"pointer-events-none absolute top-0 right-0 z-50":"absolute top-0 right-0 z-10"),children:[Ft("div",{className:w("flex min-w-0 flex-1 items-center",U&&"pointer-events-auto"),children:!I&&Ft("h2",{className:w(qo,Zu),children:A?Ft(Ka,{chatId:A,title:R??fr},A):fr})}),W&&Y&&Ft("div",{className:w("absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 overflow-visible px-1",U&&"pointer-events-auto"),children:wo(Za,{selectedIndex:H,onSelect:Y,idPrefix:Gk,className:"shrink-0 overflow-visible","data-testid":"chat-view-tabs",children:[Ft(es,{label:"Conv",index:0}),Ft(es,{label:"Raw",index:1})]})}),wo("div",{className:w("ml-auto flex shrink-0 items-center gap-2",U&&"pointer-events-auto"),children:[!T&&t&&wo("div",{className:"flex items-center gap-1",children:[S&&wo(L,{"data-testid":"chat-copy-button",variant:"ghost",size:"sm",className:mc,onClick:S,children:[Ft(Wk,{className:"h-4 w-4"}),Ft("span",{className:"hidden sm:inline",children:"Copy"})]}),P&&wo(Ir,{children:[Ft(Go,{render:wo(L,{"data-testid":"chat-export-button",variant:"ghost",size:"sm",className:mc,children:[Ft(Kk,{className:"h-4 w-4"}),Ft("span",{className:"hidden sm:inline",children:"Export"})]}),nativeButton:!0}),wo(Er,{align:"end",children:[Ft(Un,{"data-testid":"chat-export-json",onClick:()=>P("json"),children:"Export as JSON"}),Ft(Un,{"data-testid":"chat-export-markdown",onClick:()=>P("markdown"),children:"Export as Markdown"})]})]}),Ft("div",{className:"w-px h-4 bg-border mx-1"}),wo(Ie,{children:[Ft(Re,{render:wo(L,{variant:E??"default",size:"default",className:`p-2 cursor-pointer ${N?"sm:px-3":"sm:pr-1 sm:pl-3"}`,onClick:r,children:[!M&&Ft(Jk,{className:"h-4 w-4 sm:mr-2"}),Ft("span",{className:"hidden sm:inline",children:k??"New Chat"}),!N&&Ft("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:"\u2318O"})]}),nativeButton:!0}),Ft(Me,{children:Ft("p",{children:k??"New Chat"})})]})]}),(!b||f||v||x)&&Ft(ei,{open:n,onOpenChange:o,tempProvider:s,tempModel:a,tempApiKey:i,tempBaseUrl:c,onProviderChange:l,onModelChange:u,onApiKeyChange:p,onBaseUrlChange:d,onSave:h,onClear:m,showClearButton:C??(!!e&&!v&&!x),buttonLabel:e?"Change API Key":"Configure API Key",hostedInspector:f,freeTierInfo:v,managedCloudInfo:x,useManagedCloud:y,onSaveManagedCloud:g})]})]})}import{ArrowUp as AP,Loader2 as LP}from"lucide-react";import{Image as Zk,Paperclip as eP,X as tP}from"lucide-react";import{useRef as nP}from"react";import{Wrench as Yk}from"lucide-react";import{useCallback as Rv,useMemo as Xk,useState as Qk}from"react";import{jsx as Ho,jsxs as vr}from"react/jsx-runtime";function Mv({tools:e,disabledTools:t,onDisabledToolsChange:n,disabled:o}){let[r,s]=Qk(!1),a=e.length-t.size,i=t.size===0,c=t.size>0&&t.size<e.length,l=Rv(d=>{let h=new Set(t);h.has(d)?h.delete(d):h.add(d),n(h)},[t,n]),u=Rv(()=>{n(i?new Set(e.map(d=>d.name)):new Set)},[i,e,n]),p=Xk(()=>[...e].sort((d,h)=>d.name.localeCompare(h.name)),[e]);return e.length===0?null:vr(rr,{open:r,onOpenChange:s,children:[vr(Ie,{children:[Ho(Re,{render:Ho(sr,{render:vr(L,{variant:"ghost",size:"sm",disabled:o,className:w("h-auto gap-1 rounded-full px-2 py-2",c?"text-amber-500 dark:text-amber-400":"text-muted-foreground hover:text-foreground"),type:"button","data-testid":"chat-tool-selector",children:[Ho(Yk,{className:"h-4 w-4 shrink-0"}),c&&Ho("span",{className:"flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-amber-500 px-1 text-[9px] font-bold leading-none text-white",children:a})]}),nativeButton:!0}),nativeButton:!0}),Ho(Me,{side:"top",children:vr("p",{children:["Tools (",a,"/",e.length,")"]})})]}),vr(ar,{className:"w-72 gap-0 p-0",align:"start",side:"top",sideOffset:8,children:[vr("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[vr("span",{className:"text-xs font-medium text-muted-foreground",children:["Allowed Tools (",a,"/",e.length,")"]}),Ho(L,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:u,type:"button",children:i?"Disable All":"Enable All"})]}),Ho("div",{className:"max-h-64 overflow-y-auto",children:p.map(d=>{let h=!t.has(d.name);return vr("button",{type:"button",className:"flex items-center gap-2.5 w-full px-3 py-1.5 text-left hover:bg-accent/50 transition-colors cursor-pointer",onClick:()=>l(d.name),children:[Ho($a,{checked:h,className:"pointer-events-none",tabIndex:-1}),Ho("span",{className:"min-w-0 flex-1 truncate text-sm font-mono",children:d.name})]},d.name)})})]})]})}import{jsx as zn,jsxs as ti}from"react/jsx-runtime";function Iv({variant:e="default",inputValue:t,isConnected:n,isLoading:o,textareaRef:r,attachments:s,placeholder:a="Ask a question",className:i,showAttachButton:c=!0,tools:l,disabledTools:u,onDisabledToolsChange:p,onInputChange:d,onKeyDown:h,onKeyUp:m,onClick:b,onAttachmentAdd:f,onAttachmentRemove:v,inlineControls:x,trailingControls:y}){let g=kt(),C=nP(null),k=e==="fullscreen",I=N=>{let E=N.target.files;if(E&&E.length>0)for(let T=0;T<E.length;T++)f(E[T]);C.current&&(C.current.value="")},M=s.length>0;return ti("div",{className:"relative w-full","data-chat-input-variant":e,children:[!k&&M&&zn("div",{className:"absolute top-0 left-0 right-0 z-20 p-3 flex gap-2 flex-wrap",children:s.map((N,E)=>ti("div",{className:"relative group bg-zinc-100/90 dark:bg-zinc-900/90 backdrop-blur-sm rounded-lg p-2 flex items-center gap-2 border border-zinc-200 dark:border-zinc-700","data-testid":`chat-attachment-${E}`,children:[zn(Zk,{className:"h-4 w-4 text-muted-foreground shrink-0"}),ti("div",{className:"flex flex-col min-w-0",children:[zn("span",{className:"text-xs font-medium truncate max-w-[150px]",children:N.name||"Image"}),N.size&&zn("span",{className:"text-xs text-muted-foreground",children:Ng(N.size)})]}),zn("button",{onClick:()=>v(E),className:"shrink-0 p-1 rounded-full hover:bg-zinc-200 dark:hover:bg-zinc-800 transition-colors",title:"Remove attachment",type:"button","data-testid":`chat-attachment-remove-${E}`,children:zn(tP,{className:"h-3 w-3"})})]},E))}),zn(fo,{ref:r,value:t,onChange:N=>d(N.target.value),onKeyDown:h,onKeyUp:m,onClick:b,placeholder:n?a:"Server not connected",className:w(k?"field-sizing-fixed h-11 min-h-11 max-h-11 resize-none overflow-hidden py-2.5 pl-4 pr-12":"p-4 min-h-[150px] max-h-[300px]",g.container,!k&&M&&"pt-20",i),rows:k?1:void 0,disabled:!n||o,"data-testid":"chat-input"}),zn("input",{ref:C,type:"file",accept:"image/*",multiple:!0,onChange:I,className:"hidden","aria-label":"Upload images"}),k?y?zn("div",{className:"absolute right-1.5 top-1/2 flex -translate-y-1/2 items-center",children:y}):null:ti("div",{className:"absolute inset-x-0 bottom-0 flex items-center justify-between gap-2 p-3",children:[ti("div",{className:"flex min-w-0 flex-1 items-center gap-1",children:[c&&zn(L,{variant:"ghost",size:"sm",onClick:()=>C.current?.click(),disabled:!n||o,className:"h-auto w-auto aspect-square rounded-full p-2 text-muted-foreground hover:text-foreground",title:"Attach images",type:"button","data-testid":"chat-attach-button",children:zn(eP,{className:"h-4 w-4"})}),l&&l.length>0&&u&&p&&zn(Mv,{tools:l,disabledTools:u,onDisabledToolsChange:p,disabled:!n||o}),x]}),y?zn("div",{className:"flex shrink-0 items-center gap-1.5",children:y}):null]})]})}import{MessageSquare as oP,X as rP}from"lucide-react";import{jsx as ni,jsxs as sP}from"react/jsx-runtime";function Ev({promptResults:e,onDeletePromptResult:t,offsetForSkills:n=!1}){return ni("div",{className:`absolute ${n?"top-12":"top-4"} left-4 right-4 flex gap-2 overflow-x-auto z-20 flex-nowrap`,style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:e.map(({promptName:o},r)=>sP(L,{type:"button",className:"flex items-center gap-2 bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-[10px] px-1.5 py-0.5 dark:bg-zinc-700 rounded-lg border border-zinc-200 dark:border-zinc-300 font-medium hover:bg-zinc-300 dark:hover:bg-zinc-600",children:[ni(oP,{className:"h-3.5 w-3.5 shrink-0"}),ni("span",{className:"truncate",title:o,children:o}),ni("span",{className:"ml-1 h-4 w-4 rounded-full bg-zinc-400 dark:bg-zinc-600 hover:bg-zinc-500 dark:hover:bg-zinc-500 flex items-center justify-center cursor-pointer shrink-0 transition-colors",onClick:s=>{s.stopPropagation(),t(r)},title:"Remove prompt",role:"button",tabIndex:0,children:ni(rP,{className:"h-2.5 w-2.5 text-white"})})]},r))})}import{MessageSquare as aP}from"lucide-react";import{useEffect as iP}from"react";import{jsx as br,jsxs as pc}from"react/jsx-runtime";function Av({isOpen:e,focusedIndex:t,prompts:n,selectedPrompt:o,onPromptSelect:r}){return e?(iP(()=>{if(t>=0){let s=document.getElementById(`prompt-suggestion-${t}`);s&&s.scrollIntoView({behavior:"smooth",block:"nearest"})}},[t]),br("div",{className:"absolute bottom-full left-0 right-0 max-w-3xl w-full max-h-[300px] overflow-y-auto rounded-lg border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 shadow-lg z-30 flex flex-col gap-2 mb-1","data-testid":"chat-prompts-dropdown",children:pc("div",{className:"p-2",children:[n.length>0&&br("div",{className:"text-xs font-medium text-zinc-900 dark:text-zinc-100 mb-2",children:"Prompts"}),n.map((s,a)=>pc(Ie,{children:[br(Re,{render:pc(L,{id:`prompt-suggestion-${a}`,type:"button",variant:"ghost",className:w("w-full flex items-center px-3 py-2 rounded-md hover:bg-zinc-200 dark:hover:bg-zinc-700 transition-colors text-left justify-start",t===a&&"bg-zinc-200 dark:bg-zinc-700"),onClick:()=>r(s),"data-testid":`chat-prompt-option-${a}`,children:[br("div",{className:"flex items-center justify-center shrink-0",children:br(aP,{className:"h-4 w-4 text-zinc-600 dark:text-zinc-400"})}),br("div",{className:"flex-1 min-w-0",children:pc("div",{className:"text-sm font-medium text-zinc-900 dark:text-zinc-100 flex items-center gap-2",children:[s.name,o?.name===s.name&&br(An,{className:"size-3 text-zinc-600 dark:text-zinc-400"})]})})]}),nativeButton:!0}),br(Me,{children:s.description})]},a))]})})):null}import{motion as TP}from"motion/react";import{useMemo as Wv,useState as Kv}from"react";import{ExternalLink as NP}from"lucide-react";import{toast as Jv}from"sonner";import{forwardRef as hP,useCallback as Rn,useEffect as ao,useId as vP,useMemo as ri,useRef as Uo,useState as ns}from"react";import{AnimatePresence as js,motion as Co}from"motion/react";import{RadioGroup as bP}from"@base-ui/react/radio-group";import{Radio as yP}from"@base-ui/react/radio";import{CheckboxGroup as xP}from"@base-ui/react/checkbox-group";import{Checkbox as wP}from"@base-ui/react/checkbox";import{Field as sm}from"@base-ui/react/field";import{useEffect as rm,useLayoutEffect as lP,useRef as tm,useState as cP}from"react";import{AnimatePresence as dP,motion as uP}from"motion/react";import{jsx as Dv}from"react/jsx-runtime";var mP=typeof window<"u"?lP:rm,$s=ce.moderate,oi=.07,pP=($s.duration+oi)*1e3+80,fP=$s.duration*1e3+80;function nm(e,t){let n=t.filter(s=>s.start>=e.start&&s.end<=e.end).sort((s,a)=>s.start-a.start);if(n.length!==2)return null;let[o,r]=n;return r.start===o.end+2?{up:o,lo:r,gap:o.end+1}:null}function gP(e,t,n,o){let r=n[e],s=n[t];if(!r||!s)return null;if(o==="y")return{top:r.top,left:Math.min(r.left,s.left),width:Math.max(r.width,s.width),height:s.top+s.height-r.top};let a=Math.min(r.left,s.left),i=Math.max(r.left+r.width,s.left+s.width);return{top:Math.min(r.top,s.top),left:a,width:i-a,height:Math.max(r.height,s.height)}}function _v(e,t){return t==="y"?e.top+e.height/2:e.left+e.width/2}function fc(e,t){return t==="y"?[e,e,0,0]:[e,0,0,e]}function yr(e,t){return t==="y"?[0,0,e,e]:[0,e,e,0]}function om(e){return[e,e,e,e]}function Lv(e,t,n,o,r){let s=_v(n,o);if(o==="y"){let i=t.top+t.height;e.height=s-e.top,e.radii=fc(r,o),e.instant=!0,t.top=s,t.height=i-s,t.radii=yr(r,o),t.instant=!0,t.enterFrom={top:s,left:t.left,width:t.width,height:i-s,radii:yr(r,o)};return}let a=t.left+t.width;e.width=s-e.left,e.radii=fc(r,o),e.instant=!0,t.left=s,t.width=a-s,t.radii=yr(r,o),t.instant=!0,t.enterFrom={top:t.top,left:s,width:a-s,height:t.height,radii:yr(r,o)}}function Ov(e,t,n,o="y"){let[r,s]=cP([]),a=tm([]),i=tm(0),c=tm(new Map),l=e.map(d=>`${d.id}:${d.start}-${d.end}`).join("|");mP(()=>{let d=a.current,h=e,m=[];for(let f of h){let v=nm(f,d);v&&(f.id===v.up.id||f.id===v.lo.id)&&m.push({tid:++i.current,kind:"merge",survivorId:f.id,otherId:f.id===v.up.id?v.lo.id:v.up.id,gapIndex:v.gap,phase:"converge"})}for(let f of d){let v=nm(f,h);v&&m.push({tid:++i.current,kind:"split",survivorId:v.up.id,otherId:v.lo.id,gapIndex:v.gap,phase:"splitIn"})}a.current=h.map(f=>({...f}));for(let f of m)c.current.set(f.tid,setTimeout(()=>{c.current.delete(f.tid),s(v=>v.some(x=>x.tid===f.tid)?v.flatMap(x=>x.tid!==f.tid?[x]:x.kind==="merge"?[{...x,phase:"commit"}]:[]):v)},f.kind==="merge"?pP:fP));let b=f=>f.kind==="merge"?h.some(v=>v.id===f.survivorId&&f.gapIndex>v.start&&f.gapIndex<v.end):h.some(v=>v.id===f.survivorId&&v.end===f.gapIndex-1)&&h.some(v=>v.id===f.otherId&&v.start===f.gapIndex+1);s(f=>{for(let v of f){if(b(v))continue;let x=c.current.get(v.tid);x!==void 0&&(clearTimeout(x),c.current.delete(v.tid))}return[...f.filter(b),...m]})},[l]),rm(()=>{let d=c.current;return()=>d.forEach(clearTimeout)},[]),rm(()=>{r.some(d=>d.phase==="splitIn"||d.phase==="commit")&&s(d=>d.flatMap(h=>h.phase==="commit"?[]:[{...h,phase:h.phase==="splitIn"?"diverge":h.phase}]))},[r]);let u=[];for(let d of e){let h=gP(d.start,d.end,t,o);h&&u.push({key:`sel-${d.id}`,...h,radii:om(n),instant:!1,exitInstant:!1,delayCorners:!1})}let p=new Map(u.map(d=>[d.key,d]));for(let d of r){let h=t[d.gapIndex],m=p.get(`sel-${d.survivorId}`);if(!h||!m)continue;let b=_v(h,o);if(d.kind==="merge"){if(d.phase==="commit"){m.instant=!0,o==="y"?u.push({key:`sel-${d.otherId}`,top:b,left:m.left,width:m.width,height:m.top+m.height-b,radii:yr(n,o),instant:!0,exitInstant:!0,delayCorners:!1,opacity:0}):u.push({key:`sel-${d.otherId}`,top:m.top,left:b,width:m.left+m.width-b,height:m.height,radii:yr(n,o),instant:!0,exitInstant:!0,delayCorners:!1,opacity:0});continue}let f=Math.min(oi+.03,Math.max(oi,oi+b/Math.max(o==="y"?h.height:h.width,1)*.002));if(o==="y"){let v=m.top+m.height;m.height=b-m.top,m.radii=fc(n,o),m.delayCorners=!0,m.cornerDelay=f,u.push({key:`sel-${d.otherId}`,top:b,left:m.left,width:m.width,height:v-b,radii:yr(n,o),enterFrom:{top:b,left:m.left,width:m.width,height:v-b,radii:om(n)},instant:!1,exitInstant:!0,delayCorners:!0,cornerDelay:f})}else{let v=m.left+m.width;m.width=b-m.left,m.radii=fc(n,o),m.delayCorners=!0,m.cornerDelay=f,u.push({key:`sel-${d.otherId}`,top:m.top,left:b,width:v-b,height:m.height,radii:yr(n,o),enterFrom:{top:m.top,left:b,width:v-b,height:m.height,radii:om(n)},instant:!1,exitInstant:!0,delayCorners:!0,cornerDelay:f})}}else if(d.phase==="splitIn"){let f=p.get(`sel-${d.otherId}`);if(!f)continue;Lv(m,f,h,o,n)}}for(let d of a.current){let h=nm(d,e),m=h&&t[h.gap];if(!h||!m)continue;let b=p.get(`sel-${h.up.id}`),f=p.get(`sel-${h.lo.id}`);!b||!f||Lv(b,f,m,o,n)}return u}function zv({blocks:e,dimmed:t}){return Dv(dP,{children:e.map(n=>{let o=n.delayCorners?{...$s,delay:n.cornerDelay??oi}:$s,r=n.opacity??(t?.8:1);return Dv(uP.div,{"aria-hidden":!0,className:"absolute bg-active pointer-events-none",initial:n.enterFrom?{opacity:r,top:n.enterFrom.top,left:n.enterFrom.left,width:n.enterFrom.width,height:n.enterFrom.height,borderTopLeftRadius:n.enterFrom.radii[0],borderTopRightRadius:n.enterFrom.radii[1],borderBottomRightRadius:n.enterFrom.radii[2],borderBottomLeftRadius:n.enterFrom.radii[3]}:!1,animate:{top:n.top,left:n.left,width:n.width,height:n.height,borderTopLeftRadius:n.radii[0],borderTopRightRadius:n.radii[1],borderBottomRightRadius:n.radii[2],borderBottomLeftRadius:n.radii[3],opacity:r},exit:{opacity:0,transition:n.exitInstant?{duration:0}:$s.exit},transition:n.instant?{duration:0}:{...$s,borderTopLeftRadius:o,borderTopRightRadius:o,borderBottomRightRadius:o,borderBottomLeftRadius:o,opacity:{duration:.08}}},n.key)})})}import{Fragment as Hv,jsx as he,jsxs as an}from"react/jsx-runtime";function CP(e,t){return e.id??`q-${t}`}function gc(e,t){return e.id??`o-${t}`}var Vs=[],am=hP(function({questions:t,currentIndex:n,defaultCurrentIndex:o=0,onCurrentIndexChange:r,answers:s,defaultAnswers:a,onAnswersChange:i,onComplete:c,onSkip:l,skipLabel:u="Skip",intro:p,onCancel:d,cancelLabel:h="Cancel",footerLeading:m,className:b,...f},v){let[x,y]=ns(o),g=n!==void 0,C=g?n:x,k=Rn(O=>{g||y(O),r?.(O)},[g,r]),[I,M]=ns(a??{}),N=s!==void 0,E=N?s:I,T=Uo(E);ao(()=>{T.current=E},[E]);let S=Rn(O=>{let ne=O(T.current);return T.current=ne,N||M(ne),i?.(ne),ne},[N,i]),P=kt(),A=Tr("arrow-left"),R=Tr("arrow-right"),W=ri(()=>function(ne){return he(A,{...ne,className:w(ne.className,"hidden sm:block")})},[A]),H=ri(()=>function(ne){return he(R,{...ne,className:w(ne.className,"hidden sm:block")})},[R]),[Y]=ns(()=>{if(typeof navigator>"u")return!1;let O=navigator,ne=O.userAgentData?.platform||O.platform||"";return/mac/i.test(ne)}),U=vP(),V=t.length,K=Math.max(0,Math.min(C,Math.max(0,V-1))),$=t[K],G=$?CP($,K):"",te=E[G],Z=!!$?.multiSelect,z=$?.skippable!==!1,F=!!$?.freeText,ie=$?.freeTextMultiline!==!1,le=!F&&!!$?.allowOther,Ne=ri(()=>te?.selectedIds??[],[te]),de=te?.otherText??"",re=$?.options??[],me=le?re.length:-1,be=re.length+(le?1:0),pe=Uo(null),We=!!$;ao(()=>{if(!We)return;let O=pe.current;if(O)return Vs.push(O),()=>{let ne=Vs.indexOf(O);ne!==-1&&Vs.splice(ne,1)}},[We]);let Ke=Uo(null),Ve=Uo(null),pt=Uo(0),lt=Uo(new Map),{activeIndex:D,setActiveIndex:_,itemRects:j,sessionRef:Le,handlers:Oe,registerItem:He,measureItems:tt}=Rr(Ke);ao(()=>{tt()},[tt,G,be,P]);let[ln,Nt]=ns(!1);ao(()=>{Nt(!1)},[G]),ao(()=>{let O=Ve.current;if(!O)return;O.style.height="0px",O.style.height=`${O.scrollHeight}px`;let ne=parseFloat(window.getComputedStyle(O).lineHeight)||18;Nt(O.scrollHeight>ne*1.5),tt()},[de,tt,G]),ao(()=>{F&&Ve.current?.focus({preventScroll:!0})},[F,G]);let Ze=Uo(null),[cn,co]=ns("auto");ao(()=>{let O=Ze.current;if(!O)return;let ne=()=>co(O.offsetHeight);ne();let Ee=new ResizeObserver(ne);return Ee.observe(O),()=>Ee.disconnect()},[]);let[Pt,Kt]=ns(null),[Cn,Tt]=ns(null);ao(()=>{_(null),Kt(null),Tt(null)},[K,_]);let Yt=Uo(!1),oe=Rn(()=>{Ke.current?.contains(document.activeElement)&&(Yt.current=!0)},[]);ao(()=>{if(!Yt.current)return;Yt.current=!1,Ke.current?.querySelector('[data-proximity-index="0"]')?.focus()},[K]);let fe=Rn(O=>{K>=V-1?c?.(O):(oe(),k(K+1))},[K,V,c,k,oe]),Ue=Rn(O=>{if(!$)return;let ne=T.current[G]?.otherText,Ee=S(Ct=>({...Ct,[G]:{questionId:G,selectedIds:[O],otherText:ne||void 0,skipped:!1}}));fe(Ee)},[$,G,S,fe]),ft=Rn(O=>{$&&S(ne=>{let Ee=ne[G],Ct=new Set(Ee?.selectedIds??[]);return Ct.has(O)?Ct.delete(O):Ct.add(O),{...ne,[G]:{questionId:G,selectedIds:Array.from(Ct),otherText:Ee?.otherText,skipped:!1}}})},[$,G,S]),Rt=Rn(O=>{$&&S(ne=>({...ne,[G]:{questionId:G,selectedIds:O,otherText:ne[G]?.otherText,skipped:!1}}))},[$,G,S]),ue=Rn(O=>{$&&(Tt(null),S(ne=>({...ne,[G]:{questionId:G,selectedIds:ne[G]?.selectedIds??[],otherText:O,skipped:!1}})))},[$,G,S]),ve=Rn(()=>{if(!$)return;let O=(T.current[G]?.otherText??"").trim();if(!O)return;if($.freeText&&$.freeTextValidate){let Ee=$.freeTextValidate(O);if(Ee){Tt(Ee);return}}Tt(null);let ne=S(Ee=>({...Ee,[G]:{questionId:G,selectedIds:Ee[G]?.selectedIds??[],otherText:O,skipped:!1}}));fe(ne)},[$,G,S,fe]),mt=Rn(()=>{if(!$)return;let O=S(ne=>({...ne,[G]:{questionId:G,selectedIds:ne[G]?.selectedIds??[],otherText:ne[G]?.otherText,skipped:!0}}));l?.(G,K),fe(O)},[$,G,S,l,K,fe]),nt=Rn(()=>{d?.()},[d]),B=Rn(()=>{fe(E)},[fe,E]),se=Rn(()=>{K>0&&(oe(),k(K-1))},[K,k,oe]);ao(()=>{if(!$)return;let O=ne=>{if(ne.metaKey||ne.ctrlKey||ne.altKey)return;let Ee=ne.target;if(!Ee)return;let Ct=Ee.tagName;if(Ct==="INPUT"||Ct==="TEXTAREA"||Ee.isContentEditable)return;let It=pe.current;if(!It||!It.contains(Ee)&&(Vs.some(eo=>eo!==It&&eo.contains(Ee))||Vs[Vs.length-1]!==It))return;let St=ne.key;if(St<"1"||St>"9")return;let Et=parseInt(St,10)-1;if(Et>=0&&Et<re.length){ne.preventDefault();let eo=gc(re[Et],Et);Z?ft(eo):Ue(eo)}else Et===re.length&&le&&(ne.preventDefault(),Ve.current?.focus())};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[$,re,Z,le,Ue,ft]);let we=O=>{Ke.current?.querySelector(`[data-proximity-index="${O}"]`)?.focus()},Te=Rn(O=>{_(O),le&&O===me?Ve.current?.focus():we(O)},[le,me,_]),Ce=O=>{let ne=O.target,Ee=ne.tagName==="INPUT"||ne.tagName==="TEXTAREA"||ne.isContentEditable;if(Ee&&O.key!=="ArrowDown"&&O.key!=="ArrowUp")return;if(Ee&&(O.key==="ArrowUp"||O.key==="ArrowDown")&&ne.tagName==="TEXTAREA"){let It=ne;if(O.key==="ArrowUp"&&It.selectionStart>0||O.key==="ArrowDown"&&It.selectionEnd<It.value.length)return}let Ct=O.preventBaseUIHandler;if(O.key==="ArrowLeft"||O.key==="ArrowRight"){O.preventDefault(),O.stopPropagation(),Ct?.(),O.key==="ArrowLeft"?K>0&&se():z&&V>1&&mt();return}if(be!==0&&(O.key==="ArrowDown"||O.key==="ArrowUp"||O.key==="Home"||O.key==="End")){O.preventDefault(),O.stopPropagation(),Ct?.();let It;if(O.key==="Home")It=0;else if(O.key==="End")It=be-1;else{let St=Ee?me:D??-1;It=O.key==="ArrowDown"?St+1:St-1,It=(It+be)%be}Te(It)}},je=O=>{if(O.key!=="Enter"||!(Y?O.metaKey:O.ctrlKey)||!(Z||F))return;if(O.preventDefault(),F){de.trim().length>0&&ve();return}(Ne.length>0||de.trim().length>0)&&B()};if(!$)return he("div",{ref:v,className:w("w-full max-w-[520px] p-5 bg-card border border-border",P.container,b),...f,children:he("p",{className:"text-[13px] text-muted-foreground",children:"No questions."})});let Fe=D!==null?j[D]:null,rt=Pt!==null&&!(le&&Pt===me)?j[Pt]:null,ut=ri(()=>{let O=new Set;return re.forEach((ne,Ee)=>{Ne.includes(gc(ne,Ee))&&O.add(Ee)}),le&&de.length>0&&O.add(me),O},[re,Ne,le,de,me]),Mt=ri(()=>{let O=[],ne=[...ut].sort((St,Et)=>St-Et);for(let St of ne){let Et=O[O.length-1];Et&&St===Et.end+1?Et.end=St:O.push({start:St,end:St})}let Ee=new Set,Ct=new Map,It=O.map(St=>{let Et=null;for(let dn=St.start;dn<=St.end;dn++){let In=lt.current.get(dn);if(In!==void 0&&!Ee.has(In)){Et=In;break}}let eo=Et??++pt.current;Ee.add(eo);for(let dn=St.start;dn<=St.end;dn++)Ct.set(dn,eo);return{...St,id:eo}});return lt.current=Ct,It},[ut]),ls=D!==null&&!ut.has(D),Cr=Ov(Mt,j,P.bgRadius),Bn=V>1&&K>0,Mn=d!=null,Zn=!Mn&&V>1&&z,gt=Z||F,So=Bn||Zn||gt||Mn||m!=null,yi=re.findIndex((O,ne)=>Ne.includes(gc(O,ne))),xi=an("div",{ref:Ke,role:Z?"group":"radiogroup","aria-labelledby":`${U}-${G}-title`,onMouseEnter:Oe.onMouseEnter,onMouseMove:Oe.onMouseMove,onMouseLeave:Oe.onMouseLeave,onFocus:O=>{let ne=O.target.closest("[data-proximity-index]")?.getAttribute("data-proximity-index");if(ne!=null){let Ee=Number(ne);_(Ee),Kt(O.target.matches(":focus-visible")?Ee:null)}},onBlur:O=>{Ke.current?.contains(O.relatedTarget)||(Kt(null),_(null))},onKeyDown:Ce,className:"relative flex flex-col gap-0.5 -mx-3",children:[he(js,{children:(()=>{if(!le)return null;let O=j[me],ne=Pt===me&&de.length===0;return!O||!ne?null:he(Co.div,{"aria-hidden":!0,className:w("absolute pointer-events-none bg-card ring-1 ring-inset ring-border",P.bg),initial:{opacity:0,top:O.top,left:O.left,width:O.width,height:O.height},animate:{opacity:1,top:O.top,left:O.left,width:O.width,height:O.height},exit:{opacity:0,transition:ce.fast.exit},transition:{...ce.fast,opacity:{duration:.08}}},"other-input")})()}),he(js,{children:Fe&&he(Co.div,{"aria-hidden":!0,className:w("absolute pointer-events-none bg-hover",P.bg),initial:{opacity:0,top:Fe.top,left:Fe.left,width:Fe.width,height:Fe.height},animate:{opacity:1,top:Fe.top,left:Fe.left,width:Fe.width,height:Fe.height},exit:{opacity:0,transition:ce.fast.exit},transition:{...ce.fast,opacity:{duration:.08}}},`hover-${Le.current}`)}),he(zv,{blocks:Cr,dimmed:ls}),he(js,{children:rt&&he(Co.div,{"aria-hidden":!0,className:w("absolute pointer-events-none border border-[color:var(--focus-ring,#6B97FF)] z-20",P.focusRing),initial:{opacity:0,top:rt.top-2,left:rt.left-2,width:rt.width+4,height:rt.height+4},animate:{opacity:1,top:rt.top-2,left:rt.left-2,width:rt.width+4,height:rt.height+4},exit:{opacity:0,transition:ce.fast.exit},transition:{...ce.fast,opacity:{duration:.08}}})}),re.map((O,ne)=>{let Ee=gc(O,ne),Ct=Ne.includes(Ee),St=!Z&&D===ne;return he(Bv,{index:ne,registerItem:He,role:Z?"checkbox":"radio",isSelected:Ct,tabIndex:ne===yi||yi===-1&&ne===0?0:-1,onClick:()=>Z?ft(Ee):Ue(Ee),onKeyDown:Et=>{(Et.key===" "||Et.key==="Enter")&&!Et.metaKey&&!Et.ctrlKey&&(Et.preventDefault(),Z?ft(Ee):Ue(Ee))},shape:P,"aria-checked":Ct,chipContent:ne+1,chipFilled:Ct,isMulti:Z,showArrow:St,bodyLayout:$.layout==="stacked"?"stacked":"inline",topAlign:$.layout==="stacked",chipPosition:$.chipPosition??"right",arrowIcon:he(R,{size:14,strokeWidth:2,className:"h-3.5 w-3.5"}),hiddenControl:Z?he(wP.Root,{name:Ee,className:"sr-only",tabIndex:-1,"aria-hidden":!0}):he(yP.Root,{value:Ee,className:"sr-only",tabIndex:-1,"aria-hidden":!0}),children:$.layout==="stacked"?an(Hv,{children:[an("span",{className:"inline-grid",children:[he("span",{className:"col-start-1 row-start-1 invisible",style:{fontVariationSettings:At.semibold},"aria-hidden":"true",children:O.title}),he("span",{className:"col-start-1 row-start-1 text-foreground transition-[color,font-variation-settings] duration-80",style:{fontVariationSettings:Ct?At.semibold:At.medium},children:O.title})]}),O.description&&he("span",{className:"text-[12px] text-muted-foreground leading-snug",children:O.description})]}):an("span",{children:[an("span",{className:"inline-grid",children:[he("span",{className:"col-start-1 row-start-1 invisible",style:{fontVariationSettings:At.semibold},"aria-hidden":"true",children:O.title}),he("span",{className:"col-start-1 row-start-1 text-foreground transition-[color,font-variation-settings] duration-80",style:{fontVariationSettings:Ct?At.semibold:At.medium},children:O.title})]}),O.description&&an(Hv,{children:[" ",he("span",{className:"text-muted-foreground",children:O.description})]})]})},Ee)}),le&&he(Bv,{index:me,registerItem:He,role:null,isSelected:de.length>0,tabIndex:-1,onClick:()=>Ve.current?.focus(),shape:P,chipContent:me+1,chipFilled:de.length>0,isMulti:Z,topAlign:ln,chipPosition:$.chipPosition??"right",ariaLabel:$.otherPlaceholder??"Describe in your own words",showArrow:!Z&&(Pt===me||D===me)&&de.trim().length>0,arrowIcon:he(R,{size:14,strokeWidth:2,className:"h-3.5 w-3.5"}),onArrowClick:!Z&&de.trim().length>0?ve:void 0,children:he("span",{className:"inline-grid w-full",children:he("textarea",{ref:Ve,rows:1,value:de,placeholder:$.otherPlaceholder??"Describe in your own words\u2026","aria-label":$.otherPlaceholder??"Describe in your own words",onChange:O=>ue(O.target.value),onKeyDown:O=>{O.key==="Enter"&&(O.shiftKey||Z||(O.preventDefault(),ve()))},onClick:O=>O.stopPropagation(),className:w("col-start-1 row-start-1 block w-full bg-transparent border-0 p-0 m-0 outline-none resize-none overflow-hidden text-[13px] leading-snug text-foreground placeholder:text-muted-foreground"),style:{fontVariationSettings:At.medium}})})})]});return an("div",{ref:O=>{pe.current=O,typeof v=="function"?v(O):v&&(v.current=O)},className:w("relative w-full max-w-[520px] overflow-hidden bg-card border border-border",P.container,b),...f,onKeyDown:O=>{f.onKeyDown?.(O),je(O)},children:[he("div",{className:"flex items-center px-4 sm:px-5 pt-4 sm:pt-5 pb-2 text-[12px] text-muted-foreground",children:an("span",{children:["Question ",K+1," of ",V]})}),p!=null&&he("div",{className:"px-4 sm:px-5 pb-3 text-[13px] leading-snug text-muted-foreground",children:p}),an(sm.Root,{invalid:Cn!==null,className:"contents",children:[he(Co.div,{animate:{height:cn},initial:!1,transition:ce.slow,className:"overflow-hidden",children:he("div",{ref:Ze,className:w("px-4 sm:px-5",So?"pb-1":"pb-2.5 sm:pb-3"),children:an("div",{className:"flex flex-col gap-2",children:[he("h3",{id:`${U}-${G}-title`,className:"text-[16px] text-foreground leading-snug",style:{fontVariationSettings:At.semibold},children:$.title}),F?he("div",{onClick:()=>Ve.current?.focus(),className:w("relative mt-1 -mx-3 px-3 py-2.5 cursor-text transition-colors",ie?"min-h-[76px]":"min-h-10",P.bg,de.length>0?"bg-active":"hover:bg-hover focus-within:bg-card focus-within:ring-1 focus-within:ring-inset focus-within:ring-border"),children:he(sm.Control,{value:de,onValueChange:ue,render:he("textarea",{ref:Ve,rows:1,placeholder:$.freeTextPlaceholder??"Type your answer\u2026","aria-labelledby":`${U}-${G}-title`,onKeyDown:O=>{O.key==="Enter"&&(O.shiftKey||O.metaKey||O.ctrlKey||ie||(O.preventDefault(),ve()))},className:"block w-full bg-transparent border-0 p-0 m-0 outline-none resize-none overflow-hidden text-[13px] leading-snug text-foreground placeholder:text-muted-foreground",style:{fontVariationSettings:At.medium}})})}):Z?he(xP,{value:Ne,onValueChange:Rt,render:xi}):he(bP,{value:Ne[0]??null,onValueChange:O=>{typeof O=="string"&&Ue(O)},render:xi})]},G)})}),So&&he("div",{className:"px-4 sm:px-5 pt-1 pb-2",children:an("div",{className:"flex items-center justify-between gap-2 -mx-2 sm:-mx-3",children:[an("div",{className:"relative flex flex-1 min-w-0 items-center gap-2",children:[m!=null&&he("div",{className:"shrink-0 px-2 sm:px-3",children:m}),he(js,{mode:"popLayout",initial:!1,children:Bn&&he(Co.div,{layout:"position",initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.85},transition:{...ce.fast,opacity:{duration:.1}},children:he(L,{variant:"ghost",size:"sm",leadingIcon:W,onClick:se,className:"pl-3 sm:pl-[6px]",children:"Back"})},"back")}),Cn&&he(sm.Error,{match:!0,render:he(Co.p,{role:"alert",initial:{opacity:0,y:-2},animate:{opacity:1,y:0},transition:{...ce.fast,opacity:{duration:.12}},className:"min-w-0 px-2 sm:px-3 text-left text-[12px] leading-snug text-destructive"}),children:Cn},"ft-error")]}),he("div",{className:"relative flex items-center gap-2",children:an(js,{mode:"popLayout",initial:!1,children:[Mn&&he(Co.div,{layout:"position",initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.85},transition:{...ce.fast,opacity:{duration:.1}},children:he(L,{variant:"ghost",size:"sm",trailingIcon:H,onClick:nt,className:"pr-3 sm:pr-[6px]",children:h})},"cancel"),Zn&&he(Co.div,{layout:"position",initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.85},transition:{...ce.fast,opacity:{duration:.1}},children:he(L,{variant:"ghost",size:"sm",trailingIcon:H,onClick:mt,className:"pr-3 sm:pr-[6px]",children:u})},"skip"),gt&&he(Co.div,{layout:"position",initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.85},transition:{...ce.fast,opacity:{duration:.1}},children:he(L,{variant:"primary",size:"sm",onClick:F?ve:B,disabled:(F||Ne.length===0)&&de.trim().length===0,className:"pr-3 sm:pr-[6px]",children:an("span",{className:"inline-flex items-center gap-1.5",children:[$.nextLabel??(K>=V-1?"Finish":"Continue"),he("span",{className:"hidden sm:contents",children:an(SP,{shape:P,tone:"inverted",children:[Y?"\u2318":"\u2303","\u21B5"]})})]})})},"continue")]})})]})})]})]})});am.displayName="AskUserQuestions";function SP({children:e,tone:t="muted",shape:n}){return he("kbd",{"aria-hidden":!0,suppressHydrationWarning:!0,className:w("inline-flex items-center justify-center gap-0.5 px-1 min-w-[18px] h-[18px] text-[11px] leading-none font-sans tracking-wide",t==="inverted"?"bg-background/15 text-background":"bg-foreground/10 text-muted-foreground",n.bg),children:e})}function Bv({index:e,registerItem:t,role:n,isSelected:o,tabIndex:r,onClick:s,onKeyDown:a,shape:i,chipContent:c,chipFilled:l,isMulti:u,ariaLabel:p,showArrow:d,arrowIcon:h,onArrowClick:m,bodyLayout:b="inline",topAlign:f=!1,chipPosition:v="right",hiddenControl:x,children:y,...g}){let C=Uo(null);ao(()=>(t(e,C.current),()=>t(e,null)),[e,t]);let k=he(js,{children:d&&he(Co.span,{"aria-hidden":!m,role:m?"button":void 0,onClick:m?N=>{N.stopPropagation(),m()}:void 0,className:w("absolute inset-0 inline-flex items-center justify-center bg-foreground text-background",i.bg,m&&"cursor-pointer"),initial:{opacity:0,scale:.6},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.6,transition:ce.fast.exit},transition:{...ce.fast,opacity:{duration:.08}},children:h})}),I=an("span",{className:w("shrink-0 w-7 h-7 relative inline-flex items-center justify-center",f&&(b==="stacked"?"-mt-[1px]":"-mt-[5px]")),children:[he("span",{"aria-hidden":!0,className:w("absolute inline-flex items-center justify-center w-5 h-5 text-[11px] transition-[opacity,font-variation-settings] duration-80",u&&i.bg,u?l?"bg-foreground text-background":"border border-border text-muted-foreground":l?"text-foreground":"text-muted-foreground",v==="right"&&d&&"opacity-0"),style:{fontVariationSettings:l?At.semibold:At.medium},children:c}),v==="right"&&k]}),M=v==="left"&&!u&&he("span",{className:w("shrink-0 w-7 h-7 relative inline-flex items-center justify-center",f&&(b==="stacked"?"-mt-[1px]":"-mt-[5px]")),children:k});return an("div",{ref:C,"data-proximity-index":e,"data-state":o?"checked":"unchecked",role:n??void 0,"aria-checked":n==="radio"||n==="checkbox"?!!g["aria-checked"]:void 0,"aria-label":p,tabIndex:r,onMouseDown:N=>{let E=N.target.closest('button:not([tabindex="-1"]), a[href], input, select, textarea, [tabindex]:not([tabindex="-1"])');E&&E!==N.currentTarget||(N.preventDefault(),N.currentTarget.focus())},onClick:s,onKeyDown:a,className:w("relative z-10 flex cursor-pointer select-none outline-none",v==="left"?"gap-2":"gap-3",f?"items-start":"items-center",b==="stacked"?"min-h-14 py-2":"min-h-10 py-1.5",v==="left"?u?"pl-1.5 pr-3":"pl-1.5 pr-1.5":"pl-3 pr-1.5",i.item),children:[v==="left"&&I,he("span",{className:w("min-w-0 flex-1 text-[13px] leading-snug",b==="stacked"?"flex flex-col gap-0.5":"inline-flex items-center gap-0"),children:y}),v==="right"?I:M,x]})}function hc(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.const=="string"&&(t.title===void 0||typeof t.title=="string")}function Uv(e){let t=Array.isArray(e.oneOf)?e.oneOf.filter(hc):[],n=Array.isArray(e.anyOf)?e.anyOf.filter(hc):[];return t.length>0?t:n}function Fv(e){let t=e.items&&typeof e.items=="object"?e.items:{},n=Array.isArray(t.anyOf)?t.anyOf.filter(hc):[],o=Array.isArray(t.oneOf)?t.oneOf.filter(hc):[];return n.length>0?n:o}function $v(e){if(e.mode==="url"&&"url"in e)return[{id:"__url_confirm__",title:"Confirm completion",layout:"stacked",options:[{id:"confirmed",title:"I've completed the required action",description:e.url}],skippable:!1,nextLabel:"Confirm"}];let t="requestedSchema"in e?e.requestedSchema:void 0;if(!t||t.type!=="object"||!t.properties)return[{id:"__freeform__",title:"Your response",freeText:!0,freeTextPlaceholder:"Type your response\u2026",skippable:!1}];let n=t.properties,o=t.required??[];return Object.entries(n).map(([r,s])=>{let a=s,i=o.includes(r),c=a.title||r,l=a.description,u=a.type||"string",p=Uv(a),d=Fv(a),h=Array.isArray(a.enum),m=u==="array"&&Array.isArray(a.items?.enum),b=u==="array"&&d.length>0,f={id:r,title:c,skippable:!i,layout:l&&l.length>60?"stacked":"inline"};if(u==="boolean")return{...f,options:[{id:"true",title:"Yes"},{id:"false",title:"No"}]};if(b||m){let v=b?d:a.items.enum.map(x=>({const:x,title:x}))??[];return{...f,multiSelect:!0,options:v.map(x=>({id:x.const,title:x.title||x.const}))}}if(p.length>0)return{...f,layout:"stacked",options:p.map(v=>({id:v.const,title:v.title||v.const}))};if(h){let v=a.enum,x=a.enumNames;return{...f,options:v.map((y,g)=>({id:y,title:x?.[g]||y}))}}return u==="number"||u==="integer"?{...f,freeText:!0,freeTextMultiline:!1,freeTextPlaceholder:a.default!==void 0?String(a.default):"Enter a number\u2026",freeTextValidate:v=>{let x=v.trim();if(!x)return i?"Required":null;let y=u==="integer"?parseInt(x,10):parseFloat(x);return Number.isNaN(y)?"Enter a valid number":null}}:u==="string"&&(a.format==="textarea"||(a.maxLength??0)>100)?{...f,freeText:!0,freeTextPlaceholder:a.default||"Type your answer\u2026"}:{...f,freeText:!0,freeTextMultiline:!1,freeTextPlaceholder:a.default!==void 0?String(a.default):"Type your answer\u2026",freeTextValidate:v=>!v.trim()&&i?"Required":null}})}function Vv(e,t,n){if(n.mode==="url")return{};let o="requestedSchema"in n?n.requestedSchema:void 0,r=o?.type==="object"&&o.properties?o.properties:{},s={};for(let a of e){let i=a.id??"";if(i==="__freeform__"){let p=t[i]?.otherText?.trim();p&&(s.response=p);continue}let c=t[i];if(!c||c.skipped)continue;let u=r[i]?.type||"string";if(a.freeText){let p=c.otherText?.trim()??"";if(!p)continue;s[i]=u==="number"||u==="integer"?u==="integer"?parseInt(p,10):parseFloat(p):p;continue}if(a.multiSelect){s[i]=c.selectedIds;continue}if(u==="boolean"){s[i]=c.selectedIds[0]==="true";continue}c.selectedIds[0]!==void 0&&(s[i]=c.selectedIds[0])}return s}function jv(e,t,n){if(n.mode==="url")return[];let o="requestedSchema"in n?n.requestedSchema:void 0;return(o?.type==="object"?o.required??[]:[]).filter(s=>{let a=t[s];if(!a||a.skipped)return!0;let i=e.find(c=>c.id===s);return i?i.freeText?!a.otherText?.trim():(i.multiSelect,a.selectedIds.length===0):!0})}function qv(e,t){if(t.mode==="url")return{};let n="requestedSchema"in t?t.requestedSchema:void 0,o=n?.type==="object"&&n.properties?n.properties:{},r={};for(let s of e){let a=s.id;if(!a||a.startsWith("__"))continue;let i=o[a];if(!(!i||i.default===void 0)){if(s.freeText){r[a]={questionId:a,selectedIds:[],otherText:String(i.default),skipped:!1};continue}if(s.multiSelect&&Array.isArray(i.default)){r[a]={questionId:a,selectedIds:i.default.map(String),skipped:!1};continue}if(i.type==="boolean"){r[a]={questionId:a,selectedIds:[String(i.default)],skipped:!1};continue}r[a]={questionId:a,selectedIds:[String(i.default)],skipped:!1}}}return r}import{jsx as si,jsxs as vc}from"react/jsx-runtime";function Gv({request:e,onApprove:t,onReject:n,testId:o="inline-elicitation",actionTestIdPrefix:r="inline-elicitation"}){let[s,a]=Kv(!1),[i,c]=Kv(""),l=Wv(()=>$v(e.request),[e.request]),u=Wv(()=>qv(l,e.request),[l,e.request]),d=(e.request.mode||"form")==="url",h=d&&"url"in e.request?e.request.url:void 0,m=(v,x)=>{a(!0),c(v),t(e.id,x)},b=v=>{if(s)return;if(d){if(!v.__url_confirm__?.selectedIds.includes("confirmed")){Jv.error("Confirm you've completed the external action");return}m("accepted",{action:"accept"});return}let x=jv(l,v,e.request);if(x.length>0){Jv.error("Missing required fields",{description:`Please fill in: ${x.join(", ")}`});return}m("accepted",{action:"accept",content:Vv(l,v,e.request)})};if(s)return vc("p",{className:"text-sm text-muted-foreground","data-testid":`${o}-responded`,children:["Elicitation ",i," \u2014 the tool will continue executing."]});let f=vc("div",{className:"space-y-2",children:[si("p",{className:"text-foreground/90",children:e.request.message}),d&&h&&vc("div",{className:"flex items-center gap-2 rounded-md border bg-muted/40 p-2",children:[si("code",{className:"flex-1 text-xs font-mono break-all",children:h}),vc(L,{size:"sm",variant:"outline",onClick:()=>window.open(h,"_blank"),"data-testid":`${r}-open-url`,children:[si(NP,{className:"h-3 w-3 mr-1"}),"Open"]})]})]});return si(am,{questions:l,defaultAnswers:u,onComplete:b,intro:f,onCancel:()=>n(e.id,"User cancelled elicitation request"),cancelLabel:"Cancel",footerLeading:si("button",{type:"button",className:"shrink-0 cursor-pointer text-[12px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline",onClick:()=>m("declined",{action:"decline"}),"data-testid":`${r}-decline-button`,children:"Decline"}),className:"w-full max-w-none shadow-lg","data-testid":o})}import{jsx as im}from"react/jsx-runtime";function Yv({requests:e,onApprove:t,onReject:n}){return e.length===0?null:im("div",{className:"mb-3 space-y-3 pointer-events-auto","data-testid":"floating-elicitation-stack",children:e.map(o=>im(TP.div,{initial:{opacity:0,y:12,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:8,scale:.98},transition:ce.moderate,children:im(Gv,{request:o,onApprove:t,onReject:n})},o.id))})}import{Check as kP,Loader2 as PP,Settings2 as RP}from"lucide-react";import{useCallback as MP,useEffect as IP,useState as lm}from"react";var os="You are a helpful assistant with access to MCP tools. Help users interact with the MCP server.";import{jsx as io,jsxs as ai}from"react/jsx-runtime";function EP(e){let t=e?.trim();return t?t!==os:!1}function Xv({value:e,onSave:t,disabled:n,isSaving:o=!1,compact:r=!1}){let[s,a]=lm(!1),[i,c]=lm(e??""),[l,u]=lm(!1);IP(()=>{c(e??"")},[e]);let p=MP(async()=>{u(!0);try{await t(i),a(!1)}finally{u(!1)}},[i,t]),d=o||l,h=EP(e),m=ai("button",{type:"button","data-testid":"chat-system-prompt-button",onClick:()=>a(!0),disabled:n,className:r?w("inline-flex h-auto w-auto aspect-square items-center justify-center rounded-full p-2 transition-colors disabled:pointer-events-none disabled:opacity-50",h?"text-amber-500 dark:text-amber-400":"text-muted-foreground hover:text-foreground"):w("inline-flex h-9 items-center justify-center gap-1.5 rounded-full border border-input bg-secondary px-3 text-sm font-medium shadow-xs transition-colors hover:bg-secondary/80 disabled:pointer-events-none disabled:opacity-50",h?"text-amber-600 dark:text-amber-400":"text-secondary-foreground"),children:[io(RP,{className:"h-4 w-4"}),!r&&io("span",{className:"hidden sm:inline",children:"System Prompt"})]});return ai(on,{open:s,onOpenChange:a,children:[r?ai(Ie,{children:[io(Re,{render:m,nativeButton:!0}),io(Me,{side:"top",children:io("p",{children:h?"Custom system prompt":"System Prompt"})})]}):m,ai(Xt,{className:"sm:max-w-xl",children:[io(Gt,{children:io($t,{children:"System Prompt"})}),io(fo,{value:i,onChange:b=>c(b.target.value),placeholder:"Describe the assistant's behavior...",className:"min-h-[160px] text-sm"}),io($i,{children:ai(L,{size:"sm",onClick:p,disabled:d||i===(e??""),className:"gap-1.5",children:[d?io(PP,{className:"h-3.5 w-3.5 animate-spin"}):io(kP,{className:"h-3.5 w-3.5"}),"Save"]})})]})]})}import{Fragment as Qv,jsx as wn,jsxs as bc}from"react/jsx-runtime";function ii({variant:e="default",inputValue:t,isConnected:n,isLoading:o,textareaRef:r,llmConfig:s,promptsDropdownOpen:a,promptFocusedIndex:i,prompts:c,selectedPrompt:l,promptResults:u,attachments:p,tools:d,disabledTools:h,onDisabledToolsChange:m,onInputChange:b,onKeyDown:f,onKeyUp:v,onClick:x,onSendMessage:y,onStopStreaming:g,onConfigDialogOpenChange:C,onPromptSelect:k,onDeletePromptResult:I,onAttachmentAdd:M,onAttachmentRemove:N,hideModelBadge:E,freeTierInfo:T,managedCloudInfo:S,modelBadgeMode:P="byok",managedModel:A,followups:R=[],onFollowupSelect:W,pendingElicitationRequests:H,onApproveElicitation:Y,onRejectElicitation:U,systemPromptProvider:V}){let K=e==="fullscreen",$=t.trim()||u.length>0||p.length>0,G=(H?.length??0)>0,te=s&&(!E||T||S)?bc(Ie,{children:[wn(Re,{render:wn(Cv,{provider:s.provider,model:s.model,managedModel:A,mode:P,className:"shrink-0","data-testid":"chat-model-badge",onClick:()=>C(!0)}),nativeButton:!0}),wn(Me,{children:wn("p",{children:S||T?"Change model":"Change API Key"})})]}):null;return wn("div",{className:w("w-full flex shrink-0 flex-col items-center px-2 pt-0 sm:px-4 text-foreground",K?"pb-4 sm:pb-4":"pb-2 sm:pb-2"),children:bc("div",{className:w("relative w-full max-w-3xl",!K&&"backdrop-blur-xl"),children:[!K&&G&&Y&&U&&wn(Yv,{requests:H,onApprove:Y,onReject:U}),!K&&R.length>0&&wn("div",{className:"mb-2 flex flex-wrap gap-2",children:R.map(Z=>wn(L,{type:"button",variant:"outline",size:"sm",className:"rounded-full",onClick:()=>W?.(Z),disabled:o||!n,children:Z},Z))}),!K&&bc(Qv,{children:[wn(Av,{isOpen:a,prompts:c,selectedPrompt:l,focusedIndex:i,onPromptSelect:k}),wn(Ev,{promptResults:u,onDeletePromptResult:I})]}),wn(Iv,{variant:e,inputValue:t,isConnected:n,isLoading:o,textareaRef:r,attachments:p,placeholder:"Ask a question or request an action...",className:w("bg-white/80 dark:text-white dark:bg-black backdrop-blur-sm border-gray-200 dark:border-zinc-800",!K&&u.length>0&&"pt-16"),showAttachButton:!K,tools:K?void 0:d,disabledTools:K?void 0:h,onDisabledToolsChange:K?void 0:m,onInputChange:b,onKeyDown:f,onKeyUp:v,onClick:x,onAttachmentAdd:M,onAttachmentRemove:N,inlineControls:!K&&s&&V?wn(Xv,{compact:!0,value:V.prompt,onSave:V.savePrompt,disabled:!n||o||V.disabled,isSaving:V.isSaving}):null,trailingControls:bc(Qv,{children:[!K&&te,wn(L,{type:"button",size:"sm",className:w("h-8 w-8 rounded-full p-0",o&&"animate-spin",!$&&!o&&"bg-zinc-400"),disabled:!o&&(!$||!n||G),title:o?"Stop streaming":"Send",onClick:o?g:y,"data-testid":"chat-send-button",children:o?wn(LP,{className:"h-3.5 w-3.5 animate-spin"}):wn(AP,{className:"h-3.5 w-3.5"})})]})})]})})}import{AnimatePresence as DP,motion as _P,useInView as OP}from"motion/react";import{useRef as zP}from"react";import{jsx as Zv}from"react/jsx-runtime";function eb({children:e,className:t,variant:n,duration:o=.4,delay:r=0,offset:s=6,direction:a="down",inView:i=!1,inViewMargin:c="-50px",blur:l="6px",...u}){let p=zP(null),d=OP(p,{once:!0,margin:c}),h=!i||d,m={hidden:{[a==="left"||a==="right"?"x":"y"]:a==="right"||a==="down"?-s:s,opacity:0,filter:`blur(${l})`},visible:{[a==="left"||a==="right"?"x":"y"]:0,opacity:1,filter:"blur(0px)"}},b=n||m;return Zv(DP,{children:Zv(_P.div,{ref:p,initial:"hidden",animate:h?"visible":"hidden",exit:"hidden",variants:b,transition:{delay:.04+r,duration:o,ease:"easeOut"},className:t,...u,children:e})})}import{jsx as li,jsxs as yc}from"react/jsx-runtime";function cm({serverDisplayName:e,composerNotice:t,quickQuestions:n=[],onQuickQuestionSelect:o,...r}){return li("div",{className:"flex h-full flex-col items-center justify-center",children:yc(eb,{className:"w-full max-w-4xl mx-auto px-2 sm:px-4",children:[yc("div",{className:"text-center mb-6 sm:mb-8",children:[yc("h1",{className:"text-2xl sm:text-4xl font-light mb-2 dark:text-white","data-testid":"chat-landing-header",children:["Chat with ",e]}),li("p",{className:"mx-auto max-w-xl text-sm text-muted-foreground sm:text-base","data-testid":"chat-landing-description",children:"Chat, inspect traces, preview widgets, and more."})]}),yc("div",{className:"space-y-6",children:[t,li(ii,{...r}),n.length>0&&li("div",{className:"flex flex-wrap items-center justify-center gap-2 px-2",children:n.map(s=>li(L,{type:"button",variant:"outline",size:"sm",className:"rounded-full bg-white/70 dark:bg-black/50 text-gray-900 dark:text-white",onClick:()=>o?.(s),disabled:r.isLoading||!r.isConnected,children:s},s))})]})]})})}import{Key as BP,Settings as HP}from"lucide-react";import{jsx as xc,jsxs as tb}from"react/jsx-runtime";function dm({onConfigureClick:e}){return tb("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[xc(BP,{className:"h-12 w-12 text-muted-foreground mb-4"}),xc("h3",{className:"text-lg font-semibold mb-2",children:"Configure Your LLM Provider"}),xc("p",{className:"text-sm text-muted-foreground mb-4 max-w-md",children:"To start chatting with the MCP server, you need to configure your LLM provider and API key. Your credentials are stored locally and used only for this chat."}),tb(L,{onClick:e,"data-testid":"chat-configure-api-key-button",children:[xc(HP,{className:"h-4 w-4 mr-2"}),"Configure API Key"]})]})}import{motion as UP}from"motion/react";import{useMemo as FP}from"react";import{jsx as $P}from"react/jsx-runtime";function nb({children:e,as:t="p",className:n,duration:o=2,spread:r=2}){let s=UP.create(t),a=FP(()=>e.length*r,[e,r]);return $P(s,{className:w("relative inline-block bg-[length:250%_100%,auto] bg-clip-text","text-transparent [--base-color:#a1a1aa] [--base-gradient-color:#000]","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--base-gradient-color),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]","dark:[--base-color:#71717a] dark:[--base-gradient-color:#ffffff] dark:[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--base-gradient-color),#0000_calc(50%+var(--spread)))]",n),initial:{backgroundPosition:"100% center"},animate:{backgroundPosition:"0% center"},transition:{repeat:1/0,duration:o,ease:"linear"},style:{"--spread":`${a}px`,backgroundImage:"var(--bg), linear-gradient(var(--base-color), var(--base-color))"},children:e})}import{memo as fR,useCallback as gR,useMemo as hR,useRef as xm}from"react";import{memo as VP,useMemo as jP}from"react";import{jsx as ob,jsxs as WP}from"react/jsx-runtime";function qP(e){let t=e.match(/```/g);return t&&t.length%2===1?`${e}
|
|
201
|
+
}`;function MT(e){return[parseInt(e.slice(1,3),16)/255,parseInt(e.slice(3,5),16)/255,parseInt(e.slice(5,7),16)/255,1]}function Yl({className:e,colors:t=["#e0eaff","#f9ffbd","#dedede","#ffffff"],distortion:n=.8,swirl:o=.1,grainMixer:r=0,grainOverlay:s=.2,speed:a=1}){let i=Au(null),c=Au(null),l=Au({colors:t,distortion:n,swirl:o,grainMixer:r,grainOverlay:s,speed:a});return l.current={colors:t,distortion:n,swirl:o,grainMixer:r,grainOverlay:s,speed:a},kT(()=>{let u=i.current,p=c.current;if(!u||!p)return;let d=u.getContext("webgl2");if(!d)return;let h=(H,Y)=>{let U=d.createShader(H);return U?(d.shaderSource(U,Y),d.compileShader(U),d.getShaderParameter(U,d.COMPILE_STATUS)?U:(console.error(d.getShaderInfoLog(U)),null)):null},m=h(d.VERTEX_SHADER,PT),b=h(d.FRAGMENT_SHADER,RT);if(!m||!b)return;let f=d.createProgram();if(!f)return;if(d.attachShader(f,m),d.attachShader(f,b),d.linkProgram(f),!d.getProgramParameter(f,d.LINK_STATUS)){console.error(d.getProgramInfoLog(f));return}d.useProgram(f);let v=d.getAttribLocation(f,"a_position"),x=d.createBuffer();d.bindBuffer(d.ARRAY_BUFFER,x),d.bufferData(d.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),d.STATIC_DRAW),d.enableVertexAttribArray(v),d.vertexAttribPointer(v,2,d.FLOAT,!1,0,0);let y=d.getUniformLocation(f,"u_time"),g=d.getUniformLocation(f,"u_resolution"),C=[0,1,2,3].map(H=>d.getUniformLocation(f,`u_colors[${H}]`)),k=d.getUniformLocation(f,"u_colorsCount"),I=d.getUniformLocation(f,"u_distortion"),M=d.getUniformLocation(f,"u_swirl"),N=d.getUniformLocation(f,"u_grainMixer"),E=d.getUniformLocation(f,"u_grainOverlay"),T=0,S=performance.now(),P=0,A=()=>{let H=Math.min(2,window.devicePixelRatio||1);u.width=Math.floor(p.clientWidth*H),u.height=Math.floor(p.clientHeight*H),d.viewport(0,0,u.width,u.height)},R=H=>{if(document.hidden){S=H,P=requestAnimationFrame(R);return}let{colors:Y,distortion:U,swirl:V,grainMixer:K,grainOverlay:$,speed:G}=l.current,te=H-S;S=H,T+=te*G;let Z=Y.map(MT);d.uniform1f(y,T*.001),d.uniform2f(g,u.width,u.height);for(let z=0;z<4;z++){let F=C[z];F&&d.uniform4fv(F,Z[z]??[1,1,1,1])}d.uniform1f(k,Z.length),d.uniform1f(I,U),d.uniform1f(M,V),d.uniform1f(N,K),d.uniform1f(E,$),d.drawArrays(d.TRIANGLES,0,6),P=requestAnimationFrame(R)};A();let W=new ResizeObserver(A);return W.observe(p),P=requestAnimationFrame(R),()=>{cancelAnimationFrame(P),W.disconnect()}},[]),Wh("div",{ref:c,className:e,children:Wh("canvas",{ref:i,className:"h-full w-full","aria-hidden":!0})})}var IT=["#e0eaff","#f9ffbd","#dedede","#ffffff"],ET=["#27272a","#9a9448","#3f3f46","#18181b"];function Xl(e){return e==="dark"?ET:IT}import{useCallback as AT,useState as LT}from"react";import{Play as DT,Square as _T}from"lucide-react";import{jsx as Bs,jsxs as BT}from"react/jsx-runtime";var Kh="mcp-inspector-chat-mesh-animation-paused";function OT(e){try{return localStorage.getItem(e)==="true"}catch{return!1}}function Jh(e){let[t,n]=LT(()=>OT(e)),o=AT(()=>{n(r=>{let s=!r;try{localStorage.setItem(e,s?"true":"false")}catch{}return s})},[e]);return{paused:t,toggle:o}}var zT="z-50 flex h-7 w-7 cursor-pointer items-center justify-center rounded-full border border-zinc-500/60 bg-transparent text-zinc-600 transition-colors hover:border-zinc-500 hover:text-zinc-800 dark:border-zinc-500/50 dark:text-zinc-400 dark:hover:border-zinc-400 dark:hover:text-zinc-200";function Gh({paused:e,onToggle:t,className:n}){return BT(Ie,{children:[Bs(Re,{render:Bs("button",{type:"button",onClick:t,"aria-label":e?"Resume animation":"Pause animation",className:w(zT,n),children:e?Bs(DT,{className:"ml-px h-3 w-3",fill:"currentColor"}):Bs(_T,{className:"h-2.5 w-2.5",fill:"currentColor"})}),nativeButton:!0}),Bs(Me,{side:"left",children:Bs("p",{children:e?"Resume animation":"Pause animation"})})]})}import{jsx as Ya,jsxs as Qh}from"react/jsx-runtime";var FT=.54,$T=.4,Xh="linear-gradient(to top, black 0%, black 12%, rgba(0,0,0,0.55) 38%, transparent 100%)";function Zh({className:e,children:t,shaderPhase:n="hidden",onShaderFadeComplete:o,meshAnimationPaused:r=!1,...s}){let a=HT(null),[i,c]=UT(!1),{resolvedTheme:l}=go(),u=Xl(l),p=l==="dark",{paused:d,toggle:h}=Jh(Kh),m=d||r;Yh(()=>{let x=window.requestAnimationFrame(()=>c(!0));return()=>window.cancelAnimationFrame(x)},[]),Yh(()=>{n==="fading"&&!i&&o?.()},[n,i,o]);let b=n!=="hidden",f=n==="visible"&&i,v=x=>{x.propertyName==="opacity"&&n==="fading"&&o?.()};return Qh("div",{ref:a,className:w("relative flex min-h-0 flex-1 flex-col overflow-hidden bg-background",e),...s,children:[b&&Ya("div",{className:w("pointer-events-none absolute inset-x-0 bottom-0 z-0 transition-opacity duration-500",f?"opacity-100":"opacity-0"),style:{height:`${FT*100}%`},"aria-hidden":!0,onTransitionEnd:v,children:Qh("div",{className:w("absolute inset-0",i?p?"opacity-90":"opacity-75":"opacity-0"),style:{maskImage:Xh,WebkitMaskImage:Xh},children:[Ya("div",{className:"absolute inset-0 bg-[#edf2ff] dark:hidden"}),Ya(Yl,{className:"absolute inset-0 h-full w-full",colors:[...u],distortion:.8,swirl:.1,grainMixer:0,grainOverlay:p?.12:.3,speed:m?0:$T})]})}),b&&Ya(Gh,{paused:d,onToggle:h,className:"absolute bottom-3 right-3 sm:bottom-5 sm:right-5"}),Ya("div",{className:"relative z-10 flex min-h-0 flex-1 flex-col",children:t})]})}function ev(e){return e?e.apiKey==="server-managed"||e.baseUrl?.includes("/inspector/llm")===!0:!1}function Xa(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes("failed to fetch")||t.includes("networkerror")||t.includes("network request failed")||t.includes("load failed")}function Lu(e,t){if(!t)return e>=502&&e<=504?{kind:"cloud_unavailable"}:null;if(e===402)return{kind:"credits_exhausted",billingUrl:typeof t.upgradeUrl=="string"?t.upgradeUrl:typeof t.billingUrl=="string"?t.billingUrl:void 0,message:typeof t.message=="string"?t.message:"You've used your included free plan credits."};if(e===429){if(t.loginRequired&&t.loginUrl)return{kind:"login_required",loginUrl:String(t.loginUrl)};if(t.creditsExhausted)return{kind:"credits_exhausted",billingUrl:typeof t.billingUrl=="string"?t.billingUrl:void 0,message:typeof t.message=="string"?t.message:"You've used your included free plan credits."};if(t.error==="free_org_rate_limited"||typeof t.reason=="string")return{kind:"credits_exhausted",message:typeof t.message=="string"?t.message:"You've reached your included chat quota for this workspace."}}return e>=502&&e<=504?{kind:"cloud_unavailable"}:null}function VT(e){let t=e.match(/^OpenAI request failed \((\d+) /);if(!t)return null;let n=Number(t[1]),o=e.indexOf("{");if(o===-1)return null;try{let r=JSON.parse(e.slice(o));if(r&&typeof r=="object"&&!Array.isArray(r))return{status:n,body:r}}catch{}return null}function tv(e){if(e instanceof Error&&e.name==="LlmRequestError"){let t=e.status??0,n=e.body,o=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0;return Lu(t,o)}if(e instanceof Error){let t=VT(e.message);if(t)return Lu(t.status,t.body)}return Xa(e)?{kind:"cloud_unavailable"}:null}function nv(e,t){return Lu(e,t)}import{useCallback as Ql,useEffect as jT,useSyncExternalStore as qT}from"react";var Hu="openid profile email offline_access",rv="mcp-inspector:manufact-auth",WT="manufact:session-changed",Qa={loaded:!0,authorizing:!1,accessToken:null,user:null,mode:null},Zr=new Map,zu=new Set,Du=new Map,_u=new Map,sv=null,Ou=!1;typeof window<"u"&&window.addEventListener("message",e=>{if(e.data?.type!=="manufact:invalidate-oauth-client")return;for(let n of Zr.keys())Gn()?.removeItem(Pn(n,"client"));let t=sv;!t||Ou||(Ou=!0,uv(t,{isRetry:!0}).finally(()=>{Ou=!1}))});function KT(e){let t=Zr.get(e);if(t)return t;let n={...Qa,loaded:!1};return Zr.set(e,n),n}function Gn(){return typeof window>"u"?null:window.localStorage}function tc(e){return new URL(e).origin}function JT(e,t){let n=new URL(e),o=new URL(t),r=new Set(["localhost","127.0.0.1"]);return r.has(n.hostname)&&r.has(o.hostname)?n.origin===o.origin:(n.hostname==="manufact.com"||n.hostname.endsWith(".manufact.com"))&&(o.hostname==="manufact.com"||o.hostname.endsWith(".manufact.com"))}function av(e){let t=window.__MANUFACT_LOGIN_URL__;if(t)return new URL(t).origin;let n=new URL(e);return n.hostname==="localhost"||n.hostname==="127.0.0.1"?`${n.protocol}//${n.hostname}:3000`:`${n.protocol}//manufact.com`}function GT(e){return`${av(e)}/auth/embedded-sign-out`}function Pn(e,t){return`${rv}:${t}:${e}`}function YT(e){return Gn()?.getItem(Pn(e,"skip-session"))==="1"}function ec(e,t){let n=Pn(e,"skip-session");t?Gn()?.setItem(n,"1"):Gn()?.removeItem(n)}function XT(e){return`${rv}:state:${e}`}function Hs(e){let t=Gn()?.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return Gn()?.removeItem(e),null}}function Uu(e,t){Gn()?.setItem(e,JSON.stringify(t))}function xo(e,t){Zr.set(e,{...Zr.get(e)??Qa,...t}),zu.forEach(n=>n()),window.dispatchEvent(new CustomEvent(WT))}function iv(e){let t="";return e.forEach(n=>{t+=String.fromCharCode(n)}),btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Bu(e=32){let t=new Uint8Array(e);return crypto.getRandomValues(t),iv(t)}async function lv(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return iv(new Uint8Array(t))}async function nc(e){let t=await fetch(`${e}/api/auth/.well-known/openid-configuration`);if(!t.ok)throw new Error("Manufact OAuth discovery failed");return await t.json()}function cv(){return`${window.location.origin}${Yo()}/auth/callback`}function ov(e){return e==="localhost"||e==="127.0.0.1"}function QT(e){try{let t=new URL(e).hostname,n=typeof window<"u"?new URL(window.location.href).hostname:"";return ov(t)&&ov(n)}catch{return!1}}async function ZT(e,t,n){let o=new URL(`${e}/api/auth/oauth2/authorize`);o.searchParams.set("response_type","code"),o.searchParams.set("client_id",t),o.searchParams.set("redirect_uri",n),o.searchParams.set("scope",Hu),o.searchParams.set("code_challenge",await lv(Bu(32))),o.searchParams.set("code_challenge_method","S256"),o.searchParams.set("state","client-probe"),o.searchParams.set("prompt","none");try{let r=await fetch(o.toString(),{method:"GET",redirect:"manual",credentials:"include"}),s=r.headers.get("location")??"";return s.includes("/auth/error")&&s.includes("invalid_client")?!1:r.status>=300&&r.status<400||r.type==="opaqueredirect"?!!s&&!s.includes("/auth/error"):!0}catch{return!1}}async function ek(e,t){let n=cv(),o=Pn(e,"client"),r=Hs(o),s=QT(e);if(!s&&r?.client_id&&r.redirect_uri===n){if(await ZT(e,r.client_id,n))return r;Gn()?.removeItem(o)}else s&&r?.client_id&&Gn()?.removeItem(o);if(!t.registration_endpoint)throw new Error("Manufact OAuth registration is unavailable");let a=await fetch(t.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_name:"mcp-use Inspector",redirect_uris:[n],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",scope:Hu})});if(!a.ok)throw new Error("Could not register Inspector with Manufact");let i=await a.json();if(!i.client_id)throw new Error("Manufact returned no OAuth client ID");let c={...i,redirect_uri:n};return Uu(o,c),c}async function tk(e,t){let n=await fetch(e,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams(t)}),o=await n.json().catch(()=>({}));if(!n.ok||!o.access_token)throw new Error(o.error_description??"Manufact token exchange failed");return{access_token:o.access_token,refresh_token:o.refresh_token,token_type:o.token_type,expires_at:Date.now()+(o.expires_in??3600)*1e3}}async function nk(e,t){if(!t.refresh_token)return null;let n=_u.get(e);if(n)return n;let o=(async()=>{try{let r=await nc(e),s=Hs(Pn(e,"client"));if(!s?.client_id)return null;let a=await tk(r.token_endpoint,{grant_type:"refresh_token",refresh_token:t.refresh_token,client_id:s.client_id}),i={...a,refresh_token:a.refresh_token??t.refresh_token};return Uu(Pn(e,"tokens"),i),i}catch{return Gn()?.removeItem(Pn(e,"tokens")),null}finally{_u.delete(e)}})();return _u.set(e,o),o}async function ok(e){let t=Hs(Pn(e,"tokens"));return t?.access_token?t.expires_at>Date.now()+3e4?t:nk(e,t):null}async function rk(e,t){let n=await nc(e);if(!n.userinfo_endpoint)return null;let o=await fetch(n.userinfo_endpoint,{headers:{Authorization:`Bearer ${t}`}});if(!o.ok)return null;let r=await o.json();return r.sub?{id:r.sub,name:r.name,email:r.email,image:r.picture}:null}async function dv(e){try{let t=await fetch(`${e}/api/auth/get-session`,{credentials:"include"});return t.ok?(await t.json())?.user??null:null}catch{return null}}async function Zl(e){let t=Du.get(e);if(t)return t;Zr.set(e,{...Zr.get(e)??Qa,loaded:!1});let n=(async()=>{try{let o=typeof window<"u"?window.location.href:e,r=JT(o,e),s=YT(e),a=await ok(e),i=a?await rk(e,a.access_token):null;if(i&&a){ec(e,!1),xo(e,{loaded:!0,accessToken:a.access_token,user:i,mode:"oauth"});return}a&&!i&&Gn()?.removeItem(Pn(e,"tokens"));let c=r&&!s?await dv(e):null;if(c){xo(e,{loaded:!0,accessToken:null,user:c,mode:"session"});return}xo(e,{loaded:!0,accessToken:null,user:null,mode:null})}catch{xo(e,{loaded:!0,accessToken:null,user:null,mode:null})}})().finally(()=>Du.delete(e));return Du.set(e,n),n}async function uv(e,t){let n=tc(e);sv=e,ec(n,!1);let o=window.open("","manufact-oauth","width=600,height=700,resizable=yes,scrollbars=yes");if(!o)throw new Error("Allow popups to sign in with Manufact");xo(n,{authorizing:!0});try{let r=await nc(n),s=await ek(n,r),a=Bu(64),i=Bu(),c=cv();Uu(XT(i),{authOrigin:n,clientId:s.client_id,redirectUri:c,codeVerifier:a,expiresAt:Date.now()+600*1e3});let l=new URL(r.authorization_endpoint);l.searchParams.set("response_type","code"),l.searchParams.set("client_id",s.client_id),l.searchParams.set("redirect_uri",c),l.searchParams.set("scope",Hu),l.searchParams.set("state",i),l.searchParams.set("code_challenge",await lv(a)),l.searchParams.set("code_challenge_method","S256"),l.searchParams.set("prompt","consent"),o.location.href=l.toString();let u=window.setInterval(()=>{o.closed&&(window.clearInterval(u),Zl(n).finally(()=>xo(n,{authorizing:!1})))},500)}catch(r){throw o.close(),xo(n,{authorizing:!1}),r}}function sk(e){let t=tc(e);Gn()?.removeItem(Pn(t,"tokens")),xo(t,{loaded:!0,authorizing:!1,accessToken:null,user:null,mode:null})}async function ak(e){let t=Hs(Pn(e,"tokens")),n=Hs(Pn(e,"client")),o=t?.refresh_token??t?.access_token;if(!n?.client_id||!o)return null;try{let s=(await nc(e)).revocation_endpoint??`${e}/api/auth/oauth2/revoke`;return(await fetch(s,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:n.client_id,token:o,token_type_hint:t?.refresh_token?"refresh_token":"access_token"})})).status}catch{return-1}}async function ik(e){let t=av(e),n=window.open(GT(e),"manufact-sign-out","width=420,height=320");return n?new Promise(o=>{let r=!1,s=l=>{r||(r=!0,window.clearTimeout(a),window.clearInterval(c),window.removeEventListener("message",i),o(l))},a=window.setTimeout(()=>{s({attempted:!0,signOutOk:!1,signOutStatus:null})},3e4),i=l=>{l.origin===t&&l.data?.type==="manufact:sign-out-complete"&&s({attempted:!0,signOutOk:!0,signOutStatus:200})},c=window.setInterval(()=>{n.closed&&dv(e).then(l=>{s({attempted:!0,signOutOk:!l,signOutStatus:l?401:200})})},500);window.addEventListener("message",i)}):{attempted:!0,signOutOk:!1,signOutStatus:null}}async function lk(e,t){let n=tc(e),o=!!Hs(Pn(n,"tokens"))?.access_token;t==="oauth"||o?(await ak(n),ec(n,!0)):t==="session"&&(await ik(n),ec(n,!1)),sk(e)}function mv(e){let t=e?tc(e):null,n=Ql(s=>(zu.add(s),()=>zu.delete(s)),[]),o=Ql(()=>t?KT(t):Qa,[t]),r=qT(n,o,()=>Qa);return jT(()=>{if(!t)return;Zl(t);let s=i=>{i.origin===window.location.origin&&i.data?.type==="manufact:oauth-complete"&&i.data.authOrigin===t&&Zl(t).finally(()=>xo(t,{authorizing:!1}))},a=i=>{i.key!==Pn(t,"tokens")||!i.newValue||Zl(t).finally(()=>xo(t,{authorizing:!1}))};return window.addEventListener("message",s),window.addEventListener("storage",a),()=>{window.removeEventListener("message",s),window.removeEventListener("storage",a)}},[t]),{...r,authorize:Ql(async()=>{e&&await uv(e)},[e]),logout:Ql(async()=>{e&&await lk(e,r.mode)},[e,r.mode])}}function pv(e){return mv(e)}import{useEffect as ck}from"react";function fv(e){ck(()=>{let t=n=>{let o=n.target,r=o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.contentEditable==="true";if((n.metaKey||n.ctrlKey)&&n.key==="k"){n.preventDefault(),e.onCommandPalette?.();return}if((n.metaKey||n.ctrlKey)&&n.key==="o"&&e.onNewChat){n.preventDefault(),e.onNewChat();return}if(n.key==="Escape"){n.preventDefault(),document.activeElement instanceof HTMLElement&&document.activeElement.blur(),e.onBlurSearch?.();return}if(!r&&!(n.metaKey||n.ctrlKey||n.altKey||n.shiftKey))switch(n.key.toLowerCase()){case"t":n.preventDefault(),e.onToolsTab?.();break;case"p":n.preventDefault(),e.onPromptsTab?.();break;case"r":n.preventDefault(),e.onResourcesTab?.();break;case"c":n.preventDefault(),e.onChatTab?.();break;case"h":n.preventDefault(),e.onHome?.();break;case"f":n.preventDefault(),e.onFocusSearch?.();break;default:break}};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[e])}import{Copy as Wk,Download as Kk,SquarePen as Jk}from"lucide-react";import{Check as Sv,ChevronsUpDown as Nv,Eye as Pk,EyeOff as Rk,Key as Mk,Loader2 as Tv}from"lucide-react";import{useEffect as Yu,useRef as Ik,useState as ts}from"react";import{Tabs as Vu}from"@base-ui/react/tabs";import{AnimatePresence as ju,motion as oc}from"motion/react";import{createContext as pk,forwardRef as Ku,useCallback as $u,useContext as fk,useEffect as qu,useRef as rc,useState as gk}from"react";import{useCallback as Us,useEffect as Fu,useRef as Fs,useState as gv}from"react";function hv(e,t){let n=e.getBoundingClientRect(),o=t==="x"?e.offsetWidth:e.offsetHeight,r=t==="x"?n.width:n.height;return o>0?r/o:1}function dk(e,t){let n=e.getBoundingClientRect(),o=hv(e,"x"),r=hv(e,"y"),s=[];return t.forEach((a,i)=>{let c=a.getBoundingClientRect();s[i]={top:(c.top-n.top)/r+e.scrollTop,left:(c.left-n.left)/o+e.scrollLeft,width:a.offsetWidth,height:a.offsetHeight}}),s}function uk(e,t,n,o){let r=o==="x"?t:n,s=null,a=1/0,i=null;return e.forEach((c,l)=>{let u=c.getBoundingClientRect(),p=o==="x"?u.left:u.top,d=o==="x"?u.right:u.bottom;r>=p&&r<=d&&(i=l);let h=(p+d)/2,m=Math.abs(r-h);m<a&&(a=m,s=l)}),i??s}function mk(e,t){if(e.length!==t.length)return!0;for(let n=0;n<t.length;n++){let o=e[n],r=t[n];if(o!==r&&(!o||!r||o.top!==r.top||o.left!==r.left||o.width!==r.width||o.height!==r.height))return!0}return!1}function vv(e,t={}){let{axis:n="y"}=t,o=Fs(new Map),[r,s]=gv(null),[a,i]=gv([]),c=Fs([]),l=Fs(0),u=Fs(null),p=Fs(null),d=Fs(null),h=Us(()=>{let y=e.current;if(!y)return;let g=dk(y,o.current);mk(c.current,g)&&(c.current=g,i(g))},[e]),m=Us((y,g)=>{s(uk(o.current,y,g,n))},[n]),b=Us((y,g)=>{g?o.current.set(y,g):o.current.delete(y),p.current!==null&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{p.current=null,h()})},[h]),f=Us(y=>{d.current={x:y.clientX,y:y.clientY},u.current!==null&&cancelAnimationFrame(u.current),u.current=requestAnimationFrame(()=>{u.current=null,h(),m(y.clientX,y.clientY)})},[h,m]),v=Us(()=>{l.current+=1},[]),x=Us(()=>{u.current!==null&&(cancelAnimationFrame(u.current),u.current=null),d.current=null,s(null)},[]);return Fu(()=>{let y=e.current;if(!y||typeof ResizeObserver>"u")return;let g=new ResizeObserver(()=>{p.current!==null&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{p.current=null,h()})});return g.observe(y),()=>g.disconnect()},[e,h]),Fu(()=>{let y=e.current;if(!y)return;let g=()=>{h();let C=d.current;C&&m(C.x,C.y)};return y.addEventListener("scroll",g,{capture:!0,passive:!0}),()=>y.removeEventListener("scroll",g,{capture:!0})},[e,h,m]),Fu(()=>()=>{u.current!==null&&cancelAnimationFrame(u.current),p.current!==null&&cancelAnimationFrame(p.current)},[]),{activeIndex:r,setActiveIndex:s,itemRects:a,sessionRef:l,handlers:{onMouseMove:f,onMouseEnter:v,onMouseLeave:x},registerItem:b,measureItems:h}}import{jsx as On,jsxs as Wu}from"react/jsx-runtime";var bv=pk(null);function hk(){let e=fk(bv);if(!e)throw new Error("useTabsSubtle must be used within a TabsSubtle");return e}var Za=Ku(({children:e,selectedIndex:t,onSelect:n,idPrefix:o,activeLabel:r=!1,className:s,...a},i)=>{let c=rc(null),l=rc(!1),u=kt(),{activeIndex:p,setActiveIndex:d,itemRects:h,handlers:m,registerItem:b,measureItems:f}=vv(c,{axis:"x"}),v=rc(new Map),x=$u((S,P)=>{b(S,P),P?v.current.set(S,P):v.current.delete(S)},[b]);qu(()=>{f()},[f,e]),qu(()=>{let S=v.current;if(S.size===0)return;let P=new ResizeObserver(()=>f());return S.forEach(A=>P.observe(A)),()=>P.disconnect()},[f,e]);let y=$u(S=>{l.current=!0,m.onMouseMove(S)},[m]),g=$u(()=>{l.current=!1,m.onMouseLeave()},[m]),[C,k]=gk(null),I=h[t],M=p!==null?h[p]:null,N=C!==null?h[C]:null,E=p===t,T=p!==null&&!E;return On(bv.Provider,{value:{registerTab:x,hoveredIndex:p,selectedIndex:t,idPrefix:o,activeLabel:r},children:On(Vu.Root,{value:t,onValueChange:S=>{typeof S=="number"&&n(S)},render:Wu(Vu.List,{activateOnFocus:!1,ref:S=>{c.current=S,typeof i=="function"?i(S):i&&(i.current=S)},onMouseMove:y,onMouseLeave:g,onFocus:S=>{let P=S.target.closest("[data-proximity-index]")?.getAttribute("data-proximity-index");if(P!=null){let A=Number(P);d(A),k(S.target.matches(":focus-visible")?A:null)}},onBlur:S=>{c.current?.contains(S.relatedTarget)||(k(null),!l.current&&d(null))},className:w("relative flex items-center gap-0.5 select-none overflow-x-auto max-w-full -mx-1 px-1 -my-1 py-1",s),...a,children:[I&&On(oc.div,{className:w("absolute bg-accent pointer-events-none",u.bg),initial:!1,animate:{left:I.left,width:I.width,top:I.top,height:I.height,opacity:T?.8:1},transition:{...ce.moderate,opacity:{duration:.08}}}),On(ju,{children:M&&!E&&I&&On(oc.div,{className:w("absolute bg-accent pointer-events-none",u.bg),initial:{left:I.left,width:I.width,top:I.top,height:I.height,opacity:0},animate:{left:M.left,width:M.width,top:M.top,height:M.height,opacity:.4},exit:!l.current&&I?{left:I.left,width:I.width,top:I.top,height:I.height,opacity:0,transition:{...ce.moderate,opacity:{duration:.06}}}:{opacity:0,transition:ce.fast.exit},transition:{...ce.fast,opacity:{duration:.08}}})}),On(ju,{children:N&&On(oc.div,{className:w("absolute pointer-events-none z-20 border border-[color:var(--focus-ring,#6B97FF)]",u.focusRing),initial:!1,animate:{left:N.left-2,top:N.top-2,width:N.width+4,height:N.height+4},exit:{opacity:0,transition:ce.fast.exit},transition:{...ce.fast,opacity:{duration:.08}}})}),e]})})})});Za.displayName="TabsSubtle";var es=Ku(({icon:e,label:t,index:n,className:o,...r},s)=>{let a=rc(null),i=kt(),{registerTab:c,hoveredIndex:l,selectedIndex:u,idPrefix:p,activeLabel:d}=hk();qu(()=>(c(n,a.current),()=>c(n,null)),[n,c]);let h=u===n,m=l===n||h,b=d&&!!e,f=!b||h,v=Wu("span",{className:"inline-grid",children:[On("span",{className:"col-start-1 row-start-1 invisible [text-box:trim-both_cap_alphabetic]",style:{fontVariationSettings:At.semibold},"aria-hidden":"true",children:t}),On("span",{className:w("col-start-1 row-start-1 transition-[color,font-variation-settings] duration-80 [text-box:trim-both_cap_alphabetic]",m?"text-foreground":"text-muted-foreground"),style:{fontVariationSettings:h?At.semibold:At.normal},children:t})]});return Wu(Vu.Tab,{ref:x=>{let y=x;a.current=y,typeof s=="function"?s(y):s&&(s.current=y)},value:n,"data-proximity-index":n,id:p?`${p}-tab-${n}`:void 0,"aria-controls":p?`${p}-panel-${n}`:void 0,"aria-label":b&&!f?t:void 0,className:w("relative z-10 flex items-center px-2 cursor-pointer bg-transparent border-none outline-none text-xs",b?"h-7":"h-7 gap-1.5",i.bg,o),...r,children:[e&&On(e,{size:14,strokeWidth:m?2:1.5,className:w("shrink-0 transition-[color,stroke-width] duration-80",m?"text-foreground":"text-muted-foreground")}),b?On(ju,{children:f&&On(oc.span,{className:"overflow-hidden",initial:{width:0,opacity:0,marginLeft:0},animate:{width:"auto",opacity:1,marginLeft:6},exit:{width:0,opacity:0,marginLeft:0},transition:{...ce.fast,opacity:{duration:.06}},children:v},"label")}):v]})});es.displayName="TabsSubtleItem";var vk=Ku(({index:e,selectedIndex:t,idPrefix:n,children:o,className:r,...s},a)=>{let i=t===e;return On("div",{ref:a,id:`${n}-panel-${e}`,role:"tabpanel","aria-labelledby":`${n}-tab-${e}`,hidden:!i,tabIndex:-1,className:w("outline-none",r),...s,children:i&&o})});vk.displayName="TabsSubtlePanel";import*as Ut from"react";import{jsx as hr,jsxs as yk}from"react/jsx-runtime";var yv=Ut.createContext(null);function Ju(){let e=Ut.useContext(yv);if(!e)throw new Error("Command components must be used within <Command>");return e}function bk(e,t){return t?e.toLowerCase().includes(t.toLowerCase()):!0}var sc=Ut.forwardRef(({className:e,...t},n)=>{let[o,r]=Ut.useState(""),[s,a]=Ut.useState(null),[i,c]=Ut.useState(0),l=Ut.useCallback(()=>(c(u=>u+1),()=>c(u=>Math.max(0,u-1))),[]);return hr(yv.Provider,{value:{search:o,setSearch:r,activeValue:s,setActiveValue:a,visibleCount:i,registerVisible:l},children:hr("div",{ref:n,className:w("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",e),...t})})});sc.displayName="Command";var ac=Ut.forwardRef(({className:e,...t},n)=>{let{search:o,setSearch:r}=Ju();return hr("div",{className:"flex items-center border-b px-3",children:hr("input",{ref:n,value:o,onChange:s=>r(s.target.value),className:w("flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",e),...t})})});ac.displayName="CommandInput";var ic=Ut.forwardRef(({className:e,...t},n)=>hr("div",{ref:n,className:w("max-h-[300px] overflow-y-auto overflow-x-hidden",e),...t}));ic.displayName="CommandList";var lc=Ut.forwardRef(({className:e,...t},n)=>{let{visibleCount:o}=Ju();return o>0?null:hr("div",{ref:n,className:w("py-6 text-center text-sm",e),...t})});lc.displayName="CommandEmpty";var cc=Ut.forwardRef(({className:e,heading:t,children:n,...o},r)=>yk("div",{ref:r,className:w("overflow-hidden p-1 text-foreground [&_[data-command-group-heading]]:px-2 [&_[data-command-group-heading]]:py-1.5 [&_[data-command-group-heading]]:text-xs [&_[data-command-group-heading]]:font-medium [&_[data-command-group-heading]]:text-muted-foreground",e),...o,children:[t?hr("div",{"data-command-group-heading":"",children:t}):null,n]}));cc.displayName="CommandGroup";var dc=Ut.forwardRef(({className:e,value:t,keywords:n,onSelect:o,disabled:r,onClick:s,...a},i)=>{let{search:c,activeValue:l,setActiveValue:u,registerVisible:p}=Ju(),d=Array.isArray(n)?n.join(" "):n,h=d?`${t} ${d}`:t,m=bk(h,c),b=l===t;return Ut.useLayoutEffect(()=>{if(m)return p()},[m,p]),Ut.useEffect(()=>{m&&l===null&&!r&&u(t)},[m,l,r,u,t]),m?hr("div",{ref:i,role:"option","aria-selected":b,"data-selected":b,"data-disabled":r,className:w("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",e),onMouseEnter:()=>!r&&u(t),onClick:f=>{s?.(f),r||o?.(t)},...a}):null});dc.displayName="CommandItem";import{buildOllamaApiUrl as Ek,normalizeOllamaBaseUrl as Ak,OllamaCorsError as Lk}from"@mcp-use/agent";import{ChevronDown as xk,Key as wk}from"lucide-react";import{jsx as Yn,jsxs as Gu}from"react/jsx-runtime";var Ck="https://cdn.mcp-use.com/mcpuse_logo_circle_dark.svg";function xv({symbolSize:e=14,className:t,textClassName:n}){return Gu("span",{className:w("inline-flex items-center gap-1.5 text-black dark:text-white",t),children:[Yn(Sk,{size:e}),Yn("span",{className:w("font-medium leading-none text-current [font-family:var(--font-family-outfit)]",n),children:"Manufact"})]})}function Sk({size:e=14,className:t}){return Gu("svg",{width:e,height:e,viewBox:"0 0 480 480","aria-hidden":!0,className:w("block shrink-0",t),children:[Yn("path",{d:"M101.7 0 C157.9 0 203.4 45.7 203.4 102.1 C203.4 126.6 202.1 152.1 212.2 174.3 L219.8 191 C233.8 221.8 258.5 246.4 289.2 260.5 L303.5 267 C326.5 277.5 353 275.8 378.3 275.8 C434.5 275.8 480 321.5 480 377.9 C480 434.3 434.5 480 378.3 480 C322.1 480 276.6 434.3 276.6 377.9 C276.6 354.2 277.7 329.6 267.8 308 L259.8 290.3 C245.7 259.5 221 234.8 190.2 220.7 L173 212.9 C151 202.9 125.8 204.2 101.7 204.2 C45.5 204.2 0 158.5 0 102.1 C0 45.7 45.5 0 101.7 0 Z",fill:"currentColor"}),Yn("circle",{cx:"96.4",cy:"383.6",r:"96.4",fill:"currentColor"}),Yn("circle",{cx:"383.6",cy:"96.4",r:"96.4",fill:"currentColor"})]})}var Nk='<svg width="512" height="512" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg" fill="#94A3B8" stroke="#94A3B8"><g><path fill="none" d="M3 248.945C18 248.945 76 236 106 219C136 202 136 202 198 158C276.497 102.293 332 120.945 423 120.945" stroke-width="90"/><path d="M511 121.5L357.25 210.268L357.25 32.7324L511 121.5Z"/><path fill="none" d="M0 249C15 249 73 261.945 103 278.945C133 295.945 133 295.945 195 339.945C273.497 395.652 329 377 420 377" stroke-width="90"/><path d="M508 376.445L354.25 287.678L354.25 465.213L508 376.445Z"/></g></svg>',Tk=`data:image/svg+xml,${encodeURIComponent(Nk)}`,wv={openai:"OpenAI",anthropic:"Anthropic",google:"Google",deepseek:"DeepSeek","z-ai":"Z.AI",nvidia:"NVIDIA",minimax:"MiniMax",moonshotai:"Moonshot AI",inclusionai:"InclusionAI","nex-agi":"Nex AGI","x-ai":"xAI",thinkingmachines:"Thinking Machines",mistralai:"Mistral AI",stepfun:"StepFun","aion-labs":"Aion Labs","bytedance-seed":"ByteDance Seed","ibm-granite":"IBM Granite","arcee-ai":"Arcee AI",rekaai:"Reka AI",kwaipilot:"KwaiPilot"};function uc(e,t){let n=e.trim(),o=wv[t];if(o){let s=o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^${s}\\s*:\\s*`,"i"),i=n.replace(a,"").trim();if(i.length>0)return i}let r=n.indexOf(": ");return r>0&&r<48?n.slice(r+2).trim():n}function Cv({provider:e,model:t,displayName:n,managedModel:o,mode:r="byok",className:s,...a}){let i=r==="managed"?o:null,c=i?uc(i.name,i.provider):n??t,l=i?i.provider:r==="managed"&&e==="openai-compatible"&&t.split("/")[0]||e;return Gu("button",{type:"button",className:w("inline-flex items-center gap-1.5 min-w-0 border-0 bg-transparent p-1","font-mono text-[11px] text-muted-foreground cursor-pointer","hover:text-foreground transition-colors","rounded-md outline-none focus-visible:ring-1 focus-visible:ring-ring",s),...a,children:[r==="managed"?Yn("img",{src:Ck,alt:"Manufact",className:"h-3.5 w-3.5 shrink-0 rounded-full object-cover"}):Yn(wk,{className:"size-3 shrink-0 opacity-70","aria-hidden":!0}),Yn(so,{provider:l,className:"shrink-0"}),Yn("span",{className:"whitespace-nowrap",children:c}),Yn(xk,{className:"size-3 shrink-0 opacity-60","aria-hidden":!0})]})}function qt(e){let t=wv[e];if(t)return t;switch(e){case"openai":return"OpenAI";case"openai-compatible":return"OpenAI Compatible";case"anthropic":return"Anthropic";case"google":return"Google";case"openrouter":return"OpenRouter";case"ollama":return"Ollama";default:return e.split(/[-_]/).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")}}function kk(e,t){switch(e){case"openai":case"anthropic":case"google":return ma(`${e}.png`);case"ollama":return ma(`${t==="dark"?"ollama_dark":"ollama_light"}.png`);case"openrouter":return Tk;case"openai-compatible":return null;default:return null}}function so({provider:e,className:t}){let{resolvedTheme:n}=go();if(e==="openai-compatible")return null;let o=kk(e,n);if(o){let r=e==="ollama"?"h-3.5 w-3.5 object-contain":"h-4 w-4 rounded-full object-cover";return Yn("img",{src:o,alt:qt(e),className:w(r,t)})}return Yn("div",{"aria-label":qt(e),className:w("flex h-4 w-4 items-center justify-center rounded-full bg-neutral-900 text-[9px] font-semibold text-white dark:bg-neutral-100 dark:text-neutral-900",t),children:qt(e).charAt(0)})}import{Fragment as qk,jsx as ee,jsxs as $e}from"react/jsx-runtime";var Xu="mcp-inspector-models-cache",Dk=1440*60*1e3;function Pv(){try{let e=localStorage.getItem(Xu);if(e)return JSON.parse(e)}catch(e){console.error("Failed to load models cache:",e)}return{}}function _k(e,t){try{let n=Pv();n[e]={models:t,timestamp:Date.now()},localStorage.setItem(Xu,JSON.stringify(n))}catch(n){console.error("Failed to save models cache:",n)}}function Ok(e){try{let t=Pv(),n=t[e];if(n){if(Date.now()-n.timestamp<Dk)return n.models;delete t[e],localStorage.setItem(Xu,JSON.stringify(t))}}catch(t){console.error("Failed to get cached models:",t)}return null}function zk(e,t){if(!_o(e)||!t?.trim())return e;let n=e==="ollama"?Ak(t):t.trim().toLowerCase();return`${e}:${n}`}var Bk="chat-config-source",kv=["openai","anthropic","google"];async function Hk(e,t){let n={};t&&(n.Authorization=`Bearer ${t}`);let o;try{o=await fetch(`${e}/models`,{headers:n})}catch{throw new Error("Failed to reach the server. Check the URL is correct and that CORS is enabled on the server.")}if(!o.ok)throw new Error(`Failed to fetch models: ${o.statusText}`);if(!(o.headers.get("content-type")??"").includes("application/json"))throw new Error("Invalid URL \u2014 response was not JSON");let s=await o.json();if(!Array.isArray(s?.data))throw new Error("Unexpected response format \u2014 expected { data: [...] } from the OpenAI-compatible endpoint");return s.data.map(a=>({id:a.id}))}async function Uk(e){let t=await fetch("https://api.openai.com/v1/models",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw new Error(`Failed to fetch OpenAI models: ${t.statusText}`);return(await t.json()).data.map(o=>({id:o.id}))}async function Fk(e){let t=await fetch("https://api.anthropic.com/v1/models",{headers:{"x-api-key":e,"anthropic-version":"2023-06-01","anthropic-dangerous-direct-browser-access":"true"}});if(!t.ok)throw new Error(`Failed to fetch Anthropic models: ${t.statusText}`);return(await t.json()).data.map(o=>({id:o.id,displayName:o.display_name}))}async function $k(e){let t=await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${e}`);if(!t.ok)throw new Error(`Failed to fetch Google models: ${t.statusText}`);return((await t.json()).models||[]).map(o=>({id:o.name,displayName:o.displayName}))}async function Vk(e){let t=await fetch("https://openrouter.ai/api/v1/models",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw new Error(`Failed to fetch OpenRouter models: ${t.statusText}`);return(await t.json()).data.map(o=>({id:o.id,displayName:o.name}))}async function jk(e,t){let n;try{n=await fetch(Ek(e,"/api/tags"),{headers:{...t.trim()?{Authorization:`Bearer ${t.trim()}`}:{}}})}catch(r){throw new Lk(r)}if(!n.ok)throw new Error(`Failed to fetch Ollama models: ${n.statusText}`);return((await n.json()).models||[]).map(r=>({id:r.model||r.name||""}))}function ei({open:e,onOpenChange:t,tempProvider:n,tempModel:o,tempApiKey:r,tempBaseUrl:s,onProviderChange:a,onModelChange:i,onApiKeyChange:c,onBaseUrlChange:l,onSave:u,onClear:p,showClearButton:d=!1,buttonLabel:h="Configure API Key",hostedInspector:m=!1,freeTierInfo:b,managedCloudInfo:f,useManagedCloud:v=!1,onSaveManagedCloud:x}){let{resolvedTheme:y}=go(),g=Xl(y),C=y==="dark",[k,I]=ts([]),[M,N]=ts(!1),[E,T]=ts(null),[S,P]=ts(!1),[A,R]=ts(!1),[W,H]=ts(!1),[Y,U]=ts(v?0:1),V=zk(n,s),K=!!(m||b||f),$=!!(f&&Y===0);Yu(()=>{e&&U(v?0:1)},[e,v]),Yu(()=>{let D=Kr(n),_=_o(n);if($||!e||!n||D&&!r.trim()||_&&!s.trim()){I([]),T(null);return}let Le=setTimeout(async()=>{let Oe=Ok(V);if(Oe){I(Oe),T(null);return}N(!0),T(null);try{let He=[];n==="openai-compatible"?He=await Hk(s,r):n==="openai"?He=await Uk(r):n==="anthropic"?He=await Fk(r):n==="google"?He=await $k(r):n==="openrouter"?He=await Vk(r):n==="ollama"&&(He=await jk(s,r)),_k(V,He),I(He)}catch(He){T(He instanceof Error?He.message:"Failed to fetch models. Please check your API key."),I([])}finally{N(!1)}},500);return()=>clearTimeout(Le)},[r,s,n,e,V,$]);let G=Ik(null);Yu(()=>{if(!e||$){e||(G.current=null);return}let D=G.current;D!==null&&D!==n&&i(""),G.current=n},[n,e,i,$]);let te=_o(n),Z=!Kr(n),z=e&&(!Kr(n)||!!r.trim())&&(!te||!!s.trim()),F=Z?"API Key (optional)":"API Key",ie=Z?n==="ollama"?"Leave empty for local Ollama":"Enter your API key (optional)":"Enter your API key",le=n==="openai-compatible"?"http://localhost:11434/v1":dr(n),Ne=n==="openai-compatible"?"Base URL of your OpenAI-compatible API. Local servers must have CORS enabled.":null,de=n==="ollama"?"Optional for local Ollama. Stored locally and never sent to our servers.":"Your API key is stored locally and never sent to our servers.",re=f?f.models.reduce((D,_)=>(D[_.provider]||(D[_.provider]=[]),D[_.provider].push(_),D),{}):{},me=f?.models.find(D=>D.id===f.selectedModelId),be=kv.filter(D=>re[D]?.length),pe=me?.provider??be[0]??"",We=!!me&&!kv.includes(me.provider),Ke=pe?re[pe]??[]:[],Ve=!!p&&d&&(!f||Y===1),pt=()=>{if($&&x){x();return}u()},lt=$?!!(f?.isLoading||!f?.selectedModelId||f?.models.length===0):Kr(n)&&!r.trim()||te&&!s.trim()||!o.trim();return ee(on,{open:e,onOpenChange:t,children:$e(Xt,{className:"max-w-md","data-testid":"chat-config-dialog",children:[$e(Gt,{children:[ee($t,{children:K?"Configure Chat":"LLM Provider Configuration"}),ee(To,{children:f?"Pick a Manufact cloud model or bring your own API key.":b?"Chat requires an LLM. You can chat for free if you have a Manufact account, or you can use your own API key (not sent to Manufact).":"Configure your LLM provider and API key to start chatting with the MCP server"})]}),$e("div",{className:"space-y-4",children:[b&&$e("button",{type:"button",onClick:b.onLoginClick,"data-testid":"chat-config-sign-in-card",className:"relative w-full cursor-pointer overflow-hidden rounded-2xl border-0 text-left transition-opacity hover:opacity-95 active:opacity-90",children:[ee("div",{className:"absolute inset-0 bg-[#edf2ff] dark:bg-background","aria-hidden":!0}),ee("div",{className:"absolute inset-0 dark:opacity-90",children:ee(Yl,{className:"absolute inset-0 h-full w-full",colors:[...g],grainOverlay:C?.1:.15})}),$e("div",{className:"relative flex items-center justify-between gap-4 px-4 py-3.5",children:[$e("div",{className:"text-sm font-medium text-foreground",children:[ee("p",{children:"Chat for free with a"}),$e("p",{className:"mt-1 flex items-center gap-1.5",children:[ee(xv,{symbolSize:14,textClassName:"text-sm"}),"account"]})]}),ee(L,{size:"sm",render:ee("span",{"aria-hidden":"true"}),nativeButton:!1,tabIndex:-1,className:"pointer-events-none shrink-0",children:"Sign in"})]})]}),f&&ee("div",{className:"flex justify-center",children:$e(Za,{selectedIndex:Y,onSelect:U,idPrefix:Bk,className:"w-fit",children:[ee(es,{index:0,label:"Manufact cloud"}),ee(es,{index:1,label:"API key"})]})}),$e("div",{className:w("space-y-2",f&&"!mt-2"),children:[ee(Be,{children:"Provider"}),$?$e(un,{value:pe,onValueChange:D=>{let _=f?.models.find(j=>j.provider===D);_&&f?.onModelChange(_.id)},children:[ee(hn,{className:"rounded-md",leading:pe?ee(so,{provider:pe,className:"shrink-0"}):void 0,children:ee(fn,{})}),$e(gn,{children:[We&&$e(ht,{value:pe,label:qt(pe),disabled:!0,children:[qt(pe)," (current)"]}),be.map(D=>ee(ht,{value:D,label:qt(D),children:$e("div",{className:"flex items-center gap-2",children:[ee(so,{provider:D}),ee("span",{children:qt(D)})]})},D))]})]}):$e(un,{value:n,onValueChange:D=>a(D),children:[ee(hn,{className:"rounded-md",leading:ee(so,{provider:n,className:"shrink-0"}),children:ee(fn,{})}),$e(gn,{children:[ee(ht,{value:"openai",label:qt("openai"),children:$e("div",{className:"flex items-center gap-2",children:[ee(so,{provider:"openai"}),ee("span",{children:qt("openai")})]})}),ee(ht,{value:"anthropic",label:qt("anthropic"),children:$e("div",{className:"flex items-center gap-2",children:[ee(so,{provider:"anthropic"}),ee("span",{children:qt("anthropic")})]})}),ee(ht,{value:"google",label:qt("google"),children:$e("div",{className:"flex items-center gap-2",children:[ee(so,{provider:"google"}),ee("span",{children:qt("google")})]})}),ee(ht,{value:"ollama",label:qt("ollama"),children:$e("div",{className:"flex items-center gap-2",children:[ee(so,{provider:"ollama"}),ee("span",{children:qt("ollama")})]})}),ee(ht,{value:"openrouter",label:qt("openrouter"),children:$e("div",{className:"flex items-center gap-2",children:[ee(so,{provider:"openrouter"}),ee("span",{children:qt("openrouter")})]})}),ee(ht,{value:"openai-compatible",label:qt("openai-compatible"),children:ee("div",{className:"flex items-center gap-2",children:ee("span",{children:qt("openai-compatible")})})})]})]})]}),!$&&te&&$e("div",{className:"space-y-2",children:[ee(Be,{children:"Base URL"}),ee(Ae,{value:s,onChange:D=>l(D.target.value),placeholder:le,"data-testid":"chat-config-base-url-input"}),Ne&&ee("p",{className:"text-xs text-muted-foreground",children:Ne})]}),!$&&$e("div",{className:"space-y-2",children:[ee(Be,{children:F}),$e("div",{className:"relative",children:[ee(Ae,{type:W?"text":"password",value:r,onChange:D=>c(D.target.value),placeholder:ie,className:"pr-10","data-testid":"chat-config-api-key-input"}),ee(L,{type:"button",variant:"ghost",size:"sm",className:"absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent",onClick:()=>H(!W),children:W?ee(Rk,{className:"h-4 w-4 text-muted-foreground"}):ee(Pk,{className:"h-4 w-4 text-muted-foreground"})})]}),ee("p",{className:"text-xs text-muted-foreground",children:de})]}),$?$e("div",{className:"space-y-2",children:[ee(Be,{children:"Model"}),f?.isLoading?$e("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[ee(Tv,{className:"h-4 w-4 animate-spin"}),ee("span",{children:"Loading models\u2026"})]}):Ke.length>0?$e(rr,{open:A,modal:!0,onOpenChange:R,children:[ee(sr,{render:$e(L,{variant:"outline",role:"combobox","aria-expanded":A,className:"w-full justify-between rounded-md","data-testid":"chat-config-cloud-model-select",disabled:We,children:[ee("span",{className:"inline-flex min-w-0 items-center gap-2 truncate",children:me?$e(qk,{children:[ee(so,{provider:me.provider,className:"shrink-0"}),ee("span",{className:"truncate",children:uc(me.name,me.provider)})]}):"Select a model\u2026"}),ee(Nv,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]}),nativeButton:!0}),ee(ar,{className:"w-full p-0",align:"start",children:$e(sc,{children:[ee(ac,{placeholder:"Search models\u2026",className:"h-9"}),$e(ic,{children:[ee(lc,{children:"No model found."}),ee(cc,{children:Ke.map(D=>$e(dc,{value:D.id,keywords:[D.name,D.id,D.provider],onSelect:_=>{f?.onModelChange(_),R(!1)},children:[uc(D.name,D.provider),ee(Sv,{className:w("ml-auto h-4 w-4",f?.selectedModelId===D.id?"opacity-100":"opacity-0")})]},D.id))})]})]})})]}):ee("p",{className:"text-sm text-muted-foreground",children:"Cloud models unavailable \u2014 try again or use your own key."})]}):z&&$e("div",{className:"space-y-2",children:[ee(Be,{children:"Model"}),M?$e("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[ee(Tv,{className:"h-4 w-4 animate-spin"}),ee("span",{children:"Loading models..."})]}):E?ee("div",{className:"text-sm text-destructive",children:E}):k.length>0?$e(rr,{open:S,modal:!0,onOpenChange:P,children:[ee(sr,{render:$e(L,{variant:"outline",role:"combobox","aria-expanded":S,className:"w-full justify-between rounded-md","data-testid":"chat-config-model-select",children:[ee("span",{className:"truncate",children:o&&(k.find(D=>D.id===o)?.displayName||k.find(D=>D.id===o)?.id)||"Select a model..."}),ee(Nv,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]}),nativeButton:!0}),ee(ar,{className:"w-full p-0",align:"start",children:$e(sc,{children:[ee(ac,{placeholder:"Search models...",className:"h-9"}),$e(ic,{children:[ee(lc,{children:"No model found."}),ee(cc,{children:k.map(D=>$e(dc,{value:D.id,keywords:D.displayName,onSelect:_=>{i(_===o?"":_),P(!1)},children:[D.displayName||D.id,ee(Sv,{className:w("ml-auto h-4 w-4",o===D.id?"opacity-100":"opacity-0")})]},D.id))})]})]})})]}):ee(Ae,{value:o,onChange:D=>i(D.target.value),placeholder:"Enter model name manually","data-testid":"chat-config-model-input"})]}),$e("div",{className:"flex justify-between",children:[Ve&&ee(L,{variant:"outline",onClick:p,children:"Clear Config"}),$e(L,{onClick:pt,disabled:lt,className:Ve?"ml-auto":"","data-testid":"chat-config-save-button",children:[ee(Mk,{className:"h-4 w-4 mr-2"}),"Save Configuration"]})]})]})]})})}var Qu="rounded-full bg-background/80 backdrop-blur-md supports-[backdrop-filter]:bg-background/60 dark:bg-zinc-950/75 dark:supports-[backdrop-filter]:bg-zinc-950/55",Zu=w(Qu,"w-fit"),mc=w(Qu,"h-9 gap-1.5 px-3");import{jsx as Ft,jsxs as wo}from"react/jsx-runtime";var Gk="chat-view";function em({llmConfig:e,hasMessages:t,configDialogOpen:n,onConfigDialogOpenChange:o,onClearChat:r,tempProvider:s,tempModel:a,tempApiKey:i,tempBaseUrl:c,onProviderChange:l,onModelChange:u,onApiKeyChange:p,onBaseUrlChange:d,onSaveConfig:h,onClearConfig:m,hideConfigButton:b,hostedInspector:f,freeTierInfo:v,managedCloudInfo:x,useManagedCloud:y,onSaveManagedCloud:g,showClearButton:C,clearButtonLabel:k,hideTitle:I,clearButtonHideIcon:M,clearButtonHideShortcut:N,clearButtonVariant:E,hideClearButton:T,onCopyChat:S,onExportChat:P,activeChatId:A,chatTitle:R,showViewToggle:W,viewIndex:H=0,onViewIndexChange:Y,elevatedHeader:U}){return wo("div",{className:w("relative flex w-full items-center gap-2 overflow-visible",jo,U?"pointer-events-none absolute top-0 right-0 z-50":"absolute top-0 right-0 z-10"),children:[Ft("div",{className:w("flex min-w-0 flex-1 items-center",U&&"pointer-events-auto"),children:!I&&Ft("h2",{className:w(qo,Zu),children:A?Ft(Ka,{chatId:A,title:R??fr},A):fr})}),W&&Y&&Ft("div",{className:w("absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 overflow-visible px-1",U&&"pointer-events-auto"),children:wo(Za,{selectedIndex:H,onSelect:Y,idPrefix:Gk,className:"shrink-0 overflow-visible","data-testid":"chat-view-tabs",children:[Ft(es,{label:"Conv",index:0}),Ft(es,{label:"Raw",index:1})]})}),wo("div",{className:w("ml-auto flex shrink-0 items-center gap-2",U&&"pointer-events-auto"),children:[!T&&t&&wo("div",{className:"flex items-center gap-1",children:[S&&wo(L,{"data-testid":"chat-copy-button",variant:"ghost",size:"sm",className:mc,onClick:S,children:[Ft(Wk,{className:"h-4 w-4"}),Ft("span",{className:"hidden sm:inline",children:"Copy"})]}),P&&wo(Ir,{children:[Ft(Go,{render:wo(L,{"data-testid":"chat-export-button",variant:"ghost",size:"sm",className:mc,children:[Ft(Kk,{className:"h-4 w-4"}),Ft("span",{className:"hidden sm:inline",children:"Export"})]}),nativeButton:!0}),wo(Er,{align:"end",children:[Ft(Un,{"data-testid":"chat-export-json",onClick:()=>P("json"),children:"Export as JSON"}),Ft(Un,{"data-testid":"chat-export-markdown",onClick:()=>P("markdown"),children:"Export as Markdown"})]})]}),Ft("div",{className:"w-px h-4 bg-border mx-1"}),wo(Ie,{children:[Ft(Re,{render:wo(L,{variant:E??"default",size:"default",className:`p-2 cursor-pointer ${N?"sm:px-3":"sm:pr-1 sm:pl-3"}`,onClick:r,children:[!M&&Ft(Jk,{className:"h-4 w-4 sm:mr-2"}),Ft("span",{className:"hidden sm:inline",children:k??"New Chat"}),!N&&Ft("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:"\u2318O"})]}),nativeButton:!0}),Ft(Me,{children:Ft("p",{children:k??"New Chat"})})]})]}),(!b||f||v||x)&&Ft(ei,{open:n,onOpenChange:o,tempProvider:s,tempModel:a,tempApiKey:i,tempBaseUrl:c,onProviderChange:l,onModelChange:u,onApiKeyChange:p,onBaseUrlChange:d,onSave:h,onClear:m,showClearButton:C??(!!e&&!v&&!x),buttonLabel:e?"Change API Key":"Configure API Key",hostedInspector:f,freeTierInfo:v,managedCloudInfo:x,useManagedCloud:y,onSaveManagedCloud:g})]})]})}import{ArrowUp as AP,Loader2 as LP}from"lucide-react";import{Image as Zk,Paperclip as eP,X as tP}from"lucide-react";import{useRef as nP}from"react";import{Wrench as Yk}from"lucide-react";import{useCallback as Rv,useMemo as Xk,useState as Qk}from"react";import{jsx as Ho,jsxs as vr}from"react/jsx-runtime";function Mv({tools:e,disabledTools:t,onDisabledToolsChange:n,disabled:o}){let[r,s]=Qk(!1),a=e.length-t.size,i=t.size===0,c=t.size>0&&t.size<e.length,l=Rv(d=>{let h=new Set(t);h.has(d)?h.delete(d):h.add(d),n(h)},[t,n]),u=Rv(()=>{n(i?new Set(e.map(d=>d.name)):new Set)},[i,e,n]),p=Xk(()=>[...e].sort((d,h)=>d.name.localeCompare(h.name)),[e]);return e.length===0?null:vr(rr,{open:r,onOpenChange:s,children:[vr(Ie,{children:[Ho(Re,{render:Ho(sr,{render:vr(L,{variant:"ghost",size:"sm",disabled:o,className:w("h-auto gap-1 rounded-full px-2 py-2",c?"text-amber-500 dark:text-amber-400":"text-muted-foreground hover:text-foreground"),type:"button","data-testid":"chat-tool-selector",children:[Ho(Yk,{className:"h-4 w-4 shrink-0"}),c&&Ho("span",{className:"flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-amber-500 px-1 text-[9px] font-bold leading-none text-white",children:a})]}),nativeButton:!0}),nativeButton:!0}),Ho(Me,{side:"top",children:vr("p",{children:["Tools (",a,"/",e.length,")"]})})]}),vr(ar,{className:"w-72 gap-0 p-0",align:"start",side:"top",sideOffset:8,children:[vr("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[vr("span",{className:"text-xs font-medium text-muted-foreground",children:["Allowed Tools (",a,"/",e.length,")"]}),Ho(L,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:u,type:"button",children:i?"Disable All":"Enable All"})]}),Ho("div",{className:"max-h-64 overflow-y-auto",children:p.map(d=>{let h=!t.has(d.name);return vr("button",{type:"button",className:"flex items-center gap-2.5 w-full px-3 py-1.5 text-left hover:bg-accent/50 transition-colors cursor-pointer",onClick:()=>l(d.name),children:[Ho($a,{checked:h,className:"pointer-events-none",tabIndex:-1}),Ho("span",{className:"min-w-0 flex-1 truncate text-sm font-mono",children:d.name})]},d.name)})})]})]})}import{jsx as zn,jsxs as ti}from"react/jsx-runtime";function Iv({variant:e="default",inputValue:t,isConnected:n,isLoading:o,textareaRef:r,attachments:s,placeholder:a="Ask a question",className:i,showAttachButton:c=!0,tools:l,disabledTools:u,onDisabledToolsChange:p,onInputChange:d,onKeyDown:h,onKeyUp:m,onClick:b,onAttachmentAdd:f,onAttachmentRemove:v,inlineControls:x,trailingControls:y}){let g=kt(),C=nP(null),k=e==="fullscreen",I=N=>{let E=N.target.files;if(E&&E.length>0)for(let T=0;T<E.length;T++)f(E[T]);C.current&&(C.current.value="")},M=s.length>0;return ti("div",{className:"relative w-full","data-chat-input-variant":e,children:[!k&&M&&zn("div",{className:"absolute top-0 left-0 right-0 z-20 p-3 flex gap-2 flex-wrap",children:s.map((N,E)=>ti("div",{className:"relative group bg-zinc-100/90 dark:bg-zinc-900/90 backdrop-blur-sm rounded-lg p-2 flex items-center gap-2 border border-zinc-200 dark:border-zinc-700","data-testid":`chat-attachment-${E}`,children:[zn(Zk,{className:"h-4 w-4 text-muted-foreground shrink-0"}),ti("div",{className:"flex flex-col min-w-0",children:[zn("span",{className:"text-xs font-medium truncate max-w-[150px]",children:N.name||"Image"}),N.size&&zn("span",{className:"text-xs text-muted-foreground",children:Ng(N.size)})]}),zn("button",{onClick:()=>v(E),className:"shrink-0 p-1 rounded-full hover:bg-zinc-200 dark:hover:bg-zinc-800 transition-colors",title:"Remove attachment",type:"button","data-testid":`chat-attachment-remove-${E}`,children:zn(tP,{className:"h-3 w-3"})})]},E))}),zn(fo,{ref:r,value:t,onChange:N=>d(N.target.value),onKeyDown:h,onKeyUp:m,onClick:b,placeholder:n?a:"Server not connected",className:w(k?"field-sizing-fixed h-11 min-h-11 max-h-11 resize-none overflow-hidden py-2.5 pl-4 pr-12":"p-4 pb-14 min-h-[150px] max-h-[300px]",g.container,!k&&M&&"pt-20",i),rows:k?1:void 0,disabled:!n||o,"data-testid":"chat-input"}),zn("input",{ref:C,type:"file",accept:"image/*",multiple:!0,onChange:I,className:"hidden","aria-label":"Upload images"}),k?y?zn("div",{className:"absolute right-1.5 top-1/2 flex -translate-y-1/2 items-center",children:y}):null:ti("div",{className:"absolute inset-x-0 bottom-0 flex items-center justify-between gap-2 p-3",children:[ti("div",{className:"flex min-w-0 flex-1 items-center gap-1",children:[c&&zn(L,{variant:"ghost",size:"sm",onClick:()=>C.current?.click(),disabled:!n||o,className:"h-auto w-auto aspect-square rounded-full p-2 text-muted-foreground hover:text-foreground",title:"Attach images",type:"button","data-testid":"chat-attach-button",children:zn(eP,{className:"h-4 w-4"})}),l&&l.length>0&&u&&p&&zn(Mv,{tools:l,disabledTools:u,onDisabledToolsChange:p,disabled:!n||o}),x]}),y?zn("div",{className:"flex shrink-0 items-center gap-1.5",children:y}):null]})]})}import{MessageSquare as oP,X as rP}from"lucide-react";import{jsx as ni,jsxs as sP}from"react/jsx-runtime";function Ev({promptResults:e,onDeletePromptResult:t,offsetForSkills:n=!1}){return ni("div",{className:`absolute ${n?"top-12":"top-4"} left-4 right-4 flex gap-2 overflow-x-auto z-20 flex-nowrap`,style:{scrollbarWidth:"none",msOverflowStyle:"none"},children:e.map(({promptName:o},r)=>sP(L,{type:"button",className:"flex items-center gap-2 bg-zinc-200 text-zinc-700 dark:text-zinc-300 text-[10px] px-1.5 py-0.5 dark:bg-zinc-700 rounded-lg border border-zinc-200 dark:border-zinc-300 font-medium hover:bg-zinc-300 dark:hover:bg-zinc-600",children:[ni(oP,{className:"h-3.5 w-3.5 shrink-0"}),ni("span",{className:"truncate",title:o,children:o}),ni("span",{className:"ml-1 h-4 w-4 rounded-full bg-zinc-400 dark:bg-zinc-600 hover:bg-zinc-500 dark:hover:bg-zinc-500 flex items-center justify-center cursor-pointer shrink-0 transition-colors",onClick:s=>{s.stopPropagation(),t(r)},title:"Remove prompt",role:"button",tabIndex:0,children:ni(rP,{className:"h-2.5 w-2.5 text-white"})})]},r))})}import{MessageSquare as aP}from"lucide-react";import{useEffect as iP}from"react";import{jsx as br,jsxs as pc}from"react/jsx-runtime";function Av({isOpen:e,focusedIndex:t,prompts:n,selectedPrompt:o,onPromptSelect:r}){return e?(iP(()=>{if(t>=0){let s=document.getElementById(`prompt-suggestion-${t}`);s&&s.scrollIntoView({behavior:"smooth",block:"nearest"})}},[t]),br("div",{className:"absolute bottom-full left-0 right-0 max-w-3xl w-full max-h-[300px] overflow-y-auto rounded-lg border border-zinc-200 dark:border-zinc-800 bg-white dark:bg-zinc-900 shadow-lg z-30 flex flex-col gap-2 mb-1","data-testid":"chat-prompts-dropdown",children:pc("div",{className:"p-2",children:[n.length>0&&br("div",{className:"text-xs font-medium text-zinc-900 dark:text-zinc-100 mb-2",children:"Prompts"}),n.map((s,a)=>pc(Ie,{children:[br(Re,{render:pc(L,{id:`prompt-suggestion-${a}`,type:"button",variant:"ghost",className:w("w-full flex items-center px-3 py-2 rounded-md hover:bg-zinc-200 dark:hover:bg-zinc-700 transition-colors text-left justify-start",t===a&&"bg-zinc-200 dark:bg-zinc-700"),onClick:()=>r(s),"data-testid":`chat-prompt-option-${a}`,children:[br("div",{className:"flex items-center justify-center shrink-0",children:br(aP,{className:"h-4 w-4 text-zinc-600 dark:text-zinc-400"})}),br("div",{className:"flex-1 min-w-0",children:pc("div",{className:"text-sm font-medium text-zinc-900 dark:text-zinc-100 flex items-center gap-2",children:[s.name,o?.name===s.name&&br(An,{className:"size-3 text-zinc-600 dark:text-zinc-400"})]})})]}),nativeButton:!0}),br(Me,{children:s.description})]},a))]})})):null}import{motion as TP}from"motion/react";import{useMemo as Wv,useState as Kv}from"react";import{ExternalLink as NP}from"lucide-react";import{toast as Jv}from"sonner";import{forwardRef as hP,useCallback as Rn,useEffect as ao,useId as vP,useMemo as ri,useRef as Uo,useState as ns}from"react";import{AnimatePresence as js,motion as Co}from"motion/react";import{RadioGroup as bP}from"@base-ui/react/radio-group";import{Radio as yP}from"@base-ui/react/radio";import{CheckboxGroup as xP}from"@base-ui/react/checkbox-group";import{Checkbox as wP}from"@base-ui/react/checkbox";import{Field as sm}from"@base-ui/react/field";import{useEffect as rm,useLayoutEffect as lP,useRef as tm,useState as cP}from"react";import{AnimatePresence as dP,motion as uP}from"motion/react";import{jsx as Dv}from"react/jsx-runtime";var mP=typeof window<"u"?lP:rm,$s=ce.moderate,oi=.07,pP=($s.duration+oi)*1e3+80,fP=$s.duration*1e3+80;function nm(e,t){let n=t.filter(s=>s.start>=e.start&&s.end<=e.end).sort((s,a)=>s.start-a.start);if(n.length!==2)return null;let[o,r]=n;return r.start===o.end+2?{up:o,lo:r,gap:o.end+1}:null}function gP(e,t,n,o){let r=n[e],s=n[t];if(!r||!s)return null;if(o==="y")return{top:r.top,left:Math.min(r.left,s.left),width:Math.max(r.width,s.width),height:s.top+s.height-r.top};let a=Math.min(r.left,s.left),i=Math.max(r.left+r.width,s.left+s.width);return{top:Math.min(r.top,s.top),left:a,width:i-a,height:Math.max(r.height,s.height)}}function _v(e,t){return t==="y"?e.top+e.height/2:e.left+e.width/2}function fc(e,t){return t==="y"?[e,e,0,0]:[e,0,0,e]}function yr(e,t){return t==="y"?[0,0,e,e]:[0,e,e,0]}function om(e){return[e,e,e,e]}function Lv(e,t,n,o,r){let s=_v(n,o);if(o==="y"){let i=t.top+t.height;e.height=s-e.top,e.radii=fc(r,o),e.instant=!0,t.top=s,t.height=i-s,t.radii=yr(r,o),t.instant=!0,t.enterFrom={top:s,left:t.left,width:t.width,height:i-s,radii:yr(r,o)};return}let a=t.left+t.width;e.width=s-e.left,e.radii=fc(r,o),e.instant=!0,t.left=s,t.width=a-s,t.radii=yr(r,o),t.instant=!0,t.enterFrom={top:t.top,left:s,width:a-s,height:t.height,radii:yr(r,o)}}function Ov(e,t,n,o="y"){let[r,s]=cP([]),a=tm([]),i=tm(0),c=tm(new Map),l=e.map(d=>`${d.id}:${d.start}-${d.end}`).join("|");mP(()=>{let d=a.current,h=e,m=[];for(let f of h){let v=nm(f,d);v&&(f.id===v.up.id||f.id===v.lo.id)&&m.push({tid:++i.current,kind:"merge",survivorId:f.id,otherId:f.id===v.up.id?v.lo.id:v.up.id,gapIndex:v.gap,phase:"converge"})}for(let f of d){let v=nm(f,h);v&&m.push({tid:++i.current,kind:"split",survivorId:v.up.id,otherId:v.lo.id,gapIndex:v.gap,phase:"splitIn"})}a.current=h.map(f=>({...f}));for(let f of m)c.current.set(f.tid,setTimeout(()=>{c.current.delete(f.tid),s(v=>v.some(x=>x.tid===f.tid)?v.flatMap(x=>x.tid!==f.tid?[x]:x.kind==="merge"?[{...x,phase:"commit"}]:[]):v)},f.kind==="merge"?pP:fP));let b=f=>f.kind==="merge"?h.some(v=>v.id===f.survivorId&&f.gapIndex>v.start&&f.gapIndex<v.end):h.some(v=>v.id===f.survivorId&&v.end===f.gapIndex-1)&&h.some(v=>v.id===f.otherId&&v.start===f.gapIndex+1);s(f=>{for(let v of f){if(b(v))continue;let x=c.current.get(v.tid);x!==void 0&&(clearTimeout(x),c.current.delete(v.tid))}return[...f.filter(b),...m]})},[l]),rm(()=>{let d=c.current;return()=>d.forEach(clearTimeout)},[]),rm(()=>{r.some(d=>d.phase==="splitIn"||d.phase==="commit")&&s(d=>d.flatMap(h=>h.phase==="commit"?[]:[{...h,phase:h.phase==="splitIn"?"diverge":h.phase}]))},[r]);let u=[];for(let d of e){let h=gP(d.start,d.end,t,o);h&&u.push({key:`sel-${d.id}`,...h,radii:om(n),instant:!1,exitInstant:!1,delayCorners:!1})}let p=new Map(u.map(d=>[d.key,d]));for(let d of r){let h=t[d.gapIndex],m=p.get(`sel-${d.survivorId}`);if(!h||!m)continue;let b=_v(h,o);if(d.kind==="merge"){if(d.phase==="commit"){m.instant=!0,o==="y"?u.push({key:`sel-${d.otherId}`,top:b,left:m.left,width:m.width,height:m.top+m.height-b,radii:yr(n,o),instant:!0,exitInstant:!0,delayCorners:!1,opacity:0}):u.push({key:`sel-${d.otherId}`,top:m.top,left:b,width:m.left+m.width-b,height:m.height,radii:yr(n,o),instant:!0,exitInstant:!0,delayCorners:!1,opacity:0});continue}let f=Math.min(oi+.03,Math.max(oi,oi+b/Math.max(o==="y"?h.height:h.width,1)*.002));if(o==="y"){let v=m.top+m.height;m.height=b-m.top,m.radii=fc(n,o),m.delayCorners=!0,m.cornerDelay=f,u.push({key:`sel-${d.otherId}`,top:b,left:m.left,width:m.width,height:v-b,radii:yr(n,o),enterFrom:{top:b,left:m.left,width:m.width,height:v-b,radii:om(n)},instant:!1,exitInstant:!0,delayCorners:!0,cornerDelay:f})}else{let v=m.left+m.width;m.width=b-m.left,m.radii=fc(n,o),m.delayCorners=!0,m.cornerDelay=f,u.push({key:`sel-${d.otherId}`,top:m.top,left:b,width:v-b,height:m.height,radii:yr(n,o),enterFrom:{top:m.top,left:b,width:v-b,height:m.height,radii:om(n)},instant:!1,exitInstant:!0,delayCorners:!0,cornerDelay:f})}}else if(d.phase==="splitIn"){let f=p.get(`sel-${d.otherId}`);if(!f)continue;Lv(m,f,h,o,n)}}for(let d of a.current){let h=nm(d,e),m=h&&t[h.gap];if(!h||!m)continue;let b=p.get(`sel-${h.up.id}`),f=p.get(`sel-${h.lo.id}`);!b||!f||Lv(b,f,m,o,n)}return u}function zv({blocks:e,dimmed:t}){return Dv(dP,{children:e.map(n=>{let o=n.delayCorners?{...$s,delay:n.cornerDelay??oi}:$s,r=n.opacity??(t?.8:1);return Dv(uP.div,{"aria-hidden":!0,className:"absolute bg-active pointer-events-none",initial:n.enterFrom?{opacity:r,top:n.enterFrom.top,left:n.enterFrom.left,width:n.enterFrom.width,height:n.enterFrom.height,borderTopLeftRadius:n.enterFrom.radii[0],borderTopRightRadius:n.enterFrom.radii[1],borderBottomRightRadius:n.enterFrom.radii[2],borderBottomLeftRadius:n.enterFrom.radii[3]}:!1,animate:{top:n.top,left:n.left,width:n.width,height:n.height,borderTopLeftRadius:n.radii[0],borderTopRightRadius:n.radii[1],borderBottomRightRadius:n.radii[2],borderBottomLeftRadius:n.radii[3],opacity:r},exit:{opacity:0,transition:n.exitInstant?{duration:0}:$s.exit},transition:n.instant?{duration:0}:{...$s,borderTopLeftRadius:o,borderTopRightRadius:o,borderBottomRightRadius:o,borderBottomLeftRadius:o,opacity:{duration:.08}}},n.key)})})}import{Fragment as Hv,jsx as he,jsxs as an}from"react/jsx-runtime";function CP(e,t){return e.id??`q-${t}`}function gc(e,t){return e.id??`o-${t}`}var Vs=[],am=hP(function({questions:t,currentIndex:n,defaultCurrentIndex:o=0,onCurrentIndexChange:r,answers:s,defaultAnswers:a,onAnswersChange:i,onComplete:c,onSkip:l,skipLabel:u="Skip",intro:p,onCancel:d,cancelLabel:h="Cancel",footerLeading:m,className:b,...f},v){let[x,y]=ns(o),g=n!==void 0,C=g?n:x,k=Rn(O=>{g||y(O),r?.(O)},[g,r]),[I,M]=ns(a??{}),N=s!==void 0,E=N?s:I,T=Uo(E);ao(()=>{T.current=E},[E]);let S=Rn(O=>{let ne=O(T.current);return T.current=ne,N||M(ne),i?.(ne),ne},[N,i]),P=kt(),A=Tr("arrow-left"),R=Tr("arrow-right"),W=ri(()=>function(ne){return he(A,{...ne,className:w(ne.className,"hidden sm:block")})},[A]),H=ri(()=>function(ne){return he(R,{...ne,className:w(ne.className,"hidden sm:block")})},[R]),[Y]=ns(()=>{if(typeof navigator>"u")return!1;let O=navigator,ne=O.userAgentData?.platform||O.platform||"";return/mac/i.test(ne)}),U=vP(),V=t.length,K=Math.max(0,Math.min(C,Math.max(0,V-1))),$=t[K],G=$?CP($,K):"",te=E[G],Z=!!$?.multiSelect,z=$?.skippable!==!1,F=!!$?.freeText,ie=$?.freeTextMultiline!==!1,le=!F&&!!$?.allowOther,Ne=ri(()=>te?.selectedIds??[],[te]),de=te?.otherText??"",re=$?.options??[],me=le?re.length:-1,be=re.length+(le?1:0),pe=Uo(null),We=!!$;ao(()=>{if(!We)return;let O=pe.current;if(O)return Vs.push(O),()=>{let ne=Vs.indexOf(O);ne!==-1&&Vs.splice(ne,1)}},[We]);let Ke=Uo(null),Ve=Uo(null),pt=Uo(0),lt=Uo(new Map),{activeIndex:D,setActiveIndex:_,itemRects:j,sessionRef:Le,handlers:Oe,registerItem:He,measureItems:tt}=Rr(Ke);ao(()=>{tt()},[tt,G,be,P]);let[ln,Nt]=ns(!1);ao(()=>{Nt(!1)},[G]),ao(()=>{let O=Ve.current;if(!O)return;O.style.height="0px",O.style.height=`${O.scrollHeight}px`;let ne=parseFloat(window.getComputedStyle(O).lineHeight)||18;Nt(O.scrollHeight>ne*1.5),tt()},[de,tt,G]),ao(()=>{F&&Ve.current?.focus({preventScroll:!0})},[F,G]);let Ze=Uo(null),[cn,co]=ns("auto");ao(()=>{let O=Ze.current;if(!O)return;let ne=()=>co(O.offsetHeight);ne();let Ee=new ResizeObserver(ne);return Ee.observe(O),()=>Ee.disconnect()},[]);let[Pt,Kt]=ns(null),[Cn,Tt]=ns(null);ao(()=>{_(null),Kt(null),Tt(null)},[K,_]);let Yt=Uo(!1),oe=Rn(()=>{Ke.current?.contains(document.activeElement)&&(Yt.current=!0)},[]);ao(()=>{if(!Yt.current)return;Yt.current=!1,Ke.current?.querySelector('[data-proximity-index="0"]')?.focus()},[K]);let fe=Rn(O=>{K>=V-1?c?.(O):(oe(),k(K+1))},[K,V,c,k,oe]),Ue=Rn(O=>{if(!$)return;let ne=T.current[G]?.otherText,Ee=S(Ct=>({...Ct,[G]:{questionId:G,selectedIds:[O],otherText:ne||void 0,skipped:!1}}));fe(Ee)},[$,G,S,fe]),ft=Rn(O=>{$&&S(ne=>{let Ee=ne[G],Ct=new Set(Ee?.selectedIds??[]);return Ct.has(O)?Ct.delete(O):Ct.add(O),{...ne,[G]:{questionId:G,selectedIds:Array.from(Ct),otherText:Ee?.otherText,skipped:!1}}})},[$,G,S]),Rt=Rn(O=>{$&&S(ne=>({...ne,[G]:{questionId:G,selectedIds:O,otherText:ne[G]?.otherText,skipped:!1}}))},[$,G,S]),ue=Rn(O=>{$&&(Tt(null),S(ne=>({...ne,[G]:{questionId:G,selectedIds:ne[G]?.selectedIds??[],otherText:O,skipped:!1}})))},[$,G,S]),ve=Rn(()=>{if(!$)return;let O=(T.current[G]?.otherText??"").trim();if(!O)return;if($.freeText&&$.freeTextValidate){let Ee=$.freeTextValidate(O);if(Ee){Tt(Ee);return}}Tt(null);let ne=S(Ee=>({...Ee,[G]:{questionId:G,selectedIds:Ee[G]?.selectedIds??[],otherText:O,skipped:!1}}));fe(ne)},[$,G,S,fe]),mt=Rn(()=>{if(!$)return;let O=S(ne=>({...ne,[G]:{questionId:G,selectedIds:ne[G]?.selectedIds??[],otherText:ne[G]?.otherText,skipped:!0}}));l?.(G,K),fe(O)},[$,G,S,l,K,fe]),nt=Rn(()=>{d?.()},[d]),B=Rn(()=>{fe(E)},[fe,E]),se=Rn(()=>{K>0&&(oe(),k(K-1))},[K,k,oe]);ao(()=>{if(!$)return;let O=ne=>{if(ne.metaKey||ne.ctrlKey||ne.altKey)return;let Ee=ne.target;if(!Ee)return;let Ct=Ee.tagName;if(Ct==="INPUT"||Ct==="TEXTAREA"||Ee.isContentEditable)return;let It=pe.current;if(!It||!It.contains(Ee)&&(Vs.some(eo=>eo!==It&&eo.contains(Ee))||Vs[Vs.length-1]!==It))return;let St=ne.key;if(St<"1"||St>"9")return;let Et=parseInt(St,10)-1;if(Et>=0&&Et<re.length){ne.preventDefault();let eo=gc(re[Et],Et);Z?ft(eo):Ue(eo)}else Et===re.length&&le&&(ne.preventDefault(),Ve.current?.focus())};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[$,re,Z,le,Ue,ft]);let we=O=>{Ke.current?.querySelector(`[data-proximity-index="${O}"]`)?.focus()},Te=Rn(O=>{_(O),le&&O===me?Ve.current?.focus():we(O)},[le,me,_]),Ce=O=>{let ne=O.target,Ee=ne.tagName==="INPUT"||ne.tagName==="TEXTAREA"||ne.isContentEditable;if(Ee&&O.key!=="ArrowDown"&&O.key!=="ArrowUp")return;if(Ee&&(O.key==="ArrowUp"||O.key==="ArrowDown")&&ne.tagName==="TEXTAREA"){let It=ne;if(O.key==="ArrowUp"&&It.selectionStart>0||O.key==="ArrowDown"&&It.selectionEnd<It.value.length)return}let Ct=O.preventBaseUIHandler;if(O.key==="ArrowLeft"||O.key==="ArrowRight"){O.preventDefault(),O.stopPropagation(),Ct?.(),O.key==="ArrowLeft"?K>0&&se():z&&V>1&&mt();return}if(be!==0&&(O.key==="ArrowDown"||O.key==="ArrowUp"||O.key==="Home"||O.key==="End")){O.preventDefault(),O.stopPropagation(),Ct?.();let It;if(O.key==="Home")It=0;else if(O.key==="End")It=be-1;else{let St=Ee?me:D??-1;It=O.key==="ArrowDown"?St+1:St-1,It=(It+be)%be}Te(It)}},je=O=>{if(O.key!=="Enter"||!(Y?O.metaKey:O.ctrlKey)||!(Z||F))return;if(O.preventDefault(),F){de.trim().length>0&&ve();return}(Ne.length>0||de.trim().length>0)&&B()};if(!$)return he("div",{ref:v,className:w("w-full max-w-[520px] p-5 bg-card border border-border",P.container,b),...f,children:he("p",{className:"text-[13px] text-muted-foreground",children:"No questions."})});let Fe=D!==null?j[D]:null,rt=Pt!==null&&!(le&&Pt===me)?j[Pt]:null,ut=ri(()=>{let O=new Set;return re.forEach((ne,Ee)=>{Ne.includes(gc(ne,Ee))&&O.add(Ee)}),le&&de.length>0&&O.add(me),O},[re,Ne,le,de,me]),Mt=ri(()=>{let O=[],ne=[...ut].sort((St,Et)=>St-Et);for(let St of ne){let Et=O[O.length-1];Et&&St===Et.end+1?Et.end=St:O.push({start:St,end:St})}let Ee=new Set,Ct=new Map,It=O.map(St=>{let Et=null;for(let dn=St.start;dn<=St.end;dn++){let In=lt.current.get(dn);if(In!==void 0&&!Ee.has(In)){Et=In;break}}let eo=Et??++pt.current;Ee.add(eo);for(let dn=St.start;dn<=St.end;dn++)Ct.set(dn,eo);return{...St,id:eo}});return lt.current=Ct,It},[ut]),ls=D!==null&&!ut.has(D),Cr=Ov(Mt,j,P.bgRadius),Bn=V>1&&K>0,Mn=d!=null,Zn=!Mn&&V>1&&z,gt=Z||F,So=Bn||Zn||gt||Mn||m!=null,yi=re.findIndex((O,ne)=>Ne.includes(gc(O,ne))),xi=an("div",{ref:Ke,role:Z?"group":"radiogroup","aria-labelledby":`${U}-${G}-title`,onMouseEnter:Oe.onMouseEnter,onMouseMove:Oe.onMouseMove,onMouseLeave:Oe.onMouseLeave,onFocus:O=>{let ne=O.target.closest("[data-proximity-index]")?.getAttribute("data-proximity-index");if(ne!=null){let Ee=Number(ne);_(Ee),Kt(O.target.matches(":focus-visible")?Ee:null)}},onBlur:O=>{Ke.current?.contains(O.relatedTarget)||(Kt(null),_(null))},onKeyDown:Ce,className:"relative flex flex-col gap-0.5 -mx-3",children:[he(js,{children:(()=>{if(!le)return null;let O=j[me],ne=Pt===me&&de.length===0;return!O||!ne?null:he(Co.div,{"aria-hidden":!0,className:w("absolute pointer-events-none bg-card ring-1 ring-inset ring-border",P.bg),initial:{opacity:0,top:O.top,left:O.left,width:O.width,height:O.height},animate:{opacity:1,top:O.top,left:O.left,width:O.width,height:O.height},exit:{opacity:0,transition:ce.fast.exit},transition:{...ce.fast,opacity:{duration:.08}}},"other-input")})()}),he(js,{children:Fe&&he(Co.div,{"aria-hidden":!0,className:w("absolute pointer-events-none bg-hover",P.bg),initial:{opacity:0,top:Fe.top,left:Fe.left,width:Fe.width,height:Fe.height},animate:{opacity:1,top:Fe.top,left:Fe.left,width:Fe.width,height:Fe.height},exit:{opacity:0,transition:ce.fast.exit},transition:{...ce.fast,opacity:{duration:.08}}},`hover-${Le.current}`)}),he(zv,{blocks:Cr,dimmed:ls}),he(js,{children:rt&&he(Co.div,{"aria-hidden":!0,className:w("absolute pointer-events-none border border-[color:var(--focus-ring,#6B97FF)] z-20",P.focusRing),initial:{opacity:0,top:rt.top-2,left:rt.left-2,width:rt.width+4,height:rt.height+4},animate:{opacity:1,top:rt.top-2,left:rt.left-2,width:rt.width+4,height:rt.height+4},exit:{opacity:0,transition:ce.fast.exit},transition:{...ce.fast,opacity:{duration:.08}}})}),re.map((O,ne)=>{let Ee=gc(O,ne),Ct=Ne.includes(Ee),St=!Z&&D===ne;return he(Bv,{index:ne,registerItem:He,role:Z?"checkbox":"radio",isSelected:Ct,tabIndex:ne===yi||yi===-1&&ne===0?0:-1,onClick:()=>Z?ft(Ee):Ue(Ee),onKeyDown:Et=>{(Et.key===" "||Et.key==="Enter")&&!Et.metaKey&&!Et.ctrlKey&&(Et.preventDefault(),Z?ft(Ee):Ue(Ee))},shape:P,"aria-checked":Ct,chipContent:ne+1,chipFilled:Ct,isMulti:Z,showArrow:St,bodyLayout:$.layout==="stacked"?"stacked":"inline",topAlign:$.layout==="stacked",chipPosition:$.chipPosition??"right",arrowIcon:he(R,{size:14,strokeWidth:2,className:"h-3.5 w-3.5"}),hiddenControl:Z?he(wP.Root,{name:Ee,className:"sr-only",tabIndex:-1,"aria-hidden":!0}):he(yP.Root,{value:Ee,className:"sr-only",tabIndex:-1,"aria-hidden":!0}),children:$.layout==="stacked"?an(Hv,{children:[an("span",{className:"inline-grid",children:[he("span",{className:"col-start-1 row-start-1 invisible",style:{fontVariationSettings:At.semibold},"aria-hidden":"true",children:O.title}),he("span",{className:"col-start-1 row-start-1 text-foreground transition-[color,font-variation-settings] duration-80",style:{fontVariationSettings:Ct?At.semibold:At.medium},children:O.title})]}),O.description&&he("span",{className:"text-[12px] text-muted-foreground leading-snug",children:O.description})]}):an("span",{children:[an("span",{className:"inline-grid",children:[he("span",{className:"col-start-1 row-start-1 invisible",style:{fontVariationSettings:At.semibold},"aria-hidden":"true",children:O.title}),he("span",{className:"col-start-1 row-start-1 text-foreground transition-[color,font-variation-settings] duration-80",style:{fontVariationSettings:Ct?At.semibold:At.medium},children:O.title})]}),O.description&&an(Hv,{children:[" ",he("span",{className:"text-muted-foreground",children:O.description})]})]})},Ee)}),le&&he(Bv,{index:me,registerItem:He,role:null,isSelected:de.length>0,tabIndex:-1,onClick:()=>Ve.current?.focus(),shape:P,chipContent:me+1,chipFilled:de.length>0,isMulti:Z,topAlign:ln,chipPosition:$.chipPosition??"right",ariaLabel:$.otherPlaceholder??"Describe in your own words",showArrow:!Z&&(Pt===me||D===me)&&de.trim().length>0,arrowIcon:he(R,{size:14,strokeWidth:2,className:"h-3.5 w-3.5"}),onArrowClick:!Z&&de.trim().length>0?ve:void 0,children:he("span",{className:"inline-grid w-full",children:he("textarea",{ref:Ve,rows:1,value:de,placeholder:$.otherPlaceholder??"Describe in your own words\u2026","aria-label":$.otherPlaceholder??"Describe in your own words",onChange:O=>ue(O.target.value),onKeyDown:O=>{O.key==="Enter"&&(O.shiftKey||Z||(O.preventDefault(),ve()))},onClick:O=>O.stopPropagation(),className:w("col-start-1 row-start-1 block w-full bg-transparent border-0 p-0 m-0 outline-none resize-none overflow-hidden text-[13px] leading-snug text-foreground placeholder:text-muted-foreground"),style:{fontVariationSettings:At.medium}})})})]});return an("div",{ref:O=>{pe.current=O,typeof v=="function"?v(O):v&&(v.current=O)},className:w("relative w-full max-w-[520px] overflow-hidden bg-card border border-border",P.container,b),...f,onKeyDown:O=>{f.onKeyDown?.(O),je(O)},children:[he("div",{className:"flex items-center px-4 sm:px-5 pt-4 sm:pt-5 pb-2 text-[12px] text-muted-foreground",children:an("span",{children:["Question ",K+1," of ",V]})}),p!=null&&he("div",{className:"px-4 sm:px-5 pb-3 text-[13px] leading-snug text-muted-foreground",children:p}),an(sm.Root,{invalid:Cn!==null,className:"contents",children:[he(Co.div,{animate:{height:cn},initial:!1,transition:ce.slow,className:"overflow-hidden",children:he("div",{ref:Ze,className:w("px-4 sm:px-5",So?"pb-1":"pb-2.5 sm:pb-3"),children:an("div",{className:"flex flex-col gap-2",children:[he("h3",{id:`${U}-${G}-title`,className:"text-[16px] text-foreground leading-snug",style:{fontVariationSettings:At.semibold},children:$.title}),F?he("div",{onClick:()=>Ve.current?.focus(),className:w("relative mt-1 -mx-3 px-3 py-2.5 cursor-text transition-colors",ie?"min-h-[76px]":"min-h-10",P.bg,de.length>0?"bg-active":"hover:bg-hover focus-within:bg-card focus-within:ring-1 focus-within:ring-inset focus-within:ring-border"),children:he(sm.Control,{value:de,onValueChange:ue,render:he("textarea",{ref:Ve,rows:1,placeholder:$.freeTextPlaceholder??"Type your answer\u2026","aria-labelledby":`${U}-${G}-title`,onKeyDown:O=>{O.key==="Enter"&&(O.shiftKey||O.metaKey||O.ctrlKey||ie||(O.preventDefault(),ve()))},className:"block w-full bg-transparent border-0 p-0 m-0 outline-none resize-none overflow-hidden text-[13px] leading-snug text-foreground placeholder:text-muted-foreground",style:{fontVariationSettings:At.medium}})})}):Z?he(xP,{value:Ne,onValueChange:Rt,render:xi}):he(bP,{value:Ne[0]??null,onValueChange:O=>{typeof O=="string"&&Ue(O)},render:xi})]},G)})}),So&&he("div",{className:"px-4 sm:px-5 pt-1 pb-2",children:an("div",{className:"flex items-center justify-between gap-2 -mx-2 sm:-mx-3",children:[an("div",{className:"relative flex flex-1 min-w-0 items-center gap-2",children:[m!=null&&he("div",{className:"shrink-0 px-2 sm:px-3",children:m}),he(js,{mode:"popLayout",initial:!1,children:Bn&&he(Co.div,{layout:"position",initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.85},transition:{...ce.fast,opacity:{duration:.1}},children:he(L,{variant:"ghost",size:"sm",leadingIcon:W,onClick:se,className:"pl-3 sm:pl-[6px]",children:"Back"})},"back")}),Cn&&he(sm.Error,{match:!0,render:he(Co.p,{role:"alert",initial:{opacity:0,y:-2},animate:{opacity:1,y:0},transition:{...ce.fast,opacity:{duration:.12}},className:"min-w-0 px-2 sm:px-3 text-left text-[12px] leading-snug text-destructive"}),children:Cn},"ft-error")]}),he("div",{className:"relative flex items-center gap-2",children:an(js,{mode:"popLayout",initial:!1,children:[Mn&&he(Co.div,{layout:"position",initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.85},transition:{...ce.fast,opacity:{duration:.1}},children:he(L,{variant:"ghost",size:"sm",trailingIcon:H,onClick:nt,className:"pr-3 sm:pr-[6px]",children:h})},"cancel"),Zn&&he(Co.div,{layout:"position",initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.85},transition:{...ce.fast,opacity:{duration:.1}},children:he(L,{variant:"ghost",size:"sm",trailingIcon:H,onClick:mt,className:"pr-3 sm:pr-[6px]",children:u})},"skip"),gt&&he(Co.div,{layout:"position",initial:{opacity:0,scale:.85},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.85},transition:{...ce.fast,opacity:{duration:.1}},children:he(L,{variant:"primary",size:"sm",onClick:F?ve:B,disabled:(F||Ne.length===0)&&de.trim().length===0,className:"pr-3 sm:pr-[6px]",children:an("span",{className:"inline-flex items-center gap-1.5",children:[$.nextLabel??(K>=V-1?"Finish":"Continue"),he("span",{className:"hidden sm:contents",children:an(SP,{shape:P,tone:"inverted",children:[Y?"\u2318":"\u2303","\u21B5"]})})]})})},"continue")]})})]})})]})]})});am.displayName="AskUserQuestions";function SP({children:e,tone:t="muted",shape:n}){return he("kbd",{"aria-hidden":!0,suppressHydrationWarning:!0,className:w("inline-flex items-center justify-center gap-0.5 px-1 min-w-[18px] h-[18px] text-[11px] leading-none font-sans tracking-wide",t==="inverted"?"bg-background/15 text-background":"bg-foreground/10 text-muted-foreground",n.bg),children:e})}function Bv({index:e,registerItem:t,role:n,isSelected:o,tabIndex:r,onClick:s,onKeyDown:a,shape:i,chipContent:c,chipFilled:l,isMulti:u,ariaLabel:p,showArrow:d,arrowIcon:h,onArrowClick:m,bodyLayout:b="inline",topAlign:f=!1,chipPosition:v="right",hiddenControl:x,children:y,...g}){let C=Uo(null);ao(()=>(t(e,C.current),()=>t(e,null)),[e,t]);let k=he(js,{children:d&&he(Co.span,{"aria-hidden":!m,role:m?"button":void 0,onClick:m?N=>{N.stopPropagation(),m()}:void 0,className:w("absolute inset-0 inline-flex items-center justify-center bg-foreground text-background",i.bg,m&&"cursor-pointer"),initial:{opacity:0,scale:.6},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.6,transition:ce.fast.exit},transition:{...ce.fast,opacity:{duration:.08}},children:h})}),I=an("span",{className:w("shrink-0 w-7 h-7 relative inline-flex items-center justify-center",f&&(b==="stacked"?"-mt-[1px]":"-mt-[5px]")),children:[he("span",{"aria-hidden":!0,className:w("absolute inline-flex items-center justify-center w-5 h-5 text-[11px] transition-[opacity,font-variation-settings] duration-80",u&&i.bg,u?l?"bg-foreground text-background":"border border-border text-muted-foreground":l?"text-foreground":"text-muted-foreground",v==="right"&&d&&"opacity-0"),style:{fontVariationSettings:l?At.semibold:At.medium},children:c}),v==="right"&&k]}),M=v==="left"&&!u&&he("span",{className:w("shrink-0 w-7 h-7 relative inline-flex items-center justify-center",f&&(b==="stacked"?"-mt-[1px]":"-mt-[5px]")),children:k});return an("div",{ref:C,"data-proximity-index":e,"data-state":o?"checked":"unchecked",role:n??void 0,"aria-checked":n==="radio"||n==="checkbox"?!!g["aria-checked"]:void 0,"aria-label":p,tabIndex:r,onMouseDown:N=>{let E=N.target.closest('button:not([tabindex="-1"]), a[href], input, select, textarea, [tabindex]:not([tabindex="-1"])');E&&E!==N.currentTarget||(N.preventDefault(),N.currentTarget.focus())},onClick:s,onKeyDown:a,className:w("relative z-10 flex cursor-pointer select-none outline-none",v==="left"?"gap-2":"gap-3",f?"items-start":"items-center",b==="stacked"?"min-h-14 py-2":"min-h-10 py-1.5",v==="left"?u?"pl-1.5 pr-3":"pl-1.5 pr-1.5":"pl-3 pr-1.5",i.item),children:[v==="left"&&I,he("span",{className:w("min-w-0 flex-1 text-[13px] leading-snug",b==="stacked"?"flex flex-col gap-0.5":"inline-flex items-center gap-0"),children:y}),v==="right"?I:M,x]})}function hc(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.const=="string"&&(t.title===void 0||typeof t.title=="string")}function Uv(e){let t=Array.isArray(e.oneOf)?e.oneOf.filter(hc):[],n=Array.isArray(e.anyOf)?e.anyOf.filter(hc):[];return t.length>0?t:n}function Fv(e){let t=e.items&&typeof e.items=="object"?e.items:{},n=Array.isArray(t.anyOf)?t.anyOf.filter(hc):[],o=Array.isArray(t.oneOf)?t.oneOf.filter(hc):[];return n.length>0?n:o}function $v(e){if(e.mode==="url"&&"url"in e)return[{id:"__url_confirm__",title:"Confirm completion",layout:"stacked",options:[{id:"confirmed",title:"I've completed the required action",description:e.url}],skippable:!1,nextLabel:"Confirm"}];let t="requestedSchema"in e?e.requestedSchema:void 0;if(!t||t.type!=="object"||!t.properties)return[{id:"__freeform__",title:"Your response",freeText:!0,freeTextPlaceholder:"Type your response\u2026",skippable:!1}];let n=t.properties,o=t.required??[];return Object.entries(n).map(([r,s])=>{let a=s,i=o.includes(r),c=a.title||r,l=a.description,u=a.type||"string",p=Uv(a),d=Fv(a),h=Array.isArray(a.enum),m=u==="array"&&Array.isArray(a.items?.enum),b=u==="array"&&d.length>0,f={id:r,title:c,skippable:!i,layout:l&&l.length>60?"stacked":"inline"};if(u==="boolean")return{...f,options:[{id:"true",title:"Yes"},{id:"false",title:"No"}]};if(b||m){let v=b?d:a.items.enum.map(x=>({const:x,title:x}))??[];return{...f,multiSelect:!0,options:v.map(x=>({id:x.const,title:x.title||x.const}))}}if(p.length>0)return{...f,layout:"stacked",options:p.map(v=>({id:v.const,title:v.title||v.const}))};if(h){let v=a.enum,x=a.enumNames;return{...f,options:v.map((y,g)=>({id:y,title:x?.[g]||y}))}}return u==="number"||u==="integer"?{...f,freeText:!0,freeTextMultiline:!1,freeTextPlaceholder:a.default!==void 0?String(a.default):"Enter a number\u2026",freeTextValidate:v=>{let x=v.trim();if(!x)return i?"Required":null;let y=u==="integer"?parseInt(x,10):parseFloat(x);return Number.isNaN(y)?"Enter a valid number":null}}:u==="string"&&(a.format==="textarea"||(a.maxLength??0)>100)?{...f,freeText:!0,freeTextPlaceholder:a.default||"Type your answer\u2026"}:{...f,freeText:!0,freeTextMultiline:!1,freeTextPlaceholder:a.default!==void 0?String(a.default):"Type your answer\u2026",freeTextValidate:v=>!v.trim()&&i?"Required":null}})}function Vv(e,t,n){if(n.mode==="url")return{};let o="requestedSchema"in n?n.requestedSchema:void 0,r=o?.type==="object"&&o.properties?o.properties:{},s={};for(let a of e){let i=a.id??"";if(i==="__freeform__"){let p=t[i]?.otherText?.trim();p&&(s.response=p);continue}let c=t[i];if(!c||c.skipped)continue;let u=r[i]?.type||"string";if(a.freeText){let p=c.otherText?.trim()??"";if(!p)continue;s[i]=u==="number"||u==="integer"?u==="integer"?parseInt(p,10):parseFloat(p):p;continue}if(a.multiSelect){s[i]=c.selectedIds;continue}if(u==="boolean"){s[i]=c.selectedIds[0]==="true";continue}c.selectedIds[0]!==void 0&&(s[i]=c.selectedIds[0])}return s}function jv(e,t,n){if(n.mode==="url")return[];let o="requestedSchema"in n?n.requestedSchema:void 0;return(o?.type==="object"?o.required??[]:[]).filter(s=>{let a=t[s];if(!a||a.skipped)return!0;let i=e.find(c=>c.id===s);return i?i.freeText?!a.otherText?.trim():(i.multiSelect,a.selectedIds.length===0):!0})}function qv(e,t){if(t.mode==="url")return{};let n="requestedSchema"in t?t.requestedSchema:void 0,o=n?.type==="object"&&n.properties?n.properties:{},r={};for(let s of e){let a=s.id;if(!a||a.startsWith("__"))continue;let i=o[a];if(!(!i||i.default===void 0)){if(s.freeText){r[a]={questionId:a,selectedIds:[],otherText:String(i.default),skipped:!1};continue}if(s.multiSelect&&Array.isArray(i.default)){r[a]={questionId:a,selectedIds:i.default.map(String),skipped:!1};continue}if(i.type==="boolean"){r[a]={questionId:a,selectedIds:[String(i.default)],skipped:!1};continue}r[a]={questionId:a,selectedIds:[String(i.default)],skipped:!1}}}return r}import{jsx as si,jsxs as vc}from"react/jsx-runtime";function Gv({request:e,onApprove:t,onReject:n,testId:o="inline-elicitation",actionTestIdPrefix:r="inline-elicitation"}){let[s,a]=Kv(!1),[i,c]=Kv(""),l=Wv(()=>$v(e.request),[e.request]),u=Wv(()=>qv(l,e.request),[l,e.request]),d=(e.request.mode||"form")==="url",h=d&&"url"in e.request?e.request.url:void 0,m=(v,x)=>{a(!0),c(v),t(e.id,x)},b=v=>{if(s)return;if(d){if(!v.__url_confirm__?.selectedIds.includes("confirmed")){Jv.error("Confirm you've completed the external action");return}m("accepted",{action:"accept"});return}let x=jv(l,v,e.request);if(x.length>0){Jv.error("Missing required fields",{description:`Please fill in: ${x.join(", ")}`});return}m("accepted",{action:"accept",content:Vv(l,v,e.request)})};if(s)return vc("p",{className:"text-sm text-muted-foreground","data-testid":`${o}-responded`,children:["Elicitation ",i," \u2014 the tool will continue executing."]});let f=vc("div",{className:"space-y-2",children:[si("p",{className:"text-foreground/90",children:e.request.message}),d&&h&&vc("div",{className:"flex items-center gap-2 rounded-md border bg-muted/40 p-2",children:[si("code",{className:"flex-1 text-xs font-mono break-all",children:h}),vc(L,{size:"sm",variant:"outline",onClick:()=>window.open(h,"_blank"),"data-testid":`${r}-open-url`,children:[si(NP,{className:"h-3 w-3 mr-1"}),"Open"]})]})]});return si(am,{questions:l,defaultAnswers:u,onComplete:b,intro:f,onCancel:()=>n(e.id,"User cancelled elicitation request"),cancelLabel:"Cancel",footerLeading:si("button",{type:"button",className:"shrink-0 cursor-pointer text-[12px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline",onClick:()=>m("declined",{action:"decline"}),"data-testid":`${r}-decline-button`,children:"Decline"}),className:"w-full max-w-none shadow-lg","data-testid":o})}import{jsx as im}from"react/jsx-runtime";function Yv({requests:e,onApprove:t,onReject:n}){return e.length===0?null:im("div",{className:"mb-3 space-y-3 pointer-events-auto","data-testid":"floating-elicitation-stack",children:e.map(o=>im(TP.div,{initial:{opacity:0,y:12,scale:.98},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:8,scale:.98},transition:ce.moderate,children:im(Gv,{request:o,onApprove:t,onReject:n})},o.id))})}import{Check as kP,Loader2 as PP,Settings2 as RP}from"lucide-react";import{useCallback as MP,useEffect as IP,useState as lm}from"react";var os="You are a helpful assistant with access to MCP tools. Help users interact with the MCP server.";import{jsx as io,jsxs as ai}from"react/jsx-runtime";function EP(e){let t=e?.trim();return t?t!==os:!1}function Xv({value:e,onSave:t,disabled:n,isSaving:o=!1,compact:r=!1}){let[s,a]=lm(!1),[i,c]=lm(e??""),[l,u]=lm(!1);IP(()=>{c(e??"")},[e]);let p=MP(async()=>{u(!0);try{await t(i),a(!1)}finally{u(!1)}},[i,t]),d=o||l,h=EP(e),m=ai("button",{type:"button","data-testid":"chat-system-prompt-button",onClick:()=>a(!0),disabled:n,className:r?w("inline-flex h-auto w-auto aspect-square items-center justify-center rounded-full p-2 transition-colors disabled:pointer-events-none disabled:opacity-50",h?"text-amber-500 dark:text-amber-400":"text-muted-foreground hover:text-foreground"):w("inline-flex h-9 items-center justify-center gap-1.5 rounded-full border border-input bg-secondary px-3 text-sm font-medium shadow-xs transition-colors hover:bg-secondary/80 disabled:pointer-events-none disabled:opacity-50",h?"text-amber-600 dark:text-amber-400":"text-secondary-foreground"),children:[io(RP,{className:"h-4 w-4"}),!r&&io("span",{className:"hidden sm:inline",children:"System Prompt"})]});return ai(on,{open:s,onOpenChange:a,children:[r?ai(Ie,{children:[io(Re,{render:m,nativeButton:!0}),io(Me,{side:"top",children:io("p",{children:h?"Custom system prompt":"System Prompt"})})]}):m,ai(Xt,{className:"sm:max-w-xl",children:[io(Gt,{children:io($t,{children:"System Prompt"})}),io(fo,{value:i,onChange:b=>c(b.target.value),placeholder:"Describe the assistant's behavior...",className:"min-h-[160px] text-sm"}),io($i,{children:ai(L,{size:"sm",onClick:p,disabled:d||i===(e??""),className:"gap-1.5",children:[d?io(PP,{className:"h-3.5 w-3.5 animate-spin"}):io(kP,{className:"h-3.5 w-3.5"}),"Save"]})})]})]})}import{Fragment as Qv,jsx as wn,jsxs as bc}from"react/jsx-runtime";function ii({variant:e="default",inputValue:t,isConnected:n,isLoading:o,textareaRef:r,llmConfig:s,promptsDropdownOpen:a,promptFocusedIndex:i,prompts:c,selectedPrompt:l,promptResults:u,attachments:p,tools:d,disabledTools:h,onDisabledToolsChange:m,onInputChange:b,onKeyDown:f,onKeyUp:v,onClick:x,onSendMessage:y,onStopStreaming:g,onConfigDialogOpenChange:C,onPromptSelect:k,onDeletePromptResult:I,onAttachmentAdd:M,onAttachmentRemove:N,hideModelBadge:E,freeTierInfo:T,managedCloudInfo:S,modelBadgeMode:P="byok",managedModel:A,followups:R=[],onFollowupSelect:W,pendingElicitationRequests:H,onApproveElicitation:Y,onRejectElicitation:U,systemPromptProvider:V}){let K=e==="fullscreen",$=t.trim()||u.length>0||p.length>0,G=(H?.length??0)>0,te=s&&(!E||T||S)?bc(Ie,{children:[wn(Re,{render:wn(Cv,{provider:s.provider,model:s.model,managedModel:A,mode:P,className:"shrink-0","data-testid":"chat-model-badge",onClick:()=>C(!0)}),nativeButton:!0}),wn(Me,{children:wn("p",{children:S||T?"Change model":"Change API Key"})})]}):null;return wn("div",{className:w("w-full flex shrink-0 flex-col items-center px-2 pt-0 sm:px-4 text-foreground",K?"pb-4 sm:pb-4":"pb-2 sm:pb-2"),children:bc("div",{className:w("relative w-full max-w-3xl",!K&&"backdrop-blur-xl"),children:[!K&&G&&Y&&U&&wn(Yv,{requests:H,onApprove:Y,onReject:U}),!K&&R.length>0&&wn("div",{className:"mb-2 flex flex-wrap gap-2",children:R.map(Z=>wn(L,{type:"button",variant:"outline",size:"sm",className:"rounded-full",onClick:()=>W?.(Z),disabled:o||!n,children:Z},Z))}),!K&&bc(Qv,{children:[wn(Av,{isOpen:a,prompts:c,selectedPrompt:l,focusedIndex:i,onPromptSelect:k}),wn(Ev,{promptResults:u,onDeletePromptResult:I})]}),wn(Iv,{variant:e,inputValue:t,isConnected:n,isLoading:o,textareaRef:r,attachments:p,placeholder:"Ask a question or request an action...",className:w("bg-white/80 dark:text-white dark:bg-black backdrop-blur-sm border-gray-200 dark:border-zinc-800",!K&&u.length>0&&"pt-16"),showAttachButton:!K,tools:K?void 0:d,disabledTools:K?void 0:h,onDisabledToolsChange:K?void 0:m,onInputChange:b,onKeyDown:f,onKeyUp:v,onClick:x,onAttachmentAdd:M,onAttachmentRemove:N,inlineControls:!K&&s&&V?wn(Xv,{compact:!0,value:V.prompt,onSave:V.savePrompt,disabled:!n||o||V.disabled,isSaving:V.isSaving}):null,trailingControls:bc(Qv,{children:[!K&&te,wn(L,{type:"button",size:"sm",className:w("h-8 w-8 rounded-full p-0",o&&"animate-spin",!$&&!o&&"bg-zinc-400"),disabled:!o&&(!$||!n||G),title:o?"Stop streaming":"Send",onClick:o?g:y,"data-testid":"chat-send-button",children:o?wn(LP,{className:"h-3.5 w-3.5 animate-spin"}):wn(AP,{className:"h-3.5 w-3.5"})})]})})]})})}import{AnimatePresence as DP,motion as _P,useInView as OP}from"motion/react";import{useRef as zP}from"react";import{jsx as Zv}from"react/jsx-runtime";function eb({children:e,className:t,variant:n,duration:o=.4,delay:r=0,offset:s=6,direction:a="down",inView:i=!1,inViewMargin:c="-50px",blur:l="6px",...u}){let p=zP(null),d=OP(p,{once:!0,margin:c}),h=!i||d,m={hidden:{[a==="left"||a==="right"?"x":"y"]:a==="right"||a==="down"?-s:s,opacity:0,filter:`blur(${l})`},visible:{[a==="left"||a==="right"?"x":"y"]:0,opacity:1,filter:"blur(0px)"}},b=n||m;return Zv(DP,{children:Zv(_P.div,{ref:p,initial:"hidden",animate:h?"visible":"hidden",exit:"hidden",variants:b,transition:{delay:.04+r,duration:o,ease:"easeOut"},className:t,...u,children:e})})}import{jsx as li,jsxs as yc}from"react/jsx-runtime";function cm({serverDisplayName:e,composerNotice:t,quickQuestions:n=[],onQuickQuestionSelect:o,...r}){return li("div",{className:"flex h-full flex-col items-center justify-center",children:yc(eb,{className:"w-full max-w-4xl mx-auto px-2 sm:px-4",children:[yc("div",{className:"text-center mb-6 sm:mb-8",children:[yc("h1",{className:"text-2xl sm:text-4xl font-light mb-2 dark:text-white","data-testid":"chat-landing-header",children:["Chat with ",e]}),li("p",{className:"mx-auto max-w-xl text-sm text-muted-foreground sm:text-base","data-testid":"chat-landing-description",children:"Chat, inspect traces, preview widgets, and more."})]}),yc("div",{className:"space-y-6",children:[t,li(ii,{...r}),n.length>0&&li("div",{className:"flex flex-wrap items-center justify-center gap-2 px-2",children:n.map(s=>li(L,{type:"button",variant:"outline",size:"sm",className:"rounded-full bg-white/70 dark:bg-black/50 text-gray-900 dark:text-white",onClick:()=>o?.(s),disabled:r.isLoading||!r.isConnected,children:s},s))})]})]})})}import{Key as BP,Settings as HP}from"lucide-react";import{jsx as xc,jsxs as tb}from"react/jsx-runtime";function dm({onConfigureClick:e}){return tb("div",{className:"flex flex-col items-center justify-center h-full text-center",children:[xc(BP,{className:"h-12 w-12 text-muted-foreground mb-4"}),xc("h3",{className:"text-lg font-semibold mb-2",children:"Configure Your LLM Provider"}),xc("p",{className:"text-sm text-muted-foreground mb-4 max-w-md",children:"To start chatting with the MCP server, you need to configure your LLM provider and API key. Your credentials are stored locally and used only for this chat."}),tb(L,{onClick:e,"data-testid":"chat-configure-api-key-button",children:[xc(HP,{className:"h-4 w-4 mr-2"}),"Configure API Key"]})]})}import{motion as UP}from"motion/react";import{useMemo as FP}from"react";import{jsx as $P}from"react/jsx-runtime";function nb({children:e,as:t="p",className:n,duration:o=2,spread:r=2}){let s=UP.create(t),a=FP(()=>e.length*r,[e,r]);return $P(s,{className:w("relative inline-block bg-[length:250%_100%,auto] bg-clip-text","text-transparent [--base-color:#a1a1aa] [--base-gradient-color:#000]","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--base-gradient-color),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]","dark:[--base-color:#71717a] dark:[--base-gradient-color:#ffffff] dark:[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--base-gradient-color),#0000_calc(50%+var(--spread)))]",n),initial:{backgroundPosition:"100% center"},animate:{backgroundPosition:"0% center"},transition:{repeat:1/0,duration:o,ease:"linear"},style:{"--spread":`${a}px`,backgroundImage:"var(--bg), linear-gradient(var(--base-color), var(--base-color))"},children:e})}import{memo as fR,useCallback as gR,useMemo as hR,useRef as xm}from"react";import{memo as VP,useMemo as jP}from"react";import{jsx as ob,jsxs as WP}from"react/jsx-runtime";function qP(e){let t=e.match(/```/g);return t&&t.length%2===1?`${e}
|
|
202
202
|
\`\`\``:e}var rb=VP(function({content:t,isStreaming:n=!1}){let o=jP(()=>n?qP(t):t,[t,n]);return WP("div",{children:[ob(Ds,{className:w("text-[14px] leading-relaxed text-foreground","[&_p]:mb-2 [&_p:last-child]:mb-0","[&_pre]:my-3 [&_ul]:mb-2 [&_ol]:mb-2"),content:o}),n?ob("span",{className:"inline-block w-0.5 h-[1em] ml-0.5 -mt-1 align-middle bg-foreground/60 animate-pulse","aria-hidden":!0}):null]})});import{forwardRef as ZP}from"react";import{motion as eR}from"motion/react";import{useEffect as KP,useState as JP}from"react";function sb(){let[e,t]=JP(!1);return KP(()=>{if(typeof window>"u")return;let n=new AbortController,{signal:o}=n,r=()=>{let a="ontouchstart"in window||navigator.maxTouchPoints>0,i=window.matchMedia("(pointer: coarse)").matches;t(a&&i)};return window.matchMedia("(pointer: coarse)").addEventListener("change",r,{signal:o}),window.addEventListener("pointerdown",r,{signal:o}),r(),()=>n.abort()},[]),e}import{useEffect as GP,useState as YP}from"react";import{jsx as xr,jsxs as QP}from"react/jsx-runtime";function XP({size:e}){return QP("svg",{width:Math.max(16,e*.35),height:Math.max(16,e*.35),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[xr("path",{d:"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"}),xr("path",{d:"M14 3v5h5"})]})}function ab({file:e,size:t,className:n}){let o=kt(),r=e.type.startsWith("image/"),[s,a]=YP(null);GP(()=>{if(!r){a(null);return}let c=URL.createObjectURL(e);return a(c),()=>URL.revokeObjectURL(c)},[r,e]);let i=r&&!s;return xr("div",{className:w("relative shrink-0 overflow-hidden bg-accent border border-border",o.bg,n),style:{width:t,height:t},children:s?xr("img",{src:s,alt:e.name,className:"absolute inset-0 w-full h-full object-cover"}):i?xr("div",{className:"absolute inset-0 flex items-center justify-center",children:xr("div",{className:"w-6 h-6 rounded-full border-2 border-border border-t-muted-foreground animate-spin","aria-label":"Loading preview",role:"status"})}):xr("div",{className:"absolute inset-0 flex items-center justify-center text-muted-foreground",role:"img","aria-label":e.name,children:xr(XP,{size:t})})})}import{jsx as ci,jsxs as ib}from"react/jsx-runtime";var di=ZP(({from:e,files:t,thumbnailSize:n=64,time:o,actions:r,children:s,className:a,...i},c)=>{let l=kt(),u=e==="user",p=sb(),d=u&&o!=null;return ib(eR.div,{ref:c,layout:"position",initial:{opacity:0,y:8,scale:.96},animate:{opacity:1,y:0,scale:1},transition:ce.moderate,style:{transformOrigin:u?"bottom right":"bottom left"},className:w("group flex max-w-[80%] flex-col gap-1.5",u?"items-end self-end":"items-start self-start",a),...i,children:[t&&t.length>0&&ci("div",{className:w("flex flex-wrap gap-1.5",u?"justify-end":"justify-start"),children:t.map((h,m)=>ci(ab,{file:h,size:n},`${h.name}-${h.size}-${h.lastModified}-${m}`))}),s!=null&&s!==""&&ci("div",{className:w("py-2 text-[14px] whitespace-pre-wrap break-words",u?w(l.bg,"px-3.5 text-pretty bg-[color-mix(in_oklab,var(--accent),var(--background)_45%)] text-accent-foreground"):"text-foreground"),children:s}),(d||r!=null)&&ib("div",{className:w("flex items-center gap-2 px-1 text-[12px] leading-none text-muted-foreground select-none",!p&&["opacity-0 pointer-events-none transition-opacity duration-150","group-hover:opacity-100 group-hover:pointer-events-auto","group-focus-within:opacity-100 group-focus-within:pointer-events-auto"]),children:[d&&ci("span",{className:"tabular-nums",children:o}),r!=null&&ci("span",{className:"flex items-center gap-0.5",children:r})]})]})});di.displayName="ChatMessage";import{Check as tR,Copy as nR}from"lucide-react";import{useState as oR}from"react";import{jsx as um}from"react/jsx-runtime";function lb({text:e}){let[t,n]=oR(!1);return um("button",{type:"button",className:"text-muted-foreground hover:text-foreground flex items-center rounded p-0.5",onClick:async()=>{await st(e),n(!0),setTimeout(()=>n(!1),2e3)},title:"Copy message content","data-testid":"copy-button",children:t?um(tR,{className:"h-3.5 w-3.5"}):um(nR,{className:"h-3.5 w-3.5"})})}import{Fragment as ub,jsx as db,jsxs as mb}from"react/jsx-runtime";function cb(e,t){let n=e===1?"token":"tokens";return`${e.toLocaleString()} ${n} ${t}`}function wc({variant:e,copyText:t,inputTokens:n,outputTokens:o}){let r=!!t,s=e==="user"&&n!=null?cb(n,"in"):e==="assistant"&&o!=null?cb(o,"out"):null;if(!r&&!s)return null;let a=r?db(lb,{text:t}):null,i=s?db("span",{className:"tabular-nums",title:e==="user"?"Input tokens":"Output tokens","data-testid":e==="user"?"message-input-tokens":"message-output-tokens",children:s}):null;return e==="user"?mb(ub,{children:[i,a]}):mb(ub,{children:[a,i]})}import{jsx as Cc,jsxs as rR}from"react/jsx-runtime";function mm({content:e,timestamp:t,_isStreaming:n,outputTokens:o}){return!e||e.length===0?null:rR("div",{"data-testid":"chat-message-assistant",children:[Cc(di,{from:"assistant",actions:Cc(wc,{variant:"assistant",copyText:e,outputTokens:o}),"data-testid":"chat-message-content",children:Cc(rb,{content:e,isStreaming:n})}),t!=null&&Cc("span",{className:"sr-only",children:new Date(t).toLocaleTimeString()})]})}import{Check as pb,Copy as pm,Loader2 as fm,LockKeyhole as gm,Wrench as fb,X as sR}from"lucide-react";import{jsx as it,jsxs as Wt}from"react/jsx-runtime";function hm({toolName:e,args:t,result:n,state:o="result",partialArgs:r,onAuthenticate:s,isAuthenticating:a=!1,authorizationError:i,toolCallId:c}){let l=o==="call"&&r?r:t,u=()=>{switch(o){case"call":return it(fm,{className:"h-4 w-4 animate-spin text-blue-500 dark:text-blue-400"});case"authorization-required":return it(gm,{className:"h-4 w-4 text-amber-700 dark:text-amber-300"});case"result":return it(pb,{className:"h-4 w-4 text-emerald-800 dark:text-emerald-400"});case"error":return it(sR,{className:"h-4 w-4 text-red-500 dark:text-red-400"});default:return it(pb,{className:"h-4 w-4 text-emerald-800 dark:text-emerald-400"})}},p=()=>{switch(o){case"call":return" bg-blue-500/20 dark:bg-blue-500/20";case"authorization-required":return" bg-amber-400/30 dark:bg-amber-500/25";case"result":return" bg-emerald-500/20 dark:bg-emerald-500/20";case"error":return" bg-red-500/20 dark:bg-red-500/20";default:return" bg-emerald-500/20 dark:bg-emerald-500/20"}},d=h=>typeof h=="object"?Cl(h).preview:String(h);return Wt("div",{className:"my-4 flex w-fit max-w-full flex-col items-start gap-2",children:[Wt(Ss,{children:[it(hl,{render:Wt("div",{className:w("flex max-w-min items-center gap-3 rounded-full border p-1 transition-colors cursor-pointer",o==="authorization-required"?"border-amber-400/70 bg-amber-50 hover:bg-amber-100 dark:border-amber-500/50 dark:bg-amber-950/40 dark:hover:bg-amber-950/60":"bg-card hover:bg-accent/50"),"data-testid":`chat-tool-call-${e}`,children:[it("div",{className:"w-8 h-8 rounded-full bg-zinc-100 dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-800 flex items-center justify-center shrink-0",children:it(fb,{className:"size-4 text-muted-foreground"})}),it("div",{className:"flex-1 min-w-0",children:it("div",{className:"flex items-center gap-2",children:Wt("span",{className:"text-sm font-medium truncate",children:[e,"(",Object.keys(l).length>0?Wt("span",{className:"bg-muted-foreground/20 rounded-full px-1.5 mx-1 py-0.5 text-xs",children:[Object.keys(l).length," args"]}):"",")"]})})}),it("div",{className:w("w-8 h-8 rounded-full flex items-center justify-center",p()),"data-testid":`chat-tool-call-status-${o}`,children:u()})]}),nativeButton:!1}),Wt(Ns,{side:"right",className:"w-[400px] sm:w-[540px] p-4 overflow-y-auto","data-testid":"chat-tool-drawer",children:[Wt(vl,{children:[Wt(bl,{className:"flex items-center gap-2",children:[it(fb,{className:"h-5 w-5"}),"Tool Call Details"]}),Wt(ag,{className:"flex items-center gap-2",children:[e," \u2014 ",o,o==="call"&&Wt("span",{className:"flex items-center gap-1 text-blue-500 dark:text-blue-400",children:[it(fm,{className:"h-3 w-3 animate-spin"}),"streaming\u2026"]}),o==="authorization-required"&&Wt("span",{className:"flex items-center gap-1 text-amber-700 dark:text-amber-300",children:[it(gm,{className:"h-3 w-3"}),"authentication required"]})]})]}),Wt("div",{className:"flex flex-col gap-6 py-4",children:[Wt("div",{children:[it("h3",{className:"text-sm font-medium mb-2",children:"Arguments"}),Wt("div",{className:"relative","data-testid":"chat-tool-drawer-args",children:[it("pre",{className:"text-xs bg-muted/50 rounded-lg p-3 overflow-x-auto border font-mono leading-relaxed max-h-48 whitespace-pre-wrap break-words",children:d(l)}),it(L,{variant:"ghost",size:"sm",onClick:()=>st(d(l)),className:"absolute top-2 right-2 h-6 w-6 p-0 opacity-70 hover:opacity-100",title:"Copy arguments",children:it(pm,{className:"h-3 w-3"})})]})]}),n&&Wt("div",{children:[it("h3",{className:"text-sm font-medium mb-2",children:"Result"}),it("div",{className:"relative","data-testid":"chat-tool-drawer-result",children:typeof n=="string"?Wt("div",{className:w("p-3 rounded-lg border text-sm leading-relaxed max-h-48 overflow-x-auto whitespace-pre-wrap break-words max-w-full",o==="error"?"bg-destructive/10 border-destructive/20 text-destructive-foreground":"bg-muted/30 border-border"),children:[n.startsWith("Error")?Wt("div",{className:"font-mono",children:[it("div",{className:"font-semibold text-destructive mb-1",children:"Error:"}),it("div",{className:"whitespace-pre-wrap break-words",children:n.replace(/^Error:\s*/,"")})]}):it("div",{className:"whitespace-pre-wrap font-mono break-words",children:n}),it(L,{variant:"ghost",size:"sm",onClick:()=>st(n),className:"absolute top-2 right-2 h-6 w-6 p-0 opacity-70 hover:opacity-100",title:"Copy result",children:it(pm,{className:"h-3 w-3"})})]}):Wt("div",{className:w("p-3 rounded-lg border text-sm leading-relaxed max-h-96 overflow-y-auto max-w-full",o==="error"?"bg-destructive/10 border-destructive/20 text-destructive-foreground":"bg-muted/30 border-border"),children:[it(Dt,{data:n,filename:`tool-call-${e}-result-${Date.now()}.json`}),it(L,{variant:"ghost",size:"sm",onClick:()=>st(JSON.stringify(n,null,2)),className:"absolute top-2 right-2 h-6 w-6 p-0 opacity-70 hover:opacity-100",title:"Copy result",children:it(pm,{className:"h-3 w-3"})})]})})]})]})]})]}),o==="authorization-required"&&c&&s&&Wt("div",{className:"flex flex-col items-start gap-1.5 pl-1",children:[Wt(L,{"data-testid":`chat-tool-authenticate-${c}`,size:"sm",onClick:()=>{s(c)},disabled:a,className:"bg-amber-600 text-white hover:bg-amber-700 focus-visible:ring-amber-600 dark:bg-amber-500 dark:text-amber-950 dark:hover:bg-amber-400",children:[a?it(fm,{className:"size-3.5 animate-spin","aria-hidden":!0}):it(gm,{className:"size-3.5","aria-hidden":!0}),a?"Authenticating\u2026":"Authenticate"]}),i&&it("p",{className:"max-w-sm text-xs text-red-700 dark:text-red-300",children:i})]})]})}import{useMemo as aR}from"react";import{jsx as vm}from"react/jsx-runtime";function iR(e){let t=atob(e.data),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return new File([n],e.name||"attachment",{type:e.mimeType})}function gb({content:e,timestamp:t,attachments:n,inputTokens:o}){let r=aR(()=>n?.map(iR),[n]);return(!e||e.length===0)&&(!n||n.length===0)?null:vm("div",{"data-testid":"chat-message-user",className:"flex flex-col items-end",children:vm(di,{from:"user",files:r,time:t?new Date(t).toLocaleTimeString():void 0,actions:e||o!=null?vm(wc,{variant:"user",copyText:e||void 0,inputTokens:o}):void 0,"data-testid":"chat-message-content",children:e&&e.length>0?e:void 0})})}import{isViewTool as vR}from"@mcp-use/client/react";var wr={events:[],spans:[]};function Nc(e){if(!e||typeof e!="object")return;let t=e,n=(...p)=>{for(let d of p)if(typeof t[d]=="number")return t[d]},o=n("inputTokens","input_tokens","promptTokens"),r=n("outputTokens","output_tokens","completionTokens"),s=n("cachedInputTokens","cache_read_input_tokens"),a=n("cacheCreationInputTokens","cache_creation_input_tokens"),i=n("reasoningTokens","thoughtsTokenCount"),l=(n("cache_read_input_tokens")??0)+(a??0),u=n("totalTokens","total_tokens")??(o!==void 0&&r!==void 0?o+r+l:void 0);if(!(o===void 0&&r===void 0&&u===void 0&&s===void 0&&a===void 0&&i===void 0))return{inputTokens:o,outputTokens:r,totalTokens:u,cachedInputTokens:s,cacheCreationInputTokens:a,reasoningTokens:i}}var lR=new Set(["apikey","authorization","accesstoken","refreshtoken","password","cookie","secret"]);function Sc(e){return Array.isArray(e)?e.map(Sc):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([t,n])=>[t,lR.has(t.toLowerCase().replace(/[_-]/g,""))?"[REDACTED]":Sc(n)]))}function hb(e,t=120){let n;try{n=JSON.stringify(e)}catch{n=String(e)}return n.length>t?`${n.slice(0,t)}\u2026`:n}function rs(e){switch(e.type){case"request":return"LLM request";case"text-delta":return e.delta.trim()||"Text delta";case"tool-call-start":return e.toolName;case"tool-call-args":return hb(e.args);case"tool-result":return hb(e.result);case"usage":return`${e.usage.totalTokens??"?"} tokens`;case"error":return e.message;case"done":return"Completed";default:return e}}function bm(e,t){let n=(o,r)=>o===void 0&&r===void 0?void 0:(o??0)+(r??0);return{inputTokens:n(e?.inputTokens,t.inputTokens),outputTokens:n(e?.outputTokens,t.outputTokens),totalTokens:n(e?.totalTokens,t.totalTokens),cachedInputTokens:n(e?.cachedInputTokens,t.cachedInputTokens),cacheCreationInputTokens:n(e?.cacheCreationInputTokens,t.cacheCreationInputTokens),reasoningTokens:n(e?.reasoningTokens,t.reasoningTokens)}}function Tc(e,t){let n=e.spans.map(s=>({...s})),o=e.usage,r=[...n].reverse().find(s=>s.kind==="llm"&&s.status==="running");if(t.type==="request")n.push({id:`llm-${t.id}`,kind:"llm",name:"LLM",status:"running",startedAt:t.timestamp,preview:rs(t)});else if((t.type==="text-delta"||t.type==="tool-call-start")&&!r)r={id:`llm-${t.id}`,kind:"llm",name:"LLM",status:"running",startedAt:t.timestamp,preview:t.type==="text-delta"?rs(t):"LLM response"},n.push(r),t.type==="tool-call-start"&&n.push({id:t.toolCallId,kind:"tool",name:t.toolName,status:"running",startedAt:t.timestamp,preview:rs(t)});else if(t.type==="tool-call-start")n.push({id:t.toolCallId,kind:"tool",name:t.toolName,status:"running",startedAt:t.timestamp,preview:rs(t)});else if(t.type==="tool-call-args"){let s=n.find(a=>a.id===t.toolCallId);s&&(s.preview=rs(t))}else if(t.type==="tool-result"){let s=t.toolCallId?n.find(a=>a.id===t.toolCallId):[...n].reverse().find(a=>a.kind==="tool"&&a.name===t.toolName&&a.status==="running");s&&(s.status=t.isError?"error":"success",s.endedAt=t.timestamp,s.preview=rs(t))}else t.type==="usage"?(o=bm(o,t.usage),r&&(r.usage=bm(r.usage,t.usage))):(t.type==="error"||t.type==="done")&&r&&(r.status=t.type==="error"?"error":"success",r.endedAt=t.timestamp,r.preview=rs(t));return{events:[...e.events,t],spans:n,usage:o}}function ym(e,t){let n=[],o=null;for(let r of e)r.type==="request"?(o&&n.push(o),o={request:r,response:[]}):o&&o.response.push(r);return o&&n.push(o),{turns:n,tokenUsage:t??null}}function cR(e){let t;for(let n of e)n.type==="usage"&&(t=bm(t,n.usage));return t}function dR(e){let t=[],n=0;for(;n<e.length;){if(e[n]?.role!=="user"){n++;continue}let o=e[n].id;n++;let r=null;for(;n<e.length&&e[n]?.role==="assistant";)r=e[n].id,n++;t.push({userId:o,assistantId:r})}return t}function vb(e,t){let{turns:n}=ym(t),o=dR(e),r=new Map,s=Math.min(n.length,o.length);for(let a=0;a<s;a++){let i=cR(n[a].response);if(!i)continue;let{userId:c,assistantId:l}=o[a];i.inputTokens!=null&&r.set(c,{...r.get(c),inputTokens:i.inputTokens}),l!=null&&i.outputTokens!=null&&r.set(l,{...r.get(l),outputTokens:i.outputTokens})}return r}var uR=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/webp","image/svg+xml"]);function mR(e){for(let t of e)if(t>10485760)throw new Error("ui/message image exceeds the 10 MB per-file limit");if(e.reduce((t,n)=>t+n,0)>20971520)throw new Error("ui/message images exceed the 20 MB total limit")}function pR(e){let t=e.replace(/\s/g,"");if(t.length===0||t.length%4===1||!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new Error("ui/message image data must be valid base64");let n=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.floor(t.length*3/4)-n}function bb(e){if(e.length===0)throw new Error("ui/message requires at least one content block");let t=[],n=[];for(let[r,s]of e.entries()){if(s.type==="text"){if(typeof s.text!="string")throw new Error(`ui/message text block ${r} is invalid`);t.push(s.text);continue}if(s.type==="image"){if(typeof s.data!="string"||typeof s.mimeType!="string")throw new Error(`ui/message image block ${r} is invalid`);if(!uR.has(s.mimeType))throw new Error(`Unsupported ui/message image type: ${s.mimeType}`);let a=pR(s.data);mR([...n.map(i=>i.size??0),a]),n.push({type:"image",data:s.data,mimeType:s.mimeType,name:`widget-image-${n.length+1}`,size:a});continue}throw new Error(`Unsupported ui/message content block: ${s.type||"unknown"}`)}let o=t.join(`
|
|
203
203
|
`);if(!o.trim()&&n.length===0)throw new Error("ui/message must include text or an image");return{text:o,attachments:n}}import{Fragment as bR,jsx as Zt,jsxs as kc}from"react/jsx-runtime";var ui=fR(({messages:e,isLoading:t,serverId:n,readResource:o,tools:r,sendMessage:s,messagesEndRef:a,traceEvents:i=[],modelContextScope:c,llmConfig:l,renderToolResults:u=!0,onAuthenticateTool:p,authenticatingToolCallId:d,toolAuthorizationError:h})=>{let m=xm(!1),b=xm(t);b.current=t;let f=xm(s);f.current=s;let v=hR(()=>vb(e,i),[e,i]),x=T=>{let S=R=>R.replace(/-/g,"_"),P=S(T);return r?.find(R=>S(R.name)===P)?._meta},y=T=>{let S=x(T);return vR(S)},g=gR(async T=>{if(b.current||m.current)throw new Error("Chat is busy with another turn");let S=f.current;if(!S)throw new Error("Chat is not available on this host surface");let P=bb(T);m.current=!0;try{await S(P.text,P.attachments.length>0?P.attachments:void 0)}finally{m.current=!1}},[]),C=t&&(()=>{if(e.length===0)return!0;let T=e[e.length-1];if(T.role==="user")return!0;if(T.role==="assistant"){if(T.parts&&T.parts.length>0)return!1;let S=typeof T.content=="string"?T.content:Array.isArray(T.content)?T.content.map(A=>typeof A=="string"?A:A.text||JSON.stringify(A)).join(""):JSON.stringify(T.content);return!(S&&S.trim().length>0)}return!1})(),k=e[e.length-1],I=t&&k?.role==="assistant",M=T=>{for(let S=T.length-1;S>=0;S--)if(T[S]?.type==="text")return S;return-1},N=(T,S,P)=>I&&T.id===k?.id&&S===M(P),E=T=>I&&T.id===k?.id;return kc("div",{className:"space-y-6 max-w-3xl mx-auto px-2",children:[e.map(T=>{let S=typeof T.content=="string"?T.content:Array.isArray(T.content)?T.content.map(P=>typeof P=="string"?P:P.text||JSON.stringify(P)).join(""):JSON.stringify(T.content);if(T.role==="user")return Zt(gb,{content:S,timestamp:T.timestamp,attachments:T.attachments,inputTokens:v.get(T.id)?.inputTokens},T.id);if(T.role==="assistant"){let P=v.get(T.id)?.outputTokens,A=T.parts&&T.parts.length>0?M(T.parts):-1;return Zt("div",{className:"space-y-4",children:T.parts&&T.parts.length>0?T.parts.map((R,W)=>{let H=R.type==="text"?`${T.id}-text-${W}`:`${T.id}-tool-${R.toolInvocation?.toolCallId??`${R.toolInvocation?.toolName}-${W}`}`;return R.type==="text"?Zt(mm,{content:R.text||"",timestamp:W===T.parts.length-1?T.timestamp:void 0,_isStreaming:N(T,W,T.parts),outputTokens:W===A?P:void 0},H):R.type==="tool-invocation"&&R.toolInvocation?kc("div",{children:[Zt(hm,{toolName:R.toolInvocation.toolName,toolCallId:R.toolInvocation.toolCallId,args:R.toolInvocation.args,result:R.toolInvocation.result,state:R.toolInvocation.state==="authorization-required"?"authorization-required":R.toolInvocation.state==="error"?"error":R.toolInvocation.state==="streaming"||R.toolInvocation.state==="pending"?"call":"result",partialArgs:R.toolInvocation.partialArgs,onAuthenticate:p,isAuthenticating:d===R.toolInvocation.toolCallId,authorizationError:R.toolInvocation.state==="authorization-required"?h:null}),u&&(R.toolInvocation.result||R.toolInvocation.state==="streaming"||y(R.toolInvocation.toolName))&&Zt("div",{"data-tool-call-id":`${T.id}-${R.toolInvocation.toolName}-${W}`,children:Zt(Al,{toolName:R.toolInvocation.toolName,toolArgs:R.toolInvocation.args,result:R.toolInvocation.result||null,serverId:n,readResource:o,toolMeta:x(R.toolInvocation.toolName),onSendFollowUp:g,modelContextScope:c,llmConfig:l,partialToolArgs:R.toolInvocation.partialArgs,cancelled:R.toolInvocation.state==="error"&&R.toolInvocation.result==="Cancelled by user"})})]},H):null}):kc(bR,{children:[Zt(mm,{content:S,timestamp:T.timestamp,_isStreaming:E(T),outputTokens:P}),T.toolCalls&&T.toolCalls.length>0&&Zt("div",{className:"space-y-2",children:T.toolCalls.map(R=>{let W=`${T.id}-${R.toolName}-${JSON.stringify(R.args).slice(0,50)}`;return kc("div",{children:[Zt(hm,{toolName:R.toolName,args:R.args,result:R.result,state:R.result?"result":"call"}),u&&(R.result||y(R.toolName))&&Zt("div",{"data-tool-call-id":W,children:Zt(Al,{toolName:R.toolName,toolArgs:R.args,result:R.result||null,serverId:n,readResource:o,toolMeta:x(R.toolName),onSendFollowUp:g,modelContextScope:c,llmConfig:l})})]},W)})})]})},T.id)}return null}),C&&Zt("div",{className:"flex items-start gap-3",children:Zt("div",{className:"flex-1",children:Zt("div",{className:"rounded-lg p-4 max-w-fit",children:Zt("div",{className:"flex items-center gap-2",children:Zt("span",{className:"text-sm",children:Zt(nb,{duration:2,spread:1,children:"Thinking..."})})})})})}),Zt("div",{ref:a})]})});import{ArrowDown as yR}from"lucide-react";import{AnimatePresence as xR,motion as wR}from"motion/react";import{jsx as mi}from"react/jsx-runtime";function yb({visible:e,onClick:t}){return mi("div",{className:"pointer-events-none absolute bottom-2 left-0 right-0 z-30 flex justify-center",children:mi(xR,{children:e&&mi(wR.div,{initial:{opacity:0,y:8,scale:.96},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:8,scale:.96},transition:{duration:.18,ease:"easeOut"},children:mi(L,{type:"button",variant:"secondary",className:"pointer-events-auto size-9 rounded-full border bg-background/95 p-0 shadow-lg backdrop-blur supports-[backdrop-filter]:bg-background/80",onClick:t,"aria-label":"Scroll to bottom",title:"Scroll to bottom","data-testid":"chat-scroll-to-bottom",children:mi(yR,{className:"size-4"})})})})})}import{jsx as CR}from"react/jsx-runtime";function xb({visible:e}){return CR("div",{"aria-hidden":!0,className:w("pointer-events-none absolute inset-x-0 top-0 z-[5] h-32 bg-[linear-gradient(to_bottom,var(--background)_0%,var(--background)_24%,transparent_46%)] transition-opacity duration-200 sm:h-36",e?"opacity-100":"opacity-0")})}import{useCallback as wb,useEffect as Cb,useRef as wm,useState as Sb}from"react";function Nb(e,{messageCount:t,isLoading:n,enabled:o=!0}){let r=wm(null),[s,a]=Sb(!0),[i,c]=Sb(!1),l=wm(!0),u=wm({length:0,loading:!1}),p=64,d=8,h=t>0,m=o&&h&&!s,b=wb(()=>{let v=e.current;if(!v)return;let y=v.scrollHeight-(v.scrollTop+v.clientHeight)<=p;l.current=y,a(y),c(v.scrollTop>d)},[e]),f=wb(v=>{let x=e.current;x&&(x.scrollTo({top:x.scrollHeight,behavior:v}),l.current=!0,a(!0))},[e]);return Cb(()=>{if(!o)return;let v=e.current;if(!v)return;b();let x=()=>b();v.addEventListener("scroll",x,{passive:!0});let y=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null;return y?.observe(v),()=>{v.removeEventListener("scroll",x),y?.disconnect()}},[o,b,t,e]),Cb(()=>{if(!o||!h||!l.current)return;let v=u.current,x=t!==v.length,y=n!==v.loading;u.current={length:t,loading:n},!(!x&&!y)&&f(n?"auto":"smooth")},[o,h,n,t,f]),{messagesEndRef:r,showScrollToBottom:m,showTopFade:i,scrollToBottom:f}}import{ChevronDown as SR,ChevronUp as NR}from"lucide-react";import{useEffect as Pc,useRef as Tb,useState as kb}from"react";import{jsx as pi,jsxs as TR}from"react/jsx-runtime";function Cm(){let[e,t]=kb(!1);return Pc(()=>{let n=document.documentElement,o=()=>t(n.hasAttribute("data-mcp-widget-fullscreen"));o();let r=new MutationObserver(o);return r.observe(n,{attributes:!0,attributeFilter:["data-mcp-widget-fullscreen"]}),()=>r.disconnect()},[]),e}function Pb({messages:e,isLoading:t}){let n=Cm(),[o,r]=kb(!1),s=Tb(null),a=e.reduce((c,l)=>l.role==="user"?l.id:c,null),i=Tb(a);return Pc(()=>{n||r(!1)},[n]),Pc(()=>{let c=i.current;i.current=a,n&&a!==null&&a!==c&&r(!0)},[n,a]),Pc(()=>{o&&s.current?.scrollIntoView({block:"end"})},[o,e]),n?TR("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-2 px-2 pb-2 sm:px-4","data-testid":"fullscreen-chat-overlay",children:[o&&pi("section",{id:"fullscreen-chat-drawer",className:"max-h-[46vh] overflow-y-auto overscroll-contain rounded-2xl border border-border/80 bg-background/95 px-2 py-4 shadow-2xl backdrop-blur-xl sm:px-4","aria-label":"Current chat messages","data-testid":"fullscreen-chat-drawer",children:pi(ui,{messages:e,isLoading:t,messagesEndRef:s,renderToolResults:!1})}),pi("button",{type:"button",className:"grid size-9 place-items-center self-center rounded-full border border-border/80 bg-background/95 text-foreground shadow-lg backdrop-blur-xl transition-colors hover:bg-muted","aria-label":o?"Hide chat messages":"Show chat messages","aria-expanded":o,"aria-controls":"fullscreen-chat-drawer",onClick:()=>r(c=>!c),"data-testid":"fullscreen-chat-drawer-toggle",children:o?pi(SR,{className:"size-4"}):pi(NR,{className:"size-4"})})]}):null}import{useCallback as Xn,useState as MR}from"react";import{convertMessagesToProvider as kR}from"@mcp-use/agent";function Rc(e){return kR(e)}var Mc=e=>{let t=[];for(let n of e){if(n.error||n.result?.isError){let r={id:`prompt-error-${n.promptName}-${n.timestamp}`,role:"assistant",content:n.error||"Prompt execution failed",timestamp:n.timestamp};t.push(r);continue}let o=n.result;if(o&&"messages"in o&&Array.isArray(o.messages))for(let r of o.messages){let s="",a=[];if(typeof r.content=="string")s=r.content;else if(Array.isArray(r.content)){let c=[];for(let l of r.content)l.type==="text"&&l.text?c.push(l.text):l.type==="image"&&l.data?a.push({type:"image",data:l.data,mimeType:l.mimeType||"image/png"}):l.type==="resource"&&c.push(`[Resource: ${l.resource?.uri||"embedded"}]`);s=c.join(`
|
|
204
204
|
`)}else r.content&&typeof r.content=="object"&&(r.content.type==="text"&&r.content.text?s=r.content.text:r.content.type==="image"&&r.content.data?a.push({type:"image",data:r.content.data,mimeType:r.content.mimeType||"image/png"}):s=JSON.stringify(r.content));!s&&a.length===0&&(s="[no content]");let i={id:`prompt-${n.promptName}-${n.timestamp}-${t.length}`,role:r.role,content:s||"",timestamp:n.timestamp,attachments:a.length>0?a:void 0};t.push(i)}}return t};function Ic(e){if(!e)return;let t=Rb(e);if(t)return t;let n=[],o=!1,r=!1;for(let a of e){if(o){r?r=!1:a==="\\"?r=!0:a==='"'&&(o=!1);continue}a==='"'?o=!0:a==="{"?n.push("}"):a==="["?n.push("]"):(a==="}"||a==="]")&&n[n.length-1]===a&&n.pop()}let s=e;return o&&r&&(s=s.slice(0,-1)),o&&(s+='"'),s+=[...n].reverse().join(""),Rb(s)}function Rb(e){try{let t=JSON.parse(e);return t!==null&&!Array.isArray(t)&&typeof t=="object"?t:void 0}catch{return}}function Sm(e,t=[]){return{id:e,messages:t,attachments:[],isLoading:!1,trace:wr,managedChatNotice:null,pendingAuthorization:null,authenticatingToolCallId:null,toolAuthorizationError:null,mcpServerAuthRequired:null,persistedChatId:null,creation:null,runtime:{abortController:null,sendInProgress:!1,traceId:0,authorizationGate:null,pendingTurnResumed:!1}}}function ss(){let e=globalThis.crypto,t=e?.randomUUID?.();if(t)return t;if(!e?.getRandomValues)throw new Error("Secure random generation is unavailable");let n=e.getRandomValues(new Uint8Array(16));return`chat-${Array.from(n,r=>r.toString(16).padStart(2,"0")).join("")}`}import{useCallback as Nm,useRef as PR,useSyncExternalStore as RR}from"react";function Ec(e,t){return typeof t=="function"?t(e):t}var Tm=class{constructor(){ct(this,"sessions",new Map);ct(this,"listeners",new Map)}get(t){let n=this.sessions.get(t);if(n)return n;let o=Sm(t);return this.sessions.set(t,o),o}has(t){return this.sessions.has(t)}seed(t,n){let o=this.sessions.get(t);if(o)return o;let r=Sm(t,n);return this.sessions.set(t,r),r}update(t,n){let o=this.get(t),r=typeof n=="function"?n(o):n;if(Object.keys(r).every(i=>Object.is(o[i],r[i])))return o;let a={...o,...r};this.sessions.set(t,a);for(let i of this.listeners.get(t)??[])i();return a}subscribe(t,n){let o=this.listeners.get(t);return o||(o=new Set,this.listeners.set(t,o)),o.add(n),()=>{o.delete(n),o.size===0&&this.listeners.delete(t)}}delete(t){this.sessions.delete(t)}findByPersistedChatId(t){for(let n of this.sessions.values())if((n.persistedChatId??n.id)===t)return n}};function qs(){let e=PR(null);return e.current||(e.current=new Tm),e.current}function Ac(e,t){let n=Nm(a=>e.subscribe(t,a),[e,t]),o=Nm(()=>e.get(t),[e,t]),r=RR(n,o,o),s=Nm(a=>e.update(t,a),[t,e]);return[r,s]}function km({sessionStore:e,sessionId:t,onMessagesChange:n,mcpServerUrl:o,llmConfig:r,authConfig:s,mcpAuthTokens:a,isConnected:i,chatApiUrl:c,waitForChatApiUrl:l,widgetModelContexts:u,initialMessages:p,disabledTools:d,streamProtocol:h="sse",credentials:m,extraHeaders:b,body:f}){let v=qs(),x=e??v,[y]=MR(ss),g=t??y;p?.length&&!x.has(g)&&x.seed(g,p);let[C,k]=Ac(x,g),{messages:I,isLoading:M,attachments:N,managedChatNotice:E,mcpServerAuthRequired:T,runtime:S}=C,P=C.trace,A=Xn(z=>{let F=x.update(g,ie=>({messages:Ec(ie.messages,z)}));n?.(g,F.messages)},[g,n,x]),R=Xn(z=>{let F={...z,id:`trace-${++S.traceId}`,timestamp:Date.now()};k(ie=>({trace:Tc(ie.trace,F)}))},[S,k]),W=Xn(async(z,F,ie,le)=>{let Ne=[...N,...ie??[]],de=z.trim()||F.length>0||Ne.length>0,re=pe=>{if(le?.throwOnError)throw new Error(pe)};if(!de){re("Chat message must include content");return}if(!r){re("Chat is not configured");return}if(!i){re("The MCP server is not connected");return}if(S.sendInProgress){re("Chat is busy with another turn");return}S.sendInProgress=!0;let be=[...Mc(F)];if(z.trim()||Ne.length>0){let pe={id:`user-${Date.now()}`,role:"user",content:z.trim(),timestamp:Date.now(),attachments:Ne.length>0?Ne:void 0};be.push(pe)}A(pe=>[...pe,...be]),k({isLoading:!0,attachments:[]}),S.abortController=new AbortController;try{let pe=s,We=s?.type==="bearer"&&!!s.token,Ke=s?.type==="basic"&&!!(s.username||s.password);if(!We&&!Ke)if(a?.access_token)pe={type:"oauth",oauthTokens:a};else try{let ue="mcp:auth",ve=Hl(o),mt=`${ue}_${ve}_tokens`,nt=localStorage.getItem(mt);if(nt){let B=JSON.parse(nt);B?.access_token&&(pe={type:"oauth",oauthTokens:B})}}catch(ue){console.warn("Failed to retrieve OAuth tokens:",ue)}let Ve=[...I,...be],pt=Lr(u??new Map),lt=pl(pt),D=[...lt?[lt]:[],...Ve.map(ue=>({role:ue.role,content:ue.content||(ue.parts?.filter(ve=>ve.type==="text").map(ve=>ve.text).join("")??""),attachments:ue.attachments}))],_=c??(l?await l():void 0)??Ki("chat/stream"),j=[...d??[]].sort(),Le={disabledTools:j,...pt?{widgetModelContext:pt}:{}},Oe=f?f(D,Le):{mcpServerUrl:o,llmConfig:r,authConfig:pe,messages:D,...j.length>0?{disabledTools:j}:{}},He=f?Sc(Oe):{mcpServerUrl:o,llmConfig:{provider:r.provider,model:r.model,temperature:r.temperature,baseUrl:r.baseUrl},messages:D,...j.length>0?{disabledTools:j}:{}};R({type:"request",request:{url:_,protocol:h,envelope:He,providerMessages:[...lt?[lt]:[],...Rc(Ve)]}});let tt=await fetch(_,{method:"POST",headers:{"Content-Type":"application/json",...b},signal:S.abortController.signal,...m?{credentials:m}:{},body:JSON.stringify(Oe)});if(!tt.ok){let ue=await tt.json().catch(()=>null);if(c){let ve=nv(tt.status,ue);if(ve){if(k({managedChatNotice:ve}),le?.throwOnError)throw new Error(`Chat request failed with HTTP ${tt.status}`);return}}if(tt.status===401&&ue?.error==="mcp_auth_required"){if(k({mcpServerAuthRequired:{mcpServerUrl:ue.mcpServerUrl??o,message:ue.message}}),le?.throwOnError)throw new Error("The MCP server requires authentication");return}throw new Error(`HTTP error! status: ${tt.status}`)}le?.onAccepted?.();let ln=`assistant-${Date.now()}`,Nt="",Ze=[];A(ue=>[...ue,{id:ln,role:"assistant",content:"",timestamp:Date.now(),parts:[]}]);let cn=tt.body?.getReader(),co=new TextDecoder;if(!cn)throw new Error("No response body");let Pt=()=>{A(ue=>ue.map(ve=>ve.id===ln?{...ve,parts:[...Ze]}:ve))},Kt=()=>{A(ue=>ue.map(ve=>ve.id===ln?{...ve,parts:[...Ze],content:""}:ve))},Cn=ue=>{Nt+=ue;let ve=Ze[Ze.length-1];ve&&ve.type==="text"?ve.text=Nt:Ze.push({type:"text",text:Nt}),Pt()},Tt=new Map,Yt=new Map,oe=(ue,ve)=>{Nt&&(Nt=""),!Tt.has(ue)&&(Ze.push({type:"tool-invocation",toolInvocation:{toolCallId:ue,toolName:ve,args:{},state:"streaming",partialArgs:{}}}),Tt.set(ue,Ze.length-1),Yt.set(ue,""),Pt())},fe=(ue,ve)=>{let mt=Tt.get(ue);if(mt===void 0||!ve)return;let nt=(Yt.get(ue)??"")+ve;Yt.set(ue,nt);let B=Ic(nt),se=Ze[mt]?.toolInvocation;!B||!se||(se.partialArgs=B,Pt())},Ue=(ue,ve,mt)=>{Nt&&(Nt="");let nt=Tt.get(ue),B=nt===void 0?void 0:Ze[nt]?.toolInvocation;B?(B.toolName=ve,B.args=mt,B.state="pending",B.partialArgs=void 0):(Ze.push({type:"tool-invocation",toolInvocation:{toolCallId:ue,toolName:ve,args:mt,state:"pending"}}),Tt.set(ue,Ze.length-1)),Yt.delete(ue),Pt()},ft=(ue,ve)=>{let mt;ue.by==="toolName"?mt=Ze.find(nt=>nt.type==="tool-invocation"&&nt.toolInvocation?.toolName===ue.toolName&&!nt.toolInvocation?.result):mt=Ze[ue.index],mt?.toolInvocation&&(mt.toolInvocation.result=ve,mt.toolInvocation.state=ve?.isError?"error":"result",Pt())},Rt="";for(;;){if(S.abortController?.signal.aborted){await cn.cancel();break}let{done:ue,value:ve}=await cn.read();if(ue)break;Rt+=co.decode(ve,{stream:!0});let mt=Rt.split(`
|