@mcp-use/inspector 20.2.4 → 20.2.5-canary.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Binary file
package/dist/cli.js CHANGED
@@ -5,7 +5,7 @@ ${n.join(`\r
5
5
  \r
6
6
  `)},Bo=e=>{let t=e.socket.encrypted?"https":"http",r=new URL(e.url??"/",`${t}://${e.headers.host??"localhost"}`),n=new Headers;for(let o in e.headers){let s=e.headers[o];s&&n.append(o,Array.isArray(s)?s[0]:s)}return new Request(r,{headers:n})},Ho=e=>{let{server:t,fetchCallback:r,wss:n}=e,o=new Map;n.on("connection",(a,c)=>{let l=o.get(c);l&&(l.resolve(a),o.delete(c))});let s=a=>{let c=o.get(a);c&&(o.delete(a),c.reject(new Error("WebSocket handshake aborted")))},i=(a,c)=>new Promise((l,u)=>{o.set(a,{resolve:l,reject:u,connectionSymbol:c})});t.on("upgrade",async(a,c,l)=>{if(a.headers.upgrade?.toLowerCase()!=="websocket")return;let u={incoming:a,outgoing:void 0,wss:n,[ur]:i},d=400,p;try{let y=await r(Bo(a),u);y instanceof Response&&(d=y.status,p=y.headers)}catch{t.listenerCount("upgrade")===1&&Jt(c,500);return}let m=o.get(a);if(!m||m.connectionSymbol!==u[lr]){s(a),t.listenerCount("upgrade")===1&&Jt(c,d,p);return}let g=y=>{dr(y,p)},h=()=>s(a);c.once("close",h),n.on("headers",g);try{n.handleUpgrade(a,c,l,y=>{c.off("close",h),n.emit("connection",y,a)})}finally{n.off("headers",g)}}),t.on("close",()=>{n.close()})},Hi=Wt(async(e,t,r)=>{if(e.req.header("upgrade")?.toLowerCase()!=="websocket")return;let n=e.env,o=n[ur];if(!o||!n.incoming)return new Response(null,{status:500});let s=Uo();return n[lr]=s,(async()=>{let i;try{i=await o(n.incoming,s)}catch{return}let a=[],c=(d,p)=>{a.push([d,p])};i.on("message",c);let l={binaryType:"arraybuffer",close(d,p){i.close(d,p)},protocol:i.protocol,raw:i,get readyState(){return i.readyState},send(d,p){i.send(d,{compress:p?.compress})},url:new URL(e.req.url)};try{t?.onOpen?.(new Event("open"),l)}catch(d){(r?.onError??console.error)(d)}let u=(d,p)=>{let m=Array.isArray(d)?d:[d];for(let g of m)try{t?.onMessage?.(new MessageEvent("message",{data:p?g instanceof ArrayBuffer?g:g.buffer.slice(g.byteOffset,g.byteOffset+g.byteLength):typeof g=="string"?g:Buffer.from(g).toString("utf-8")}),l)}catch(h){(r?.onError??console.error)(h)}};i.off("message",c);for(let d of a)u(...d);i.on("message",(d,p)=>{u(d,p)}),i.on("close",(d,p)=>{try{t?.onClose?.(new Do("close",{code:d,reason:p.toString()}),l)}catch(m){(r?.onError??console.error)(m)}}),i.on("error",d=>{try{t?.onError?.(new No("error",{error:d}),l)}catch(p){(r?.onError??console.error)(p)}})})(),new Response}),$o=e=>{let t=e.fetch,r=Io(t,{hostname:e.hostname,overrideGlobalObjects:e.overrideGlobalObjects,autoCleanupIncoming:e.autoCleanupIncoming}),n=(e.createServer||ro)(e.serverOptions||{},r);if(e.websocket&&e.websocket.server){if(e.websocket.server.options.noServer!==!0)throw new Error("WebSocket server must be created with { noServer: true } option");Ho({server:n,fetchCallback:t,wss:e.websocket.server})}return n},fr=(e,t)=>{let r=$o(e);return r.listen(e?.port??3e3,e.hostname,()=>{let n=r.address();t&&t(n)}),r};var nt=(e,t,r)=>(n,o)=>{let s=-1;return i(0);async function i(a){if(a<=s)throw new Error("next() called multiple times");s=a;let c,l=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&o||void 0,u)try{c=await u(n,()=>i(a+1))}catch(d){if(d instanceof Error&&t)n.error=d,c=await t(d,n),l=!0;else throw d}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||l)&&(n.res=c),n}};var pr=Symbol();var hr=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,n=>n.toLowerCase())}}).formData();var Oe=e=>"headers"in e,gr=async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,i=(Oe(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return i==="multipart/form-data"||i==="application/x-www-form-urlencoded"?Fo(e,{all:r,dot:n}):{}};async function Fo(e,t){if(!Oe(e)&&e.bodyCache.formData)return mr(await e.bodyCache.formData,t);let r=Oe(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=hr(n,r.get("Content-Type")||"");Oe(e)||(e.bodyCache.formData=o);let s=await o;return s?mr(s,t):{}}function mr(e,t){let r=Object.create(null);return e.forEach((n,o)=>{t.all||o.endsWith("[]")?Wo(r,o,n):r[o]=n}),t.dot&&Object.entries(r).forEach(([n,o])=>{n.includes(".")&&(zo(r,n,o),delete r[n])}),r}var Wo=(e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},zo=(e,t,r)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".");o.forEach((s,i)=>{i===o.length-1?n[s]=r:((!n[s]||typeof n[s]!="object"||Array.isArray(n[s])||n[s]instanceof File)&&(n[s]=Object.create(null)),n=n[s])})};var st=e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},yr=e=>{let{groups:t,path:r}=qo(e),n=st(r);return Ko(n,t)},qo=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},Ko=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},Te={},wr=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return Te[n]||(r[2]?Te[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:Te[n]=[e,r[1],!0]),Te[n]}return null},Le=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},Vo=e=>Le(e,decodeURI),it=e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let s=t.indexOf("?",n),i=t.indexOf("#",n),a=s===-1?i===-1?void 0:i:i===-1?s:Math.min(s,i),c=t.slice(r,a);return Vo(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)};var br=e=>{let t=it(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},K=(e,t,...r)=>(r.length&&(t=K(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),ke=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(/\?/.test(o)){r.length===0&&n===""?r.push("/"):r.push(n);let s=o.replace("?","");n+="/"+s,r.push(n)}else n+="/"+o}),r.filter((o,s,i)=>i.indexOf(o)===s)},ot=e=>/[%+]/.test(e)?(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),e.indexOf("%")!==-1?Le(e,at):e):e,vr=(e,t,r)=>{let n;if(!r&&t&&!/[%+]/.test(t)){let i=e.indexOf("?",8);if(i===-1)return;for(e.startsWith(t,i+1)||(i=e.indexOf(`&${t}`,i+1));i!==-1;){let a=e.charCodeAt(i+t.length+1);if(a===61){let c=i+t.length+2,l=e.indexOf("&",c);return ot(e.slice(c,l===-1?void 0:l))}else if(a==38||isNaN(a))return"";i=e.indexOf(`&${t}`,i+1)}if(n=/[%+]/.test(e),!n)return}let o=Object.create(null);n??=/[%+]/.test(e);let s=e.indexOf("?",8);for(;s!==-1;){let i=e.indexOf("&",s+1),a=e.indexOf("=",s);a>i&&i!==-1&&(a=-1);let c=e.slice(s+1,a===-1?i===-1?void 0:i:a);if(n&&(c=ot(c)),s=i,c==="")continue;let l;a===-1?l="":(l=e.slice(a+1,i===-1?void 0:i),n&&(l=ot(l))),r?(o[c]&&Array.isArray(o[c])||(o[c]=[]),o[c].push(l)):o[c]??=l}return t?o[t]:o},xr=vr,Er=(e,t)=>vr(e,t,!0),at=decodeURIComponent;var Sr=e=>Le(e,at),Rr=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#t=r,this.#e={}}param(e){return e?this.#r(e):this.#s()}#r(e){let t=this.#t[0][this.routeIndex][1][e],r=this.#o(t);return r&&/\%/.test(r)?Sr(r):r}#s(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let r of t){let n=this.#o(this.#t[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=/\%/.test(n)?Sr(n):n)}return e}#o(e){return this.#t[1]?this.#t[1][e]:e}query(e){return xr(this.url,e)}queries(e){return Er(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return gr(this,e)}#n=e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;let o=Object.keys(t)[0];return o?t[o].then(s=>(o==="json"&&(s=JSON.stringify(s)),new Response(s)[e]())):t[e]=r[e]()};json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){this.#e[e]=t}valid(e){return this.#e[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[pr](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}};var Pr={Stringify:1,BeforeStream:2,Stream:3},Go=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var ct=async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let s=e.callbacks;if(!s?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let i=Promise.all(s.map(a=>a({phase:t,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>ct(c,t,!1,n,o))).then(()=>o[0]));return r?Go(await i,s):i};var Yo="text/plain; charset=UTF-8",lt=(e,t)=>({"Content-Type":e,...t}),me=(e,t)=>new Response(e,t),ut=class{#e;#t;env={};#r;finalized=!1;error;#s;#o;#n;#u;#c;#l;#a;#d;#f;constructor(e,t){this.#e=e,t&&(this.#o=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#d=t.matchResult)}get req(){return this.#t??=new Rr(this.#e,this.#f,this.#d),this.#t}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=me(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=me(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#n=e,this.finalized=!0}render=(...e)=>(this.#c??=t=>this.html(t),this.#c(...e));setLayout=e=>this.#u=e;getLayout=()=>this.#u;setRenderer=e=>{this.#c=e};header=(e,t,r)=>{this.finalized&&(this.#n=me(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)};status=e=>{this.#s=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=e=>this.#r?this.#r.get(e):void 0;get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a??new Headers;if(typeof t=="object"&&"headers"in t){let s=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[i,a]of s)i.toLowerCase()==="set-cookie"?n.append(i,a):n.set(i,a)}if(r)for(let[s,i]of Object.entries(r))if(typeof i=="string")n.set(s,i);else{n.delete(s);for(let a of i)n.append(s,a)}let o=typeof t=="number"?t:t?.status??this.#s;return me(e,{status:o,headers:n})}newResponse=(...e)=>this.#i(...e);body=(e,t,r)=>this.#i(e,t,r);text=(e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,lt(Yo,r));json=(e,t,r)=>this.#i(JSON.stringify(e),t,lt("application/json",r));html=(e,t,r)=>{let n=o=>this.#i(o,t,lt("text/html; charset=UTF-8",r));return typeof e=="object"?ct(e,Pr.Stringify,!1,{}).then(n):n(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>me(),this.#l(this))};var x="ALL",Ar="all",Cr=["get","post","put","delete","options","patch"],Me="Can not add a route since the matcher is already built.",Ie=class extends Error{};var _r="__COMPOSED_HANDLER";var Xo=e=>e.text("404 Not Found",404),Or=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},Tr=class Lr{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#e="/";routes=[];constructor(t={}){[...Cr,Ar].forEach(s=>{this[s]=(i,...a)=>(typeof i=="string"?this.#e=i:this.#s(s,this.#e,i),a.forEach(c=>{this.#s(s,this.#e,c)}),this)}),this.on=(s,i,...a)=>{for(let c of[i].flat()){this.#e=c;for(let l of[s].flat())a.map(u=>{this.#s(l.toUpperCase(),this.#e,u)})}return this},this.use=(s,...i)=>(typeof s=="string"?this.#e=s:(this.#e="*",i.unshift(s)),i.forEach(a=>{this.#s(x,this.#e,a)}),this);let{strict:n,...o}=t;Object.assign(this,o),this.getPath=n??!0?t.getPath??it:br}#t(){let t=new Lr({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Xo;errorHandler=Or;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let s;r.errorHandler===Or?s=o.handler:(s=async(i,a)=>(await nt([],r.errorHandler)(i,()=>o.handler(i,a))).res,s[_r]=o.handler),n.#s(o.method,o.path,s,o.basePath)}),this}basePath(t){let r=this.#t();return r._basePath=K(this._basePath,t),r}onError=t=>(this.errorHandler=t,this);notFound=t=>(this.#r=t,this);mount(t,r,n){let o,s;n&&(typeof n=="function"?s=n:(s=n.optionHandler,n.replaceRequest===!1?o=c=>c:o=n.replaceRequest));let i=s?c=>{let l=s(c);return Array.isArray(l)?l:[l]}:c=>{let l;try{l=c.executionCtx}catch{}return[c.env,l]};o||=(()=>{let c=K(this._basePath,t),l=c==="/"?0:c.length;return u=>{let d=new URL(u.url);return d.pathname=this.getPath(u).slice(l)||"/",new Request(d,u)}})();let a=async(c,l)=>{let u=await r(o(c.req.raw),...i(c));if(u)return u;await l()};return this.#s(x,K(t,"*"),a),this}#s(t,r,n,o){t=t.toUpperCase(),r=K(this._basePath,r);let s={basePath:o!==void 0?K(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,s]),this.routes.push(s)}#o(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let s=this.getPath(t,{env:n}),i=this.router.match(o,s),a=new ut(t,{path:s,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let l;try{l=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#o(u,a)}return l instanceof Promise?l.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#o(u,a)):l??this.#r(a)}let c=nt(i[0],this.errorHandler,this.#r);return(async()=>{try{let l=await c(a);if(!l.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return l.res}catch(l){return this.#o(l,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${K("/",t)}`,r),n,o));fire=()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var De=[];function dt(e,t){let r=this.buildAllMatchers(),n=((o,s)=>{let i=r[o]||r[x],a=i[2][s];if(a)return a;let c=s.match(i[0]);if(!c)return[[],De];let l=c.indexOf("",1);return[i[1][l],c]});return this.match=n,n(e,t)}var Ne="[^/]+",ge=".*",ye="(?:|/.*)",J=Symbol(),Jo=new Set(".\\+*[^]$()");function Qo(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===ge||e===ye?1:t===ge||t===ye?-1:e===Ne?1:t===Ne?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var kr=class ft{#e;#t;#r=Object.create(null);insert(t,r,n,o,s){if(t.length===0){if(this.#e!==void 0)throw J;if(s)return;this.#e=r;return}let[i,...a]=t,c=i==="*"?a.length===0?["","",ge]:["","",Ne]:i==="/*"?["","",ye]:i.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let u=c[1],d=c[2]||Ne;if(u&&c[2]&&(d===".*"||(d=d.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(d))))throw J;if(l=this.#r[d],!l){if(Object.keys(this.#r).some(p=>p!==ge&&p!==ye))throw J;if(s)return;l=this.#r[d]=new ft,u!==""&&(l.#t=o.varIndex++)}!s&&u!==""&&n.push([u,l.#t])}else if(l=this.#r[i],!l){if(Object.keys(this.#r).some(u=>u.length>1&&u!==ge&&u!==ye))throw J;if(s)return;l=this.#r[i]=new ft}l.insert(a,r,n,o,s)}buildRegExpStr(){let r=Object.keys(this.#r).sort(Qo).map(n=>{let o=this.#r[n];return(typeof o.#t=="number"?`(${n})@${o.#t}`:Jo.has(n)?`\\${n}`:n)+o.buildRegExpStr()});return typeof this.#e=="number"&&r.unshift(`#${this.#e}`),r.length===0?"":r.length===1?r[0]:"(?:"+r.join("|")+")"}};var Mr=class{#e={varIndex:0};#t=new kr;insert(e,t,r){let n=[],o=[];for(let i=0;;){let a=!1;if(e=e.replace(/\{[^}]+\}/g,c=>{let l=`@\\${i}`;return o[i]=[l,c],i++,a=!0,l}),!a)break}let s=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=o.length-1;i>=0;i--){let[a]=o[i];for(let c=s.length-1;c>=0;c--)if(s[c].indexOf(a)!==-1){s[c]=s[c].replace(a,o[i][1]);break}}return this.#t.insert(s,t,n,this.#e,r),n}buildRegExp(){let e=this.#t.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,s,i)=>s!==void 0?(r[++t]=Number(s),"$()"):(i!==void 0&&(n[Number(i)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var Zo=[/^$/,[],Object.create(null)],Ir=Object.create(null);function Dr(e){return Ir[e]??=new RegExp(e==="*"?"":`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(t,r)=>r?`\\${r}`:"(?:|/.*)")}$`)}function es(){Ir=Object.create(null)}function ts(e){let t=new Mr,r=[];if(e.length===0)return Zo;let n=e.map(l=>[!/\*|\/:/.test(l[0]),...l]).sort(([l,u],[d,p])=>l?1:d?-1:u.length-p.length),o=Object.create(null);for(let l=0,u=-1,d=n.length;l<d;l++){let[p,m,g]=n[l];p?o[m]=[g.map(([y])=>[y,Object.create(null)]),De]:u++;let h;try{h=t.insert(m,u,p)}catch(y){throw y===J?new Ie(m):y}p||(r[u]=g.map(([y,f])=>{let w=Object.create(null);for(f-=1;f>=0;f--){let[v,L]=h[f];w[v]=L}return[y,w]}))}let[s,i,a]=t.buildRegExp();for(let l=0,u=r.length;l<u;l++)for(let d=0,p=r[l].length;d<p;d++){let m=r[l][d]?.[1];if(!m)continue;let g=Object.keys(m);for(let h=0,y=g.length;h<y;h++)m[g[h]]=a[m[g[h]]]}let c=[];for(let l in i)c[l]=r[i[l]];return[s,c,o]}function se(e,t){if(e){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(Dr(r).test(t))return[...e[r]]}}var Ue=class{name="RegExpRouter";#e;#t;constructor(){this.#e={[x]:Object.create(null)},this.#t={[x]:Object.create(null)}}add(e,t,r){let n=this.#e,o=this.#t;if(!n||!o)throw new Error(Me);n[e]||[n,o].forEach(a=>{a[e]=Object.create(null),Object.keys(a[x]).forEach(c=>{a[e][c]=[...a[x][c]]})}),t==="/*"&&(t="*");let s=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let a=Dr(t);e===x?Object.keys(n).forEach(c=>{n[c][t]||=se(n[c],t)||se(n[x],t)||[]}):n[e][t]||=se(n[e],t)||se(n[x],t)||[],Object.keys(n).forEach(c=>{(e===x||e===c)&&Object.keys(n[c]).forEach(l=>{a.test(l)&&n[c][l].push([r,s])})}),Object.keys(o).forEach(c=>{(e===x||e===c)&&Object.keys(o[c]).forEach(l=>a.test(l)&&o[c][l].push([r,s]))});return}let i=ke(t)||[t];for(let a=0,c=i.length;a<c;a++){let l=i[a];Object.keys(o).forEach(u=>{(e===x||e===u)&&(o[u][l]||=[...se(n[u],l)||se(n[x],l)||[]],o[u][l].push([r,s-c+a+1]))})}}match=dt;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#r(t)}),this.#e=this.#t=void 0,es(),e}#r(e){let t=[],r=e===x;return[this.#e,this.#t].forEach(n=>{let o=n[e]?Object.keys(n[e]).map(s=>[s,n[e][s]]):[];o.length!==0?(r||=!0,t.push(...o)):e!==x&&t.push(...Object.keys(n[x]).map(s=>[s,n[x][s]]))}),r?ts(t):null}};var pt=class{name="SmartRouter";#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,r){if(!this.#t)throw new Error(Me);this.#t.push([e,t,r])}match(e,t){if(!this.#t)throw new Error("Fatal error");let r=this.#e,n=this.#t,o=r.length,s=0,i;for(;s<o;s++){let a=r[s];try{for(let c=0,l=n.length;c<l;c++)a.add(...n[c]);i=a.match(e,t)}catch(c){if(c instanceof Ie)continue;throw c}this.match=a.match.bind(a),this.#e=[a],this.#t=void 0;break}if(s===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#t||this.#e.length!==1)throw new Error("No active router has been determined yet.");return this.#e[0]}};var we=Object.create(null),rs=e=>{for(let t in e)return!0;return!1},Nr=class Ur{#e;#t;#r;#s=0;#o=we;constructor(t,r,n){if(this.#t=n||Object.create(null),this.#e=[],t&&r){let o=Object.create(null);o[t]={handler:r,possibleKeys:[],score:0},this.#e=[o]}this.#r=[]}insert(t,r,n){this.#s=++this.#s;let o=this,s=yr(r),i=[];for(let a=0,c=s.length;a<c;a++){let l=s[a],u=s[a+1],d=wr(l,u),p=Array.isArray(d)?d[0]:l;if(p in o.#t){o=o.#t[p],d&&i.push(d[1]);continue}o.#t[p]=new Ur,d&&(o.#r.push(d),i.push(d[1])),o=o.#t[p]}return o.#e.push({[t]:{handler:n,possibleKeys:i.filter((a,c,l)=>l.indexOf(a)===c),score:this.#s}}),o}#n(t,r,n,o,s){for(let i=0,a=r.#e.length;i<a;i++){let c=r.#e[i],l=c[n]||c[x],u={};if(l!==void 0&&(l.params=Object.create(null),t.push(l),o!==we||s&&s!==we))for(let d=0,p=l.possibleKeys.length;d<p;d++){let m=l.possibleKeys[d],g=u[l.score];l.params[m]=s?.[m]&&!g?s[m]:o[m]??s?.[m],u[l.score]=!0}}}search(t,r){let n=[];this.#o=we;let s=[this],i=st(r),a=[],c=i.length,l=null;for(let u=0;u<c;u++){let d=i[u],p=u===c-1,m=[];for(let h=0,y=s.length;h<y;h++){let f=s[h],w=f.#t[d];w&&(w.#o=f.#o,p?(w.#t["*"]&&this.#n(n,w.#t["*"],t,f.#o),this.#n(n,w,t,f.#o)):m.push(w));for(let v=0,L=f.#r.length;v<L;v++){let k=f.#r[v],S=f.#o===we?{}:{...f.#o};if(k==="*"){let R=f.#t["*"];R&&(this.#n(n,R,t,f.#o),R.#o=S,m.push(R));continue}let[P,A,E]=k;if(!d&&!(E instanceof RegExp))continue;let b=f.#t[P];if(E instanceof RegExp){if(l===null){l=new Array(c);let G=r[0]==="/"?1:0;for(let Y=0;Y<c;Y++)l[Y]=G,G+=i[Y].length+1}let R=r.substring(l[u]),T=E.exec(R);if(T){if(S[A]=T[0],this.#n(n,b,t,f.#o,S),T[0].length===R.length&&b.#t["*"]&&this.#n(n,b.#t["*"],t,f.#o,S),rs(b.#t)){b.#o=S;let G=T[0].match(/\//)?.length??0;(a[G]||=[]).push(b)}continue}}(E===!0||E.test(d))&&(S[A]=d,p?(this.#n(n,b,t,S,f.#o),b.#t["*"]&&this.#n(n,b.#t["*"],t,S,f.#o)):(b.#o=S,m.push(b)))}}let g=a.shift();s=g?m.concat(g):m}return n.length>1&&n.sort((u,d)=>u.score-d.score),[n.map(({handler:u,params:d})=>[u,d])]}};var ht=class{name="TrieRouter";#e;constructor(){this.#e=new Nr}add(e,t,r){let n=ke(t);if(n){for(let o=0,s=n.length;o<s;o++)this.#e.insert(e,n[o],r);return}this.#e.insert(e,t,r)}match(e,t){return this.#e.search(e,t)}};var mt=class extends Tr{constructor(e={}){super(e),this.router=e.router??new pt({routers:[new Ue,new ht]})}};var je=e=>{let t={origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[],...e},r=(o=>typeof o=="string"?o==="*"?()=>o:s=>o===s?s:null:typeof o=="function"?o:s=>o.includes(s)?s:null)(t.origin),n=(o=>typeof o=="function"?o:Array.isArray(o)?()=>o:()=>[])(t.allowMethods);return async function(s,i){function a(l,u){s.res.headers.set(l,u)}let c=await r(s.req.header("origin")||"",s);if(c&&a("Access-Control-Allow-Origin",c),t.credentials&&a("Access-Control-Allow-Credentials","true"),t.exposeHeaders?.length&&a("Access-Control-Expose-Headers",t.exposeHeaders.join(",")),s.req.method==="OPTIONS"){t.origin!=="*"&&a("Vary","Origin"),t.maxAge!=null&&a("Access-Control-Max-Age",t.maxAge.toString());let l=await n(s.req.header("origin")||"",s);l.length&&a("Access-Control-Allow-Methods",l.join(","));let u=t.allowHeaders;if(!u?.length){let d=s.req.header("Access-Control-Request-Headers");d&&(u=d.split(",").map(p=>p.trim()))}return u?.length&&(a("Access-Control-Allow-Headers",u.join(",")),s.res.headers.append("Vary","Access-Control-Request-Headers")),s.res.headers.delete("Content-Length"),s.res.headers.delete("Content-Type"),new Response(null,{headers:s.res.headers,status:204,statusText:"No Content"})}await i(),t.origin!=="*"&&s.header("Vary","Origin",{append:!0})}};import en from"process";import tn from"path";import{fileURLToPath as Is}from"url";import Ds from"child_process";import Ns,{constants as Us}from"fs/promises";import{promisify as ps}from"util";import hs from"child_process";import vt,{constants as zr}from"fs/promises";import Hr from"process";import as from"os";import cs from"fs";import ss from"fs";import jr from"fs";var gt;function ns(){try{return jr.statSync("/.dockerenv"),!0}catch{return!1}}function os(){try{return jr.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function yt(){return gt===void 0&&(gt=ns()||os()),gt}var wt,is=()=>{try{return ss.statSync("/run/.containerenv"),!0}catch{return!1}};function ie(){return wt===void 0&&(wt=is()||yt()),wt}var Br=()=>{if(Hr.platform!=="linux")return!1;if(as.release().toLowerCase().includes("microsoft"))return!ie();try{return cs.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!ie():!1}catch{return!1}},H=Hr.env.__IS_WSL_TEST__?Br:Br();import $r from"process";import{Buffer as ls}from"buffer";import{promisify as us}from"util";import ds from"child_process";import Lc,{constants as kc}from"fs/promises";var fs=us(ds.execFile),bt=()=>`${$r.env.SYSTEMROOT||$r.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var O=async(e,t={})=>{let{powerShellPath:r,...n}=t,o=O.encodeCommand(e);return fs(r??bt(),[...O.argumentsPrefix,o],{encoding:"utf8",...n})};O.argumentsPrefix=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"];O.encodeCommand=e=>ls.from(e,"utf16le").toString("base64");O.escapeArgument=e=>`'${String(e).replaceAll("'","''")}'`;function Fr(e){for(let t of e.split(`
7
7
  `)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(r)return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var ms=ps(hs.execFile),gs=(()=>{let e="/mnt/",t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await vt.access(r,zr.F_OK),n=!0}catch{}if(!n)return e;let o=await vt.readFile(r,{encoding:"utf8"}),s=Fr(o);return s===void 0?e:(t=s,t=t.endsWith("/")?t:`${t}/`,t)}})(),ys=async()=>`${await gs()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Be=H?ys:bt,Wr,qr=async()=>(Wr??=(async()=>{try{let e=await Be();return await vt.access(e,zr.X_OK),!0}catch{return!1}})(),Wr),Kr=async()=>{let e=await Be(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await O(t,{powerShellPath:e});return r.trim()},Vr=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await ms("wslpath",["-aw",e],{encoding:"utf8"});return t.trim()}catch{return e}};function Q(e,t,r){let n=o=>Object.defineProperty(e,t,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let o=r();return n(o),o},set(o){n(o)}}),e}import{promisify as Os}from"util";import At from"process";import{execFile as Ts}from"child_process";import{promisify as ws}from"util";import bs from"process";import{execFile as vs}from"child_process";var xs=ws(vs);async function xt(){if(bs.platform!=="darwin")throw new Error("macOS only");let{stdout:e}=await xs("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),r=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";return r==="com.apple.safari"?"com.apple.Safari":r}import Es from"process";import{promisify as Ss}from"util";import{execFile as Rs,execFileSync as Jc}from"child_process";var Ps=Ss(Rs);async function Gr(e,{humanReadableOutput:t=!0,signal:r}={}){if(Es.platform!=="darwin")throw new Error("macOS only");let n=t?[]:["-ss"],o={};r&&(o.signal=r);let{stdout:s}=await Ps("osascript",["-e",e,n],o);return s.trim()}async function Et(e){return Gr(`tell application "Finder" to set app_path to application file id "${e}" as string
8
- tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as As}from"util";import{execFile as Cs}from"child_process";var _s=As(Cs),He={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},Rt=new Map(Object.entries(He)),St=class extends Error{};async function Pt(e=_s){let{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new St(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:n}=r.groups,o=n.lastIndexOf("."),s=n.lastIndexOf("-"),i=o===-1?void 0:n.slice(0,o),a=s===-1?void 0:n.slice(0,s);return He[n]??He[i]??He[a]??{name:n,id:n}}var Ls=Os(Ts),ks=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function Ct(){if(At.platform==="darwin"){let e=await xt();return{name:await Et(e),id:e}}if(At.platform==="linux"){let{stdout:e}=await Ls("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:ks(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(At.platform==="win32")return Pt();throw new Error("Only macOS, Linux, and Windows are supported")}import _t from"process";var Ms=!!(_t.env.SSH_CONNECTION||_t.env.SSH_CLIENT||_t.env.SSH_TTY),Yr=Ms;var $e=Symbol("fallbackAttempt"),Ot=import.meta.url?tn.dirname(Is(import.meta.url)):"",Xr=tn.join(Ot,"xdg-open"),{platform:ae,arch:Jr}=en,Qr=async(e,t)=>{if(e.length===0)return;let r=[];for(let n of e)try{return await t(n)}catch(o){r.push(o)}throw new AggregateError(r,"Failed to open in all supported apps")},Fe=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[$e]===!0;if(delete e[$e],Array.isArray(e.app))return Qr(e.app,l=>Fe({...e,app:l,[$e]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return Qr(r,l=>Fe({...e,app:{name:l,arguments:n},[$e]:!0}));if(r==="browser"||r==="browserPrivate"){let l={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d;if(H){let p=await Kr();d=Rt.get(p)??{}}else d=await Ct();if(d.id in l){let p=l[d.id.toLowerCase()];if(r==="browserPrivate"){if(p==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(u[p])}return Fe({...e,app:{name:ce[p],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(H&&!ie()&&!Yr&&!r&&(a=await qr()),ae==="darwin")o="open",e.wait&&s.push("--wait-apps"),e.background&&s.push("--background"),e.newInstance&&s.push("--new"),r&&s.push("-a",r);else if(ae==="win32"||a){o=await Be(),s.push(...O.argumentsPrefix),H||(i.windowsVerbatimArguments=!0),H&&e.target&&(e.target=await Vr(e.target));let l=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&l.push("-Wait"),r?(l.push(O.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&l.push(O.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>O.escapeArgument(u)),l.push("-ArgumentList",n.join(","))),e.target=O.encodeCommand(l.join(" ")),e.wait||(i.stdio="ignore")}else{if(r)o=r;else{let l=!Ot||Ot==="/",u=!1;try{await Ns.access(Xr,Us.X_OK),u=!0}catch{}o=en.versions.electron??(ae==="android"||l||!u)?"xdg-open":Xr}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}ae==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=Ds.spawn(o,s,i);return e.wait?new Promise((l,u)=>{c.once("error",u),c.once("close",d=>{if(!e.allowNonzeroExitCode&&d!==0){u(new Error(`Exited with code ${d}`));return}l(c)})}):t?new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.once("close",d=>{if(c.off("error",u),d!==0){u(new Error(`Exited with code ${d}`));return}c.unref(),l(c)})})}):(c.unref(),new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.off("error",u),l(c)})}))},js=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Fe({...t,target:e})};function Zr(e){if(typeof e=="string"||Array.isArray(e))return e;let{[Jr]:t}=e;if(!t)throw new Error(`${Jr} is not supported`);return t}function be({[ae]:e},{wsl:t}={}){if(t&&H)return Zr(t);if(!e)throw new Error(`${ae} is not supported`);return Zr(e)}var ce={browser:"browser",browserPrivate:"browserPrivate"};Q(ce,"chrome",()=>be({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Q(ce,"brave",()=>be({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Q(ce,"firefox",()=>be({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Q(ce,"edge",()=>be({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Q(ce,"safari",()=>be({darwin:"Safari"}));var rn=js;function nn(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as gn,readFileSync as Ws}from"fs";import F from"path";import{fileURLToPath as zs}from"url";import{gunzipSync as qs}from"zlib";var $=eo(mn(),1);function le(e,t){return e.header("Retry-After",String($s(t))),e.json({error:"Too Many Requests"},429)}function $s(e){return e&&typeof e=="object"&&"msBeforeNext"in e&&typeof e.msBeforeNext=="number"&&Number.isFinite(e.msBeforeNext)?Math.max(1,Math.ceil(e.msBeforeNext/1e3)):60}var Ks={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Vs(){let e=F.dirname(zs(import.meta.url));for(let t of[F.resolve(e,"app"),F.resolve(e,"../app"),F.resolve(e,"../../dist/app")])if(gn(F.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function yn(e,t="/inspector/assets"){let r=Vs(),n=new Map,o=new $.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return le(i,c)}return a()};e.use(`${t}/*`,s),e.get(`${t}/*`,async i=>{let a=i.req.path.slice(t.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=F.resolve(r,l),d=r.endsWith(F.sep)?r:`${r}${F.sep}`;if(!u.startsWith(d)||!gn(u))return i.notFound();let p=F.extname(c),m=l.endsWith(".gz"),g=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),h=Ws(u),y=m&&!g?n.get(u)??Gs(n,u,h):h,f=y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength);return i.body(f,200,{"Content-Type":Ks[p]??"application/octet-stream",...m&&g?{"Content-Encoding":"gzip"}:{},...m?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Gs(e,t,r){let n=qs(r);return e.set(t,n),n}var wn={name:"@mcp-use/inspector",type:"module",version:"20.2.4",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"},"./client/styles.css":{default:"./dist/client/styles.css"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts && node scripts/copy-client-styles.mjs","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.7","@mcp-use/client":"^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"^2.2.4",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},"mcp-use":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^2.0.5","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.34",jsdom:"^27.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^8.3.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",yaml:"^2.8.3",zod:"^4.2.0"}};var Xs=wn.version;function We(){return Xs}var Js=`<!doctype html>
8
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import{promisify as As}from"util";import{execFile as Cs}from"child_process";var _s=As(Cs),He={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},Rt=new Map(Object.entries(He)),St=class extends Error{};async function Pt(e=_s){let{stdout:t}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),r=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!r)throw new St(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:n}=r.groups,o=n.lastIndexOf("."),s=n.lastIndexOf("-"),i=o===-1?void 0:n.slice(0,o),a=s===-1?void 0:n.slice(0,s);return He[n]??He[i]??He[a]??{name:n,id:n}}var Ls=Os(Ts),ks=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,t=>t.toUpperCase());async function Ct(){if(At.platform==="darwin"){let e=await xt();return{name:await Et(e),id:e}}if(At.platform==="linux"){let{stdout:e}=await Ls("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:ks(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(At.platform==="win32")return Pt();throw new Error("Only macOS, Linux, and Windows are supported")}import _t from"process";var Ms=!!(_t.env.SSH_CONNECTION||_t.env.SSH_CLIENT||_t.env.SSH_TTY),Yr=Ms;var $e=Symbol("fallbackAttempt"),Ot=import.meta.url?tn.dirname(Is(import.meta.url)):"",Xr=tn.join(Ot,"xdg-open"),{platform:ae,arch:Jr}=en,Qr=async(e,t)=>{if(e.length===0)return;let r=[];for(let n of e)try{return await t(n)}catch(o){r.push(o)}throw new AggregateError(r,"Failed to open in all supported apps")},Fe=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[$e]===!0;if(delete e[$e],Array.isArray(e.app))return Qr(e.app,l=>Fe({...e,app:l,[$e]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return Qr(r,l=>Fe({...e,app:{name:l,arguments:n},[$e]:!0}));if(r==="browser"||r==="browserPrivate"){let l={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},d;if(H){let p=await Kr();d=Rt.get(p)??{}}else d=await Ct();if(d.id in l){let p=l[d.id.toLowerCase()];if(r==="browserPrivate"){if(p==="safari")throw new Error("Safari doesn't support opening in private mode via command line");n.push(u[p])}return Fe({...e,app:{name:ce[p],arguments:n}})}throw new Error(`${d.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(H&&!ie()&&!Yr&&!r&&(a=await qr()),ae==="darwin")o="open",e.wait&&s.push("--wait-apps"),e.background&&s.push("--background"),e.newInstance&&s.push("--new"),r&&s.push("-a",r);else if(ae==="win32"||a){o=await Be(),s.push(...O.argumentsPrefix),H||(i.windowsVerbatimArguments=!0),H&&e.target&&(e.target=await Vr(e.target));let l=["$ProgressPreference = 'SilentlyContinue';","Start"];e.wait&&l.push("-Wait"),r?(l.push(O.escapeArgument(r)),e.target&&n.push(e.target)):e.target&&l.push(O.escapeArgument(e.target)),n.length>0&&(n=n.map(u=>O.escapeArgument(u)),l.push("-ArgumentList",n.join(","))),e.target=O.encodeCommand(l.join(" ")),e.wait||(i.stdio="ignore")}else{if(r)o=r;else{let l=!Ot||Ot==="/",u=!1;try{await Ns.access(Xr,Us.X_OK),u=!0}catch{}o=en.versions.electron??(ae==="android"||l||!u)?"xdg-open":Xr}n.length>0&&s.push(...n),e.wait||(i.stdio="ignore",i.detached=!0)}ae==="darwin"&&n.length>0&&s.push("--args",...n),e.target&&s.push(e.target);let c=Ds.spawn(o,s,i);return e.wait?new Promise((l,u)=>{c.once("error",u),c.once("close",d=>{if(!e.allowNonzeroExitCode&&d!==0){u(new Error(`Exited with code ${d}`));return}l(c)})}):t?new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.once("close",d=>{if(c.off("error",u),d!==0){u(new Error(`Exited with code ${d}`));return}c.unref(),l(c)})})}):(c.unref(),new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.off("error",u),l(c)})}))},js=(e,t)=>{if(typeof e!="string")throw new TypeError("Expected a `target`");return Fe({...t,target:e})};function Zr(e){if(typeof e=="string"||Array.isArray(e))return e;let{[Jr]:t}=e;if(!t)throw new Error(`${Jr} is not supported`);return t}function be({[ae]:e},{wsl:t}={}){if(t&&H)return Zr(t);if(!e)throw new Error(`${ae} is not supported`);return Zr(e)}var ce={browser:"browser",browserPrivate:"browserPrivate"};Q(ce,"chrome",()=>be({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));Q(ce,"brave",()=>be({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));Q(ce,"firefox",()=>be({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));Q(ce,"edge",()=>be({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));Q(ce,"safari",()=>be({darwin:"Safari"}));var rn=js;function nn(e=""){return`<link rel="icon" type="image/svg+xml" href="${`${e.replace(/\/$/,"")}/favicon-black.svg?v=4`}" />`}import{existsSync as gn,readFileSync as Ws}from"fs";import F from"path";import{fileURLToPath as zs}from"url";import{gunzipSync as qs}from"zlib";var $=eo(mn(),1);function le(e,t){return e.header("Retry-After",String($s(t))),e.json({error:"Too Many Requests"},429)}function $s(e){return e&&typeof e=="object"&&"msBeforeNext"in e&&typeof e.msBeforeNext=="number"&&Number.isFinite(e.msBeforeNext)?Math.max(1,Math.ceil(e.msBeforeNext/1e3)):60}var Ks={".js":"application/javascript",".css":"text/css",".svg":"image/svg+xml",".png":"image/png",".ico":"image/x-icon",".webmanifest":"application/manifest+json"};function Vs(){let e=F.dirname(zs(import.meta.url));for(let t of[F.resolve(e,"app"),F.resolve(e,"../app"),F.resolve(e,"../../dist/app")])if(gn(F.join(t,"inspector.js.gz")))return t;throw new Error("Inspector bundle not found (expected dist/app/inspector.js.gz)")}function yn(e,t="/inspector/assets"){let r=Vs(),n=new Map,o=new $.default({points:600,duration:60}),s=async(i,a)=>{try{await o.consume(i.req)}catch(c){return le(i,c)}return a()};e.use(`${t}/*`,s),e.get(`${t}/*`,async i=>{let a=i.req.path.slice(t.length),c=a.startsWith("/")?a.slice(1):a;if(!c||c.includes(".."))return i.notFound();let l=c==="inspector.js"||c==="inspector.css"?`${c}.gz`:c,u=F.resolve(r,l),d=r.endsWith(F.sep)?r:`${r}${F.sep}`;if(!u.startsWith(d)||!gn(u))return i.notFound();let p=F.extname(c),m=l.endsWith(".gz"),g=/(?:^|,)\s*gzip\s*(?:,|$)/i.test(i.req.header("accept-encoding")??""),h=Ws(u),y=m&&!g?n.get(u)??Gs(n,u,h):h,f=y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength);return i.body(f,200,{"Content-Type":Ks[p]??"application/octet-stream",...m&&g?{"Content-Encoding":"gzip"}:{},...m?{Vary:"Accept-Encoding"}:{},"Cache-Control":"no-cache"})})}function Gs(e,t,r){let n=qs(r);return e.set(t,n),n}var wn={name:"@mcp-use/inspector",type:"module",version:"20.2.5-canary.1",description:"MCP Inspector - A tool for inspecting and debugging MCP servers",author:"",license:"MIT",homepage:"https://github.com/mcp-use/mcp-use#readme",repository:{type:"git",url:"git+https://github.com/mcp-use/mcp-use.git",directory:"libraries/typescript/packages/inspector"},bugs:{url:"https://github.com/mcp-use/mcp-use/issues"},keywords:["mcp","inspector","debug","tools"],exports:{".":{types:"./dist/server/index.d.ts",import:"./dist/server/index.js"},"./client":{types:"./dist/client/index.d.ts",import:"./dist/client/index.js"},"./client/styles.css":{default:"./dist/client/styles.css"}},main:"./dist/server/index.js",types:"./dist/server/index.d.ts",bin:{"mcp-inspect":"./dist/cli.js"},files:["dist"],scripts:{dev:"rimraf node_modules/.vite && vite --strictPort","dev:client":"pnpm run dev","dev:server":"VITE_DEV=true tsx watch src/server/server.ts","dev:standalone":"tsx watch src/server/server.ts",clean:"rimraf dist",build:"npm run clean && npm run build:client-exports && npm run build:server && npm run build:app && npm run verify:package","build:app":"vite build --config vite.app.config.ts && node scripts/compress-app.mjs","watch:app":"vite build --watch --config vite.app.config.ts","preview:app":"vite preview --config vite.app.config.ts --host 127.0.0.1","serve:app":"pnpm build:app && pnpm preview:app","analyze:app":"ANALYZE=true vite build --config vite.app.config.ts","build:client-exports":"tsup --config tsup.client.ts && node scripts/copy-client-styles.mjs","build:server":"tsup --config tsup.server.ts","verify:package":"node scripts/verify-package.mjs",prepublishOnly:"pnpm --filter @mcp-use/client build && pnpm build",start:"node dist/cli.js --port 3000",preview:"vite preview","type-check":"tsc --noEmit",lint:"eslint .","lint:fix":"eslint . --fix","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","test:e2e:debug":"playwright test --debug","test:e2e:builtin":"node tests/e2e/scripts/run-test-matrix.mjs builtin","test:e2e:prod":"node tests/e2e/scripts/run-test-matrix.mjs prod","test:e2e:mix":"node tests/e2e/scripts/run-test-matrix.mjs mix","test:e2e:prod:ui":"TEST_MODE=production playwright test --ui","test:e2e:codegen":"playwright codegen http://localhost:3000/inspector","test:e2e:report":"playwright show-report","test:e2e:python":"node tests/e2e/scripts/run-python-e2e.mjs","test:unit":"vitest run","test:unit:watch":"vitest","test:e2e:tunnel":"node tests/e2e/scripts/run-tunnel-test.mjs","install:pnpm":"pnpm install","install:npm":"npm install","lint:npm":"npm run lint:fix","lint:pnpm":"pnpm lint:fix"},engines:{node:">=22.22.2"},peerDependencies:{"@base-ui/react":"^1.6.0","@mcp-use/agent":"^2.0.7 || ^2.0.8-canary.0","@mcp-use/client":"^2.0.1 || ^2.1.0 || ^2.1.1 || ^2.1.2 || ^2.1.3 || ^2.1.4 || ^2.1.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",express:"^4.21.2 || ^5.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4","mcp-use":"^2.2.5-canary.0",motion:"^12.34.2",react:"^18.0.0 || ^19.0.0","react-dom":"^18.0.0 || ^19.0.0","react-resizable-panels":"^4.6.4",sonner:"^2.0.7","tailwind-merge":"^3.5.0"},peerDependenciesMeta:{"@base-ui/react":{optional:!0},"@mcp-use/agent":{optional:!0},"@mcp-use/client":{optional:!0},"class-variance-authority":{optional:!0},clsx:{optional:!0},express:{optional:!0},"lucide-react":{optional:!0},"markdown-to-jsx":{optional:!0},"mcp-use":{optional:!0},motion:{optional:!0},react:{optional:!0},"react-dom":{optional:!0},"react-resizable-panels":{optional:!0},sonner:{optional:!0},"tailwind-merge":{optional:!0}},dependencies:{},publishConfig:{access:"public"},devDependencies:{"@base-ui/react":"^1.6.0","@hono/node-server":"^2.0.5","@mcp-use/agent":"workspace:*","@mcp-use/client":"workspace:*","@playwright/test":"^1.58.2","@tailwindcss/vite":"^4.2.0","@types/express":"^5.0.6","@vitejs/plugin-react":"^6.0.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1",emulate:"0.5.0",eslint:"^9.39.2",express:"^5.2.1",hono:"^4.12.34",jsdom:"^27.0.0","lucide-react":"^0.562.0","markdown-to-jsx":"^9.7.4",motion:"^12.34.2","oauth2-mock-server":"^8.2.2",open:"^11.0.0",react:"^19.2.3","react-dom":"^19.2.3","react-router":"^8.3.0","react-resizable-panels":"^4.6.4","rate-limiter-flexible":"^11.2.0","rollup-plugin-visualizer":"^6.0.3",sonner:"^2.0.7","tailwind-merge":"^3.5.0",tailwindcss:"^4.2.0",tsup:"^8.5.1",tsx:"^4.21.0","tw-animate-css":"^1.4.0",typescript:"^5.9.3",vite:"^8.0.16",vitest:"^4.1.0","wait-on":"^9.0.4",yaml:"^2.8.3",zod:"^4.2.0"}};var Xs=wn.version;function We(){return Xs}var Js=`<!doctype html>
9
9
  <html>
10
10
  <head>
11
11
  <meta charset="utf-8" />
@@ -3,7 +3,7 @@ import { Tool, Resource, Prompt, McpServer, ElicitRequestFormParams, ElicitReque
3
3
  export { ViewRenderer, getViewResourceUri, isViewTool } from '@mcp-use/client/react';
4
4
  import { ProviderName, McpConnectionLike } from '@mcp-use/agent';
5
5
  import * as react from 'react';
6
- import react__default, { ReactNode, RefObject } from 'react';
6
+ import react__default, { ReactNode, RefObject, SetStateAction } from 'react';
7
7
 
8
8
  interface AddToClientDropdownProps {
9
9
  serverConfig: {
@@ -629,6 +629,13 @@ interface ChatStorageProvider {
629
629
  }>;
630
630
  getMessages(chatId: string): Promise<Message$1[]>;
631
631
  createChat(params: {
632
+ /**
633
+ * Id the caller already uses for this chat session. Providers should adopt
634
+ * it so runtime and persisted state share one identity, and should return
635
+ * the existing chat when it is already stored. Providers that must mint
636
+ * their own id may ignore it — the caller keeps the returned id instead.
637
+ */
638
+ id?: string;
632
639
  agentId: string;
633
640
  title?: string;
634
641
  agentName?: string;
@@ -662,6 +669,7 @@ interface InspectorTokenUsage {
662
669
  outputTokens?: number;
663
670
  totalTokens?: number;
664
671
  cachedInputTokens?: number;
672
+ cacheCreationInputTokens?: number;
665
673
  reasoningTokens?: number;
666
674
  }
667
675
  interface TraceEventBase {
@@ -1178,6 +1186,21 @@ declare function readStoredSystemPrompt(serverId: string): string | null;
1178
1186
  declare function writeStoredSystemPrompt(serverId: string, prompt: string): void;
1179
1187
  declare function resolveSystemPrompt(stored: string | null | undefined): string;
1180
1188
 
1189
+ /** Serializable chat turn retained across a full-page OAuth redirect. */
1190
+ interface PendingChatTurn {
1191
+ serverId: string;
1192
+ /** Chat session that owns the interrupted turn. */
1193
+ sessionId: string;
1194
+ /** Persisted id when the storage backend minted one instead of adopting the session id. */
1195
+ persistedChatId?: string;
1196
+ userInput: string;
1197
+ promptResults: PromptResult[];
1198
+ attachments: MessageAttachment[];
1199
+ /** Conversation through the user turn, excluding the interrupted assistant. */
1200
+ baseMessages: Message$1[];
1201
+ savedAt: number;
1202
+ }
1203
+
1181
1204
  type ManagedChatNotice = {
1182
1205
  kind: "cloud_unavailable";
1183
1206
  } | {
@@ -1189,19 +1212,86 @@ type ManagedChatNotice = {
1189
1212
  message?: string;
1190
1213
  };
1191
1214
 
1192
- /** Serializable chat turn retained across a full-page OAuth redirect. */
1193
- interface PendingChatTurn {
1194
- serverId: string;
1195
- userInput: string;
1196
- promptResults: PromptResult[];
1215
+ /** Holds a tool call open while the user completes an interactive OAuth flow. */
1216
+ interface ChatAuthorizationGate {
1217
+ toolCallId: string;
1218
+ resolve: () => void;
1219
+ reject: (error: Error) => void;
1220
+ }
1221
+ interface PendingAuthorization {
1222
+ toolCallId: string;
1223
+ replay: Omit<PendingChatTurn, "savedAt">;
1224
+ }
1225
+ interface McpServerAuthRequired {
1226
+ mcpServerUrl: string;
1227
+ message?: string;
1228
+ }
1229
+ /** Turn machinery that must survive re-renders without triggering them. */
1230
+ interface ChatSessionRuntime {
1231
+ abortController: AbortController | null;
1232
+ sendInProgress: boolean;
1233
+ traceId: number;
1234
+ authorizationGate: ChatAuthorizationGate | null;
1235
+ /** Set once the turn restored from an OAuth redirect has replayed. */
1236
+ pendingTurnResumed: boolean;
1237
+ }
1238
+ /**
1239
+ * Everything one chat session owns.
1240
+ *
1241
+ * `id` is the session's only identity: it is minted when the session is created
1242
+ * and handed to `ChatStorageProvider.createChat`, so runtime state, persistence
1243
+ * and OAuth recovery all name the same chat. `persistedChatId` differs from
1244
+ * `id` only when a storage backend insists on minting its own id.
1245
+ */
1246
+ interface ChatSessionState {
1247
+ readonly id: string;
1248
+ messages: Message$1[];
1197
1249
  attachments: MessageAttachment[];
1198
- /** Conversation through the user turn, excluding the interrupted assistant. */
1199
- baseMessages: Message$1[];
1200
- savedAt: number;
1250
+ isLoading: boolean;
1251
+ trace: InspectorTraceState;
1252
+ managedChatNotice: ManagedChatNotice | null;
1253
+ pendingAuthorization: PendingAuthorization | null;
1254
+ authenticatingToolCallId: string | null;
1255
+ toolAuthorizationError: string | null;
1256
+ mcpServerAuthRequired: McpServerAuthRequired | null;
1257
+ persistedChatId: string | null;
1258
+ /** In-flight `createChat` call, so concurrent writes persist to one chat. */
1259
+ creation: Promise<string | null> | null;
1260
+ readonly runtime: ChatSessionRuntime;
1261
+ }
1262
+
1263
+ /** Fields a session update may touch — identity and runtime are fixed per record. */
1264
+ type ChatSessionPatch = Partial<Omit<ChatSessionState, "id" | "runtime">>;
1265
+ type ChatSessionUpdate = ChatSessionPatch | ((session: ChatSessionState) => ChatSessionPatch);
1266
+ /**
1267
+ * Owns one record per chat session and notifies only the subscribers of the
1268
+ * session that changed. A background turn therefore keeps streaming into its
1269
+ * own record without re-rendering the chat the user is currently looking at.
1270
+ */
1271
+ declare class ChatSessionStore {
1272
+ private readonly sessions;
1273
+ private readonly listeners;
1274
+ /** Returns the session record, creating an empty one on first access. */
1275
+ get(id: string): ChatSessionState;
1276
+ has(id: string): boolean;
1277
+ /** Seeds a session that does not exist yet; live sessions are left alone. */
1278
+ seed(id: string, messages: ChatSessionState["messages"]): ChatSessionState;
1279
+ update(id: string, update: ChatSessionUpdate): ChatSessionState;
1280
+ subscribe(id: string, listener: () => void): () => void;
1281
+ /** Drops a session nobody can reach any more (e.g. an untouched draft). */
1282
+ delete(id: string): void;
1283
+ /** Session whose persisted chat is `chatId`, if that chat is already loaded. */
1284
+ findByPersistedChatId(chatId: string): ChatSessionState | undefined;
1201
1285
  }
1202
1286
 
1203
1287
  type MCPConnection = McpServer;
1204
1288
  interface UseChatMessagesClientSideProps {
1289
+ /** Store holding one record per chat session. Defaults to a private store. */
1290
+ sessionStore?: ChatSessionStore;
1291
+ /** Session this hook renders. Defaults to a single private session. */
1292
+ sessionId?: string;
1293
+ /** Fires for every session whose messages change, including background ones. */
1294
+ onMessagesChange?: (sessionId: string, messages: Message$1[]) => void;
1205
1295
  connection: MCPConnection;
1206
1296
  llmConfig: LLMConfig | null;
1207
1297
  isConnected: boolean;
@@ -1209,11 +1299,13 @@ interface UseChatMessagesClientSideProps {
1209
1299
  widgetModelContexts?: Map<string, WidgetModelContext | undefined>;
1210
1300
  disabledTools?: Set<string>;
1211
1301
  appToolConnections?: McpConnectionLike[];
1302
+ /** Seeds the session on first use; a session already in the store is kept. */
1212
1303
  initialMessages?: Message$1[];
1213
1304
  systemPrompt?: string;
1214
1305
  skills?: Skill[];
1215
1306
  }
1216
- declare function useChatMessagesClientSide({ connection, llmConfig, isConnected, readResource, widgetModelContexts, disabledTools, appToolConnections, initialMessages, systemPrompt, skills, }: UseChatMessagesClientSideProps): {
1307
+ declare function useChatMessagesClientSide({ sessionStore, sessionId, onMessagesChange, connection, llmConfig, isConnected, readResource, widgetModelContexts, disabledTools, appToolConnections, initialMessages, systemPrompt, skills, }: UseChatMessagesClientSideProps): {
1308
+ sessionId: string;
1217
1309
  messages: Message$1[];
1218
1310
  isLoading: boolean;
1219
1311
  attachments: MessageAttachment[];
@@ -1222,24 +1314,27 @@ declare function useChatMessagesClientSide({ connection, llmConfig, isConnected,
1222
1314
  clearMessages: () => void;
1223
1315
  clearManagedChatNotice: () => void;
1224
1316
  showManagedChatNotice: (notice: ManagedChatNotice) => void;
1225
- setMessages: react.Dispatch<react.SetStateAction<Message$1[]>>;
1317
+ setMessages: (action: SetStateAction<Message$1[]>) => void;
1226
1318
  stop: () => void;
1227
1319
  addAttachment: (file: File) => Promise<void>;
1228
1320
  removeAttachment: (index: number) => void;
1229
1321
  clearAttachments: () => void;
1230
- clearTrace: () => void;
1322
+ clearTrace: () => ChatSessionState;
1231
1323
  traceEvents: InspectorTraceEvent[];
1232
1324
  tokenUsage: InspectorTokenUsage | undefined;
1233
- pendingAuthorization: {
1234
- toolCallId: string;
1235
- replay: Omit<PendingChatTurn, "savedAt">;
1236
- } | null;
1325
+ pendingAuthorization: PendingAuthorization | null;
1237
1326
  authenticatePendingTool: (toolCallId: string) => Promise<void>;
1238
1327
  authenticatingToolCallId: string | null;
1239
1328
  toolAuthorizationError: string | null;
1240
1329
  };
1241
1330
 
1242
1331
  interface UseChatMessagesProps {
1332
+ /** Store holding one record per chat session. Defaults to a private store. */
1333
+ sessionStore?: ChatSessionStore;
1334
+ /** Session this hook renders. Defaults to a single private session. */
1335
+ sessionId?: string;
1336
+ /** Fires for every session whose messages change, including background ones. */
1337
+ onMessagesChange?: (sessionId: string, messages: Message$1[]) => void;
1243
1338
  mcpServerUrl: string;
1244
1339
  llmConfig: LLMConfig | null;
1245
1340
  authConfig: AuthConfig | null;
@@ -1252,7 +1347,7 @@ interface UseChatMessagesProps {
1252
1347
  waitForChatApiUrl?: () => Promise<string | undefined>;
1253
1348
  /** Active widget model contexts to inject into the LLM conversation */
1254
1349
  widgetModelContexts?: Map<string, WidgetModelContext | undefined>;
1255
- /** Pre-populate the chat with messages from a previous session (e.g. when restoring history). */
1350
+ /** Seeds the session on first use; a session already in the store is kept. */
1256
1351
  initialMessages?: Message$1[];
1257
1352
  /** Tool names the user has disabled via the tool selector. Sent to the server so it can exclude them. */
1258
1353
  disabledTools?: Set<string>;
@@ -1276,26 +1371,24 @@ interface UseChatMessagesProps {
1276
1371
  */
1277
1372
  body?: ChatBodyBuilder;
1278
1373
  }
1279
- declare function useChatMessages({ mcpServerUrl, llmConfig, authConfig, mcpAuthTokens, isConnected, chatApiUrl, waitForChatApiUrl, widgetModelContexts, initialMessages, disabledTools, streamProtocol, credentials, extraHeaders, body: bodyBuilder, }: UseChatMessagesProps): {
1374
+ declare function useChatMessages({ sessionStore, sessionId, onMessagesChange, mcpServerUrl, llmConfig, authConfig, mcpAuthTokens, isConnected, chatApiUrl, waitForChatApiUrl, widgetModelContexts, initialMessages, disabledTools, streamProtocol, credentials, extraHeaders, body: bodyBuilder, }: UseChatMessagesProps): {
1375
+ sessionId: string;
1280
1376
  messages: Message$1[];
1281
1377
  isLoading: boolean;
1282
1378
  attachments: MessageAttachment[];
1283
1379
  managedChatNotice: ManagedChatNotice | null;
1284
- mcpServerAuthRequired: {
1285
- mcpServerUrl: string;
1286
- message?: string;
1287
- } | null;
1380
+ mcpServerAuthRequired: McpServerAuthRequired | null;
1288
1381
  sendMessage: (userInput: string, promptResults: PromptResult[], extraAttachments?: MessageAttachment[], options?: SendMessageOptions) => Promise<void>;
1289
1382
  clearMessages: () => void;
1290
1383
  clearManagedChatNotice: () => void;
1291
1384
  showManagedChatNotice: (notice: ManagedChatNotice) => void;
1292
1385
  clearMcpServerAuthRequired: () => void;
1293
- setMessages: react.Dispatch<react.SetStateAction<Message$1[]>>;
1386
+ setMessages: (action: SetStateAction<Message$1[]>) => void;
1294
1387
  stop: () => void;
1295
1388
  addAttachment: (file: File) => Promise<void>;
1296
1389
  removeAttachment: (index: number) => void;
1297
1390
  clearAttachments: () => void;
1298
- clearTrace: () => void;
1391
+ clearTrace: () => ChatSessionState;
1299
1392
  traceEvents: InspectorTraceEvent[];
1300
1393
  tokenUsage: InspectorTokenUsage | undefined;
1301
1394
  };
@@ -1389,6 +1482,7 @@ declare class LocalChatStorageProvider implements ChatStorageProvider {
1389
1482
  }>;
1390
1483
  getMessages(chatId: string): Promise<Message$1[]>;
1391
1484
  createChat(params: {
1485
+ id?: string;
1392
1486
  agentId: string;
1393
1487
  title?: string;
1394
1488
  agentName?: string;