@sourcegraph/amp 0.0.1761350495-gee8ea9 → 0.0.1761379287-ge22fe5
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/main.js +9 -9
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4730,7 +4730,7 @@ Minimum version required to store current data is: `+K+`.
|
|
|
4730
4730
|
`;if(typeof X==="function")X(null,H);return H}});var JG6=a((ZK9)=>{var QK9=Gh1();ZK9.render=QK9.render;ZK9.renderToFile=function(Q,Z,X,Y){if(typeof Y>"u")Y=X,X=void 0;let K=n1("fs"),q='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+ZK9.render(Z,X);K.writeFile(Q,q,Y)}});var ZG6=a((GK9)=>{var qh1=Np();function YK9(J,Q,Z){if(J.clearRect(0,0,Q.width,Q.height),!Q.style)Q.style={};Q.height=Z,Q.width=Z,Q.style.height=Z+"px",Q.style.width=Z+"px"}function KK9(){try{return document.createElement("canvas")}catch(J){throw Error("You need to specify a canvas element")}}GK9.render=function(Q,Z,X){let Y=X,K=Z;if(typeof Y>"u"&&(!Z||!Z.getContext))Y=Z,Z=void 0;if(!Z)K=KK9();Y=qh1.getOptions(Y);let G=qh1.getImageWidth(Q.modules.size,Y),q=K.getContext("2d"),z=q.createImageData(G,G);return qh1.qrToImageData(z.data,Q,Y),YK9(q,K,G),q.putImageData(z,0,0),K};GK9.renderToDataURL=function(Q,Z,X){let Y=X;if(typeof Y>"u"&&(!Z||!Z.getContext))Y=Z,Z=void 0;if(!Y)Y={};let K=GK9.render(Q,Z,Y),G=Y.type||"image/png",q=Y.rendererOpts||{};return K.toDataURL(G,q.quality)}});var YG6=a((WK9)=>{var zK9=Lf1(),zh1=pf1(),XG6=ZG6(),UK9=Gh1();function Uh1(J,Q,Z,X,Y){let K=[].slice.call(arguments,1),G=K.length,q=typeof K[G-1]==="function";if(!q&&!zK9())throw Error("Callback required as last argument");if(q){if(G<2)throw Error("Too few arguments provided");if(G===2)Y=Z,Z=Q,Q=X=void 0;else if(G===3)if(Q.getContext&&typeof Y>"u")Y=X,X=void 0;else Y=X,X=Z,Z=Q,Q=void 0}else{if(G<1)throw Error("Too few arguments provided");if(G===1)Z=Q,Q=X=void 0;else if(G===2&&!Q.getContext)X=Z,Z=Q,Q=void 0;return new Promise(function(z,U){try{let W=zh1.create(Z,X);z(J(W,Q,X))}catch(W){U(W)}})}try{let z=zh1.create(Z,X);Y(null,J(z,Q,X))}catch(z){Y(z)}}WK9.create=zh1.create;WK9.toCanvas=Uh1.bind(null,XG6.render);WK9.toDataURL=Uh1.bind(null,XG6.renderToDataURL);WK9.toString=Uh1.bind(null,function(J,Q,Z){return UK9.render(J,Z)})});var wp=a((AK9)=>{var KG6=Lf1(),Wh1=pf1(),MK9=cK6(),GG6=iK6(),VK9=oK6(),qG6=JG6();function Lp(J,Q,Z){if(typeof J>"u")throw Error("String required as first argument");if(typeof Z>"u")Z=Q,Q={};if(typeof Z!=="function")if(!KG6())throw Error("Callback required as last argument");else Q=Z||{},Z=null;return{opts:Q,cb:Z}}function NK9(J){return J.slice((J.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function QJ1(J){switch(J){case"svg":return qG6;case"txt":case"utf8":return GG6;case"png":case"image/png":default:return MK9}}function LK9(J){switch(J){case"svg":return qG6;case"terminal":return VK9;case"utf8":default:return GG6}}function Ap(J,Q,Z){if(!Z.cb)return new Promise(function(X,Y){try{let K=Wh1.create(Q,Z.opts);return J(K,Z.opts,function(G,q){return G?Y(G):X(q)})}catch(K){Y(K)}});try{let X=Wh1.create(Q,Z.opts);return J(X,Z.opts,Z.cb)}catch(X){Z.cb(X)}}AK9.create=Wh1.create;AK9.toCanvas=YG6().toCanvas;AK9.toString=function(Q,Z,X){let Y=Lp(Q,Z,X),K=Y.opts?Y.opts.type:void 0,G=LK9(K);return Ap(G.render,Q,Y)};AK9.toDataURL=function(Q,Z,X){let Y=Lp(Q,Z,X),K=QJ1(Y.opts.type);return Ap(K.renderToDataURL,Q,Y)};AK9.toBuffer=function(Q,Z,X){let Y=Lp(Q,Z,X),K=QJ1(Y.opts.type);return Ap(K.renderToBuffer,Q,Y)};AK9.toFile=function(Q,Z,X,Y){if(typeof Q!=="string"||!(typeof Z==="string"||typeof Z==="object"))throw Error("Invalid argument");if(arguments.length<3&&!KG6())throw Error("Too few arguments provided");let K=Lp(Z,X,Y),G=K.opts.type||NK9(Q),z=QJ1(G).renderToFile.bind(null,Q);return Ap(z,Z,K)};AK9.toFileStream=function(Q,Z,X){if(arguments.length<2)throw Error("Too few arguments provided");let Y=Lp(Z,X,Q.emit.bind(Q,"error")),G=QJ1("png").renderToFileStream.bind(null,Q);Ap(G,Z,Y)}});var IG6=a((Ej2,GJ1)=>{var IG9=typeof window<"u"?window:typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope?self:{},m6=function(J){var Q=/(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,Z=0,X={},Y={manual:J.Prism&&J.Prism.manual,disableWorkerMessageHandler:J.Prism&&J.Prism.disableWorkerMessageHandler,util:{encode:function V(N){if(N instanceof K)return new K(N.type,V(N.content),N.alias);else if(Array.isArray(N))return N.map(V);else return N.replace(/&/g,"&").replace(/</g,"<").replace(/\u00a0/g," ")},type:function(V){return Object.prototype.toString.call(V).slice(8,-1)},objId:function(V){if(!V.__id)Object.defineProperty(V,"__id",{value:++Z});return V.__id},clone:function V(N,L){L=L||{};var A,w;switch(Y.util.type(N)){case"Object":if(w=Y.util.objId(N),L[w])return L[w];A={},L[w]=A;for(var R in N)if(N.hasOwnProperty(R))A[R]=V(N[R],L);return A;case"Array":if(w=Y.util.objId(N),L[w])return L[w];return A=[],L[w]=A,N.forEach(function(O,j){A[j]=V(O,L)}),A;default:return N}},getLanguage:function(V){while(V){var N=Q.exec(V.className);if(N)return N[1].toLowerCase();V=V.parentElement}return"none"},setLanguage:function(V,N){V.className=V.className.replace(RegExp(Q,"gi"),""),V.classList.add("language-"+N)},currentScript:function(){if(typeof document>"u")return null;if(document.currentScript&&document.currentScript.tagName==="SCRIPT")return document.currentScript;try{throw Error()}catch(A){var V=(/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(A.stack)||[])[1];if(V){var N=document.getElementsByTagName("script");for(var L in N)if(N[L].src==V)return N[L]}return null}},isActive:function(V,N,L){var A="no-"+N;while(V){var w=V.classList;if(w.contains(N))return!0;if(w.contains(A))return!1;V=V.parentElement}return!!L}},languages:{plain:X,plaintext:X,text:X,txt:X,extend:function(V,N){var L=Y.util.clone(Y.languages[V]);for(var A in N)L[A]=N[A];return L},insertBefore:function(V,N,L,A){A=A||Y.languages;var w=A[V],R={};for(var O in w)if(w.hasOwnProperty(O)){if(O==N){for(var j in L)if(L.hasOwnProperty(j))R[j]=L[j]}if(!L.hasOwnProperty(O))R[O]=w[O]}var $=A[V];return A[V]=R,Y.languages.DFS(Y.languages,function(E,I){if(I===$&&E!=V)this[E]=R}),R},DFS:function V(N,L,A,w){w=w||{};var R=Y.util.objId;for(var O in N)if(N.hasOwnProperty(O)){L.call(N,O,N[O],A||O);var j=N[O],$=Y.util.type(j);if($==="Object"&&!w[R(j)])w[R(j)]=!0,V(j,L,null,w);else if($==="Array"&&!w[R(j)])w[R(j)]=!0,V(j,L,O,w)}}},plugins:{},highlightAll:function(V,N){Y.highlightAllUnder(document,V,N)},highlightAllUnder:function(V,N,L){var A={callback:L,container:V,selector:'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'};Y.hooks.run("before-highlightall",A),A.elements=Array.prototype.slice.apply(A.container.querySelectorAll(A.selector)),Y.hooks.run("before-all-elements-highlight",A);for(var w=0,R;R=A.elements[w++];)Y.highlightElement(R,N===!0,A.callback)},highlightElement:function(V,N,L){var A=Y.util.getLanguage(V),w=Y.languages[A];Y.util.setLanguage(V,A);var R=V.parentElement;if(R&&R.nodeName.toLowerCase()==="pre")Y.util.setLanguage(R,A);var O=V.textContent,j={element:V,language:A,grammar:w,code:O};function $(I){j.highlightedCode=I,Y.hooks.run("before-insert",j),j.element.innerHTML=j.highlightedCode,Y.hooks.run("after-highlight",j),Y.hooks.run("complete",j),L&&L.call(j.element)}if(Y.hooks.run("before-sanity-check",j),R=j.element.parentElement,R&&R.nodeName.toLowerCase()==="pre"&&!R.hasAttribute("tabindex"))R.setAttribute("tabindex","0");if(!j.code){Y.hooks.run("complete",j),L&&L.call(j.element);return}if(Y.hooks.run("before-highlight",j),!j.grammar){$(Y.util.encode(j.code));return}if(N&&J.Worker){var E=new Worker(Y.filename);E.onmessage=function(I){$(I.data)},E.postMessage(JSON.stringify({language:j.language,code:j.code,immediateClose:!0}))}else $(Y.highlight(j.code,j.grammar,j.language))},highlight:function(V,N,L){var A={code:V,grammar:N,language:L};if(Y.hooks.run("before-tokenize",A),!A.grammar)throw Error('The language "'+A.language+'" has no grammar.');return A.tokens=Y.tokenize(A.code,A.grammar),Y.hooks.run("after-tokenize",A),K.stringify(Y.util.encode(A.tokens),A.language)},tokenize:function(V,N){var L=N.rest;if(L){for(var A in L)N[A]=L[A];delete N.rest}var w=new z;return U(w,w.head,V),q(V,w,N,w.head,0),F(w)},hooks:{all:{},add:function(V,N){var L=Y.hooks.all;L[V]=L[V]||[],L[V].push(N)},run:function(V,N){var L=Y.hooks.all[V];if(!L||!L.length)return;for(var A=0,w;w=L[A++];)w(N)}},Token:K};J.Prism=Y;function K(V,N,L,A){this.type=V,this.content=N,this.alias=L,this.length=(A||"").length|0}K.stringify=function V(N,L){if(typeof N=="string")return N;if(Array.isArray(N)){var A="";return N.forEach(function($){A+=V($,L)}),A}var w={type:N.type,content:V(N.content,L),tag:"span",classes:["token",N.type],attributes:{},language:L},R=N.alias;if(R)if(Array.isArray(R))Array.prototype.push.apply(w.classes,R);else w.classes.push(R);Y.hooks.run("wrap",w);var O="";for(var j in w.attributes)O+=" "+j+'="'+(w.attributes[j]||"").replace(/"/g,""")+'"';return"<"+w.tag+' class="'+w.classes.join(" ")+'"'+O+">"+w.content+"</"+w.tag+">"};function G(V,N,L,A){V.lastIndex=N;var w=V.exec(L);if(w&&A&&w[1]){var R=w[1].length;w.index+=R,w[0]=w[0].slice(R)}return w}function q(V,N,L,A,w,R){for(var O in L){if(!L.hasOwnProperty(O)||!L[O])continue;var j=L[O];j=Array.isArray(j)?j:[j];for(var $=0;$<j.length;++$){if(R&&R.cause==O+","+$)return;var E=j[$],I=E.inside,T=!!E.lookbehind,S=!!E.greedy,x=E.alias;if(S&&!E.pattern.global){var h=E.pattern.toString().match(/[imsuy]*$/)[0];E.pattern=RegExp(E.pattern.source,h+"g")}var v=E.pattern||E;for(var _=A.next,b=w;_!==N.tail;b+=_.value.length,_=_.next){if(R&&b>=R.reach)break;var g=_.value;if(N.length>V.length)return;if(g instanceof K)continue;var k=1,y;if(S){if(y=G(v,b,V,T),!y||y.index>=V.length)break;var p=y.index,f=y.index+y[0].length,m=b;m+=_.value.length;while(p>=m)_=_.next,m+=_.value.length;if(m-=_.value.length,b=m,_.value instanceof K)continue;for(var n=_;n!==N.tail&&(m<f||typeof n.value==="string");n=n.next)k++,m+=n.value.length;k--,g=V.slice(b,m),y.index-=b}else if(y=G(v,0,g,T),!y)continue;var p=y.index,e=y[0],G1=g.slice(0,p),U1=g.slice(p+e.length),Z1=b+g.length;if(R&&Z1>R.reach)R.reach=Z1;var F1=_.prev;if(G1)F1=U(N,F1,G1),b+=G1.length;W(N,F1,k);var l=new K(O,I?Y.tokenize(e,I):e,x,e);if(_=U(N,F1,l),U1)U(N,_,U1);if(k>1){var d={cause:O+","+$,reach:Z1};if(q(V,N,L,_.prev,b,d),R&&d.reach>R.reach)R.reach=d.reach}}}}}function z(){var V={value:null,prev:null,next:null},N={value:null,prev:V,next:null};V.next=N,this.head=V,this.tail=N,this.length=0}function U(V,N,L){var A=N.next,w={value:L,prev:N,next:A};return N.next=w,A.prev=w,V.length++,w}function W(V,N,L){var A=N.next;for(var w=0;w<L&&A!==V.tail;w++)A=A.next;N.next=A,A.prev=N,V.length-=w}function F(V){var N=[],L=V.head.next;while(L!==V.tail)N.push(L.value),L=L.next;return N}if(!J.document){if(!J.addEventListener)return Y;if(!Y.disableWorkerMessageHandler)J.addEventListener("message",function(V){var N=JSON.parse(V.data),L=N.language,A=N.code,w=N.immediateClose;if(J.postMessage(Y.highlight(A,Y.languages[L],L)),w)J.close()},!1);return Y}var H=Y.util.currentScript();if(H){if(Y.filename=H.src,H.hasAttribute("data-manual"))Y.manual=!0}function B(){if(!Y.manual)Y.highlightAll()}if(!Y.manual){var M=document.readyState;if(M==="loading"||M==="interactive"&&H&&H.defer)document.addEventListener("DOMContentLoaded",B);else if(window.requestAnimationFrame)window.requestAnimationFrame(B);else window.setTimeout(B,16)}return Y}(IG9);if(typeof GJ1<"u"&&GJ1.exports)GJ1.exports=m6;if(typeof global<"u")global.Prism=m6;m6.languages.markup={comment:{pattern:/<!--(?:(?!<!--)[\s\S])*?-->/,greedy:!0},prolog:{pattern:/<\?[\s\S]+?\?>/,greedy:!0},doctype:{pattern:/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,greedy:!0,inside:{"internal-subset":{pattern:/(^[^\[]*\[)[\s\S]+(?=\]>$)/,lookbehind:!0,greedy:!0,inside:null},string:{pattern:/"[^"]*"|'[^']*'/,greedy:!0},punctuation:/^<!|>$|[[\]]/,"doctype-tag":/^DOCTYPE/i,name:/[^\s<>'"]+/}},cdata:{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,greedy:!0},tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"special-attr":[],"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,inside:{punctuation:[{pattern:/^=/,alias:"attr-equals"},{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:[{pattern:/&[\da-z]{1,8};/i,alias:"named-entity"},/&#x?[\da-f]{1,8};/i]};m6.languages.markup.tag.inside["attr-value"].inside.entity=m6.languages.markup.entity;m6.languages.markup.doctype.inside["internal-subset"].inside=m6.languages.markup;m6.hooks.add("wrap",function(J){if(J.type==="entity")J.attributes.title=J.content.replace(/&/,"&")});Object.defineProperty(m6.languages.markup.tag,"addInlined",{value:function(Q,Z){var X={};X["language-"+Z]={pattern:/(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,lookbehind:!0,inside:m6.languages[Z]},X.cdata=/^<!\[CDATA\[|\]\]>$/i;var Y={"included-cdata":{pattern:/<!\[CDATA\[[\s\S]*?\]\]>/i,inside:X}};Y["language-"+Z]={pattern:/[\s\S]+/,inside:m6.languages[Z]};var K={};K[Q]={pattern:RegExp(/(<__[^>]*>)(?:<!\[CDATA\[(?:[^\]]|\](?!\]>))*\]\]>|(?!<!\[CDATA\[)[\s\S])*?(?=<\/__>)/.source.replace(/__/g,function(){return Q}),"i"),lookbehind:!0,greedy:!0,inside:Y},m6.languages.insertBefore("markup","cdata",K)}});Object.defineProperty(m6.languages.markup.tag,"addAttribute",{value:function(J,Q){m6.languages.markup.tag.inside["special-attr"].push({pattern:RegExp(/(^|["'\s])/.source+"(?:"+J+")"+/\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))/.source,"i"),lookbehind:!0,inside:{"attr-name":/^[^\s=]+/,"attr-value":{pattern:/=[\s\S]+/,inside:{value:{pattern:/(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,lookbehind:!0,alias:[Q,"language-"+Q],inside:m6.languages[Q]},punctuation:[{pattern:/^=/,alias:"attr-equals"},/"|'/]}}}})}});m6.languages.html=m6.languages.markup;m6.languages.mathml=m6.languages.markup;m6.languages.svg=m6.languages.markup;m6.languages.xml=m6.languages.extend("markup",{});m6.languages.ssml=m6.languages.xml;m6.languages.atom=m6.languages.xml;m6.languages.rss=m6.languages.xml;(function(J){var Q=/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;J.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:RegExp("@[\\w-](?:"+/[^;{\s"']|\s+(?!\s)/.source+"|"+Q.source+")*?"+/(?:;|(?=\s*\{))/.source),inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,lookbehind:!0,alias:"selector"},keyword:{pattern:/(^|[^\w-])(?:and|not|only|or)(?![\w-])/,lookbehind:!0}}},url:{pattern:RegExp("\\burl\\((?:"+Q.source+"|"+/(?:[^\\\r\n()"']|\\[\s\S])*/.source+")\\)","i"),greedy:!0,inside:{function:/^url/i,punctuation:/^\(|\)$/,string:{pattern:RegExp("^"+Q.source+"$"),alias:"url"}}},selector:{pattern:RegExp(`(^|[{}\\s])[^{}\\s](?:[^{};"'\\s]|\\s+(?![\\s{])|`+Q.source+")*(?=\\s*\\{)"),lookbehind:!0},string:{pattern:Q,greedy:!0},property:{pattern:/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,lookbehind:!0},important:/!important\b/i,function:{pattern:/(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i,lookbehind:!0},punctuation:/[(){};:,]/},J.languages.css.atrule.inside.rest=J.languages.css;var Z=J.languages.markup;if(Z)Z.tag.addInlined("style","css"),Z.tag.addAttribute("style","css")})(m6);m6.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,boolean:/\b(?:false|true)\b/,function:/\b\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/};m6.languages.javascript=m6.languages.extend("clike",{"class-name":[m6.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,lookbehind:!0}],keyword:[{pattern:/((?:^|\})\s*)catch\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],function:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,number:{pattern:RegExp(/(^|[^\w$])/.source+"(?:"+(/NaN|Infinity/.source+"|"+/0[bB][01]+(?:_[01]+)*n?/.source+"|"+/0[oO][0-7]+(?:_[0-7]+)*n?/.source+"|"+/0[xX][\dA-Fa-f]+(?:_[\dA-Fa-f]+)*n?/.source+"|"+/\d+(?:_\d+)*n/.source+"|"+/(?:\d+(?:_\d+)*(?:\.(?:\d+(?:_\d+)*)?)?|\.\d+(?:_\d+)*)(?:[Ee][+-]?\d+(?:_\d+)*)?/.source)+")"+/(?![\w$])/.source),lookbehind:!0},operator:/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/});m6.languages.javascript["class-name"][0].pattern=/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/;m6.languages.insertBefore("javascript","keyword",{regex:{pattern:RegExp(/((?:^|[^$\w\xA0-\uFFFF."'\])\s]|\b(?:return|yield))\s*)/.source+/\//.source+"(?:"+/(?:\[(?:[^\]\\\r\n]|\\.)*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}/.source+"|"+/(?:\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.|\[(?:[^[\]\\\r\n]|\\.)*\])*\])*\]|\\.|[^/\\\[\r\n])+\/[dgimyus]{0,7}v[dgimyus]{0,7}/.source+")"+/(?=(?:\s|\/\*(?:[^*]|\*(?!\/))*\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/.source),lookbehind:!0,greedy:!0,inside:{"regex-source":{pattern:/^(\/)[\s\S]+(?=\/[a-z]*$)/,lookbehind:!0,alias:"language-regex",inside:m6.languages.regex},"regex-delimiter":/^\/|\/$/,"regex-flags":/^[a-z]+$/}},"function-variable":{pattern:/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,lookbehind:!0,inside:m6.languages.javascript},{pattern:/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,lookbehind:!0,inside:m6.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,lookbehind:!0,inside:m6.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,lookbehind:!0,inside:m6.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/});m6.languages.insertBefore("javascript","string",{hashbang:{pattern:/^#!.*/,greedy:!0,alias:"comment"},"template-string":{pattern:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\$\{|\}$/,alias:"punctuation"},rest:m6.languages.javascript}},string:/[\s\S]+/}},"string-property":{pattern:/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,lookbehind:!0,greedy:!0,alias:"property"}});m6.languages.insertBefore("javascript","operator",{"literal-property":{pattern:/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,lookbehind:!0,alias:"property"}});if(m6.languages.markup)m6.languages.markup.tag.addInlined("script","javascript"),m6.languages.markup.tag.addAttribute(/on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)/.source,"javascript");m6.languages.js=m6.languages.javascript;(function(){if(typeof m6>"u"||typeof document>"u")return;if(!Element.prototype.matches)Element.prototype.matches=Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector;var J="Loading…",Q=function(H,B){return"✖ Error "+H+" while fetching file: "+B},Z="✖ Error: File does not exist or is empty",X={js:"javascript",py:"python",rb:"ruby",ps1:"powershell",psm1:"powershell",sh:"bash",bat:"batch",h:"c",tex:"latex"},Y="data-src-status",K="loading",G="loaded",q="failed",z="pre[data-src]:not(["+Y+'="'+G+'"]):not(['+Y+'="'+K+'"])';function U(H,B,M){var V=new XMLHttpRequest;V.open("GET",H,!0),V.onreadystatechange=function(){if(V.readyState==4)if(V.status<400&&V.responseText)B(V.responseText);else if(V.status>=400)M(Q(V.status,V.statusText));else M(Z)},V.send(null)}function W(H){var B=/^\s*(\d+)\s*(?:(,)\s*(?:(\d+)\s*)?)?$/.exec(H||"");if(B){var M=Number(B[1]),V=B[2],N=B[3];if(!V)return[M,M];if(!N)return[M,void 0];return[M,Number(N)]}return}m6.hooks.add("before-highlightall",function(H){H.selector+=", "+z}),m6.hooks.add("before-sanity-check",function(H){var B=H.element;if(B.matches(z)){H.code="",B.setAttribute(Y,K);var M=B.appendChild(document.createElement("CODE"));M.textContent=J;var V=B.getAttribute("data-src"),N=H.language;if(N==="none"){var L=(/\.(\w+)$/.exec(V)||[,"none"])[1];N=X[L]||L}m6.util.setLanguage(M,N),m6.util.setLanguage(B,N);var A=m6.plugins.autoloader;if(A)A.loadLanguages(N);U(V,function(w){B.setAttribute(Y,G);var R=W(B.getAttribute("data-range"));if(R){var O=w.split(/\r\n?|\n/g),j=R[0],$=R[1]==null?O.length:R[1];if(j<0)j+=O.length;if(j=Math.max(0,Math.min(j-1,O.length)),$<0)$+=O.length;if($=Math.max(0,Math.min($,O.length)),w=O.slice(j,$).join(`
|
|
4731
4731
|
`),!B.hasAttribute("data-start"))B.setAttribute("data-start",String(j+1))}M.textContent=w,m6.highlightElement(M)},function(w){B.setAttribute(Y,q),M.textContent=w})}}),m6.plugins.fileHighlight={highlight:function(B){var M=(B||document).querySelectorAll(z);for(var V=0,N;N=M[V++];)m6.highlightElement(N)}};var F=!1;m6.fileHighlight=function(){if(!F)console.warn("Prism.fileHighlight is deprecated. Use `Prism.plugins.fileHighlight.highlight` instead."),F=!0;m6.plugins.fileHighlight.highlight.apply(this,arguments)}})()});var mG6={};R6(mG6,{setTerminalFocused:()=>hG9,initFocusTracking:()=>fG9,getTerminalFocused:()=>Th1});function fG9(J){let Q=(Z)=>{if(Z.type==="focus")Ph1=Z.focused};J.onFocus(Q)}function Th1(){return Ph1}function hG9(J){Ph1=J}var Ph1=!0;var pG6={};R6(pG6,{initIdleTracking:()=>gG9,getIsIdle:()=>Ch1});function gG9(J,Q=300000){uG6=Q,WJ1=Date.now(),J.onKey(()=>{WJ1=Date.now()}),J.onMouse(()=>{WJ1=Date.now()})}function Ch1(){return Date.now()-WJ1>=uG6}var WJ1,uG6=300000;var Sh1=B1(()=>{WJ1=Date.now()});var EJ1=a((Lq6)=>{Object.defineProperty(Lq6,"__esModule",{value:!0});function rG9(J){var Q=new Uint32Array(1);return Q[0]=J[0]*1664525+1013904223,Q}Lq6.default=rG9});var jq6=a((Rq6)=>{Object.defineProperty(Rq6,"__esModule",{value:!0});Rq6.makeNoise2D=void 0;var IJ1=EJ1(),oG9=0.02127659574468085,Xg1=(Math.sqrt(3)-1)/2,tG9=(1/Math.sqrt(3)-1)/2;function Aq6(J,Q,Z){return{dx:-Q-J*Xg1,dy:-Z-J*Xg1,xsb:Q,ysb:Z}}function eG9(J){var Q=[];for(var Z=0;Z<ip.length;Z+=4){var X=Jq9[ip[Z]],Y=null,K=null;for(var G=0;G<X.length;G+=3){if(K=Aq6(X[G],X[G+1],X[G+2]),Y===null)Q[Z/4]=K;else Y.next=K;Y=K}K.next=Aq6(ip[Z+1],ip[Z+2],ip[Z+3])}var q=[];for(var Z=0;Z<Zg1.length;Z+=2)q[Zg1[Z]]=Q[Zg1[Z+1]];var z=new Uint8Array(256),U=new Uint8Array(256),W=new Uint8Array(256);for(var Z=0;Z<256;Z++)W[Z]=Z;var F=new Uint32Array(1);F[0]=J,F=IJ1.default(IJ1.default(IJ1.default(F)));for(var Z=255;Z>=0;Z--){F=IJ1.default(F);var H=new Uint32Array(1);if(H[0]=(F[0]+31)%(Z+1),H[0]<0)H[0]+=Z+1;z[Z]=W[H[0]],U[Z]=z[Z]&14,W[H[0]]=W[Z]}return function(B,M){var V=(B+M)*tG9,N=B+V,L=M+V,A=Math.floor(N),w=Math.floor(L),R=(A+w)*Xg1,O=B-(A+R),j=M-(w+R),$=N-A,E=L-w,I=$+E,T=$-E+1|I<<1|I+E<<2|I+$<<4,S=0;for(var x=q[T];x!==void 0;x=x.next){var h=O+x.dx,v=j+x.dy,_=2-h*h-v*v;if(_>0){var b=A+x.xsb,g=w+x.ysb,k=z[b&255],y=U[k+g&255],f=wq6[y]*h+wq6[y+1]*v;S+=_*_*_*_*f}}return S*oG9}}Rq6.makeNoise2D=eG9;var Jq9=[[1,1,0,1,0,1,0,0,0],[1,1,0,1,0,1,2,1,1]],wq6=[5,2,2,5,-5,2,-2,5,5,-2,2,-5,-5,-2,-2,-5],Zg1=[0,1,1,0,4,1,17,0,20,2,21,2,22,5,23,5,26,4,39,3,42,4,43,3],ip=[0,0,1,-1,0,0,-1,1,0,2,1,1,1,2,2,0,1,2,0,2,1,0,0,0]});var Iq6=a(($q6)=>{Object.defineProperty($q6,"__esModule",{value:!0});$q6.makeNoise3D=void 0;var PJ1=EJ1(),Qq9=0.009708737864077669,TJ1=(Math.sqrt(4)-1)/3,Zq9=(1/Math.sqrt(4)-1)/3;function Yg1(J,Q,Z,X){return{dx:-Q-J*TJ1,dy:-Z-J*TJ1,dz:-X-J*TJ1,xsb:Q,ysb:Z,zsb:X}}function Xq9(J){var Q=[];for(var Z=0;Z<KW.length;Z+=9){var X=Yq9[KW[Z]],Y=null,K=null;for(var G=0;G<X.length;G+=4){if(K=Yg1(X[G],X[G+1],X[G+2],X[G+3]),Y===null)Q[Z/9]=K;else Y.next=K;Y=K}K.next=Yg1(KW[Z+1],KW[Z+2],KW[Z+3],KW[Z+4]),K.next.next=Yg1(KW[Z+5],KW[Z+6],KW[Z+7],KW[Z+8])}var q=[];for(var Z=0;Z<Gg1.length;Z+=2)q[Gg1[Z]]=Q[Gg1[Z+1]];var z=new Uint8Array(256),U=new Uint8Array(256),W=new Uint8Array(256);for(var Z=0;Z<256;Z++)W[Z]=Z;var F=new Uint32Array(1);F[0]=J,F=PJ1.default(PJ1.default(PJ1.default(F)));for(var Z=255;Z>=0;Z--){F=PJ1.default(F);var H=new Uint32Array(1);if(H[0]=(F[0]+31)%(Z+1),H[0]<0)H[0]+=Z+1;z[Z]=W[H[0]],U[Z]=z[Z]%24*3,W[H[0]]=W[Z]}return function(B,M,V){var N=(B+M+V)*Zq9,L=B+N,A=M+N,w=V+N,R=Math.floor(L),O=Math.floor(A),j=Math.floor(w),$=(R+O+j)*TJ1,E=B-(R+$),I=M-(O+$),T=V-(j+$),S=L-R,x=A-O,h=w-j,v=S+x+h,_=x-h+1|S-x+1<<1|S-h+1<<2|v<<3|v+h<<5|v+x<<7|v+S<<9,b=0;for(var g=q[_];g!==void 0;g=g.next){var k=E+g.dx,y=I+g.dy,f=T+g.dz,m=2-k*k-y*y-f*f;if(m>0){var n=R+g.xsb,p=O+g.ysb,e=j+g.zsb,G1=z[n&255],U1=z[G1+p&255],Z1=U[U1+e&255],F1=Kg1[Z1]*k+Kg1[Z1+1]*y+Kg1[Z1+2]*f;b+=m*m*m*m*F1}}return b*Qq9}}$q6.makeNoise3D=Xq9;var Yq9=[[0,0,0,0,1,1,0,0,1,0,1,0,1,0,0,1],[2,1,1,0,2,1,0,1,2,0,1,1,3,1,1,1],[1,1,0,0,1,0,1,0,1,0,0,1,2,1,1,0,2,1,0,1,2,0,1,1]],Kg1=[-11,4,4,-4,11,4,-4,4,11,11,4,4,4,11,4,4,4,11,-11,-4,4,-4,-11,4,-4,-4,11,11,-4,4,4,-11,4,4,-4,11,-11,4,-4,-4,11,-4,-4,4,-11,11,4,-4,4,11,-4,4,4,-11,-11,-4,-4,-4,-11,-4,-4,-4,-11,11,-4,-4,4,-11,-4,4,-4,-11],Gg1=[0,2,1,1,2,2,5,1,6,0,7,0,32,2,34,2,129,1,133,1,160,5,161,5,518,0,519,0,546,4,550,4,645,3,647,3,672,5,673,5,674,4,677,3,678,4,679,3,680,13,681,13,682,12,685,14,686,12,687,14,712,20,714,18,809,21,813,23,840,20,841,21,1198,19,1199,22,1226,18,1230,19,1325,23,1327,22,1352,15,1353,17,1354,15,1357,17,1358,16,1359,16,1360,11,1361,10,1362,11,1365,10,1366,9,1367,9,1392,11,1394,11,1489,10,1493,10,1520,8,1521,8,1878,9,1879,9,1906,7,1910,7,2005,6,2007,6,2032,8,2033,8,2034,7,2037,6,2038,7,2039,6],KW=[0,0,1,-1,0,0,1,0,-1,0,0,-1,1,0,0,0,1,-1,0,0,-1,0,1,0,0,-1,1,0,2,1,1,0,1,1,1,-1,0,2,1,0,1,1,1,-1,1,0,2,0,1,1,1,-1,1,1,1,3,2,1,0,3,1,2,0,1,3,2,0,1,3,1,0,2,1,3,0,2,1,3,0,1,2,1,1,1,0,0,2,2,0,0,1,1,0,1,0,2,0,2,0,1,1,0,0,1,2,0,0,2,2,0,0,0,0,1,1,-1,1,2,0,0,0,0,1,-1,1,1,2,0,0,0,0,1,1,1,-1,2,3,1,1,1,2,0,0,2,2,3,1,1,1,2,2,0,0,2,3,1,1,1,2,0,2,0,2,1,1,-1,1,2,0,0,2,2,1,1,-1,1,2,2,0,0,2,1,-1,1,1,2,0,0,2,2,1,-1,1,1,2,0,2,0,2,1,1,1,-1,2,2,0,0,2,1,1,1,-1,2,0,2,0]});var Cq6=a((Pq6)=>{Object.defineProperty(Pq6,"__esModule",{value:!0});Pq6.makeNoise4D=void 0;var CJ1=EJ1(),Kq9=0.03333333333333333,np=(Math.sqrt(5)-1)/4,Gq9=(1/Math.sqrt(5)-1)/4;function SJ1(J,Q,Z,X,Y){return{dx:-Q-J*np,dy:-Z-J*np,dz:-X-J*np,dw:-Y-J*np,xsb:Q,ysb:Z,zsb:X,wsb:Y}}function qq9(J){var Q=[];for(var Z=0;Z<TJ.length;Z+=16){var X=zq9[TJ[Z]],Y=null,K=null;for(var G=0;G<X.length;G+=5){if(K=SJ1(X[G],X[G+1],X[G+2],X[G+3],X[G+4]),Y===null)Q[Z/16]=K;else Y.next=K;Y=K}K.next=SJ1(TJ[Z+1],TJ[Z+2],TJ[Z+3],TJ[Z+4],TJ[Z+5]),K.next.next=SJ1(TJ[Z+6],TJ[Z+7],TJ[Z+8],TJ[Z+9],TJ[Z+10]),K.next.next.next=SJ1(TJ[Z+11],TJ[Z+12],TJ[Z+13],TJ[Z+14],TJ[Z+15])}var q=[];for(var Z=0;Z<qg1.length;Z+=2)q[qg1[Z]]=Q[qg1[Z+1]];var z=new Uint8Array(256),U=new Uint8Array(256),W=new Uint8Array(256);for(var Z=0;Z<256;Z++)W[Z]=Z;var F=new Uint32Array(1);F[0]=J,F=CJ1.default(CJ1.default(CJ1.default(F)));for(var Z=255;Z>=0;Z--){F=CJ1.default(F);var H=new Uint32Array(1);if(H[0]=(F[0]+31)%(Z+1),H[0]<0)H[0]+=Z+1;z[Z]=W[H[0]],U[Z]=z[Z]&252,W[H[0]]=W[Z]}return function(B,M,V,N){var L=(B+M+V+N)*Gq9,A=B+L,w=M+L,R=V+L,O=N+L,j=Math.floor(A),$=Math.floor(w),E=Math.floor(R),I=Math.floor(O),T=(j+$+E+I)*np,S=B-(j+T),x=M-($+T),h=V-(E+T),v=N-(I+T),_=A-j,b=w-$,g=R-E,k=O-I,y=_+b+g+k,f=g-k+1|b-g+1<<1|b-k+1<<2|_-b+1<<3|_-g+1<<4|_-k+1<<5|y<<6|y+k<<8|y+g<<11|y+b<<14|y+_<<17,m=0;for(var n=q[f];n!==void 0;n=n.next){var p=S+n.dx,e=x+n.dy,G1=h+n.dz,U1=v+n.dw,Z1=2-p*p-e*e-G1*G1-U1*U1;if(Z1>0){var F1=j+n.xsb,l=$+n.ysb,d=E+n.zsb,i=I+n.wsb,r=z[F1&255],o=z[r+l&255],Y1=z[o+d&255],J1=U[Y1+i&255],H1=vJ1[J1]*p+vJ1[J1+1]*e+vJ1[J1+2]*G1+vJ1[J1+3]*U1;m+=Z1*Z1*Z1*Z1*H1}}return m*Kq9}}Pq6.makeNoise4D=qq9;var zq9=[[0,0,0,0,0,1,1,0,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1],[3,1,1,1,0,3,1,1,0,1,3,1,0,1,1,3,0,1,1,1,4,1,1,1,1],[1,1,0,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,2,1,1,0,0,2,1,0,1,0,2,1,0,0,1,2,0,1,1,0,2,0,1,0,1,2,0,0,1,1],[3,1,1,1,0,3,1,1,0,1,3,1,0,1,1,3,0,1,1,1,2,1,1,0,0,2,1,0,1,0,2,1,0,0,1,2,0,1,1,0,2,0,1,0,1,2,0,0,1,1]],vJ1=[3,1,1,1,1,3,1,1,1,1,3,1,1,1,1,3,-3,1,1,1,-1,3,1,1,-1,1,3,1,-1,1,1,3,3,-1,1,1,1,-3,1,1,1,-1,3,1,1,-1,1,3,-3,-1,1,1,-1,-3,1,1,-1,-1,3,1,-1,-1,1,3,3,1,-1,1,1,3,-1,1,1,1,-3,1,1,1,-1,3,-3,1,-1,1,-1,3,-1,1,-1,1,-3,1,-1,1,-1,3,3,-1,-1,1,1,-3,-1,1,1,-1,-3,1,1,-1,-1,3,-3,-1,-1,1,-1,-3,-1,1,-1,-1,-3,1,-1,-1,-1,3,3,1,1,-1,1,3,1,-1,1,1,3,-1,1,1,1,-3,-3,1,1,-1,-1,3,1,-1,-1,1,3,-1,-1,1,1,-3,3,-1,1,-1,1,-3,1,-1,1,-1,3,-1,1,-1,1,-3,-3,-1,1,-1,-1,-3,1,-1,-1,-1,3,-1,-1,-1,1,-3,3,1,-1,-1,1,3,-1,-1,1,1,-3,-1,1,1,-1,-3,-3,1,-1,-1,-1,3,-1,-1,-1,1,-3,-1,-1,1,-1,-3,3,-1,-1,-1,1,-3,-1,-1,1,-1,-3,-1,1,-1,-1,-3,-3,-1,-1,-1,-1,-3,-1,-1,-1,-1,-3,-1,-1,-1,-1,-3],qg1=[0,3,1,2,2,3,5,2,6,1,7,1,8,3,9,2,10,3,13,2,16,3,18,3,22,1,23,1,24,3,26,3,33,2,37,2,38,1,39,1,41,2,45,2,54,1,55,1,56,0,57,0,58,0,59,0,60,0,61,0,62,0,63,0,256,3,258,3,264,3,266,3,272,3,274,3,280,3,282,3,2049,2,2053,2,2057,2,2061,2,2081,2,2085,2,2089,2,2093,2,2304,9,2305,9,2312,9,2313,9,16390,1,16391,1,16406,1,16407,1,16422,1,16423,1,16438,1,16439,1,16642,8,16646,8,16658,8,16662,8,18437,6,18439,6,18469,6,18471,6,18688,9,18689,9,18690,8,18693,6,18694,8,18695,6,18696,9,18697,9,18706,8,18710,8,18725,6,18727,6,131128,0,131129,0,131130,0,131131,0,131132,0,131133,0,131134,0,131135,0,131352,7,131354,7,131384,7,131386,7,133161,5,133165,5,133177,5,133181,5,133376,9,133377,9,133384,9,133385,9,133400,7,133402,7,133417,5,133421,5,133432,7,133433,5,133434,7,133437,5,147510,4,147511,4,147518,4,147519,4,147714,8,147718,8,147730,8,147734,8,147736,7,147738,7,147766,4,147767,4,147768,7,147770,7,147774,4,147775,4,149509,6,149511,6,149541,6,149543,6,149545,5,149549,5,149558,4,149559,4,149561,5,149565,5,149566,4,149567,4,149760,9,149761,9,149762,8,149765,6,149766,8,149767,6,149768,9,149769,9,149778,8,149782,8,149784,7,149786,7,149797,6,149799,6,149801,5,149805,5,149814,4,149815,4,149816,7,149817,5,149818,7,149821,5,149822,4,149823,4,149824,37,149825,37,149826,36,149829,34,149830,36,149831,34,149832,37,149833,37,149842,36,149846,36,149848,35,149850,35,149861,34,149863,34,149865,33,149869,33,149878,32,149879,32,149880,35,149881,33,149882,35,149885,33,149886,32,149887,32,150080,49,150082,48,150088,49,150098,48,150104,47,150106,47,151873,46,151877,45,151881,46,151909,45,151913,44,151917,44,152128,49,152129,46,152136,49,152137,46,166214,43,166215,42,166230,43,166247,42,166262,41,166263,41,166466,48,166470,43,166482,48,166486,43,168261,45,168263,42,168293,45,168295,42,168512,31,168513,28,168514,31,168517,28,168518,25,168519,25,280952,40,280953,39,280954,40,280957,39,280958,38,280959,38,281176,47,281178,47,281208,40,281210,40,282985,44,282989,44,283001,39,283005,39,283208,30,283209,27,283224,30,283241,27,283256,22,283257,22,297334,41,297335,41,297342,38,297343,38,297554,29,297558,24,297562,29,297590,24,297594,21,297598,21,299365,26,299367,23,299373,26,299383,23,299389,20,299391,20,299584,31,299585,28,299586,31,299589,28,299590,25,299591,25,299592,30,299593,27,299602,29,299606,24,299608,30,299610,29,299621,26,299623,23,299625,27,299629,26,299638,24,299639,23,299640,22,299641,22,299642,21,299645,20,299646,21,299647,20,299648,61,299649,60,299650,61,299653,60,299654,59,299655,59,299656,58,299657,57,299666,55,299670,54,299672,58,299674,55,299685,52,299687,51,299689,57,299693,52,299702,54,299703,51,299704,56,299705,56,299706,53,299709,50,299710,53,299711,50,299904,61,299906,61,299912,58,299922,55,299928,58,299930,55,301697,60,301701,60,301705,57,301733,52,301737,57,301741,52,301952,79,301953,79,301960,76,301961,76,316038,59,316039,59,316054,54,316071,51,316086,54,316087,51,316290,78,316294,78,316306,73,316310,73,318085,77,318087,77,318117,70,318119,70,318336,79,318337,79,318338,78,318341,77,318342,78,318343,77,430776,56,430777,56,430778,53,430781,50,430782,53,430783,50,431000,75,431002,72,431032,75,431034,72,432809,74,432813,69,432825,74,432829,69,433032,76,433033,76,433048,75,433065,74,433080,75,433081,74,447158,71,447159,68,447166,71,447167,68,447378,73,447382,73,447386,72,447414,71,447418,72,447422,71,449189,70,449191,70,449197,69,449207,68,449213,69,449215,68,449408,67,449409,67,449410,66,449413,64,449414,66,449415,64,449416,67,449417,67,449426,66,449430,66,449432,65,449434,65,449445,64,449447,64,449449,63,449453,63,449462,62,449463,62,449464,65,449465,63,449466,65,449469,63,449470,62,449471,62,449472,19,449473,19,449474,18,449477,16,449478,18,449479,16,449480,19,449481,19,449490,18,449494,18,449496,17,449498,17,449509,16,449511,16,449513,15,449517,15,449526,14,449527,14,449528,17,449529,15,449530,17,449533,15,449534,14,449535,14,449728,19,449729,19,449730,18,449734,18,449736,19,449737,19,449746,18,449750,18,449752,17,449754,17,449784,17,449786,17,451520,19,451521,19,451525,16,451527,16,451528,19,451529,19,451557,16,451559,16,451561,15,451565,15,451577,15,451581,15,451776,19,451777,19,451784,19,451785,19,465858,18,465861,16,465862,18,465863,16,465874,18,465878,18,465893,16,465895,16,465910,14,465911,14,465918,14,465919,14,466114,18,466118,18,466130,18,466134,18,467909,16,467911,16,467941,16,467943,16,468160,13,468161,13,468162,13,468163,13,468164,13,468165,13,468166,13,468167,13,580568,17,580570,17,580585,15,580589,15,580598,14,580599,14,580600,17,580601,15,580602,17,580605,15,580606,14,580607,14,580824,17,580826,17,580856,17,580858,17,582633,15,582637,15,582649,15,582653,15,582856,12,582857,12,582872,12,582873,12,582888,12,582889,12,582904,12,582905,12,596982,14,596983,14,596990,14,596991,14,597202,11,597206,11,597210,11,597214,11,597234,11,597238,11,597242,11,597246,11,599013,10,599015,10,599021,10,599023,10,599029,10,599031,10,599037,10,599039,10,599232,13,599233,13,599234,13,599235,13,599236,13,599237,13,599238,13,599239,13,599240,12,599241,12,599250,11,599254,11,599256,12,599257,12,599258,11,599262,11,599269,10,599271,10,599272,12,599273,12,599277,10,599279,10,599282,11,599285,10,599286,11,599287,10,599288,12,599289,12,599290,11,599293,10,599294,11,599295,10],TJ=[0,0,1,-1,0,0,0,1,0,-1,0,0,1,0,0,-1,0,0,-1,1,0,0,0,0,1,-1,0,0,0,1,0,-1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,-1,0,0,-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,2,1,1,0,0,1,1,1,-1,0,1,1,1,0,-1,0,2,1,0,1,0,1,1,-1,1,0,1,1,0,1,-1,0,2,0,1,1,0,1,-1,1,1,0,1,0,1,1,-1,0,2,1,0,0,1,1,1,-1,0,1,1,1,0,-1,1,0,2,0,1,0,1,1,-1,1,0,1,1,0,1,-1,1,0,2,0,0,1,1,1,-1,0,1,1,1,0,-1,1,1,1,4,2,1,1,0,4,1,2,1,0,4,1,1,2,0,1,4,2,1,0,1,4,1,2,0,1,4,1,1,0,2,1,4,2,0,1,1,4,1,0,2,1,4,1,0,1,2,1,4,0,2,1,1,4,0,1,2,1,4,0,1,1,2,1,2,1,1,0,0,3,2,1,0,0,3,1,2,0,0,1,2,1,0,1,0,3,2,0,1,0,3,1,0,2,0,1,2,0,1,1,0,3,0,2,1,0,3,0,1,2,0,1,2,1,0,0,1,3,2,0,0,1,3,1,0,0,2,1,2,0,1,0,1,3,0,2,0,1,3,0,1,0,2,1,2,0,0,1,1,3,0,0,2,1,3,0,0,1,2,2,3,1,1,1,0,2,1,1,1,-1,2,2,0,0,0,2,3,1,1,0,1,2,1,1,-1,1,2,2,0,0,0,2,3,1,0,1,1,2,1,-1,1,1,2,2,0,0,0,2,3,1,1,1,0,2,1,1,1,-1,2,0,2,0,0,2,3,1,1,0,1,2,1,1,-1,1,2,0,2,0,0,2,3,0,1,1,1,2,-1,1,1,1,2,0,2,0,0,2,3,1,1,1,0,2,1,1,1,-1,2,0,0,2,0,2,3,1,0,1,1,2,1,-1,1,1,2,0,0,2,0,2,3,0,1,1,1,2,-1,1,1,1,2,0,0,2,0,2,3,1,1,0,1,2,1,1,-1,1,2,0,0,0,2,2,3,1,0,1,1,2,1,-1,1,1,2,0,0,0,2,2,3,0,1,1,1,2,-1,1,1,1,2,0,0,0,2,2,1,1,1,-1,0,1,1,1,0,-1,0,0,0,0,0,2,1,1,-1,1,0,1,1,0,1,-1,0,0,0,0,0,2,1,-1,1,1,0,1,0,1,1,-1,0,0,0,0,0,2,1,1,-1,0,1,1,1,0,-1,1,0,0,0,0,0,2,1,-1,1,0,1,1,0,1,-1,1,0,0,0,0,0,2,1,-1,0,1,1,1,0,-1,1,1,0,0,0,0,0,2,1,1,1,-1,0,1,1,1,0,-1,2,2,0,0,0,2,1,1,-1,1,0,1,1,0,1,-1,2,2,0,0,0,2,1,1,-1,0,1,1,1,0,-1,1,2,2,0,0,0,2,1,1,1,-1,0,1,1,1,0,-1,2,0,2,0,0,2,1,-1,1,1,0,1,0,1,1,-1,2,0,2,0,0,2,1,-1,1,0,1,1,0,1,-1,1,2,0,2,0,0,2,1,1,-1,1,0,1,1,0,1,-1,2,0,0,2,0,2,1,-1,1,1,0,1,0,1,1,-1,2,0,0,2,0,2,1,-1,0,1,1,1,0,-1,1,1,2,0,0,2,0,2,1,1,-1,0,1,1,1,0,-1,1,2,0,0,0,2,2,1,-1,1,0,1,1,0,1,-1,1,2,0,0,0,2,2,1,-1,0,1,1,1,0,-1,1,1,2,0,0,0,2,3,1,1,0,0,0,2,2,0,0,0,2,1,1,1,-1,3,1,0,1,0,0,2,0,2,0,0,2,1,1,1,-1,3,1,0,0,1,0,2,0,0,2,0,2,1,1,1,-1,3,1,1,0,0,0,2,2,0,0,0,2,1,1,-1,1,3,1,0,1,0,0,2,0,2,0,0,2,1,1,-1,1,3,1,0,0,0,1,2,0,0,0,2,2,1,1,-1,1,3,1,1,0,0,0,2,2,0,0,0,2,1,-1,1,1,3,1,0,0,1,0,2,0,0,2,0,2,1,-1,1,1,3,1,0,0,0,1,2,0,0,0,2,2,1,-1,1,1,3,1,0,1,0,0,2,0,2,0,0,2,-1,1,1,1,3,1,0,0,1,0,2,0,0,2,0,2,-1,1,1,1,3,1,0,0,0,1,2,0,0,0,2,2,-1,1,1,1,3,3,2,1,0,0,3,1,2,0,0,4,1,1,1,1,3,3,2,0,1,0,3,1,0,2,0,4,1,1,1,1,3,3,0,2,1,0,3,0,1,2,0,4,1,1,1,1,3,3,2,0,0,1,3,1,0,0,2,4,1,1,1,1,3,3,0,2,0,1,3,0,1,0,2,4,1,1,1,1,3,3,0,0,2,1,3,0,0,1,2,4,1,1,1,1,3,3,2,1,0,0,3,1,2,0,0,2,1,1,1,-1,3,3,2,0,1,0,3,1,0,2,0,2,1,1,1,-1,3,3,0,2,1,0,3,0,1,2,0,2,1,1,1,-1,3,3,2,1,0,0,3,1,2,0,0,2,1,1,-1,1,3,3,2,0,0,1,3,1,0,0,2,2,1,1,-1,1,3,3,0,2,0,1,3,0,1,0,2,2,1,1,-1,1,3,3,2,0,1,0,3,1,0,2,0,2,1,-1,1,1,3,3,2,0,0,1,3,1,0,0,2,2,1,-1,1,1,3,3,0,0,2,1,3,0,0,1,2,2,1,-1,1,1,3,3,0,2,1,0,3,0,1,2,0,2,-1,1,1,1,3,3,0,2,0,1,3,0,1,0,2,2,-1,1,1,1,3,3,0,0,2,1,3,0,0,1,2,2,-1,1,1,1]});var Sq6=a((ap)=>{Object.defineProperty(ap,"__esModule",{value:!0});ap.makeNoise4D=ap.makeNoise3D=ap.makeNoise2D=void 0;var Uq9=jq6();Object.defineProperty(ap,"makeNoise2D",{enumerable:!0,get:function(){return Uq9.makeNoise2D}});var Wq9=Iq6();Object.defineProperty(ap,"makeNoise3D",{enumerable:!0,get:function(){return Wq9.makeNoise3D}});var Fq9=Cq6();Object.defineProperty(ap,"makeNoise4D",{enumerable:!0,get:function(){return Fq9.makeNoise4D}})});var gW6=a((Wo2,hW6)=>{hW6.exports=LQ1;function LQ1(){this.pending=0,this.max=1/0,this.listeners=[],this.waiting=[],this.error=null}LQ1.prototype.go=function(J){if(this.pending<this.max)fW6(this,J);else this.waiting.push(J)};LQ1.prototype.wait=function(J){if(this.pending===0)J(this.error);else this.listeners.push(J)};LQ1.prototype.hold=function(){return yW6(this)};function yW6(J){J.pending+=1;var Q=!1;return Z;function Z(Y){if(Q)throw Error("callback called twice");if(Q=!0,J.error=J.error||Y,J.pending-=1,J.waiting.length>0&&J.pending<J.max)fW6(J,J.waiting.shift());else if(J.pending===0){var K=J.listeners;J.listeners=[],K.forEach(X)}}function X(Y){Y(J.error)}}function fW6(J,Q){Q(yW6(J))}});var uW6=a((EF9)=>{var Ud=n1("fs"),AQ1=n1("util"),Su1=n1("stream"),mW6=Su1.Readable,vu1=Su1.Writable,RF9=Su1.PassThrough,OF9=gW6(),wQ1=n1("events").EventEmitter;EF9.createFromBuffer=jF9;EF9.createFromFd=$F9;EF9.BufferSlicer=HB;EF9.FdSlicer=FB;AQ1.inherits(FB,wQ1);function FB(J,Q){Q=Q||{},wQ1.call(this),this.fd=J,this.pend=new OF9,this.pend.max=1,this.refCount=0,this.autoClose=!!Q.autoClose}FB.prototype.read=function(J,Q,Z,X,Y){var K=this;K.pend.go(function(G){Ud.read(K.fd,J,Q,Z,X,function(q,z,U){G(),Y(q,z,U)})})};FB.prototype.write=function(J,Q,Z,X,Y){var K=this;K.pend.go(function(G){Ud.write(K.fd,J,Q,Z,X,function(q,z,U){G(),Y(q,z,U)})})};FB.prototype.createReadStream=function(J){return new RQ1(this,J)};FB.prototype.createWriteStream=function(J){return new OQ1(this,J)};FB.prototype.ref=function(){this.refCount+=1};FB.prototype.unref=function(){var J=this;if(J.refCount-=1,J.refCount>0)return;if(J.refCount<0)throw Error("invalid unref");if(J.autoClose)Ud.close(J.fd,Q);function Q(Z){if(Z)J.emit("error",Z);else J.emit("close")}};AQ1.inherits(RQ1,mW6);function RQ1(J,Q){Q=Q||{},mW6.call(this,Q),this.context=J,this.context.ref(),this.start=Q.start||0,this.endOffset=Q.end,this.pos=this.start,this.destroyed=!1}RQ1.prototype._read=function(J){var Q=this;if(Q.destroyed)return;var Z=Math.min(Q._readableState.highWaterMark,J);if(Q.endOffset!=null)Z=Math.min(Z,Q.endOffset-Q.pos);if(Z<=0){Q.destroyed=!0,Q.push(null),Q.context.unref();return}Q.context.pend.go(function(X){if(Q.destroyed)return X();var Y=Buffer.allocUnsafe(Z);Ud.read(Q.context.fd,Y,0,Z,Q.pos,function(K,G){if(K)Q.destroy(K);else if(G===0)Q.destroyed=!0,Q.push(null),Q.context.unref();else Q.pos+=G,Q.push(Y.slice(0,G));X()})})};RQ1.prototype.destroy=function(J){if(this.destroyed)return;J=J||Error("stream destroyed"),this.destroyed=!0,this.emit("error",J),this.context.unref()};AQ1.inherits(OQ1,vu1);function OQ1(J,Q){Q=Q||{},vu1.call(this,Q),this.context=J,this.context.ref(),this.start=Q.start||0,this.endOffset=Q.end==null?1/0:+Q.end,this.bytesWritten=0,this.pos=this.start,this.destroyed=!1,this.on("finish",this.destroy.bind(this))}OQ1.prototype._write=function(J,Q,Z){var X=this;if(X.destroyed)return;if(X.pos+J.length>X.endOffset){var Y=Error("maximum file length exceeded");Y.code="ETOOBIG",X.destroy(),Z(Y);return}X.context.pend.go(function(K){if(X.destroyed)return K();Ud.write(X.context.fd,J,0,J.length,X.pos,function(G,q){if(G)X.destroy(),K(),Z(G);else X.bytesWritten+=q,X.pos+=q,X.emit("progress"),K(),Z()})})};OQ1.prototype.destroy=function(){if(this.destroyed)return;this.destroyed=!0,this.context.unref()};AQ1.inherits(HB,wQ1);function HB(J,Q){wQ1.call(this),Q=Q||{},this.refCount=0,this.buffer=J,this.maxChunkSize=Q.maxChunkSize||Number.MAX_SAFE_INTEGER}HB.prototype.read=function(J,Q,Z,X,Y){if(!(0<=Q&&Q<=J.length))throw RangeError("offset outside buffer: 0 <= "+Q+" <= "+J.length);if(X<0)throw RangeError("position is negative: "+X);if(Q+Z>J.length)Z=J.length-Q;if(X+Z>this.buffer.length)Z=this.buffer.length-X;if(Z<=0){setImmediate(function(){Y(null,0)});return}this.buffer.copy(J,Q,X,X+Z),setImmediate(function(){Y(null,Z)})};HB.prototype.write=function(J,Q,Z,X,Y){J.copy(this.buffer,X,Q,Q+Z),setImmediate(function(){Y(null,Z,J)})};HB.prototype.createReadStream=function(J){J=J||{};var Q=new RF9(J);Q.destroyed=!1,Q.start=J.start||0,Q.endOffset=J.end,Q.pos=Q.endOffset||this.buffer.length;var Z=this.buffer.slice(Q.start,Q.pos),X=0;while(!0){var Y=X+this.maxChunkSize;if(Y>=Z.length){if(X<Z.length)Q.write(Z.slice(X,Z.length));break}Q.write(Z.slice(X,Y)),X=Y}return Q.end(),Q.destroy=function(){Q.destroyed=!0},Q};HB.prototype.createWriteStream=function(J){var Q=this;J=J||{};var Z=new vu1(J);return Z.start=J.start||0,Z.endOffset=J.end==null?this.buffer.length:+J.end,Z.bytesWritten=0,Z.pos=Z.start,Z.destroyed=!1,Z._write=function(X,Y,K){if(Z.destroyed)return;var G=Z.pos+X.length;if(G>Z.endOffset){var q=Error("maximum file length exceeded");q.code="ETOOBIG",Z.destroyed=!0,K(q);return}X.copy(Q.buffer,Z.pos,0,X.length),Z.bytesWritten+=X.length,Z.pos=G,Z.emit("progress"),K()},Z.destroy=function(){Z.destroyed=!0},Z};HB.prototype.ref=function(){this.refCount+=1};HB.prototype.unref=function(){if(this.refCount-=1,this.refCount<0)throw Error("invalid unref")};function jF9(J,Q){return new HB(J,Q)}function $F9(J,Q){return new FB(J,Q)}});var cW6=a((Ho2,dW6)=>{var jN=n1("buffer").Buffer,ku1=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918000,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];if(typeof Int32Array<"u")ku1=new Int32Array(ku1);function pW6(J){if(jN.isBuffer(J))return J;var Q=typeof jN.alloc==="function"&&typeof jN.from==="function";if(typeof J==="number")return Q?jN.alloc(J):new jN(J);else if(typeof J==="string")return Q?jN.from(J):new jN(J);else throw Error("input must be buffer, number, or string, received "+typeof J)}function SF9(J){var Q=pW6(4);return Q.writeInt32BE(J,0),Q}function _u1(J,Q){if(J=pW6(J),jN.isBuffer(Q))Q=Q.readUInt32BE(0);var Z=~~Q^-1;for(var X=0;X<J.length;X++)Z=ku1[(Z^J[X])&255]^Z>>>8;return Z^-1}function xu1(){return SF9(_u1.apply(null,arguments))}xu1.signed=function(){return _u1.apply(null,arguments)};xu1.unsigned=function(){return _u1.apply(null,arguments)>>>0};dW6.exports=xu1});function ou1(J){let Q={},Z={};for(let X in J){if(!Object.hasOwn(J,X))continue;let Y=J[X];switch(typeof Y){case"number":Q[X]=Y;break;case"boolean":Q[X]=Y?1:0;break;case"object":{if(Y===null||Y===void 0){Z[X]=Y;break}let{metadata:K}=ou1(Y);for(let[G,q]of Object.entries(K))Q[`${X}.${G}`]=q;Z[X]=Y;break}default:Z[X]=Y}}return{metadata:Q,sensitiveMetadata:Z}}function tu1(J,Q){let{metadata:Z,sensitiveMetadata:X}=ou1(J.metadata||{});return{feature:J.feature,action:J.action,timestamp:Date.now()*1000,source:{client:Q},parameters:{...Object.keys(Z).length>0&&{metadata:Z},...Object.keys(X).length>0&&{sensitiveMetadata:X}}}}var BF6=()=>{};class eu1{configService;constructor(J){this.configService=J}recordEvent(J){let Q=tu1(J,"cli"),Z=JSON.stringify([Q]);$a(Z,this.configService).catch((X)=>{u.error("Failed to send telemetry",{error:X,feature:J.feature,action:J.action})})}}var DF6=B1(()=>{G0();fX();BF6()});var _Q1={};R6(_Q1,{recordEvent:()=>w3,recordAdEvent:()=>B10,initializeCLITelemetry:()=>IH9});function IH9(J){if(MF6)return;let Q=new eu1(J);H10(Q),MF6=!0}var MF6=!1;var xQ1=B1(()=>{zW1();DF6()});import{randomBytes as vH9}from"node:crypto";import{mkdir as kH9,readFile as OF6,writeFile as _H9}from"node:fs/promises";import xH9 from"node:os";import Qp1 from"node:path";import{stderr as QG,stdout as e2}from"node:process";Ed();G0();var WD6=60;class fZ1{deps;constructor(J){this.deps=J}getRelativePath(J){for(let Q of this.deps.workspaceRoots)if(b0.hasPrefix(J,Q)){let Z=b0.relativePath(Q,J);if(Z)return Z}if(this.deps.workspaceRoots.length===0)return J.path.startsWith("/")?J.path.slice(1):J.path;return null}async getCurrentFile(){let J=this.deps.getCurrentFile?.();if(!J)return[];let Q=this.getRelativePath(J);return Q?[Q]:[]}async getOpenFiles(){let J=this.deps.getOpenFiles?.()??[],Q=this.deps.getCurrentFile?.(),Z=J.filter((Y)=>!Q||!b0.equalURIs(Y,Q)).slice(0,WD6),X=new Set;for(let Y of Z){let K=this.getRelativePath(Y);if(K)X.add(K)}return Array.from(X)}async getContext(){let[J,Q]=await Promise.all([this.getCurrentFile(),this.getOpenFiles()]),Z={currentFile:J,openFilesContext:Q};return u.debug("[Ads] Collected codebase context",{currentFile:J,openFilesContext:Q.slice(0,10)}),Z}}C0();G0();var ml1={workspacePaths:[".agents/commands"],globalPaths:["~/.config/amp/commands"],enableWatching:!0};function wD6(J,Q){if(J.length!==Q.length)return!1;for(let Z=0;Z<J.length;Z++){let X=J[Z],Y=Q[Z];if(!X||!Y)return!1;if(X.name!==Y.name||X.available!==Y.available||X.lastModified!==Y.lastModified)return!1}return!0}function AS(J=ml1,Q=null){let Z=new W4([]),X=!1,Y=null,K,G=Z.pipe(J8(wD6),AQ((H)=>{return u.warn("Command stream error, using fallback",{error:H}),e1.of([])}),M9());async function q(){if(Y)return;let H=await G6(Q);if(!H)return;let{CommandDiscovery:B}=await Promise.resolve().then(() => (gl1(),hl1));Y=new B(J,H),K={dispose:Y.commandChanges.subscribe((M)=>{if(!X)Z.next(M)}).unsubscribe}}async function z(){if(await q(),!Y)return u.debug("No workspace roots available, skipping command discovery"),[];return await Y.discoverCommands()}async function U(){if(X)return;try{let H=await z();Z.next(H)}catch(H){u.warn("Failed to refresh commands",{error:H})}}async function W(H){let M=(await G6(G)).find((A)=>A.name===H);if(!M)return;let{available:V,unavailableReason:N,...L}=M;return L}async function F(H){return(await G6(G)).find((V)=>V.name===H)?.available??!1}return U(),{commands:G,getCommand:W,refreshCommands:U,isCommandAvailable:F,dispose(){X=!0,K?.dispose(),Y?.dispose()}}}DW();G0();import XO from"node:diagnostics_channel";import{mkdirSync as $D6}from"node:fs";import{writeFile as ED6}from"node:fs/promises";import ID6 from"node:path";var dl1=!1;function ll1(){if(dl1)return;dl1=!0;try{$D6(rZ1,{recursive:!0})}catch(X){u.error("Failed to create HTTP logs directory",{error:X})}let J=new WeakMap,Q=new WeakMap,Z=new WeakMap;XO.channel("undici:request:create").subscribe((X)=>{let{request:Y}=X,K=`${Y.origin}${Y.path}`,G={};if(Array.isArray(Y.headers))for(let z=0;z<Y.headers.length;z+=2)G[Y.headers[z]||""]=Y.headers[z+1]||"";else if(Y.headers)G=Y.headers;let q={timestamp:new Date().toISOString(),method:Y.method||"UNKNOWN",url:K,headers:G};Z.set(Y,q),J.set(Y,[])}),XO.channel("undici:request:bodyChunkSent").subscribe((X)=>{let{request:Y,chunk:K}=X;if(K&&Y){let G=J.get(Y)||[],q=typeof K==="string"?Buffer.from(K,"utf-8"):K;G.push(q),J.set(Y,G)}}),XO.channel("undici:request:headers").subscribe((X)=>{let{request:Y,response:K}=X,G=Z.get(Y);if(G){G.responseStatus=K.statusCode;let q={};if(Array.isArray(K.headers))for(let z=0;z<K.headers.length;z+=2){let U=K.headers[z],W=K.headers[z+1];if(U&&W){let F=Buffer.isBuffer(U)?U.toString("utf-8"):String(U),H=Buffer.isBuffer(W)?W.toString("utf-8"):String(W);q[F]=H}}G.responseHeaders=q}}),XO.channel("undici:request:bodyChunkReceived").subscribe((X)=>{let{request:Y,chunk:K}=X;if(K&&Y){let G=Q.get(Y)||[];G.push(K),Q.set(Y,G)}}),XO.channel("undici:request:trailers").subscribe((X)=>{let{request:Y}=X,K=Z.get(Y);if(!K)return;cl1(K).catch((G)=>{u.error("Failed to write HTTP request log",{error:G})}),J.delete(Y),Q.delete(Y),Z.delete(Y)}),XO.channel("undici:request:error").subscribe((X)=>{let{request:Y,error:K}=X,G=Z.get(Y);if(G){let q=J.get(Y),z=Q.get(Y);if(q&&q.length>0)G.requestBody=Buffer.concat(q.map((W)=>Buffer.from(W))).toString("utf-8");if(z&&z.length>0)G.responseBody=Buffer.concat(z).toString("utf-8");let U={...G,error:{message:K.message,stack:K.stack}};cl1(U).catch((W)=>{u.error("Failed to write HTTP error log",{error:W})})}J.delete(Y),Q.delete(Y),Z.delete(Y)}),u.info("HTTP request/response logging initialized")}async function cl1(J){let Z=new URL(J.url).pathname.replace(/^\//,"").replace(/\//g,"_")||"root",Y=`${new Date(J.timestamp).getTime()}_${Z}_${J.method}.json`,K=ID6.join(rZ1,Y),G=JSON.stringify(J,null,2);await ED6(K,G,"utf-8")}G0();C0();import SD6 from"node:fs";import vD6 from"node:os";var PD6=/("(?:\\?[^])*?")|(\/\/.*)|(\/\*[^]*?\*\/)/g,TD6=/("(?:\\?[^])*?")|(,\s*)(?=]|})/g,CD6={parse:(J)=>{J=String(J);try{return JSON.parse(J)}catch{return JSON.parse(J.replace(PD6,"$1").replace(TD6,"$1"))}}},il1=CD6;G0();C0();G0();class sZ1{options;value;lastError;lastUpdated=0;pendingPromise;eventsSubject=new b8;events=this.eventsSubject;constructor(J){this.options=J}async get(){if(this.lastError)return this.recompute();let Q=Date.now()-this.lastUpdated;if(this.value===void 0||Q>=this.options.hardTTL)return this.recompute();if(Q>=this.options.softTTL&&!this.pendingPromise)this.recompute().catch(()=>{});return this.value}getCached(){return this.value}async refresh(){return this.recompute()}recompute(){if(this.pendingPromise)return this.pendingPromise;return this.pendingPromise=this.performRecomputation(),this.pendingPromise.finally(()=>{this.pendingPromise=void 0}),this.pendingPromise}async performRecomputation(){try{let J=await this.options.compute(),Q=this.value;this.lastError=void 0,this.value=J,this.lastUpdated=Date.now();let Z=this.options.changes(Q,J);if(Z!==void 0)try{this.eventsSubject.next(Z)}catch(X){u.error("Uncaught error for GlobalCachedValue.events subscriber",X)}return J}catch(J){let Q=J instanceof Error?J:Error(String(J));this.lastError=Q;let Z=this.value;this.value=void 0;let X=this.options.changes(Z,void 0);if(X!==void 0)try{this.eventsSubject.next(X)}catch(Y){u.error("Uncaught error for GlobalCachedValue.events subscriber",Y)}throw Q}}}function kD6(J){if(!/^\d{4}-\d{2}-\d{2}$/.test(J))throw Error(`Invalid compatibility date format "${J}". Expected format: YYYY-MM-DD (e.g., "2024-01-15")`);let Z=new Date(J+"T00:00:00.000Z");if(Number.isNaN(Z.getTime()))throw Error(`Invalid compatibility date "${J}". Date could not be parsed.`);let X=J.split("-").map(Number),[Y,K,G]=X;if(X.length!==3||Y===void 0||K===void 0||G===void 0)throw Error(`Invalid compatibility date "${J}". Could not parse date components.`);if(Z.getUTCFullYear()!==Y||Z.getUTCMonth()!==K-1||Z.getUTCDate()!==G)throw Error(`Invalid compatibility date "${J}". Date components are invalid.`);return Z}var nl1=new sZ1({compute:async()=>{try{let J=await bD6(),Q;try{Q=il1.parse(J)}catch(X){throw Error(`Invalid JSON in admin settings: ${X} (content: "${J}")`)}u.debug("Admin settings loaded",{rawConfig:Q});let Z={};for(let[X,Y]of Object.entries(Q))if(X.startsWith("amp.")){let K=X.substring(4);if(K==="admin.compatibilityDate")try{Z.compatibilityDate=kD6(Y)}catch(G){u.warn(`Invalid admin compatibility date: ${G instanceof Error?G.message:String(G)}`)}else Z[K]=Y}return Z}catch(J){if(J.code==="ENOENT")return{};return u.error("Failed to read admin settings",{error:J}),{}}},softTTL:30000,hardTTL:120000,changes:(J,Q)=>{let Z=_D6(J,Q);return Z.length>0?Z:void 0}});function al1(J,Q={fetch:()=>nl1.get(),changes:nl1.events}){return{...J,async get(Z,X){let Y=await Q.fetch();if(X==="admin"||!X&&Z in Y)return Y[Z];return J.get(Z,X)},async keys(){let Z=await J.keys(),X=await Q.fetch(),Y=Object.keys(X),K=new Set([...Z,...Y]);return Array.from(K)},get changes(){if(Q.changes)return VS(J.changes,Q.changes);return J.changes}}}function _D6(J,Q){let Z=J??{},X=Q??{},Y=JSON.stringify(Z,Object.keys(Z).sort()),K=JSON.stringify(X,Object.keys(X).sort());if(Y===K)return[];let G=new Set([...Object.keys(Z),...Object.keys(X)]);return Array.from(G)}function xD6(){switch(vD6.platform()){case"darwin":return"/Library/Application Support/ampcode/managed-settings.json";case"linux":return"/etc/ampcode/managed-settings.json";case"win32":return"C:\\ProgramData\\ampcode\\managed-settings.json";default:return null}}async function bD6(){let J=xD6();if(!J)return"{}";try{return await SD6.promises.readFile(J,"utf-8")}catch(Q){if(Q.code==="ENOENT")return"{}";throw Q}}G0();zO();function DM6(J,Q){let{default:Z,global:X,workspace:Y}=Q;if(!KX1(J))return;let K=[];for(let q of[Y,X,Z])if(Array.isArray(q))K.push(...q);else if(q!==void 0)u.warn("Expected array value for merged array key",{key:J,value:q});let G=new Map;for(let q of K){let z=JSON.stringify(q);if(!G.has(z))G.set(z,q)}return G.size>0?Array.from(G.values()):void 0}function MM6(J){let Q={};if(J.default&&typeof J.default==="object")for(let[Z,X]of Object.entries(J.default))Q[Z]={...X,_target:"default"};else if(J.default!==void 0)u.warn("Expected object for mcpServers default",{value:J.default});if(J.global&&typeof J.global==="object")for(let[Z,X]of Object.entries(J.global))Q[Z]={...X,_target:"global"};else if(J.global!==void 0)u.warn("Expected object for mcpServers global",{value:J.global});if(J.workspace&&typeof J.workspace==="object")for(let[Z,X]of Object.entries(J.workspace))Q[Z]={...X,_target:"workspace"};else if(J.workspace!==void 0)u.warn("Expected object for mcpServers workspace",{value:J.workspace});return Object.keys(Q).length>0?Q:void 0}function PS(J,Q){if(J==="mcpServers")return MM6(Q);if(KX1(J))return DM6(J,Q);return Q.workspace??Q.global??Q.default}C0();var Gc=new W4({});function BZ(J,Q){let Z=Gc.getValue();Gc.next({...Z,[J]:Q})}b6();C0();TB();nN();bB();Sc();zO();function hX1({storage:J,secretStorage:Q,workspaceRoots:Z,defaultAmpURL:X=DZ,preferThreadEnv:Y,homeDir:K,userConfigDir:G}){let q=d6(async()=>{let H=await J.keys();return Object.fromEntries(await Promise.all(H.map(async(M)=>[M,await J.get(M)])))}).pipe(q8((H)=>NS(e1.of(H),J.changes.pipe(BW(async(B)=>{return await Promise.all(B.map(async(M)=>{let V=await J.get(M);H[M]=V})),H})))),k0((H)=>{let B={...H,url:H.url||X,"todos.enabled":H["todos.enabled"]??!0};if(B.permissions)B.permissions=EO(B.permissions);return B}),M9(),J8()),z=b9(Q.changes.pipe(v2(void 0)),q.pipe(k0(({url:H})=>H),J8())).pipe(BW(async([,H])=>({getToken:async(B,M)=>{return Q.get(B,M)},isSet:{[H]:Object.fromEntries(await Promise.all(Ii1.map(async(B)=>[B,!!await Q.get(B,H)])))}}))),U=b9(q,z,Gc).pipe(J8(([H,B,M],[V,N,L])=>H===V&&B===N&&M===L),k0(([H,B,M])=>({settings:{...H,...M},secrets:B})),M9()),W=Z.pipe(k0((H)=>({workspaceFolders:H?.map(k6)??null,isWindows:SO().os==="windows",homeDir:typeof process==="object"&&process.env.HOME?k6(w0.file(process.env.HOME)):void 0,preferThreadEnv:Y}))),F=W.subscribe((H)=>{Dc(H)});return{get(H,B){return J.get(H,B)},updateSettings(H,B,M){return J.set(H,B,M)},async appendSettings(H,B,M){let V=await J.get(H,M);if(V===void 0)return J.set(H,B,M);else if(!Array.isArray(V))throw Error(`Cannot append to non-array setting: ${H}`);else if(V.length===0)return J.set(H,B,M);else{let N=[...V,...B];return J.set(H,N,M)}},async prependSettings(H,B,M){let V=await J.get(H,M);if(V===void 0)return J.set(H,B,M);else if(!Array.isArray(V))throw Error(`Cannot prepend to non-array setting: ${H}`);else if(V.length===0)return J.set(H,B,M);else{let N=[...B,...V];return J.set(H,N,M)}},updateSecret(H,B,M){return Q.set(H,B,M)},workspaceRoots:Z,displayPathEnvInfo:W,homeDir:K,userConfigDir:G,config:U,async getLatest(H){return G6(U,H)},unsubscribe(){F.unsubscribe()}}}gX1();TB();D3();bv();W2();b6();C0();G0();ol();c2();vW();var mR6=60000;class BU1{constructor(J){this._options=J,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(Qi,(Q)=>{let Z=this._requestHandlerAbortControllers.get(Q.params.requestId);Z===null||Z===void 0||Z.abort(Q.params.reason)}),this.setNotificationHandler(Xi,(Q)=>{this._onprogress(Q)}),this.setRequestHandler(Zi,(Q)=>({}))}_setupTimeout(J,Q,Z,X,Y=!1){this._timeoutInfo.set(J,{timeoutId:setTimeout(X,Q),startTime:Date.now(),timeout:Q,maxTotalTimeout:Z,resetTimeoutOnProgress:Y,onTimeout:X})}_resetTimeout(J){let Q=this._timeoutInfo.get(J);if(!Q)return!1;let Z=Date.now()-Q.startTime;if(Q.maxTotalTimeout&&Z>=Q.maxTotalTimeout)throw this._timeoutInfo.delete(J),new DG(CY.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Q.maxTotalTimeout,totalElapsed:Z});return clearTimeout(Q.timeoutId),Q.timeoutId=setTimeout(Q.onTimeout,Q.timeout),!0}_cleanupTimeout(J){let Q=this._timeoutInfo.get(J);if(Q)clearTimeout(Q.timeoutId),this._timeoutInfo.delete(J)}async connect(J){var Q,Z,X;this._transport=J;let Y=(Q=this.transport)===null||Q===void 0?void 0:Q.onclose;this._transport.onclose=()=>{Y===null||Y===void 0||Y(),this._onclose()};let K=(Z=this.transport)===null||Z===void 0?void 0:Z.onerror;this._transport.onerror=(q)=>{K===null||K===void 0||K(q),this._onerror(q)};let G=(X=this._transport)===null||X===void 0?void 0:X.onmessage;this._transport.onmessage=(q,z)=>{if(G===null||G===void 0||G(q,z),iv(q)||bo1(q))this._onresponse(q);else if(Ji(q))this._onrequest(q,z);else if(ko1(q))this._onnotification(q);else this._onerror(Error(`Unknown message type: ${JSON.stringify(q)}`))},await this._transport.start()}_onclose(){var J;let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(J=this.onclose)===null||J===void 0||J.call(this);let Z=new DG(CY.ConnectionClosed,"Connection closed");for(let X of Q.values())X(Z)}_onerror(J){var Q;(Q=this.onerror)===null||Q===void 0||Q.call(this,J)}_onnotification(J){var Q;let Z=(Q=this._notificationHandlers.get(J.method))!==null&&Q!==void 0?Q:this.fallbackNotificationHandler;if(Z===void 0)return;Promise.resolve().then(()=>Z(J)).catch((X)=>this._onerror(Error(`Uncaught error in notification handler: ${X}`)))}_onrequest(J,Q){var Z,X;let Y=(Z=this._requestHandlers.get(J.method))!==null&&Z!==void 0?Z:this.fallbackRequestHandler,K=this._transport;if(Y===void 0){K===null||K===void 0||K.send({jsonrpc:"2.0",id:J.id,error:{code:CY.MethodNotFound,message:"Method not found"}}).catch((z)=>this._onerror(Error(`Failed to send an error response: ${z}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set(J.id,G);let q={signal:G.signal,sessionId:K===null||K===void 0?void 0:K.sessionId,_meta:(X=J.params)===null||X===void 0?void 0:X._meta,sendNotification:(z)=>this.notification(z,{relatedRequestId:J.id}),sendRequest:(z,U,W)=>this.request(z,U,{...W,relatedRequestId:J.id}),authInfo:Q===null||Q===void 0?void 0:Q.authInfo,requestId:J.id,requestInfo:Q===null||Q===void 0?void 0:Q.requestInfo};Promise.resolve().then(()=>Y(J,q)).then((z)=>{if(G.signal.aborted)return;return K===null||K===void 0?void 0:K.send({result:z,jsonrpc:"2.0",id:J.id})},(z)=>{var U;if(G.signal.aborted)return;return K===null||K===void 0?void 0:K.send({jsonrpc:"2.0",id:J.id,error:{code:Number.isSafeInteger(z.code)?z.code:CY.InternalError,message:(U=z.message)!==null&&U!==void 0?U:"Internal error"}})}).catch((z)=>this._onerror(Error(`Failed to send response: ${z}`))).finally(()=>{this._requestHandlerAbortControllers.delete(J.id)})}_onprogress(J){let{progressToken:Q,...Z}=J.params,X=Number(Q),Y=this._progressHandlers.get(X);if(!Y){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(J)}`));return}let K=this._responseHandlers.get(X),G=this._timeoutInfo.get(X);if(G&&K&&G.resetTimeoutOnProgress)try{this._resetTimeout(X)}catch(q){K(q);return}Y(Z)}_onresponse(J){let Q=Number(J.id),Z=this._responseHandlers.get(Q);if(Z===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(J)}`));return}if(this._responseHandlers.delete(Q),this._progressHandlers.delete(Q),this._cleanupTimeout(Q),iv(J))Z(J);else{let X=new DG(J.error.code,J.error.message,J.error.data);Z(X)}}get transport(){return this._transport}async close(){var J;await((J=this._transport)===null||J===void 0?void 0:J.close())}request(J,Q,Z){let{relatedRequestId:X,resumptionToken:Y,onresumptiontoken:K}=Z!==null&&Z!==void 0?Z:{};return new Promise((G,q)=>{var z,U,W,F,H,B;if(!this._transport){q(Error("Not connected"));return}if(((z=this._options)===null||z===void 0?void 0:z.enforceStrictCapabilities)===!0)this.assertCapabilityForMethod(J.method);(U=Z===null||Z===void 0?void 0:Z.signal)===null||U===void 0||U.throwIfAborted();let M=this._requestMessageId++,V={...J,jsonrpc:"2.0",id:M};if(Z===null||Z===void 0?void 0:Z.onprogress)this._progressHandlers.set(M,Z.onprogress),V.params={...J.params,_meta:{...((W=J.params)===null||W===void 0?void 0:W._meta)||{},progressToken:M}};let N=(w)=>{var R;this._responseHandlers.delete(M),this._progressHandlers.delete(M),this._cleanupTimeout(M),(R=this._transport)===null||R===void 0||R.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:M,reason:String(w)}},{relatedRequestId:X,resumptionToken:Y,onresumptiontoken:K}).catch((O)=>this._onerror(Error(`Failed to send cancellation: ${O}`))),q(w)};this._responseHandlers.set(M,(w)=>{var R;if((R=Z===null||Z===void 0?void 0:Z.signal)===null||R===void 0?void 0:R.aborted)return;if(w instanceof Error)return q(w);try{let O=Q.parse(w.result);G(O)}catch(O){q(O)}}),(F=Z===null||Z===void 0?void 0:Z.signal)===null||F===void 0||F.addEventListener("abort",()=>{var w;N((w=Z===null||Z===void 0?void 0:Z.signal)===null||w===void 0?void 0:w.reason)});let L=(H=Z===null||Z===void 0?void 0:Z.timeout)!==null&&H!==void 0?H:mR6,A=()=>N(new DG(CY.RequestTimeout,"Request timed out",{timeout:L}));this._setupTimeout(M,L,Z===null||Z===void 0?void 0:Z.maxTotalTimeout,A,(B=Z===null||Z===void 0?void 0:Z.resetTimeoutOnProgress)!==null&&B!==void 0?B:!1),this._transport.send(V,{relatedRequestId:X,resumptionToken:Y,onresumptiontoken:K}).catch((w)=>{this._cleanupTimeout(M),q(w)})})}async notification(J,Q){var Z,X;if(!this._transport)throw Error("Not connected");if(this.assertNotificationCapability(J.method),((X=(Z=this._options)===null||Z===void 0?void 0:Z.debouncedNotificationMethods)!==null&&X!==void 0?X:[]).includes(J.method)&&!J.params&&!(Q===null||Q===void 0?void 0:Q.relatedRequestId)){if(this._pendingDebouncedNotifications.has(J.method))return;this._pendingDebouncedNotifications.add(J.method),Promise.resolve().then(()=>{var q;if(this._pendingDebouncedNotifications.delete(J.method),!this._transport)return;let z={...J,jsonrpc:"2.0"};(q=this._transport)===null||q===void 0||q.send(z,Q).catch((U)=>this._onerror(U))});return}let G={...J,jsonrpc:"2.0"};await this._transport.send(G,Q)}setRequestHandler(J,Q){let Z=J.shape.method.value;this.assertRequestHandlerCapability(Z),this._requestHandlers.set(Z,(X,Y)=>{return Promise.resolve(Q(J.parse(X),Y))})}removeRequestHandler(J){this._requestHandlers.delete(J)}assertCanSetRequestHandler(J){if(this._requestHandlers.has(J))throw Error(`A request handler for ${J} already exists, which would be overridden`)}setNotificationHandler(J,Q){this._notificationHandlers.set(J.shape.method.value,(Z)=>Promise.resolve(Q(J.parse(Z))))}removeNotificationHandler(J){this._notificationHandlers.delete(J)}}function lo1(J,Q){return Object.entries(Q).reduce((Z,[X,Y])=>{if(Y&&typeof Y==="object")Z[X]=Z[X]?{...Z[X],...Y}:Y;else Z[X]=Y;return Z},{...J})}vW();var ne1=C6(ie1(),1);class rv extends BU1{constructor(J,Q){var Z;super(Q);this._clientInfo=J,this._cachedToolOutputValidators=new Map,this._capabilities=(Z=Q===null||Q===void 0?void 0:Q.capabilities)!==null&&Z!==void 0?Z:{},this._ajv=new ne1.default}registerCapabilities(J){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=lo1(this._capabilities,J)}assertCapability(J,Q){var Z;if(!((Z=this._serverCapabilities)===null||Z===void 0?void 0:Z[J]))throw Error(`Server does not support ${J} (required for ${Q})`)}async connect(J,Q){if(await super.connect(J),J.sessionId!==void 0)return;try{let Z=await this.request({method:"initialize",params:{protocolVersion:tO,capabilities:this._capabilities,clientInfo:this._clientInfo}},oz1,Q);if(Z===void 0)throw Error(`Server sent invalid initialize result: ${Z}`);if(!Po1.includes(Z.protocolVersion))throw Error(`Server's protocol version is not supported: ${Z.protocolVersion}`);if(this._serverCapabilities=Z.capabilities,this._serverVersion=Z.serverInfo,J.setProtocolVersion)J.setProtocolVersion(Z.protocolVersion);this._instructions=Z.instructions,await this.notification({method:"notifications/initialized"})}catch(Z){throw this.close(),Z}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(J){var Q,Z,X,Y,K;switch(J){case"logging/setLevel":if(!((Q=this._serverCapabilities)===null||Q===void 0?void 0:Q.logging))throw Error(`Server does not support logging (required for ${J})`);break;case"prompts/get":case"prompts/list":if(!((Z=this._serverCapabilities)===null||Z===void 0?void 0:Z.prompts))throw Error(`Server does not support prompts (required for ${J})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!((X=this._serverCapabilities)===null||X===void 0?void 0:X.resources))throw Error(`Server does not support resources (required for ${J})`);if(J==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${J})`);break;case"tools/call":case"tools/list":if(!((Y=this._serverCapabilities)===null||Y===void 0?void 0:Y.tools))throw Error(`Server does not support tools (required for ${J})`);break;case"completion/complete":if(!((K=this._serverCapabilities)===null||K===void 0?void 0:K.completions))throw Error(`Server does not support completions (required for ${J})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(J){var Q;switch(J){case"notifications/roots/list_changed":if(!((Q=this._capabilities.roots)===null||Q===void 0?void 0:Q.listChanged))throw Error(`Client does not support roots list changed notifications (required for ${J})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(J){switch(J){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${J})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${J})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${J})`);break;case"ping":break}}async ping(J){return this.request({method:"ping"},M3,J)}async complete(J,Q){return this.request({method:"completion/complete",params:J},HU1,Q)}async setLoggingLevel(J,Q){return this.request({method:"logging/setLevel",params:{level:J}},M3,Q)}async getPrompt(J,Q){return this.request({method:"prompts/get",params:J},qU1,Q)}async listPrompts(J,Q){return this.request({method:"prompts/list",params:J},XU1,Q)}async listResources(J,Q){return this.request({method:"resources/list",params:J},ez1,Q)}async listResourceTemplates(J,Q){return this.request({method:"resources/templates/list",params:J},JU1,Q)}async readResource(J,Q){return this.request({method:"resources/read",params:J},QU1,Q)}async subscribeResource(J,Q){return this.request({method:"resources/subscribe",params:J},M3,Q)}async unsubscribeResource(J,Q){return this.request({method:"resources/unsubscribe",params:J},M3,Q)}async callTool(J,Q=Gi,Z){let X=await this.request({method:"tools/call",params:J},Q,Z),Y=this.getToolOutputValidator(J.name);if(Y){if(!X.structuredContent&&!X.isError)throw new DG(CY.InvalidRequest,`Tool ${J.name} has an output schema but did not return structured content`);if(X.structuredContent)try{if(!Y(X.structuredContent))throw new DG(CY.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(Y.errors)}`)}catch(K){if(K instanceof DG)throw K;throw new DG(CY.InvalidParams,`Failed to validate structured content: ${K instanceof Error?K.message:String(K)}`)}}return X}cacheToolOutputSchemas(J){this._cachedToolOutputValidators.clear();for(let Q of J)if(Q.outputSchema)try{let Z=this._ajv.compile(Q.outputSchema);this._cachedToolOutputValidators.set(Q.name,Z)}catch(Z){}}getToolOutputValidator(J){return this._cachedToolOutputValidators.get(J)}async listTools(J,Q){let Z=await this.request({method:"tools/list",params:J},UU1,Q);return this.cacheToolOutputSchemas(Z.tools),Z}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}$i();class mU1 extends Event{constructor(J,Q){var Z,X;super(J),this.code=(Z=Q==null?void 0:Q.code)!=null?Z:void 0,this.message=(X=Q==null?void 0:Q.message)!=null?X:void 0}[Symbol.for("nodejs.util.inspect.custom")](J,Q,Z){return Z(ae1(this),Q)}[Symbol.for("Deno.customInspect")](J,Q){return J(ae1(this),Q)}}function wj6(J){let Q=globalThis.DOMException;return typeof Q=="function"?new Q(J,"SyntaxError"):SyntaxError(J)}function uU1(J){return J instanceof Error?"errors"in J&&Array.isArray(J.errors)?J.errors.map(uU1).join(", "):("cause"in J)&&J.cause instanceof Error?`${J}: ${uU1(J.cause)}`:J.message:`${J}`}function ae1(J){return{type:J.type,message:J.message,code:J.code,defaultPrevented:J.defaultPrevented,cancelable:J.cancelable,timeStamp:J.timeStamp}}var se1=(J)=>{throw TypeError(J)},rU1=(J,Q,Z)=>Q.has(J)||se1("Cannot "+Z),j9=(J,Q,Z)=>(rU1(J,Q,"read from private field"),Z?Z.call(J):Q.get(J)),e7=(J,Q,Z)=>Q.has(J)?se1("Cannot add the same private member more than once"):Q instanceof WeakSet?Q.add(J):Q.set(J,Z),j4=(J,Q,Z,X)=>(rU1(J,Q,"write to private field"),Q.set(J,Z),Z),kW=(J,Q,Z)=>(rU1(J,Q,"access private method"),Z),RZ,L3,Qj,Ei,Ii,tv,Yj,ev,oB,Zj,Kj,Xj,sv,MG,pU1,dU1,cU1,re1,lU1,iU1,ov,nU1,aU1;class Gj extends EventTarget{constructor(J,Q){var Z,X;super(),e7(this,MG),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,e7(this,RZ),e7(this,L3),e7(this,Qj),e7(this,Ei),e7(this,Ii),e7(this,tv),e7(this,Yj),e7(this,ev,null),e7(this,oB),e7(this,Zj),e7(this,Kj,null),e7(this,Xj,null),e7(this,sv,null),e7(this,dU1,async(Y)=>{var K;j9(this,Zj).reset();let{body:G,redirected:q,status:z,headers:U}=Y;if(z===204){kW(this,MG,ov).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(q?j4(this,Qj,new URL(Y.url)):j4(this,Qj,void 0),z!==200){kW(this,MG,ov).call(this,`Non-200 status code (${z})`,z);return}if(!(U.get("content-type")||"").startsWith("text/event-stream")){kW(this,MG,ov).call(this,'Invalid content type, expected "text/event-stream"',z);return}if(j9(this,RZ)===this.CLOSED)return;j4(this,RZ,this.OPEN);let W=new Event("open");if((K=j9(this,sv))==null||K.call(this,W),this.dispatchEvent(W),typeof G!="object"||!G||!("getReader"in G)){kW(this,MG,ov).call(this,"Invalid response body, expected a web ReadableStream",z),this.close();return}let F=new TextDecoder,H=G.getReader(),B=!0;do{let{done:M,value:V}=await H.read();V&&j9(this,Zj).feed(F.decode(V,{stream:!M})),M&&(B=!1,j9(this,Zj).reset(),kW(this,MG,nU1).call(this))}while(B)}),e7(this,cU1,(Y)=>{j4(this,oB,void 0),!(Y.name==="AbortError"||Y.type==="aborted")&&kW(this,MG,nU1).call(this,uU1(Y))}),e7(this,lU1,(Y)=>{typeof Y.id=="string"&&j4(this,ev,Y.id);let K=new MessageEvent(Y.event||"message",{data:Y.data,origin:j9(this,Qj)?j9(this,Qj).origin:j9(this,L3).origin,lastEventId:Y.id||""});j9(this,Xj)&&(!Y.event||Y.event==="message")&&j9(this,Xj).call(this,K),this.dispatchEvent(K)}),e7(this,iU1,(Y)=>{j4(this,tv,Y)}),e7(this,aU1,()=>{j4(this,Yj,void 0),j9(this,RZ)===this.CONNECTING&&kW(this,MG,pU1).call(this)});try{if(J instanceof URL)j4(this,L3,J);else if(typeof J=="string")j4(this,L3,new URL(J,Rj6()));else throw Error("Invalid URL")}catch{throw wj6("An invalid or illegal string was specified")}j4(this,Zj,Jj({onEvent:j9(this,lU1),onRetry:j9(this,iU1)})),j4(this,RZ,this.CONNECTING),j4(this,tv,3000),j4(this,Ii,(Z=Q==null?void 0:Q.fetch)!=null?Z:globalThis.fetch),j4(this,Ei,(X=Q==null?void 0:Q.withCredentials)!=null?X:!1),kW(this,MG,pU1).call(this)}get readyState(){return j9(this,RZ)}get url(){return j9(this,L3).href}get withCredentials(){return j9(this,Ei)}get onerror(){return j9(this,Kj)}set onerror(J){j4(this,Kj,J)}get onmessage(){return j9(this,Xj)}set onmessage(J){j4(this,Xj,J)}get onopen(){return j9(this,sv)}set onopen(J){j4(this,sv,J)}addEventListener(J,Q,Z){let X=Q;super.addEventListener(J,X,Z)}removeEventListener(J,Q,Z){let X=Q;super.removeEventListener(J,X,Z)}close(){j9(this,Yj)&&clearTimeout(j9(this,Yj)),j9(this,RZ)!==this.CLOSED&&(j9(this,oB)&&j9(this,oB).abort(),j4(this,RZ,this.CLOSED),j4(this,oB,void 0))}}RZ=new WeakMap,L3=new WeakMap,Qj=new WeakMap,Ei=new WeakMap,Ii=new WeakMap,tv=new WeakMap,Yj=new WeakMap,ev=new WeakMap,oB=new WeakMap,Zj=new WeakMap,Kj=new WeakMap,Xj=new WeakMap,sv=new WeakMap,MG=new WeakSet,pU1=function(){j4(this,RZ,this.CONNECTING),j4(this,oB,new AbortController),j9(this,Ii)(j9(this,L3),kW(this,MG,re1).call(this)).then(j9(this,dU1)).catch(j9(this,cU1))},dU1=new WeakMap,cU1=new WeakMap,re1=function(){var J;let Q={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...j9(this,ev)?{"Last-Event-ID":j9(this,ev)}:void 0},cache:"no-store",signal:(J=j9(this,oB))==null?void 0:J.signal};return"window"in globalThis&&(Q.credentials=this.withCredentials?"include":"same-origin"),Q},lU1=new WeakMap,iU1=new WeakMap,ov=function(J,Q){var Z;j9(this,RZ)!==this.CLOSED&&j4(this,RZ,this.CLOSED);let X=new mU1("error",{code:Q,message:J});(Z=j9(this,Kj))==null||Z.call(this,X),this.dispatchEvent(X)},nU1=function(J,Q){var Z;if(j9(this,RZ)===this.CLOSED)return;j4(this,RZ,this.CONNECTING);let X=new mU1("error",{code:Q,message:J});(Z=j9(this,Kj))==null||Z.call(this,X),this.dispatchEvent(X),j4(this,Yj,setTimeout(j9(this,aU1),j9(this,tv)))},aU1=new WeakMap,Gj.CONNECTING=0,Gj.OPEN=1,Gj.CLOSED=2;function Rj6(){let J="document"in globalThis?globalThis.document:void 0;return J&&typeof J=="object"&&"baseURI"in J&&typeof J.baseURI=="string"?J.baseURI:void 0}vW();var sU1;sU1=globalThis.crypto?.webcrypto??globalThis.crypto??import("node:crypto").then((J)=>J.webcrypto);async function Oj6(J){return(await sU1).getRandomValues(new Uint8Array(J))}async function jj6(J){let Z="",X=await Oj6(J);for(let Y=0;Y<J;Y++){let K=X[Y]%66;Z+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[K]}return Z}async function $j6(J){return await jj6(J)}async function Ej6(J){let Q=await(await sU1).subtle.digest("SHA-256",new TextEncoder().encode(J));return btoa(String.fromCharCode(...new Uint8Array(Q))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function oU1(J){if(!J)J=43;if(J<43||J>128)throw`Expected a length between 43 and 128. Received ${J}.`;let Q=await $j6(J),Z=await Ej6(Q);return{code_verifier:Q,code_challenge:Z}}vW();LW();var oe1=Q1.object({resource:Q1.string().url(),authorization_servers:Q1.array(Q1.string().url()).optional(),jwks_uri:Q1.string().url().optional(),scopes_supported:Q1.array(Q1.string()).optional(),bearer_methods_supported:Q1.array(Q1.string()).optional(),resource_signing_alg_values_supported:Q1.array(Q1.string()).optional(),resource_name:Q1.string().optional(),resource_documentation:Q1.string().optional(),resource_policy_uri:Q1.string().url().optional(),resource_tos_uri:Q1.string().url().optional(),tls_client_certificate_bound_access_tokens:Q1.boolean().optional(),authorization_details_types_supported:Q1.array(Q1.string()).optional(),dpop_signing_alg_values_supported:Q1.array(Q1.string()).optional(),dpop_bound_access_tokens_required:Q1.boolean().optional()}).passthrough(),tU1=Q1.object({issuer:Q1.string(),authorization_endpoint:Q1.string(),token_endpoint:Q1.string(),registration_endpoint:Q1.string().optional(),scopes_supported:Q1.array(Q1.string()).optional(),response_types_supported:Q1.array(Q1.string()),response_modes_supported:Q1.array(Q1.string()).optional(),grant_types_supported:Q1.array(Q1.string()).optional(),token_endpoint_auth_methods_supported:Q1.array(Q1.string()).optional(),token_endpoint_auth_signing_alg_values_supported:Q1.array(Q1.string()).optional(),service_documentation:Q1.string().optional(),revocation_endpoint:Q1.string().optional(),revocation_endpoint_auth_methods_supported:Q1.array(Q1.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:Q1.array(Q1.string()).optional(),introspection_endpoint:Q1.string().optional(),introspection_endpoint_auth_methods_supported:Q1.array(Q1.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:Q1.array(Q1.string()).optional(),code_challenge_methods_supported:Q1.array(Q1.string()).optional()}).passthrough(),Ij6=Q1.object({issuer:Q1.string(),authorization_endpoint:Q1.string(),token_endpoint:Q1.string(),userinfo_endpoint:Q1.string().optional(),jwks_uri:Q1.string(),registration_endpoint:Q1.string().optional(),scopes_supported:Q1.array(Q1.string()).optional(),response_types_supported:Q1.array(Q1.string()),response_modes_supported:Q1.array(Q1.string()).optional(),grant_types_supported:Q1.array(Q1.string()).optional(),acr_values_supported:Q1.array(Q1.string()).optional(),subject_types_supported:Q1.array(Q1.string()),id_token_signing_alg_values_supported:Q1.array(Q1.string()),id_token_encryption_alg_values_supported:Q1.array(Q1.string()).optional(),id_token_encryption_enc_values_supported:Q1.array(Q1.string()).optional(),userinfo_signing_alg_values_supported:Q1.array(Q1.string()).optional(),userinfo_encryption_alg_values_supported:Q1.array(Q1.string()).optional(),userinfo_encryption_enc_values_supported:Q1.array(Q1.string()).optional(),request_object_signing_alg_values_supported:Q1.array(Q1.string()).optional(),request_object_encryption_alg_values_supported:Q1.array(Q1.string()).optional(),request_object_encryption_enc_values_supported:Q1.array(Q1.string()).optional(),token_endpoint_auth_methods_supported:Q1.array(Q1.string()).optional(),token_endpoint_auth_signing_alg_values_supported:Q1.array(Q1.string()).optional(),display_values_supported:Q1.array(Q1.string()).optional(),claim_types_supported:Q1.array(Q1.string()).optional(),claims_supported:Q1.array(Q1.string()).optional(),service_documentation:Q1.string().optional(),claims_locales_supported:Q1.array(Q1.string()).optional(),ui_locales_supported:Q1.array(Q1.string()).optional(),claims_parameter_supported:Q1.boolean().optional(),request_parameter_supported:Q1.boolean().optional(),request_uri_parameter_supported:Q1.boolean().optional(),require_request_uri_registration:Q1.boolean().optional(),op_policy_uri:Q1.string().optional(),op_tos_uri:Q1.string().optional()}).passthrough(),te1=Ij6.merge(tU1.pick({code_challenge_methods_supported:!0})),eU1=Q1.object({access_token:Q1.string(),id_token:Q1.string().optional(),token_type:Q1.string(),expires_in:Q1.number().optional(),scope:Q1.string().optional(),refresh_token:Q1.string().optional()}).strip(),ee1=Q1.object({error:Q1.string(),error_description:Q1.string().optional(),error_uri:Q1.string().optional()}),Pj6=Q1.object({redirect_uris:Q1.array(Q1.string()).refine((J)=>J.every((Q)=>URL.canParse(Q)),{message:"redirect_uris must contain valid URLs"}),token_endpoint_auth_method:Q1.string().optional(),grant_types:Q1.array(Q1.string()).optional(),response_types:Q1.array(Q1.string()).optional(),client_name:Q1.string().optional(),client_uri:Q1.string().optional(),logo_uri:Q1.string().optional(),scope:Q1.string().optional(),contacts:Q1.array(Q1.string()).optional(),tos_uri:Q1.string().optional(),policy_uri:Q1.string().optional(),jwks_uri:Q1.string().optional(),jwks:Q1.any().optional(),software_id:Q1.string().optional(),software_version:Q1.string().optional(),software_statement:Q1.string().optional()}).strip(),Tj6=Q1.object({client_id:Q1.string(),client_secret:Q1.string().optional(),client_id_issued_at:Q1.number().optional(),client_secret_expires_at:Q1.number().optional()}).strip(),J10=Pj6.merge(Tj6),HR9=Q1.object({error:Q1.string(),error_description:Q1.string().optional()}).strip(),BR9=Q1.object({token:Q1.string(),token_type_hint:Q1.string().optional()}).strip();function Q10(J){let Q=typeof J==="string"?new URL(J):new URL(J.href);return Q.hash="",Q}function Z10({requestedResource:J,configuredResource:Q}){let Z=typeof J==="string"?new URL(J):new URL(J.href),X=typeof Q==="string"?new URL(Q):new URL(Q.href);if(Z.origin!==X.origin)return!1;if(Z.pathname.length<X.pathname.length)return!1;let Y=Z.pathname.endsWith("/")?Z.pathname:Z.pathname+"/",K=X.pathname.endsWith("/")?X.pathname:X.pathname+"/";return Y.startsWith(K)}class J5 extends Error{constructor(J,Q){super(J);this.errorUri=Q,this.name=this.constructor.name}toResponseObject(){let J={error:this.errorCode,error_description:this.message};if(this.errorUri)J.error_uri=this.errorUri;return J}get errorCode(){return this.constructor.errorCode}}class Pi extends J5{}Pi.errorCode="invalid_request";class qj extends J5{}qj.errorCode="invalid_client";class zj extends J5{}zj.errorCode="invalid_grant";class Uj extends J5{}Uj.errorCode="unauthorized_client";class Ti extends J5{}Ti.errorCode="unsupported_grant_type";class Ci extends J5{}Ci.errorCode="invalid_scope";class Si extends J5{}Si.errorCode="access_denied";class tB extends J5{}tB.errorCode="server_error";class ki extends J5{}ki.errorCode="temporarily_unavailable";class _i extends J5{}_i.errorCode="unsupported_response_type";class xi extends J5{}xi.errorCode="unsupported_token_type";class bi extends J5{}bi.errorCode="invalid_token";class yi extends J5{}yi.errorCode="method_not_allowed";class fi extends J5{}fi.errorCode="too_many_requests";class hi extends J5{}hi.errorCode="invalid_client_metadata";class gi extends J5{}gi.errorCode="insufficient_scope";var X10={[Pi.errorCode]:Pi,[qj.errorCode]:qj,[zj.errorCode]:zj,[Uj.errorCode]:Uj,[Ti.errorCode]:Ti,[Ci.errorCode]:Ci,[Si.errorCode]:Si,[tB.errorCode]:tB,[ki.errorCode]:ki,[_i.errorCode]:_i,[xi.errorCode]:xi,[bi.errorCode]:bi,[yi.errorCode]:yi,[fi.errorCode]:fi,[hi.errorCode]:hi,[gi.errorCode]:gi};class vX extends Error{constructor(J){super(J!==null&&J!==void 0?J:"Unauthorized")}}function K10(J,Q){let Z=J.client_secret!==void 0;if(Q.length===0)return Z?"client_secret_post":"none";if(Z&&Q.includes("client_secret_basic"))return"client_secret_basic";if(Z&&Q.includes("client_secret_post"))return"client_secret_post";if(Q.includes("none"))return"none";return Z?"client_secret_post":"none"}function G10(J,Q,Z,X){let{client_id:Y,client_secret:K}=Q;switch(J){case"client_secret_basic":Cj6(Y,K,Z);return;case"client_secret_post":Sj6(Y,K,X);return;case"none":vj6(Y,X);return;default:throw Error(`Unsupported client authentication method: ${J}`)}}function Cj6(J,Q,Z){if(!Q)throw Error("client_secret_basic authentication requires a client_secret");let X=btoa(`${J}:${Q}`);Z.set("Authorization",`Basic ${X}`)}function Sj6(J,Q,Z){if(Z.set("client_id",J),Q)Z.set("client_secret",Q)}function vj6(J,Q){Q.set("client_id",J)}async function QW1(J){let Q=J instanceof Response?J.status:void 0,Z=J instanceof Response?await J.text():J;try{let X=ee1.parse(JSON.parse(Z)),{error:Y,error_description:K,error_uri:G}=X;return new(X10[Y]||tB)(K||"",G)}catch(X){let Y=`${Q?`HTTP ${Q}: `:""}Invalid OAuth error response: ${X}. Raw body: ${Z}`;return new tB(Y)}}async function eB(J,Q){var Z,X;try{return await JW1(J,Q)}catch(Y){if(Y instanceof qj||Y instanceof Uj)return await((Z=J.invalidateCredentials)===null||Z===void 0?void 0:Z.call(J,"all")),await JW1(J,Q);else if(Y instanceof zj)return await((X=J.invalidateCredentials)===null||X===void 0?void 0:X.call(J,"tokens")),await JW1(J,Q);throw Y}}async function JW1(J,{serverUrl:Q,authorizationCode:Z,scope:X,resourceMetadataUrl:Y,fetchFn:K}){let G,q;try{if(G=await _j6(Q,{resourceMetadataUrl:Y},K),G.authorization_servers&&G.authorization_servers.length>0)q=G.authorization_servers[0]}catch(V){}if(!q)q=Q;let z=await kj6(Q,J,G),U=await hj6(q,{fetchFn:K}),W=await Promise.resolve(J.clientInformation());if(!W){if(Z!==void 0)throw Error("Existing OAuth client information is required when exchanging an authorization code");if(!J.saveClientInformation)throw Error("OAuth client information must be saveable for dynamic registration");let V=await pj6(q,{metadata:U,clientMetadata:J.clientMetadata});await J.saveClientInformation(V),W=V}if(Z!==void 0){let V=await J.codeVerifier(),N=await mj6(q,{metadata:U,clientInformation:W,authorizationCode:Z,codeVerifier:V,redirectUri:J.redirectUrl,resource:z,addClientAuthentication:J.addClientAuthentication,fetchFn:K});return await J.saveTokens(N),"AUTHORIZED"}let F=await J.tokens();if(F===null||F===void 0?void 0:F.refresh_token)try{let V=await uj6(q,{metadata:U,clientInformation:W,refreshToken:F.refresh_token,resource:z,addClientAuthentication:J.addClientAuthentication});return await J.saveTokens(V),"AUTHORIZED"}catch(V){if(!(V instanceof J5)||V instanceof tB);else throw V}let H=J.state?await J.state():void 0,{authorizationUrl:B,codeVerifier:M}=await gj6(q,{metadata:U,clientInformation:W,state:H,redirectUrl:J.redirectUrl,scope:X||J.clientMetadata.scope,resource:z});return await J.saveCodeVerifier(M),await J.redirectToAuthorization(B),"REDIRECT"}async function kj6(J,Q,Z){let X=Q10(J);if(Q.validateResourceURL)return await Q.validateResourceURL(X,Z===null||Z===void 0?void 0:Z.resource);if(!Z)return;if(!Z10({requestedResource:X,configuredResource:Z.resource}))throw Error(`Protected resource ${Z.resource} does not match expected ${X} (or origin)`);return new URL(Z.resource)}function Jk(J){let Q=J.headers.get("WWW-Authenticate");if(!Q)return;let[Z,X]=Q.split(" ");if(Z.toLowerCase()!=="bearer"||!X)return;let K=/resource_metadata="([^"]*)"/.exec(Q);if(!K)return;try{return new URL(K[1])}catch(G){return}}async function _j6(J,Q,Z=fetch){let X=await yj6(J,"oauth-protected-resource",Z,{protocolVersion:Q===null||Q===void 0?void 0:Q.protocolVersion,metadataUrl:Q===null||Q===void 0?void 0:Q.resourceMetadataUrl});if(!X||X.status===404)throw Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!X.ok)throw Error(`HTTP ${X.status} trying to load well-known OAuth protected resource metadata.`);return oe1.parse(await X.json())}async function ZW1(J,Q,Z=fetch){try{return await Z(J,{headers:Q})}catch(X){if(X instanceof TypeError)if(Q)return ZW1(J,void 0,Z);else return;throw X}}function xj6(J,Q="",Z={}){if(Q.endsWith("/"))Q=Q.slice(0,-1);return Z.prependPathname?`${Q}/.well-known/${J}`:`/.well-known/${J}${Q}`}async function Y10(J,Q,Z=fetch){return await ZW1(J,{"MCP-Protocol-Version":Q},Z)}function bj6(J,Q){return!J||J.status===404&&Q!=="/"}async function yj6(J,Q,Z,X){var Y,K;let G=new URL(J),q=(Y=X===null||X===void 0?void 0:X.protocolVersion)!==null&&Y!==void 0?Y:tO,z;if(X===null||X===void 0?void 0:X.metadataUrl)z=new URL(X.metadataUrl);else{let W=xj6(Q,G.pathname);z=new URL(W,(K=X===null||X===void 0?void 0:X.metadataServerUrl)!==null&&K!==void 0?K:G),z.search=G.search}let U=await Y10(z,q,Z);if(!(X===null||X===void 0?void 0:X.metadataUrl)&&bj6(U,G.pathname)){let W=new URL(`/.well-known/${Q}`,G);U=await Y10(W,q,Z)}return U}function fj6(J){let Q=typeof J==="string"?new URL(J):J,Z=Q.pathname!=="/",X=[];if(!Z)return X.push({url:new URL("/.well-known/oauth-authorization-server",Q.origin),type:"oauth"}),X.push({url:new URL("/.well-known/openid-configuration",Q.origin),type:"oidc"}),X;let Y=Q.pathname;if(Y.endsWith("/"))Y=Y.slice(0,-1);return X.push({url:new URL(`/.well-known/oauth-authorization-server${Y}`,Q.origin),type:"oauth"}),X.push({url:new URL("/.well-known/oauth-authorization-server",Q.origin),type:"oauth"}),X.push({url:new URL(`/.well-known/openid-configuration${Y}`,Q.origin),type:"oidc"}),X.push({url:new URL(`${Y}/.well-known/openid-configuration`,Q.origin),type:"oidc"}),X}async function hj6(J,{fetchFn:Q=fetch,protocolVersion:Z=tO}={}){var X;let Y={"MCP-Protocol-Version":Z},K=fj6(J);for(let{url:G,type:q}of K){let z=await ZW1(G,Y,Q);if(!z)continue;if(!z.ok){if(z.status>=400&&z.status<500)continue;throw Error(`HTTP ${z.status} trying to load ${q==="oauth"?"OAuth":"OpenID provider"} metadata from ${G}`)}if(q==="oauth")return tU1.parse(await z.json());else{let U=te1.parse(await z.json());if(!((X=U.code_challenge_methods_supported)===null||X===void 0?void 0:X.includes("S256")))throw Error(`Incompatible OIDC provider at ${G}: does not support S256 code challenge method required by MCP specification`);return U}}return}async function gj6(J,{metadata:Q,clientInformation:Z,redirectUrl:X,scope:Y,state:K,resource:G}){let U;if(Q){if(U=new URL(Q.authorization_endpoint),!Q.response_types_supported.includes("code"))throw Error("Incompatible auth server: does not support response type code");if(!Q.code_challenge_methods_supported||!Q.code_challenge_methods_supported.includes("S256"))throw Error("Incompatible auth server: does not support code challenge method S256")}else U=new URL("/authorize",J);let W=await oU1(),F=W.code_verifier,H=W.code_challenge;if(U.searchParams.set("response_type","code"),U.searchParams.set("client_id",Z.client_id),U.searchParams.set("code_challenge",H),U.searchParams.set("code_challenge_method","S256"),U.searchParams.set("redirect_uri",String(X)),K)U.searchParams.set("state",K);if(Y)U.searchParams.set("scope",Y);if(Y===null||Y===void 0?void 0:Y.includes("offline_access"))U.searchParams.append("prompt","consent");if(G)U.searchParams.set("resource",G.href);return{authorizationUrl:U,codeVerifier:F}}async function mj6(J,{metadata:Q,clientInformation:Z,authorizationCode:X,codeVerifier:Y,redirectUri:K,resource:G,addClientAuthentication:q,fetchFn:z}){var U;let W="authorization_code",F=(Q===null||Q===void 0?void 0:Q.token_endpoint)?new URL(Q.token_endpoint):new URL("/token",J);if((Q===null||Q===void 0?void 0:Q.grant_types_supported)&&!Q.grant_types_supported.includes("authorization_code"))throw Error("Incompatible auth server: does not support grant type authorization_code");let H=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"}),B=new URLSearchParams({grant_type:"authorization_code",code:X,code_verifier:Y,redirect_uri:String(K)});if(q)q(H,B,J,Q);else{let V=(U=Q===null||Q===void 0?void 0:Q.token_endpoint_auth_methods_supported)!==null&&U!==void 0?U:[],N=K10(Z,V);G10(N,Z,H,B)}if(G)B.set("resource",G.href);let M=await(z!==null&&z!==void 0?z:fetch)(F,{method:"POST",headers:H,body:B});if(!M.ok)throw await QW1(M);return eU1.parse(await M.json())}async function uj6(J,{metadata:Q,clientInformation:Z,refreshToken:X,resource:Y,addClientAuthentication:K,fetchFn:G}){var q;let z="refresh_token",U;if(Q){if(U=new URL(Q.token_endpoint),Q.grant_types_supported&&!Q.grant_types_supported.includes("refresh_token"))throw Error("Incompatible auth server: does not support grant type refresh_token")}else U=new URL("/token",J);let W=new Headers({"Content-Type":"application/x-www-form-urlencoded"}),F=new URLSearchParams({grant_type:"refresh_token",refresh_token:X});if(K)K(W,F,J,Q);else{let B=(q=Q===null||Q===void 0?void 0:Q.token_endpoint_auth_methods_supported)!==null&&q!==void 0?q:[],M=K10(Z,B);G10(M,Z,W,F)}if(Y)F.set("resource",Y.href);let H=await(G!==null&&G!==void 0?G:fetch)(U,{method:"POST",headers:W,body:F});if(!H.ok)throw await QW1(H);return eU1.parse({refresh_token:X,...await H.json()})}async function pj6(J,{metadata:Q,clientMetadata:Z,fetchFn:X}){let Y;if(Q){if(!Q.registration_endpoint)throw Error("Incompatible auth server: does not support dynamic client registration");Y=new URL(Q.registration_endpoint)}else Y=new URL("/register",J);let K=await(X!==null&&X!==void 0?X:fetch)(Y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!K.ok)throw await QW1(K);return J10.parse(await K.json())}class q10 extends Error{constructor(J,Q,Z){super(`SSE error: ${Q}`);this.code=J,this.event=Z}}class XW1{constructor(J,Q){this._url=J,this._resourceMetadataUrl=void 0,this._eventSourceInit=Q===null||Q===void 0?void 0:Q.eventSourceInit,this._requestInit=Q===null||Q===void 0?void 0:Q.requestInit,this._authProvider=Q===null||Q===void 0?void 0:Q.authProvider,this._fetch=Q===null||Q===void 0?void 0:Q.fetch}async _authThenStart(){var J;if(!this._authProvider)throw new vX("No auth provider");let Q;try{Q=await eB(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(Z){throw(J=this.onerror)===null||J===void 0||J.call(this,Z),Z}if(Q!=="AUTHORIZED")throw new vX;return await this._startOrAuth()}async _commonHeaders(){var J;let Q={};if(this._authProvider){let Z=await this._authProvider.tokens();if(Z)Q.Authorization=`Bearer ${Z.access_token}`}if(this._protocolVersion)Q["mcp-protocol-version"]=this._protocolVersion;return new Headers({...Q,...(J=this._requestInit)===null||J===void 0?void 0:J.headers})}_startOrAuth(){var J,Q,Z;let X=(Z=(Q=(J=this===null||this===void 0?void 0:this._eventSourceInit)===null||J===void 0?void 0:J.fetch)!==null&&Q!==void 0?Q:this._fetch)!==null&&Z!==void 0?Z:fetch;return new Promise((Y,K)=>{this._eventSource=new Gj(this._url.href,{...this._eventSourceInit,fetch:async(G,q)=>{let z=await this._commonHeaders();z.set("Accept","text/event-stream");let U=await X(G,{...q,headers:z});if(U.status===401&&U.headers.has("www-authenticate"))this._resourceMetadataUrl=Jk(U);return U}}),this._abortController=new AbortController,this._eventSource.onerror=(G)=>{var q;if(G.code===401&&this._authProvider){this._authThenStart().then(Y,K);return}let z=new q10(G.code,G.message,G);K(z),(q=this.onerror)===null||q===void 0||q.call(this,z)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",(G)=>{var q;let z=G;try{if(this._endpoint=new URL(z.data,this._url),this._endpoint.origin!==this._url.origin)throw Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(U){K(U),(q=this.onerror)===null||q===void 0||q.call(this,U),this.close();return}Y()}),this._eventSource.onmessage=(G)=>{var q,z;let U=G,W;try{W=nB.parse(JSON.parse(U.data))}catch(F){(q=this.onerror)===null||q===void 0||q.call(this,F);return}(z=this.onmessage)===null||z===void 0||z.call(this,W)}})}async start(){if(this._eventSource)throw Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(J){if(!this._authProvider)throw new vX("No auth provider");if(await eB(this._authProvider,{serverUrl:this._url,authorizationCode:J,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new vX("Failed to authorize")}async close(){var J,Q,Z;(J=this._abortController)===null||J===void 0||J.abort(),(Q=this._eventSource)===null||Q===void 0||Q.close(),(Z=this.onclose)===null||Z===void 0||Z.call(this)}async send(J){var Q,Z,X;if(!this._endpoint)throw Error("Not connected");try{let Y=await this._commonHeaders();Y.set("content-type","application/json");let K={...this._requestInit,method:"POST",headers:Y,body:JSON.stringify(J),signal:(Q=this._abortController)===null||Q===void 0?void 0:Q.signal},G=await((Z=this._fetch)!==null&&Z!==void 0?Z:fetch)(this._endpoint,K);if(!G.ok){if(G.status===401&&this._authProvider){if(this._resourceMetadataUrl=Jk(G),await eB(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new vX;return this.send(J)}let q=await G.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${G.status}): ${q}`)}}catch(Y){throw(X=this.onerror)===null||X===void 0||X.call(this,Y),Y}}setProtocolVersion(J){this._protocolVersion=J}}vW();$i();class YW1 extends TransformStream{constructor({onError:J,onRetry:Q,onComment:Z}={}){let X;super({start(Y){X=Jj({onEvent:(K)=>{Y.enqueue(K)},onError(K){J==="terminate"?Y.error(K):typeof J=="function"&&J(K)},onRetry:Q,onComment:Z})},transform(Y){X.feed(Y)}})}}var dj6={initialReconnectionDelay:1000,maxReconnectionDelay:30000,reconnectionDelayGrowFactor:1.5,maxRetries:2};class mi extends Error{constructor(J,Q){super(`Streamable HTTP error: ${Q}`);this.code=J}}class KW1{constructor(J,Q){var Z;this._url=J,this._resourceMetadataUrl=void 0,this._requestInit=Q===null||Q===void 0?void 0:Q.requestInit,this._authProvider=Q===null||Q===void 0?void 0:Q.authProvider,this._fetch=Q===null||Q===void 0?void 0:Q.fetch,this._sessionId=Q===null||Q===void 0?void 0:Q.sessionId,this._reconnectionOptions=(Z=Q===null||Q===void 0?void 0:Q.reconnectionOptions)!==null&&Z!==void 0?Z:dj6}async _authThenStart(){var J;if(!this._authProvider)throw new vX("No auth provider");let Q;try{Q=await eB(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})}catch(Z){throw(J=this.onerror)===null||J===void 0||J.call(this,Z),Z}if(Q!=="AUTHORIZED")throw new vX;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){var J;let Q={};if(this._authProvider){let X=await this._authProvider.tokens();if(X)Q.Authorization=`Bearer ${X.access_token}`}if(this._sessionId)Q["mcp-session-id"]=this._sessionId;if(this._protocolVersion)Q["mcp-protocol-version"]=this._protocolVersion;let Z=this._normalizeHeaders((J=this._requestInit)===null||J===void 0?void 0:J.headers);return new Headers({...Q,...Z})}async _startOrAuthSse(J){var Q,Z,X;let{resumptionToken:Y}=J;try{let K=await this._commonHeaders();if(K.set("Accept","text/event-stream"),Y)K.set("last-event-id",Y);let G=await((Q=this._fetch)!==null&&Q!==void 0?Q:fetch)(this._url,{method:"GET",headers:K,signal:(Z=this._abortController)===null||Z===void 0?void 0:Z.signal});if(!G.ok){if(G.status===401&&this._authProvider)return await this._authThenStart();if(G.status===405)return;throw new mi(G.status,`Failed to open SSE stream: ${G.statusText}`)}this._handleSseStream(G.body,J,!0)}catch(K){throw(X=this.onerror)===null||X===void 0||X.call(this,K),K}}_getNextReconnectionDelay(J){let Q=this._reconnectionOptions.initialReconnectionDelay,Z=this._reconnectionOptions.reconnectionDelayGrowFactor,X=this._reconnectionOptions.maxReconnectionDelay;return Math.min(Q*Math.pow(Z,J),X)}_normalizeHeaders(J){if(!J)return{};if(J instanceof Headers)return Object.fromEntries(J.entries());if(Array.isArray(J))return Object.fromEntries(J);return{...J}}_scheduleReconnection(J,Q=0){var Z;let X=this._reconnectionOptions.maxRetries;if(X>0&&Q>=X){(Z=this.onerror)===null||Z===void 0||Z.call(this,Error(`Maximum reconnection attempts (${X}) exceeded.`));return}let Y=this._getNextReconnectionDelay(Q);setTimeout(()=>{this._startOrAuthSse(J).catch((K)=>{var G;(G=this.onerror)===null||G===void 0||G.call(this,Error(`Failed to reconnect SSE stream: ${K instanceof Error?K.message:String(K)}`)),this._scheduleReconnection(J,Q+1)})},Y)}_handleSseStream(J,Q,Z){if(!J)return;let{onresumptiontoken:X,replayMessageId:Y}=Q,K;(async()=>{var q,z,U,W;try{let F=J.pipeThrough(new TextDecoderStream).pipeThrough(new YW1).getReader();while(!0){let{value:H,done:B}=await F.read();if(B)break;if(H.id)K=H.id,X===null||X===void 0||X(H.id);if(!H.event||H.event==="message")try{let M=nB.parse(JSON.parse(H.data));if(Y!==void 0&&iv(M))M.id=Y;(q=this.onmessage)===null||q===void 0||q.call(this,M)}catch(M){(z=this.onerror)===null||z===void 0||z.call(this,M)}}}catch(F){if((U=this.onerror)===null||U===void 0||U.call(this,Error(`SSE stream disconnected: ${F}`)),Z&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:K,onresumptiontoken:X,replayMessageId:Y},0)}catch(H){(W=this.onerror)===null||W===void 0||W.call(this,Error(`Failed to reconnect: ${H instanceof Error?H.message:String(H)}`))}}})()}async start(){if(this._abortController)throw Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(J){if(!this._authProvider)throw new vX("No auth provider");if(await eB(this._authProvider,{serverUrl:this._url,authorizationCode:J,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new vX("Failed to authorize")}async close(){var J,Q;(J=this._abortController)===null||J===void 0||J.abort(),(Q=this.onclose)===null||Q===void 0||Q.call(this)}async send(J,Q){var Z,X,Y,K;try{let{resumptionToken:G,onresumptiontoken:q}=Q||{};if(G){this._startOrAuthSse({resumptionToken:G,replayMessageId:Ji(J)?J.id:void 0}).catch((V)=>{var N;return(N=this.onerror)===null||N===void 0?void 0:N.call(this,V)});return}let z=await this._commonHeaders();z.set("content-type","application/json"),z.set("accept","application/json, text/event-stream");let U={...this._requestInit,method:"POST",headers:z,body:JSON.stringify(J),signal:(Z=this._abortController)===null||Z===void 0?void 0:Z.signal},W=await((X=this._fetch)!==null&&X!==void 0?X:fetch)(this._url,U),F=W.headers.get("mcp-session-id");if(F)this._sessionId=F;if(!W.ok){if(W.status===401&&this._authProvider){if(this._resourceMetadataUrl=Jk(W),await eB(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,fetchFn:this._fetch})!=="AUTHORIZED")throw new vX;return this.send(J)}let V=await W.text().catch(()=>null);throw Error(`Error POSTing to endpoint (HTTP ${W.status}): ${V}`)}if(W.status===202){if(ho1(J))this._startOrAuthSse({resumptionToken:void 0}).catch((V)=>{var N;return(N=this.onerror)===null||N===void 0?void 0:N.call(this,V)});return}let B=(Array.isArray(J)?J:[J]).filter((V)=>("method"in V)&&("id"in V)&&V.id!==void 0).length>0,M=W.headers.get("content-type");if(B)if(M===null||M===void 0?void 0:M.includes("text/event-stream"))this._handleSseStream(W.body,{onresumptiontoken:q},!1);else if(M===null||M===void 0?void 0:M.includes("application/json")){let V=await W.json(),N=Array.isArray(V)?V.map((L)=>nB.parse(L)):[nB.parse(V)];for(let L of N)(Y=this.onmessage)===null||Y===void 0||Y.call(this,L)}else throw new mi(-1,`Unexpected content type: ${M}`)}catch(G){throw(K=this.onerror)===null||K===void 0||K.call(this,G),G}}get sessionId(){return this._sessionId}async terminateSession(){var J,Q,Z;if(!this._sessionId)return;try{let X=await this._commonHeaders(),Y={...this._requestInit,method:"DELETE",headers:X,signal:(J=this._abortController)===null||J===void 0?void 0:J.signal},K=await((Q=this._fetch)!==null&&Q!==void 0?Q:fetch)(this._url,Y);if(!K.ok&&K.status!==405)throw new mi(K.status,`Failed to terminate session: ${K.statusText}`);this._sessionId=void 0}catch(X){throw(Z=this.onerror)===null||Z===void 0||Z.call(this,X),X}}setProtocolVersion(J){this._protocolVersion=J}get protocolVersion(){return this._protocolVersion}}vW();b6();C0();G0();Bj();zW1();_X();ri();function si(J,Q){for(let Z of J??[])if(ai(G$6(Q),Z.matches))return Z.action==="allow";return!0}function G$6(J){if("command"in J)return{command:J.command,args:J.args?.join(" "),env:J.env};return J}vW();G0();x5();W2();var G20=d2.CLAUDE_3_5_SONNET.name;function q20(J,Q,Z){J.setRequestHandler(FU1,async(X,Y)=>{try{u.info("MCP sampling request:",X,Y);let K=X.params.messages.map((q)=>({role:q.role,content:[{type:"text",text:String(q.content.text||"")}]})),G=await nj(K,[],X.params.systemPrompt?[{type:"text",text:X.params.systemPrompt}]:[],Q,{configService:Z.configService},void 0,void 0);if(G.message){let q=G.message.content.find((z)=>z.type==="text");if(q&&q.type==="text")return{content:{type:"text",text:q.text},model:G.message.model,role:"assistant"}}return u.error("MCP sampling missing result"),{content:{type:"text",text:"No response generated"},model:G20,role:"assistant"}}catch(K){return u.error("MCP sampling failed:",K),{content:{type:"text",text:"Error generating response"},model:G20,role:"assistant"}}})}var YB1=di,G40=new WeakMap;function af6(J){return J.map((Q)=>{if(Q.type==="text"){let Z=_2.bufferByteLengthCompat(Q.text);if(Z>YB1){let X=_2.utf8Clamp(Q.text,YB1),Y=Math.round(Z/1024);return{type:"text",text:`${X}
|
|
4732
4732
|
|
|
4733
|
-
... [Tool result truncated - showing first ${Math.round(YB1/1024)}KB of ${Y}KB total. The tool result was too long and has been shortened. Consider using more specific queries or parameters to get focused results.]`}}}return Q})}var KJ=Symbol.for("disabled-client"),ba={clientInfo:{name:"amp-mcp-client",version:"0.0.0-dev"},capabilities:{sampling:{},prompts:{listChanged:!0}}};function ya(J,Q,Z,X,Y){let K=new rv(ba.clientInfo,{capabilities:ba.capabilities}),G=e1.of(void 0).pipe(bN(()=>NS(d6(async()=>{if(await K.close(),await new Promise((N)=>setTimeout(N,100)),Z)return KJ;let V=await sf6(J,K,Q,X,Y);if("url"in J&&V.transportInfo)G40.set(V.client,V.transportInfo);return V.client}),$Y).pipe(YG((V)=>{if(V instanceof rv)V?.close()})),{shouldCountRefs:!0})),q=G.subscribe({}),z=G.pipe(k0((V)=>{if(V===KJ)return{type:"disabled"};if(V===vJ)return{type:"connecting"};if(V instanceof Error){let N=V;return{type:"connection-failed",error:{message:N.message,stderr:N.stderr}}}return{type:"connected",capabilities:V.getServerCapabilities(),serverInfo:V.getServerVersion()}})),U=G.pipe(q8((V)=>{if(V===vJ||V instanceof Error||V===KJ)return e1.of(V);let N=new b8;return V.setNotificationHandler(WU1,()=>{N.next()}),N.pipe(hd({onUnsubscribe:()=>V.removeNotificationHandler("notifications/tools/list_changed")}),v2(void 0),k0(()=>V))})),W=G.pipe(q8((V)=>{if(V===vJ||V instanceof Error||V===KJ)return e1.of(V);let N=new b8;return V.setNotificationHandler(ZU1,()=>{N.next()}),N.pipe(hd({onUnsubscribe:()=>V.removeNotificationHandler("notifications/resources/list_changed")}),v2(void 0),k0(()=>V))})),F=U.pipe(bN((V)=>{if(V instanceof Error)return e1.of(V);if(V===KJ)return e1.of([]);return d6(async(N)=>{return(await V.listTools({signal:N})).tools})})),B=G.pipe(q8((V)=>{if(V===vJ||V instanceof Error||V===KJ)return e1.of(V);let N=new b8;return V.setNotificationHandler(zU1,()=>{N.next()}),N.pipe(hd({onUnsubscribe:()=>V.removeNotificationHandler("notifications/prompts/list_changed")}),v2(void 0),k0(()=>V))})).pipe(bN((V)=>{if(V instanceof Error)return e1.of(V);if(V===KJ)return e1.of([]);return d6(async(N)=>{if(!V.getServerCapabilities()?.prompts)return[];return(await V.listPrompts({signal:N})).prompts})})),M=W.pipe(bN((V)=>{if(V instanceof Error)return e1.of(V);if(V===KJ)return e1.of([]);return d6(async(N)=>{if(!V.getServerCapabilities()?.resources)return[];return(await V.listResources({signal:N})).resources})}));return{status:z,tools:F,resources:M,prompts:B,async callTool(V,N,L){let A=await LS(G);if(A===KJ)throw Error("cannot call tools for disabled client");let w=Y?G40.get(A):void 0;q20(A,N.thread,{configService:N.configService});let R=await A.callTool(V,void 0,{signal:L,timeout:999999000});if(!("content"in R))throw Error("unexpected response");if(
|
|
4733
|
+
... [Tool result truncated - showing first ${Math.round(YB1/1024)}KB of ${Y}KB total. The tool result was too long and has been shortened. Consider using more specific queries or parameters to get focused results.]`}}}return Q})}var KJ=Symbol.for("disabled-client"),ba={clientInfo:{name:"amp-mcp-client",version:"0.0.0-dev"},capabilities:{sampling:{},prompts:{listChanged:!0}}};function ya(J,Q,Z,X,Y){let K=new rv(ba.clientInfo,{capabilities:ba.capabilities}),G=e1.of(void 0).pipe(bN(()=>NS(d6(async()=>{if(await K.close(),await new Promise((N)=>setTimeout(N,100)),Z)return KJ;let V=await sf6(J,K,Q,X,Y);if("url"in J&&V.transportInfo)G40.set(V.client,V.transportInfo);return V.client}),$Y).pipe(YG((V)=>{if(V instanceof rv)V?.close()})),{shouldCountRefs:!0})),q=G.subscribe({}),z=G.pipe(k0((V)=>{if(V===KJ)return{type:"disabled"};if(V===vJ)return{type:"connecting"};if(V instanceof Error){let N=V;return{type:"connection-failed",error:{message:N.message,stderr:N.stderr}}}return{type:"connected",capabilities:V.getServerCapabilities(),serverInfo:V.getServerVersion()}})),U=G.pipe(q8((V)=>{if(V===vJ||V instanceof Error||V===KJ)return e1.of(V);let N=new b8;return V.setNotificationHandler(WU1,()=>{N.next()}),N.pipe(hd({onUnsubscribe:()=>V.removeNotificationHandler("notifications/tools/list_changed")}),v2(void 0),k0(()=>V))})),W=G.pipe(q8((V)=>{if(V===vJ||V instanceof Error||V===KJ)return e1.of(V);let N=new b8;return V.setNotificationHandler(ZU1,()=>{N.next()}),N.pipe(hd({onUnsubscribe:()=>V.removeNotificationHandler("notifications/resources/list_changed")}),v2(void 0),k0(()=>V))})),F=U.pipe(bN((V)=>{if(V instanceof Error)return e1.of(V);if(V===KJ)return e1.of([]);return d6(async(N)=>{return(await V.listTools({signal:N})).tools})})),B=G.pipe(q8((V)=>{if(V===vJ||V instanceof Error||V===KJ)return e1.of(V);let N=new b8;return V.setNotificationHandler(zU1,()=>{N.next()}),N.pipe(hd({onUnsubscribe:()=>V.removeNotificationHandler("notifications/prompts/list_changed")}),v2(void 0),k0(()=>V))})).pipe(bN((V)=>{if(V instanceof Error)return e1.of(V);if(V===KJ)return e1.of([]);return d6(async(N)=>{if(!V.getServerCapabilities()?.prompts)return[];return(await V.listPrompts({signal:N})).prompts})})),M=W.pipe(bN((V)=>{if(V instanceof Error)return e1.of(V);if(V===KJ)return e1.of([]);return d6(async(N)=>{if(!V.getServerCapabilities()?.resources)return[];return(await V.listResources({signal:N})).resources})}));return{status:z,tools:F,resources:M,prompts:B,async callTool(V,N,L){let A=await LS(G);if(A===KJ)throw Error("cannot call tools for disabled client");let w=Y?G40.get(A):void 0;q20(A,N.thread,{configService:N.configService});let R=await A.callTool(V,void 0,{signal:L,timeout:999999000});if(!("content"in R))throw Error("unexpected response");if(w)try{w3({feature:"mcp.tool_usage",action:"remote_tool_called",metadata:{url:w.url,transport:w.type,toolName:V.name,threadId:N.thread.id}})}catch(O){u.debug("Failed to record MCP tool usage telemetry",{error:O})}return af6(R.content)},async listResources(V,N){let L=await LS(G);if(L===KJ)throw Error("cannot list resources for disabled client");if(!L.getServerCapabilities()?.resources)return[];return(await L.listResources(V,{signal:N,timeout:999999000})).resources},async readResource(V,N){let L=await LS(G);if(L===KJ)throw Error("cannot read resource for disabled client");return(await L.readResource(V,{signal:N,timeout:999999000})).contents},async getPrompt(V,N,L){let A=await LS(G);if(A===KJ)return null;try{return await A.getPrompt({name:V,arguments:N},{signal:L,timeout:999999000})}catch(w){return null}},async dispose(){q.unsubscribe();try{await K.close()}catch(V){u.error("Error closing MCP client:",V)}}}}function q40(J){let Q=new URL(J.toString());Q.username="",Q.password="",Q.hash="";let Z=["token","key","api_key","apikey","access_token","secret","password","auth","authorization","bearer","jwt","session","sessionid","sid"];for(let X of Array.from(Q.searchParams.keys())){let Y=X.toLowerCase();if(Z.some((K)=>Y.includes(K))){let K=Q.searchParams.getAll(X);Q.searchParams.delete(X);for(let G=0;G<K.length;G++)Q.searchParams.append(X,"[REDACTED]")}}return Q.toString()}async function rf6(J,Q,Z,X){let Y=Q?{headers:Q}:void 0;try{let K=new KW1(J,Y?{requestInit:Y}:void 0),G=Z.connect(K);G.catch(()=>{}),await Promise.race([G,KB1()]),u.debug("Connected using StreamableHTTPClientTransport");let q=q40(J);try{w3({feature:"mcp.connection",action:"remote_connected",metadata:{url:q,transport:"StreamableHTTPClientTransport"}})}catch(z){u.debug("Failed to record MCP connection telemetry",{error:z})}return{client:Z,transportInfo:{type:"StreamableHTTPClientTransport",url:q}}}catch(K){u.debug("StreamableHTTPClientTransport failed, falling back to SSE");try{await Z.close()}catch{}let G=new rv(ba.clientInfo,{capabilities:ba.capabilities}),q=new XW1(J,Y?{requestInit:Y}:void 0),z=G.connect(q);z.catch(()=>{}),await Promise.race([z,KB1()]),u.debug("Connected using SSEClientTransport");let U=q40(J);try{w3({feature:"mcp.connection",action:"remote_connected",metadata:{url:U,transport:"SSEClientTransport"}})}catch(W){u.debug("Failed to record MCP connection telemetry",{error:W})}return{client:G,transportInfo:{type:"SSEClientTransport",url:U}}}}async function sf6(J,Q,Z,X,Y){if(!si(X,J))throw Error("MCP server is not allowed by MCP permissions");let K;if("url"in J){let q=T_(J.url,process.env),z=J.headers?Object.entries(J.headers).reduce((W,[F,H])=>({...W,[F]:T_(H,process.env)}),{}):void 0,U=new URL(q);return await rf6(U,z,Q,Y)}else{let{loadProfileEnvironmentVariables:q}=await Promise.resolve().then(() => (nH1(),U20)),z=Z.loadProfile==="never"||!Z.workingDirectory||!MB(Z.workingDirectory)?process.env:await G6(q(Z.workingDirectory.fsPath,Z.loadProfile)),U=J.env?Object.entries(J.env).reduce((B,[M,V])=>({...B,[M]:T_(V,z)}),{}):void 0,W=of6({...z,...U}),F=T_(J.command,W),H=J.args?J.args.map((B)=>T_(B,W)):void 0;K=await Promise.resolve().then(() => (K40(),Y40)).then(({StdioClientTransport:B})=>{return new B({command:F,args:H,stderr:"pipe",cwd:Z.workingDirectory&&MB(Z.workingDirectory)?Z.workingDirectory.fsPath:void 0,env:W})})}let G=[];if("stderr"in K&&K.stderr&&typeof K.stderr==="object"&&K.stderr!==null&&"on"in K.stderr&&typeof K.stderr.on==="function")K.stderr.on("data",(q)=>{let z=q.toString().trim();if(z){if(G.push(z),G.length>50)G=["[...]",...G.slice(-49)];u.info("mcp-server-stderr",{stderr:z,server:{type:"stdio"}})}});try{let q=Q.connect(K);return q.catch(()=>{}),await Promise.race([q,KB1()]),{client:Q}}catch(q){let z=(U)=>{let W=Error(U);if(G.length>0)W.stderr=G.join(`
|
|
4734
4734
|
`);return W};if(q instanceof Error){if(q.message.includes("Connection closed"))throw z("MCP server connection was closed unexpectedly.");else if(q.message.includes("Invalid content type"))throw z('SSE error: Invalid content type, expected "text/event-stream". Check that the URL is correct and points to a valid MCP SSE endpoint. The server must respond with Content-Type: text/event-stream header.');else if("url"in J&&q.message.includes("fetch failed"))throw z(`Could not connect to MCP server at ${J.url}. Check that the server is running and accessible.`);else if(G.length>0)throw z(q.message)}throw q}}function KB1(){return new Promise((J,Q)=>{let Z=setTimeout(()=>{clearTimeout(Z),Q(Error("Connection timeout: MCP server did not respond within 60 seconds"))},60000)})}function T_(J,Q){return J.replace(/\$\{([^}]+)\}/g,(Z,X)=>{let Y=Q[X];if(Y===void 0)return u.warn(`Environment variable ${X} is not defined`),Z;return Y})}function of6(J){let{AMP_API_KEY:Q,...Z}=J;return Z}async function U40(J){let Q=tf6(J),Z=JSON.stringify(Q);if(typeof globalThis.crypto<"u"&&globalThis.crypto.subtle){let K=new TextEncoder().encode(Z),G=await globalThis.crypto.subtle.digest("SHA-256",K);return Array.from(new Uint8Array(G)).map((z)=>z.toString(16).padStart(2,"0")).join("")}let{createHash:X}=await import("node:crypto");return X("sha256").update(Z).digest("hex")}function tf6(J){if("command"in J)return{type:"command",command:J.command,args:J.args||[],env:z40(J.env||{})};return{type:"url",url:J.url,headers:z40(J.headers||{}),transport:J.transport||"http"}}function z40(J){let Q={};for(let Z of Object.keys(J).sort())Q[Z]=J[Z];return Q}C0();class GB1{async isTrusted(J){return!0}async setTrust(J,Q){}isWorkspaceTrusted(){return e1.of(!0)}}function F40({configService:J,toolService:Q,externalMCPServers:Z=e1.of({}),trustStore:X=new GB1}){let Y=new H40,K=new b8,G,q=b9(J.config,Z).pipe(k0(([{settings:{mcpServers:j,mcpPermissions:$,"terminal.commands.nodeSpawn.loadProfile":E,"security.audit.logMcpConnections":I}},T])=>({mcpServers:j,mcpPermissions:$,loadProfile:E,logMcpConnections:I,externalMCPServers:T})),J8()),z=J.workspaceRoots.pipe(k0((j)=>j?.at(0))),U=new Map,W,F=b9(q,z,K.pipe(v2(void 0))).pipe(KG(300),q8(([{mcpServers:j,mcpPermissions:$,loadProfile:E,logMcpConnections:I,externalMCPServers:T},S,x])=>d6(async(h)=>{let v=Y.consume(),_={...j,...T},b=Jh6(W,$);W=$;for(let[g,k]of Object.entries(_)){let y=U.get(g);if(!v&&y&&ef6(y.spec,k)&&b)continue;let f=k._target==="workspace",m=await U40(k),n=!1,p;if(f){let e={serverName:g,specHash:m};if(!await X.isTrusted(e)){if(p=ya(k,{workingDirectory:S,loadProfile:E},!0,$,I),n=!0,u.info(`MCP server ${g} requires approval before execution`,{specHash:m}),!await X.hasEntry?.(e))G?.(g,k)}else p=ya(k,{workingDirectory:S,loadProfile:E},!1,$,I)}else p=ya(k,{workingDirectory:S,loadProfile:E},!1,$,I);if(U.set(g,{spec:k,client:p,isExternal:Boolean(T[g]),requiresApproval:n,specHash:m}),y)await y.client.dispose()}for(let[g,{client:k}]of U.entries())if(!_||!(g in _))await k.dispose(),U.delete(g);return Array.from(U.entries())})),M9({shouldCountRefs:!1})),H=F.subscribe({}),B=new Map,M=30000,V=(j)=>{if(j)B.delete(j);else B.clear()},N=F.pipe(q8((j)=>j.length===0?e1.of(!0):b9(...j.map(([$,{client:E}])=>E.tools.pipe(T5((I)=>I!==vJ&&I!==KJ),xN(1)))).pipe(k0(()=>!0))),xN(1)),L=b9(F.pipe(q8((j)=>j.length===0?e1.of([]):b9(...j.map(([$,{spec:E,client:I}])=>I.tools.pipe(k0((T)=>({name:$,spec:E,tools:T===vJ||T instanceof Error||T===KJ?[]:T,client:I}))))))),J.config.pipe(k0((j)=>j.settings.mcpPermissions),J8())).pipe(k0(([j,$])=>({mcpServers:j,mcpPermissions:$}))),A,w=L.subscribe(({mcpServers:j,mcpPermissions:$})=>{if(A)for(let I of A)I.dispose();A=[];let E=[];for(let{name:I,spec:T,tools:S,client:x}of j){if(!si($,T)){if(S.length>0)u.error(`Ignoring ${S.length} tools from MCP server ${I} due to MCP permissions`);else u.debug(`Ignoring tools from MCP server ${I} due to MCP permissions`);continue}for(let h of S){u.debug("mcpService.toolRegisterer",{name:h.name});try{let v=W40(h,x,I);A.push(Q.registerTool(v)),E.push(v.spec.name)}catch(v){u.warn(`Failed to register MCP tool ${h.name} from ${I}:`,v)}}}if(E.length>0)G6(Q.tools.pipe(k0((I)=>E.every((T)=>I.some((S)=>S.spec.name===T))),T5(Boolean),xN(1)),AbortSignal.timeout(5000)).then(()=>{u.debug("mcpService.toolsRegistered",{registeredCount:E.length})}).catch((I)=>{u.warn("Failed to verify tool registration:",I)})},(j)=>{u.error("MCP toolRegisterer error",j)}),R=new Promise((j)=>{try{G6(N,AbortSignal.timeout(1e4)).then(()=>{u.info("mcpService.initialized",{value:Array.from(U.keys())}),j()}).catch(($)=>{u.warn("MCP service initialization failed, but service will continue:",$),j()})}catch($){u.warn("MCP service initialization failed, but service will continue:",$),j()}}),O=b9(J.config,F).pipe(q8(([j,$])=>$.length===0?e1.of([]):b9(...$.map(([E,{spec:I,client:T,isExternal:S,requiresApproval:x,specHash:h}])=>b9(T.status,T.tools,T.prompts).pipe(k0(([v,_,b])=>({name:E,spec:I,isExternal:S,requiresApproval:x,specHash:h,status:v,tools:_ instanceof Error?_:_===vJ||_===KJ?[]:_.map((g)=>({spec:{name:g.name,description:g.description,inputSchema:g.inputSchema,source:{mcp:E}},...lS({name:g.name,source:{mcp:E}},j)})),prompts:b instanceof Error?b:b===vJ||b===KJ?[]:b})))))),M9({shouldCountRefs:!1}));return{initialized:R,servers:O,restartServers(){Y.replenish(),K.next()},async approveWorkspaceServer(j){let $=U.get(j);if(!$)throw Error(`MCP server not found: ${j}`);if($.spec._target!=="workspace")throw Error(`Server ${j} is not a workspace server`);await X.setTrust({serverName:j,specHash:$.specHash},!0),this.restartServers()},async denyWorkspaceServer(j){let $=U.get(j);if(!$)throw Error(`MCP server not found: ${j}`);if($.spec._target!=="workspace")throw Error(`Server ${j} is not a workspace server`);await X.setTrust({serverName:j,specHash:$.specHash},!1)},isWorkspaceTrusted(){return X.isWorkspaceTrusted?.()??e1.of(!0)},getClient(j){return U.get(j)?.client},async searchResources(j){try{let $=await G6(F),E=Date.now(),I=[];for(let[T,{client:S}]of $){if((await G6(S.status)).type!=="connected")continue;try{let h,v=B.get(T);if(v&&E<v.expires)h=v.resources;else h=await S.listResources(),B.set(T,{resources:h,timestamp:E,expires:E+30000});for(let _ of h){let b=_.title||_.name;if(!j||T.toLowerCase().includes(j.toLowerCase())||b.toLowerCase().includes(j.toLowerCase())||_.description?.toLowerCase().includes(j.toLowerCase())||_.uri.toLowerCase().includes(j.toLowerCase()))I.push({resource:_,serverName:T})}}catch(h){u.warn(`Failed to list resources from MCP server ${T}`,h),V(T)}}return I.slice(0,50)}catch($){return u.warn("Failed to search MCP resources",$),[]}},async getPrompt(j,$,E,I){let T=U.get($);if(T)try{return await T.client.getPrompt(j,E,I)}catch(S){return null}return null},async registerToolsWithService(j){return new Promise(($)=>{let E=[],I=!1,T=L.subscribe(({mcpServers:S})=>{for(let x of E)x.dispose();E.length=0;for(let{name:x,tools:h,client:v}of S)for(let _ of h)E.push(j.registerTool(W40(_,v,x)));if(!I)I=!0,$({dispose:()=>{T.unsubscribe();for(let x of E)x.dispose();E.length=0}})},(S)=>{u.error("MCP external tool registration error",S)})})},async addServer(j,$){let E=(await J.getLatest()).settings.mcpServers;if(E&&j in E)throw Error(`MCP server already exists with name ${JSON.stringify(j)}`);if("command"in $&&typeof $.command!=="string")throw Error("Command must be a string");if("url"in $)try{new URL($.url)}catch(I){throw Error(`Invalid URL: ${$.url}`)}await J.updateSettings("mcpServers",{...E,[j]:$},"global")},async removeServer(j){let $=(await J.getLatest()).settings.mcpServers;if(!$||!(j in $))throw Error(`MCP server does not exist with name ${JSON.stringify(j)}`);let E={...$};delete E[j],await J.updateSettings("mcpServers",E,"global")},async updateServer(j,$){let E=(await J.getLatest()).settings.mcpServers;if(!E||!(j in E))throw Error(`MCP server does not exist with name ${JSON.stringify(j)}`);await J.updateSettings("mcpServers",{...E,[j]:$},"global")},searchPrompts(j){return this.servers.pipe(k0(($)=>{let E=[];for(let I of $)if(I.status.type==="connected"&&Array.isArray(I.prompts)){let T=I.prompts.map((S)=>Qh6(S,I.name)).filter((S)=>{if(!j)return!0;let x=j.toLowerCase();return S.label.toLowerCase().includes(x)||S.detail&&S.detail.toLowerCase().includes(x)});E.push(...T)}return E.sort((I,T)=>I.label.localeCompare(T.label)).slice(0,Math.min(10,iB))}))},async dispose(){w.unsubscribe(),H.unsubscribe();let j=Array.from(U.values()).map(async({client:$})=>{try{await $.dispose()}catch(E){u.error("Error disposing MCP client:",E)}});await Promise.all(j),U.clear()},get onUntrustedWorkspaceServer(){return G},set onUntrustedWorkspaceServer(j){G=j}}}function ef6(J,Q){return JSON.stringify(J)===JSON.stringify(Q)}function Jh6(J,Q){return JSON.stringify(J)===JSON.stringify(Q)}function W40(J,Q,Z){let X=`mcp__${Z.replace(/\s+/g,"_")}__${J.name.replace(/\s+/g,"_")}`;return{spec:{name:X.length>=64?J.name:X,description:J.description??"",inputSchema:J.inputSchema,source:{mcp:Z}},fn:({args:K},G)=>d6((q)=>Q.callTool({name:J.name,arguments:K??void 0},G,q).then((z)=>({status:"done",result:z.map((U)=>{if(U.type==="text"||U.type==="image")return U;throw Error(`unsupported content type: ${U.type}`)})})))}}class H40{forceRestart=!1;consume(){let J=this.forceRestart;return this.forceRestart=!1,J}replenish(){this.forceRestart=!0}}function Qh6(J,Q){let Z=J.arguments?.map((Y)=>({name:Y.name,required:Y.required??!1}))||[],X={uri:k6(`mcp://${Q}/${J.name}`),label:`${Q}/${J.name}`,detail:J.description||`From ${Q}`,insertText:"",filterText:`${J.name} ${J.description||""}`.toLowerCase()};return{...X,kind:"prompt",promptData:{...X,arguments:Z}}}HG();zB1();b6();C0();G0();D3();var v40=C6(R40(),1);b6();C0();G0();BB1();EQ();Dj();import*as hX from"node:fs";import*as ia from"node:path";var k9={readFile:async(J,Q)=>{try{return await hX.promises.readFile(D8(J).fsPath,{encoding:"utf8",signal:Q?.signal})}catch(Z){if(oW(Z))throw new XJ(J);throw Z}},readBinaryFile:async(J,Q)=>{try{return await hX.promises.readFile(D8(J).fsPath,{signal:Q?.signal})}catch(Z){if(oW(Z))throw new XJ(J);throw Z}},getMtime:async(J,Q)=>{try{return(await hX.promises.stat(D8(J).fsPath)).mtimeMs}catch(Z){if(oW(Z))throw new XJ(J);throw Z}},stat:async(J,Q)=>{J=D8(J);try{let Z=await hX.promises.stat(J.fsPath);return{name:ia.basename(J.fsPath),size:Z.size,isDirectory:Z.isDirectory()}}catch(Z){if(oW(Z))throw new XJ(J);throw Z}},realpath:async(J,Q)=>{return bh6(D8(J))},rename:async(J,Q)=>{try{await hX.promises.rename(D8(J).fsPath,D8(Q).fsPath)}catch(Z){if(oW(Z))throw new XJ(J);throw Z}},writeFile:async(J,Q,Z)=>{await hX.promises.writeFile(D8(J).fsPath,Q,{encoding:"utf-8",signal:Z?.signal,flush:!0})},delete:async(J,Q)=>{J=D8(J);try{if(Q?.recursive)await hX.promises.rm(J.fsPath,{recursive:!0,force:!0});else await hX.promises.unlink(J.fsPath)}catch(Z){if(oW(Z))throw new XJ(J);throw Z}},mkdirp:async(J)=>{await hX.promises.mkdir(D8(J).fsPath,{recursive:!0})},readdir:async(J,Q)=>{J=D8(J);try{return(await hX.promises.readdir(J.fsPath,{withFileTypes:!0})).map((X)=>({uri:w0.file(ia.join(J.fsPath,X.name)),isDirectory:X.isDirectory()}))}catch(Z){if(oW(Z))throw new XJ(J);throw Z}},findFiles:async(J,Q)=>{try{return(await la(J.base,{pattern:J.pattern,caseInsensitive:!0},{limit:Q?.maxResults,signal:Q?.signal})).files.map((X)=>VG(X)?w0.file(X):b0.joinPath(J.base,X))}catch(Z){return u.error(`Error finding files with pattern ${J.pattern}:`,Z instanceof Error?Z:Error(String(Z))),[]}},watch:()=>$Y,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{let Z=D8(J);xh6(Z);try{await hX.promises.access(Z.fsPath)}catch(X){if(oW(X))throw new XJ(Z);throw X}}};function xh6(J){if(!MB(J))throw Error(`Expected a file URI (got ${J.toString()})`)}function oW(J){return J!==null&&typeof J==="object"&&"code"in J&&J.code==="ENOENT"}async function bh6(J){if(J.scheme!=="file")throw Error("nodeRealpath only supports file URIs");try{return w0.file(await hX.promises.realpath(J.fsPath))}catch(Q){if(oW(Q))throw new XJ(J);throw Q}}async function S40(J,Q){if(!J.startsWith(process.cwd()))return;if(await T7.isConnected())try{let Z=await T7.sendRequest("readFile",{path:J});if(Z?.content)return Q(Z.content);throw Error(`Failed to readFile via IDE ${J}: ${Z?.message??"unknown cause"}`)}catch(Z){if(process.env.IDE_FS_NO_FALLBACK)throw Z;u.debug("IDE readFile failed, falling back to Node.js filesystem",{path:J,error:Z});return}else return}async function yh6(J,Q){if(!J.startsWith(process.cwd()))return!1;if(await T7.isConnected())try{let Z=await T7.sendRequest("editFile",{path:J,fullContent:Q});if(!Z?.success)throw Error(`Failed to writeFile via IDE ${J}: ${Z?.message??"unknown cause"}`);return!0}catch(Z){if(process.env.IDE_FS_NO_FALLBACK)throw Z;return u.debug("IDE writeFile failed, falling back to Node.js filesystem",{path:J,error:Z}),!1}else return!1}var k40={readFile:async(J,Q)=>{let Z=D8(J).fsPath;return u.debug("ide-fs",{method:"readFile",path:Z}),await S40(Z,(X)=>X)??await k9.readFile(J,Q).finally(()=>{u.debug("ide-fs",{fallback:"readFile",uri:J})})},readBinaryFile:async(J,Q)=>{let Z=D8(J).fsPath;u.debug("ide-fs",{method:"readBinaryFile",path:Z});let X;if(!await v40.isBinaryFile(Z))X=await S40(Z,(Y)=>Buffer.from(Y,"utf8"));return X??await k9.readBinaryFile(J,Q).finally(()=>{u.debug("ide-fs",{fallback:"readBinaryFile",uri:J})})},getMtime:async(J,Q)=>{return k9.getMtime(J,Q)},stat:async(J,Q)=>{return k9.stat(J,Q)},realpath:async(J,Q)=>{return k9.realpath(J,Q)},rename:async(J,Q)=>{return k9.rename(J,Q)},writeFile:async(J,Q,Z)=>{let X=D8(J).fsPath;if(u.debug("ide-fs",{method:"writeFile",path:X}),await yh6(X,Q))return;return await k9.writeFile(J,Q,Z).finally(()=>{u.debug("ide-fs",{fallback:"writeFile",uri:J})})},delete:async(J,Q)=>{return k9.delete(J,Q)},mkdirp:async(J)=>{return k9.mkdirp(J)},readdir:async(J,Q)=>{return k9.readdir(J,Q)},findFiles:async(J,Q)=>{return k9.findFiles(J,Q)},watch:()=>$Y,isExclusiveWriterFor:async(J)=>!1,access:async(J,Q)=>{return k9.access(J,Q)}};jG();fX();AD();b6();import{homedir as ph6}from"node:os";import $D from"node:path";import{Worker as dh6}from"node:worker_threads";var tj=typeof performance==="object"&&performance&&typeof performance.now==="function"?performance:Date,f40=new Set,VB1=typeof process==="object"&&!!process?process:{},h40=(J,Q,Z,X)=>{typeof VB1.emitWarning==="function"?VB1.emitWarning(J,Q,Z,X):console.error(`[${Z}] ${Q}: ${J}`)},aa=globalThis.AbortController,y40=globalThis.AbortSignal;if(typeof aa>"u"){y40=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(X,Y){this._onabort.push(Y)}},aa=class{constructor(){Q()}signal=new y40;abort(X){if(this.signal.aborted)return;this.signal.reason=X,this.signal.aborted=!0;for(let Y of this.signal._onabort)Y(X);this.signal.onabort?.(X)}};let J=VB1.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",Q=()=>{if(!J)return;J=!1,h40("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",Q)}}var mh6=(J)=>!f40.has(J),Jv9=Symbol("type"),jD=(J)=>J&&J===Math.floor(J)&&J>0&&isFinite(J),g40=(J)=>!jD(J)?null:J<=Math.pow(2,8)?Uint8Array:J<=Math.pow(2,16)?Uint16Array:J<=Math.pow(2,32)?Uint32Array:J<=Number.MAX_SAFE_INTEGER?b_:null;class b_ extends Array{constructor(J){super(J);this.fill(0)}}class ej{heap;length;static#J=!1;static create(J){let Q=g40(J);if(!Q)return[];ej.#J=!0;let Z=new ej(J,Q);return ej.#J=!1,Z}constructor(J,Q){if(!ej.#J)throw TypeError("instantiate Stack using Stack.create(n)");this.heap=new Q(J),this.length=0}push(J){this.heap[this.length++]=J}pop(){return this.heap[--this.length]}}class ra{#J;#Q;#Y;#X;#q;#I;#T;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#U;#L;#z;#G;#Z;#B;#M;#H;#W;#A;#F;#w;#R;#V;#O;#C;#D;#_;static unsafeExposeInternals(J){return{starts:J.#R,ttls:J.#V,sizes:J.#w,keyMap:J.#z,keyList:J.#G,valList:J.#Z,next:J.#B,prev:J.#M,get head(){return J.#H},get tail(){return J.#W},free:J.#A,isBackgroundFetch:(Q)=>J.#K(Q),backgroundFetch:(Q,Z,X,Y)=>J.#y(Q,Z,X,Y),moveToTail:(Q)=>J.#k(Q),indexes:(Q)=>J.#j(Q),rindexes:(Q)=>J.#$(Q),isStale:(Q)=>J.#N(Q)}}get max(){return this.#J}get maxSize(){return this.#Q}get calculatedSize(){return this.#L}get size(){return this.#U}get fetchMethod(){return this.#I}get memoMethod(){return this.#T}get dispose(){return this.#Y}get onInsert(){return this.#X}get disposeAfter(){return this.#q}constructor(J){let{max:Q=0,ttl:Z,ttlResolution:X=1,ttlAutopurge:Y,updateAgeOnGet:K,updateAgeOnHas:G,allowStale:q,dispose:z,onInsert:U,disposeAfter:W,noDisposeOnSet:F,noUpdateTTL:H,maxSize:B=0,maxEntrySize:M=0,sizeCalculation:V,fetchMethod:N,memoMethod:L,noDeleteOnFetchRejection:A,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:R,allowStaleOnFetchAbort:O,ignoreFetchAbort:j}=J;if(Q!==0&&!jD(Q))throw TypeError("max option must be a nonnegative integer");let $=Q?g40(Q):Array;if(!$)throw Error("invalid max value: "+Q);if(this.#J=Q,this.#Q=B,this.maxEntrySize=M||this.#Q,this.sizeCalculation=V,this.sizeCalculation){if(!this.#Q&&!this.maxEntrySize)throw TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!=="function")throw TypeError("sizeCalculation set to non-function")}if(L!==void 0&&typeof L!=="function")throw TypeError("memoMethod must be a function if defined");if(this.#T=L,N!==void 0&&typeof N!=="function")throw TypeError("fetchMethod must be a function if specified");if(this.#I=N,this.#C=!!N,this.#z=new Map,this.#G=Array(Q).fill(void 0),this.#Z=Array(Q).fill(void 0),this.#B=new $(Q),this.#M=new $(Q),this.#H=0,this.#W=0,this.#A=ej.create(Q),this.#U=0,this.#L=0,typeof z==="function")this.#Y=z;if(typeof U==="function")this.#X=U;if(typeof W==="function")this.#q=W,this.#F=[];else this.#q=void 0,this.#F=void 0;if(this.#O=!!this.#Y,this.#_=!!this.#X,this.#D=!!this.#q,this.noDisposeOnSet=!!F,this.noUpdateTTL=!!H,this.noDeleteOnFetchRejection=!!A,this.allowStaleOnFetchRejection=!!R,this.allowStaleOnFetchAbort=!!O,this.ignoreFetchAbort=!!j,this.maxEntrySize!==0){if(this.#Q!==0){if(!jD(this.#Q))throw TypeError("maxSize must be a positive integer if specified")}if(!jD(this.maxEntrySize))throw TypeError("maxEntrySize must be a positive integer if specified");this.#d()}if(this.allowStale=!!q,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!K,this.updateAgeOnHas=!!G,this.ttlResolution=jD(X)||X===0?X:1,this.ttlAutopurge=!!Y,this.ttl=Z||0,this.ttl){if(!jD(this.ttl))throw TypeError("ttl must be a positive integer if specified");this.#f()}if(this.#J===0&&this.ttl===0&&this.#Q===0)throw TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#J&&!this.#Q){if(mh6("LRU_CACHE_UNBOUNDED"))f40.add("LRU_CACHE_UNBOUNDED"),h40("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning","LRU_CACHE_UNBOUNDED",ra)}}getRemainingTTL(J){return this.#z.has(J)?1/0:0}#f(){let J=new b_(this.#J),Q=new b_(this.#J);this.#V=J,this.#R=Q,this.#h=(Y,K,G=tj.now())=>{if(Q[Y]=K!==0?G:0,J[Y]=K,K!==0&&this.ttlAutopurge){let q=setTimeout(()=>{if(this.#N(Y))this.#E(this.#G[Y],"expire")},K+1);if(q.unref)q.unref()}},this.#S=(Y)=>{Q[Y]=J[Y]!==0?tj.now():0},this.#P=(Y,K)=>{if(J[K]){let G=J[K],q=Q[K];if(!G||!q)return;Y.ttl=G,Y.start=q,Y.now=Z||X();let z=Y.now-q;Y.remainingTTL=G-z}};let Z=0,X=()=>{let Y=tj.now();if(this.ttlResolution>0){Z=Y;let K=setTimeout(()=>Z=0,this.ttlResolution);if(K.unref)K.unref()}return Y};this.getRemainingTTL=(Y)=>{let K=this.#z.get(Y);if(K===void 0)return 0;let G=J[K],q=Q[K];if(!G||!q)return 1/0;let z=(Z||X())-q;return G-z},this.#N=(Y)=>{let K=Q[Y],G=J[Y];return!!G&&!!K&&(Z||X())-K>G}}#S=()=>{};#P=()=>{};#h=()=>{};#N=()=>!1;#d(){let J=new b_(this.#J);this.#L=0,this.#w=J,this.#v=(Q)=>{this.#L-=J[Q],J[Q]=0},this.#g=(Q,Z,X,Y)=>{if(this.#K(Z))return 0;if(!jD(X))if(Y){if(typeof Y!=="function")throw TypeError("sizeCalculation must be a function");if(X=Y(Z,Q),!jD(X))throw TypeError("sizeCalculation return invalid (expect positive integer)")}else throw TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return X},this.#x=(Q,Z,X)=>{if(J[Q]=Z,this.#Q){let Y=this.#Q-J[Q];while(this.#L>Y)this.#b(!0)}if(this.#L+=J[Q],X)X.entrySize=Z,X.totalCalculatedSize=this.#L}}#v=(J)=>{};#x=(J,Q,Z)=>{};#g=(J,Q,Z,X)=>{if(Z||X)throw TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#j({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#W;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#H)break;else Q=this.#M[Q]}}*#$({allowStale:J=this.allowStale}={}){if(this.#U)for(let Q=this.#H;;){if(!this.#m(Q))break;if(J||!this.#N(Q))yield Q;if(Q===this.#W)break;else Q=this.#B[Q]}}#m(J){return J!==void 0&&this.#z.get(this.#G[J])===J}*entries(){for(let J of this.#j())if(this.#Z[J]!==void 0&&this.#G[J]!==void 0&&!this.#K(this.#Z[J]))yield[this.#G[J],this.#Z[J]]}*rentries(){for(let J of this.#$())if(this.#Z[J]!==void 0&&this.#G[J]!==void 0&&!this.#K(this.#Z[J]))yield[this.#G[J],this.#Z[J]]}*keys(){for(let J of this.#j()){let Q=this.#G[J];if(Q!==void 0&&!this.#K(this.#Z[J]))yield Q}}*rkeys(){for(let J of this.#$()){let Q=this.#G[J];if(Q!==void 0&&!this.#K(this.#Z[J]))yield Q}}*values(){for(let J of this.#j())if(this.#Z[J]!==void 0&&!this.#K(this.#Z[J]))yield this.#Z[J]}*rvalues(){for(let J of this.#$())if(this.#Z[J]!==void 0&&!this.#K(this.#Z[J]))yield this.#Z[J]}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(J,Q={}){for(let Z of this.#j()){let X=this.#Z[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;if(J(Y,this.#G[Z],this))return this.get(this.#G[Z],Q)}}forEach(J,Q=this){for(let Z of this.#j()){let X=this.#Z[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#G[Z],this)}}rforEach(J,Q=this){for(let Z of this.#$()){let X=this.#Z[Z],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0)continue;J.call(Q,Y,this.#G[Z],this)}}purgeStale(){let J=!1;for(let Q of this.#$({allowStale:!0}))if(this.#N(Q))this.#E(this.#G[Q],"expire"),J=!0;return J}info(J){let Q=this.#z.get(J);if(Q===void 0)return;let Z=this.#Z[Q],X=this.#K(Z)?Z.__staleWhileFetching:Z;if(X===void 0)return;let Y={value:X};if(this.#V&&this.#R){let K=this.#V[Q],G=this.#R[Q];if(K&&G){let q=K-(tj.now()-G);Y.ttl=q,Y.start=Date.now()}}if(this.#w)Y.size=this.#w[Q];return Y}dump(){let J=[];for(let Q of this.#j({allowStale:!0})){let Z=this.#G[Q],X=this.#Z[Q],Y=this.#K(X)?X.__staleWhileFetching:X;if(Y===void 0||Z===void 0)continue;let K={value:Y};if(this.#V&&this.#R){K.ttl=this.#V[Q];let G=tj.now()-this.#R[Q];K.start=Math.floor(Date.now()-G)}if(this.#w)K.size=this.#w[Q];J.unshift([Z,K])}return J}load(J){this.clear();for(let[Q,Z]of J){if(Z.start){let X=Date.now()-Z.start;Z.start=tj.now()-X}this.set(Q,Z.value,Z)}}set(J,Q,Z={}){if(Q===void 0)return this.delete(J),this;let{ttl:X=this.ttl,start:Y,noDisposeOnSet:K=this.noDisposeOnSet,sizeCalculation:G=this.sizeCalculation,status:q}=Z,{noUpdateTTL:z=this.noUpdateTTL}=Z,U=this.#g(J,Q,Z.size||0,G);if(this.maxEntrySize&&U>this.maxEntrySize){if(q)q.set="miss",q.maxEntrySizeExceeded=!0;return this.#E(J,"set"),this}let W=this.#U===0?void 0:this.#z.get(J);if(W===void 0){if(W=this.#U===0?this.#W:this.#A.length!==0?this.#A.pop():this.#U===this.#J?this.#b(!1):this.#U,this.#G[W]=J,this.#Z[W]=Q,this.#z.set(J,W),this.#B[this.#W]=W,this.#M[W]=this.#W,this.#W=W,this.#U++,this.#x(W,U,q),q)q.set="add";if(z=!1,this.#_)this.#X?.(Q,J,"add")}else{this.#k(W);let F=this.#Z[W];if(Q!==F){if(this.#C&&this.#K(F)){F.__abortController.abort(Error("replaced"));let{__staleWhileFetching:H}=F;if(H!==void 0&&!K){if(this.#O)this.#Y?.(H,J,"set");if(this.#D)this.#F?.push([H,J,"set"])}}else if(!K){if(this.#O)this.#Y?.(F,J,"set");if(this.#D)this.#F?.push([F,J,"set"])}if(this.#v(W),this.#x(W,U,q),this.#Z[W]=Q,q){q.set="replace";let H=F&&this.#K(F)?F.__staleWhileFetching:F;if(H!==void 0)q.oldValue=H}}else if(q)q.set="update";if(this.#_)this.onInsert?.(Q,J,Q===F?"update":"replace")}if(X!==0&&!this.#V)this.#f();if(this.#V){if(!z)this.#h(W,X,Y);if(q)this.#P(q,W)}if(!K&&this.#D&&this.#F){let F=this.#F,H;while(H=F?.shift())this.#q?.(...H)}return this}pop(){try{while(this.#U){let J=this.#Z[this.#H];if(this.#b(!0),this.#K(J)){if(J.__staleWhileFetching)return J.__staleWhileFetching}else if(J!==void 0)return J}}finally{if(this.#D&&this.#F){let J=this.#F,Q;while(Q=J?.shift())this.#q?.(...Q)}}}#b(J){let Q=this.#H,Z=this.#G[Q],X=this.#Z[Q];if(this.#C&&this.#K(X))X.__abortController.abort(Error("evicted"));else if(this.#O||this.#D){if(this.#O)this.#Y?.(X,Z,"evict");if(this.#D)this.#F?.push([X,Z,"evict"])}if(this.#v(Q),J)this.#G[Q]=void 0,this.#Z[Q]=void 0,this.#A.push(Q);if(this.#U===1)this.#H=this.#W=0,this.#A.length=0;else this.#H=this.#B[Q];return this.#z.delete(Z),this.#U--,Q}has(J,Q={}){let{updateAgeOnHas:Z=this.updateAgeOnHas,status:X}=Q,Y=this.#z.get(J);if(Y!==void 0){let K=this.#Z[Y];if(this.#K(K)&&K.__staleWhileFetching===void 0)return!1;if(!this.#N(Y)){if(Z)this.#S(Y);if(X)X.has="hit",this.#P(X,Y);return!0}else if(X)X.has="stale",this.#P(X,Y)}else if(X)X.has="miss";return!1}peek(J,Q={}){let{allowStale:Z=this.allowStale}=Q,X=this.#z.get(J);if(X===void 0||!Z&&this.#N(X))return;let Y=this.#Z[X];return this.#K(Y)?Y.__staleWhileFetching:Y}#y(J,Q,Z,X){let Y=Q===void 0?void 0:this.#Z[Q];if(this.#K(Y))return Y;let K=new aa,{signal:G}=Z;G?.addEventListener("abort",()=>K.abort(G.reason),{signal:K.signal});let q={signal:K.signal,options:Z,context:X},z=(M,V=!1)=>{let{aborted:N}=K.signal,L=Z.ignoreFetchAbort&&M!==void 0;if(Z.status)if(N&&!V){if(Z.status.fetchAborted=!0,Z.status.fetchError=K.signal.reason,L)Z.status.fetchAbortIgnored=!0}else Z.status.fetchResolved=!0;if(N&&!L&&!V)return W(K.signal.reason);let A=H;if(this.#Z[Q]===H)if(M===void 0)if(A.__staleWhileFetching)this.#Z[Q]=A.__staleWhileFetching;else this.#E(J,"fetch");else{if(Z.status)Z.status.fetchUpdated=!0;this.set(J,M,q.options)}return M},U=(M)=>{if(Z.status)Z.status.fetchRejected=!0,Z.status.fetchError=M;return W(M)},W=(M)=>{let{aborted:V}=K.signal,N=V&&Z.allowStaleOnFetchAbort,L=N||Z.allowStaleOnFetchRejection,A=L||Z.noDeleteOnFetchRejection,w=H;if(this.#Z[Q]===H){if(!A||w.__staleWhileFetching===void 0)this.#E(J,"fetch");else if(!N)this.#Z[Q]=w.__staleWhileFetching}if(L){if(Z.status&&w.__staleWhileFetching!==void 0)Z.status.returnedStale=!0;return w.__staleWhileFetching}else if(w.__returned===w)throw M},F=(M,V)=>{let N=this.#I?.(J,Y,q);if(N&&N instanceof Promise)N.then((L)=>M(L===void 0?void 0:L),V);K.signal.addEventListener("abort",()=>{if(!Z.ignoreFetchAbort||Z.allowStaleOnFetchAbort){if(M(void 0),Z.allowStaleOnFetchAbort)M=(L)=>z(L,!0)}})};if(Z.status)Z.status.fetchDispatched=!0;let H=new Promise(F).then(z,U),B=Object.assign(H,{__abortController:K,__staleWhileFetching:Y,__returned:void 0});if(Q===void 0)this.set(J,B,{...q.options,status:void 0}),Q=this.#z.get(J);else this.#Z[Q]=B;return B}#K(J){if(!this.#C)return!1;let Q=J;return!!Q&&Q instanceof Promise&&Q.hasOwnProperty("__staleWhileFetching")&&Q.__abortController instanceof aa}async fetch(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,ttl:K=this.ttl,noDisposeOnSet:G=this.noDisposeOnSet,size:q=0,sizeCalculation:z=this.sizeCalculation,noUpdateTTL:U=this.noUpdateTTL,noDeleteOnFetchRejection:W=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:F=this.allowStaleOnFetchRejection,ignoreFetchAbort:H=this.ignoreFetchAbort,allowStaleOnFetchAbort:B=this.allowStaleOnFetchAbort,context:M,forceRefresh:V=!1,status:N,signal:L}=Q;if(!this.#C){if(N)N.fetch="get";return this.get(J,{allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,status:N})}let A={allowStale:Z,updateAgeOnGet:X,noDeleteOnStaleGet:Y,ttl:K,noDisposeOnSet:G,size:q,sizeCalculation:z,noUpdateTTL:U,noDeleteOnFetchRejection:W,allowStaleOnFetchRejection:F,allowStaleOnFetchAbort:B,ignoreFetchAbort:H,status:N,signal:L},w=this.#z.get(J);if(w===void 0){if(N)N.fetch="miss";let R=this.#y(J,w,A,M);return R.__returned=R}else{let R=this.#Z[w];if(this.#K(R)){let I=Z&&R.__staleWhileFetching!==void 0;if(N){if(N.fetch="inflight",I)N.returnedStale=!0}return I?R.__staleWhileFetching:R.__returned=R}let O=this.#N(w);if(!V&&!O){if(N)N.fetch="hit";if(this.#k(w),X)this.#S(w);if(N)this.#P(N,w);return R}let j=this.#y(J,w,A,M),E=j.__staleWhileFetching!==void 0&&Z;if(N){if(N.fetch=O?"stale":"refresh",E&&O)N.returnedStale=!0}return E?j.__staleWhileFetching:j.__returned=j}}async forceFetch(J,Q={}){let Z=await this.fetch(J,Q);if(Z===void 0)throw Error("fetch() returned undefined");return Z}memo(J,Q={}){let Z=this.#T;if(!Z)throw Error("no memoMethod provided to constructor");let{context:X,forceRefresh:Y,...K}=Q,G=this.get(J,K);if(!Y&&G!==void 0)return G;let q=Z(J,G,{options:K,context:X});return this.set(J,q,K),q}get(J,Q={}){let{allowStale:Z=this.allowStale,updateAgeOnGet:X=this.updateAgeOnGet,noDeleteOnStaleGet:Y=this.noDeleteOnStaleGet,status:K}=Q,G=this.#z.get(J);if(G!==void 0){let q=this.#Z[G],z=this.#K(q);if(K)this.#P(K,G);if(this.#N(G)){if(K)K.get="stale";if(!z){if(!Y)this.#E(J,"expire");if(K&&Z)K.returnedStale=!0;return Z?q:void 0}else{if(K&&Z&&q.__staleWhileFetching!==void 0)K.returnedStale=!0;return Z?q.__staleWhileFetching:void 0}}else{if(K)K.get="hit";if(z)return q.__staleWhileFetching;if(this.#k(G),X)this.#S(G);return q}}else if(K)K.get="miss"}#u(J,Q){this.#M[Q]=J,this.#B[J]=Q}#k(J){if(J!==this.#W){if(J===this.#H)this.#H=this.#B[J];else this.#u(this.#M[J],this.#B[J]);this.#u(this.#W,J),this.#W=J}}delete(J){return this.#E(J,"delete")}#E(J,Q){let Z=!1;if(this.#U!==0){let X=this.#z.get(J);if(X!==void 0)if(Z=!0,this.#U===1)this.#p(Q);else{this.#v(X);let Y=this.#Z[X];if(this.#K(Y))Y.__abortController.abort(Error("deleted"));else if(this.#O||this.#D){if(this.#O)this.#Y?.(Y,J,Q);if(this.#D)this.#F?.push([Y,J,Q])}if(this.#z.delete(J),this.#G[X]=void 0,this.#Z[X]=void 0,X===this.#W)this.#W=this.#M[X];else if(X===this.#H)this.#H=this.#B[X];else{let K=this.#M[X];this.#B[K]=this.#B[X];let G=this.#B[X];this.#M[G]=this.#M[X]}this.#U--,this.#A.push(X)}}if(this.#D&&this.#F?.length){let X=this.#F,Y;while(Y=X?.shift())this.#q?.(...Y)}return Z}clear(){return this.#p("delete")}#p(J){for(let Q of this.#$({allowStale:!0})){let Z=this.#Z[Q];if(this.#K(Z))Z.__abortController.abort(Error("deleted"));else{let X=this.#G[Q];if(this.#O)this.#Y?.(Z,X,J);if(this.#D)this.#F?.push([Z,X,J])}}if(this.#z.clear(),this.#Z.fill(void 0),this.#G.fill(void 0),this.#V&&this.#R)this.#V.fill(0),this.#R.fill(0);if(this.#w)this.#w.fill(0);if(this.#H=0,this.#W=0,this.#A.length=0,this.#L=0,this.#U=0,this.#D&&this.#F){let Q=this.#F,Z;while(Z=Q?.shift())this.#q?.(...Z)}}}G0();EQ();b6();C0();G0();EQ();function y_(J,Q,Z){let X=new b8,K=(()=>{let B=new Map;return(M,V)=>{let L=(B.get(M)?.catch(()=>{})||Promise.resolve()).then(()=>V()).finally(()=>{if(B.get(M)===L)B.delete(M)});return B.set(M,L),L}})(),G=Z?b0.joinPath(Q,Z):Q;function q(B){return b0.joinPath(G,`${B.toString()}.json`)}async function z(B){let M=q(B);try{let V=await J.readBinaryFile(M),N=52428800;if(V.length>52428800){let L=Math.round(V.length/1048576);u.warn(`File too large to load safely: ${String(B)} (${L}MB)`,{key:String(B),size:V.length,maxSize:52428800});return}try{let L=V instanceof Uint8Array?V:new Uint8Array(V);return JSON.parse(new TextDecoder().decode(L))}catch(L){let A=L,{contentLength:w,contentPreview:R}=uh6(V);u.warn("Corrupted JSON detected.",{key:String(B),storageUri:G.toString(),error:A.message,contentLength:w,contentPreview:R});return}}catch(V){if($Q(V))return;throw V}}async function U(B,M){let V=q(B),N=V.with({path:V.path+".amptmp"}),L=JSON.stringify(M,null,2);await J.mkdirp(b0.joinPath(V,"..")),await K(B,async()=>{await J.writeFile(N,L),await J.rename(N,V)}),X.next(B)}async function W(B){let M=q(B);await K(B,async()=>{await J.delete(M)}),X.next(B)}async function F(){let B;try{B=await J.readdir(G)}catch(M){if($Q(M))return[];throw M}return B.map((M)=>{let V=M.uri.path.split("/").pop()||"";if(M.isDirectory||!V.endsWith(".json"))return null;return V.slice(0,-5)}).filter((M)=>M!==null)}async function H(B){return q(B).fsPath}return{get:z,set:U,delete:W,keys:F,path:H,changes:X}}function uh6(J){try{let Q=J instanceof Uint8Array?J:new Uint8Array(J),Z=new TextDecoder().decode(Q);return{contentLength:J.length,contentPreview:Z.slice(0,128)}}catch{let Q=J instanceof Uint8Array?J:new Uint8Array(J),X=Array.from(Q.slice(0,64)).map((Y)=>{if(Y>=32&&Y<=126)return String.fromCharCode(Y);return`\\x${Y.toString(16).padStart(2,"0")}`}).join("");return{contentLength:J.length,contentPreview:`${X}${J.length>64?"...":""}`}}}async function m40(J){let Q=J.isDevelopment||!1,Z=lh6(),X=Q?"threads-development":"threads",Y=y_(k9,Z,X),K=new u40(Y);if(!J.vscodeMigrationContext)return u.debug("Using centralized thread storage (CLI)",{storageUri:Z.toString(),storageSubdir:X}),K;let{fileSystem:G,vscodeContext:q}=J.vscodeMigrationContext,z=w0.file($D.join(Z.path,X)),U=Q?"threads3-development":"threads3",W=w0.file($D.join(q.globalStorageUri.path,U));if(await ih6(z,Q,W))return u.debug("Using centralized thread storage (VS Code, migration complete)",{storageUri:Z.toString(),storageSubdir:X}),K;else{u.debug("Using fallback thread storage (VS Code, migration in progress)",{centralizedStorageUri:Z.toString(),legacyStorageUri:q.globalStorageUri.toString(),storageSubdir:X,legacySubdir:U}),nh6(W,z,Q);let H=y_(G,q.globalStorageUri,U);return ch6(K,H)}}class u40{delegate;cache=new ra({max:30,maxSize:1e8,ttl:600000,sizeCalculation:(J)=>JSON.stringify(J).length});constructor(J){this.delegate=J}async get(J){if(this.cache.has(J))return this.cache.get(J);let Q=await this.delegate.get(J);if(Q!==void 0)this.cache.set(J,Q);return Q}async set(J,Q){await this.delegate.set(J,Q),this.cache.set(J,Q)}async delete(J){await this.delegate.delete(J),this.cache.delete(J)}keys(){return this.delegate.keys()}path(J){return this.delegate.path(J)}get changes(){return this.delegate.changes}}function ch6(J,Q){return{async get(Z){let X=await J.get(Z);if(X!==void 0)return X;return Q.get(Z)},async set(Z,X){await J.set(Z,X)},async delete(Z){await J.delete(Z).catch(()=>{}),await Q.delete(Z).catch(()=>{})},async keys(){let[Z,X]=await Promise.all([J.keys(),Q.keys()]);return[...new Set([...Z,...X])]},async path(Z){let X=await J.path(Z);if(X)return X;return Q.path(Z)},get changes(){return J.changes}}}function lh6(){let J=process.env.XDG_DATA_HOME||$D.join(ph6(),".local","share"),Q=$D.resolve(J,"amp");return w0.file(Q)}async function ih6(J,Q,Z){let X=w0.file($D.join(J.path,"..","migration")),Y=ah6(Q),K=w0.file($D.join(X.path,Y.done));if(await xn(k9,K))return!0;if(Z)try{if((await k9.readdir(Z)).filter((z)=>$D.basename(z.uri.path).endsWith(".json")).length===0){if((await k9.readdir(J)).filter((W)=>$D.basename(W.uri.path).endsWith(".json")).length>0){u.info("Detected completed migration without marker, creating completion marker");try{await k9.mkdirp(X),await k9.writeFile(K,"completed")}catch(W){u.debug("Could not create migration completion marker:",W)}return!0}}}catch(G){u.debug("Could not check legacy directory for completion detection:",G)}return!1}function nh6(J,Q,Z){try{let X=new dh6(n1.resolve("/home/runner/work/amp/amp/core/src/storage/migration-worker.node.ts"),{workerData:{legacyDir:J.toString(),centralizedDir:Q.toString(),isDevelopment:Z}});X.on("message",(Y)=>{u.info("Background migration completed:",Y)}),X.on("error",(Y)=>{u.warn("Background migration failed:",Y)}),X.on("exit",(Y)=>{if(Y!==0)u.warn(`Migration worker exited with code ${Y}`)})}catch(X){let Y=X instanceof Error?X.message:String(X);if(Y.includes("Worker is not supported")||Y.includes("Cannot resolve module")||Y.includes("ENOENT")&&Y.includes("migration-worker"))u.debug("Migration worker could not be started (expected in tests):",X);else u.warn("Migration worker failed to start, migration will be skipped:",X)}}function ah6(J){let Q=J?"-dev":"";return{progress:`migration-in-progress${Q}`,done:`migration-done${Q}`}}sa();M2();C0();EQ();AD();C0();function p40(J){let Q={},Z=!0;return J.changes.pipe(v2(void 0),BW(async(X,Y)=>{if(X===void 0||Z){let K=await J.keys();Y?.throwIfAborted(),Q=Object.fromEntries(await Promise.all(K.map(async(G)=>[G,await J.get(G)]))),Y?.throwIfAborted(),Z=!1}else{let K=await J.get(X);if(Y?.throwIfAborted(),K===void 0)Q={...Q,[X]:void 0},delete Q[X];else Q={...Q,[X]:K}}return Q}))}M2();class LB1{storage;configService;constructor(J,Q,Z={}){this.storage=J;this.configService=Q;if(!Z.lazy)this.initializeObservable()}initializeObservable(){if(this._observeHistory)return;this._observeHistory=El1(p40(this.storage).pipe(k0((J)=>{let Q=Object.values(J).filter((X)=>X&&("messages"in X)).toSorted((X,Y)=>Y.created-X.created),Z=[];for(let X of Q)if(X.messages.length!==0)Z.push(X);return Z.map((X)=>({id:X.id,v:X.v,created:X.created,title:X.title??null,userLastInteractedAt:oa(X),env:X.env,originThreadID:X.originThreadID,mainThreadID:X.mainThreadID,summaryStats:{diffStats:Cc(X)}})).toSorted((X,Y)=>Y.userLastInteractedAt-X.userLastInteractedAt)}),M9()))}async delete(J){let Q=await this.storage.keys(),Z=[];for(let X of Q){let Y=await this.storage.get(X);if(Y&&Y.mainThreadID===J)Z.push(Y.id)}for(let X of Z)try{await this.storage.delete(X)}catch(Y){if(!$Q(Y))throw Y}try{await this.storage.delete(J)}catch(X){if(!$Q(X))throw X}try{let X=await YJ.deleteThread({thread:J},{config:this.configService});if(!X.ok&&X.error.code!=="thread-not-found")throw Error(`Error deleting thread from server: ${X.error.message??X.error.code}`)}catch(X){if(X instanceof Error&&X.message.includes("404"))return;throw X}}observeHistory(){if(!this._observeHistory)this.initializeObservable();return this._observeHistory.observable}observeThreadList(){if(!this._observeHistory)this.initializeObservable();return this._observeHistory.observable.pipe(J8((J,Q)=>{if(J.length!==Q.length)return!1;return J.every((Z,X)=>{let Y=Q[X];if(!Y)return!1;return Z.id===Y.id&&Z.title===Y.title&&Z.userLastInteractedAt===Y.userLastInteractedAt&&Z.mainThreadID===Y.mainThreadID&&JSON.stringify(Z.env?.initial?.trees?.map((K)=>K.displayName))===JSON.stringify(Y.env?.initial?.trees?.map((K)=>K.displayName))})}))}_observeHistory;dispose(){this._observeHistory?.subscription.unsubscribe()}}function oa(J){return Math.max(J.created,...J.messages.map((Q)=>Q.role==="user"?Q.meta?.sentAt:void 0).filter((Q)=>Q!==void 0))}gH1();C0();OQ();OQ();G0();M2();v3();U3();G0();l$();pq0();var dq0=R0.object({instructions:R0.string().describe("Clear, actionable instructions for another agent to accomplish the user's goal, including relevant context and step-by-step guidance"),relevantFiles:R0.array(R0.string()).describe("List of file URIs that are relevant to accomplishing the goal, prioritized by importance")}),X98=xY`
|
|
4735
4735
|
The user wants to start a new thread to work on the following goal:
|
|
4736
4736
|
|
|
@@ -5906,11 +5906,11 @@ Actual: ${Y}`)}async function e79(J,Q,Z){let{execSync:X}=await import("node:ch
|
|
|
5906
5906
|
${B}`;if(Y==="pnpm"&&B.includes("Unable to find the global bin directory"))M+=`
|
|
5907
5907
|
|
|
5908
5908
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
5909
|
-
npm install -g @sourcegraph/amp`;q(Error(M))}},error:(H)=>{if(!W)W=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!W)W=!0,G()}})})}G0();G0();async function b51(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),G=K["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=Y59(J,G),z=q<0,U,W;if(K.time){let F=K.time[J],H=K.time[G],B=Date.now();if(F)U=Math.floor((B-new Date(F).getTime())/3600000);if(H)W=Math.floor((B-new Date(H).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return u.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function Y59(J,Q){let Z=(G)=>{let[q,z]=G.split("-");return{parts:q?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let G=0;G<K;G++){let q=X.parts[G]||0,z=Y.parts[G]||0;if(q<z)return-1;if(q>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}C0();function Qf1(J,Q){let Z=new b8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new rq().scoped("update"),K=X.subscribe({next:(G)=>{Y.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){Y.debug("using fake update status for testing",{status:G}),await E_(500),Z.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:q});let z=await b51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await x51();if(!q)q=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:q});if(q==="warn"){Z.next("update-available");return}if(!U){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await Zp(z.latestVersion,U);let W=await eV(z.latestVersion),F={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",F),Z.next("updated");else Y.warn("success with warning",F),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await E_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as JW}from"node:process";function iZ6(J){let Q=new Bu().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(X)=>{await ty1(X.force||!1,X.verbose||!1,"0.0.
|
|
5909
|
+
npm install -g @sourcegraph/amp`;q(Error(M))}},error:(H)=>{if(!W)W=!0,q(Error(`Failed to spawn ${Y}: ${H.message}`))},complete:()=>{if(!W)W=!0,G()}})})}G0();G0();async function b51(J){try{let Z=new AbortController,X=setTimeout(()=>Z.abort(),5000),Y=await fetch("https://registry.npmjs.org/@sourcegraph/amp",{signal:Z.signal});if(clearTimeout(X),!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let K=await Y.json(),G=K["dist-tags"]?.latest;if(!G)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=Y59(J,G),z=q<0,U,W;if(K.time){let F=K.time[J],H=K.time[G],B=Date.now();if(F)U=Math.floor((B-new Date(F).getTime())/3600000);if(H)W=Math.floor((B-new Date(H).getTime())/3600000)}return u.info("NPM version comparison",{currentVersion:J,latestVersion:G,compareResult:q,hasUpdate:z,currentVersionAge:U,latestVersionAge:W}),{hasUpdate:z,latestVersion:G,currentVersion:J,currentVersionAge:U,latestVersionAge:W,source:"npm"}}catch(Z){return u.debug("Error checking npm version",{error:Z}),{hasUpdate:!1,currentVersion:J,source:"npm"}}}function Y59(J,Q){let Z=(G)=>{let[q,z]=G.split("-");return{parts:q?.split(".").map(Number)||[],label:z}},X=Z(J),Y=Z(Q),K=Math.max(X.parts.length,Y.parts.length);for(let G=0;G<K;G++){let q=X.parts[G]||0,z=Y.parts[G]||0;if(q<z)return-1;if(q>z)return 1}if(X.label===Y.label)return 0;if(!X.label&&Y.label)return 1;if(X.label&&!Y.label)return-1;if(X.label&&Y.label)return X.label<Y.label?-1:1;return 0}C0();function Qf1(J,Q){let Z=new b8,X=Z.pipe(M9({shouldCountRefs:!1}));return setImmediate(async()=>{let Y=new rq().scoped("update"),K=X.subscribe({next:(G)=>{Y.debug("emit new state",G)}});try{let G=process.env.AMP_TEST_UPDATE_STATUS;if(G){Y.debug("using fake update status for testing",{status:G}),await E_(500),Z.next(G);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){Y.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let q=await Q.get("updates.mode");if(q==="disabled"){Y.debug("checking disabled");return}Y.debug("checking",{currentVersion:J,mode:q});let z=await b51(J);if(!(z.latestVersion&&z.hasUpdate)){Y.debug("no update available");return}let U=await x51();if(!q)q=U==="pnpm"?"warn":"auto",Y.debug("no configured update mode; selected default based on package manager",{packageManager:U,mode:q});if(q==="warn"){Z.next("update-available");return}if(!U){Y.debug("auto-update not supported, falling back to warn mode"),Z.next("update-available");return}try{await Zp(z.latestVersion,U);let W=await eV(z.latestVersion),F={from:z.currentVersion,to:z.latestVersion,...W};if(W.status==="same")Y.info("success",F),Z.next("updated");else Y.warn("success with warning",F),Z.next("updated-with-warning")}catch(W){Z.next("update-error")}}catch(G){Y.debug("check failed",{error:G})}finally{await E_(5000),Z.next("hidden"),K.unsubscribe(),Z.complete()}}),{state:X}}import{stderr as JW}from"node:process";function iZ6(J){let Q=new Bu().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(X)=>{await ty1(X.force||!1,X.verbose||!1,"0.0.1761379287-ge22fe5"),process.exit()});J.addCommand(Q,{hidden:!0});let Z=new Bu("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(X)=>{await K59(X.version)});J.addCommand(Z)}async function K59(J){if(process.env.AMP_SKIP_UPDATE_CHECK==="1")JW.write(z8.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
5910
5910
|
|
|
5911
5911
|
`));try{if(!J){JW.write(z8.blue(`Checking for updates...
|
|
5912
|
-
`));let{hasUpdate:Z,latestVersion:X}=await b51("0.0.
|
|
5913
|
-
`));let Y=await eV("0.0.
|
|
5912
|
+
`));let{hasUpdate:Z,latestVersion:X}=await b51("0.0.1761379287-ge22fe5");if(!Z){JW.write(z8.green(`✓ Amp CLI is already up to date.
|
|
5913
|
+
`));let Y=await eV("0.0.1761379287-ge22fe5");if(Y.warning)JW.write(`
|
|
5914
5914
|
`+z8.yellow(Y.warning)+`
|
|
5915
5915
|
`);process.exit(0)}if(!X)JW.write(z8.yellow("[WARN] could not find latest version")),process.exit(0);J=X}JW.write(z8.blue(`Updating to version ${J}...
|
|
5916
5916
|
`)),await Zp(J,void 0,(Z)=>{JW.write(z8.dim(`Running: ${Z}
|
|
@@ -6282,7 +6282,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||ZO}function vX6(J,Q){let
|
|
|
6282
6282
|
`);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Z).option("--only <field>","Extract only the specified field from the result").allowUnknownOption(!0).allowExcessArguments(!0).action(async function(X,Y,K){let G=K.optsWithGlobals(),q=await Q(K,G),z=0;await q.mcpService.initialized;let U=K.args.slice(1),W;if(CX6()){let F=[];for await(let H of process.stdin)F.push(H);W=Buffer.concat(F).toString("utf-8").trim()}await PX6({toolName:X,rawArgs:U,stdinInput:W,only:Y.only,threadDeps:q,stdout:process.stdout,stderr:process.stderr,exit:(F)=>{z=F}}),await q.asyncDispose(),q.cleanupTerminal(),process.exit(z)})}import{randomBytes as PH9}from"node:crypto";import{homedir as TH9}from"node:os";import Dd from"node:path";C0();G0();var kX6=120000,_X6=180000;function Uf1(J,Q=Date.now()){return Q-J<_X6}function Wf1(J,Q,Z=()=>!0,X){let Y=null,K=[],G=5;return fd(kX6).pipe(v2(void 0),q8(()=>d6(async(q)=>{if(!Z())return u.debug("[Ads] Skipping ad fetch (user inactive or ad already fetched)"),Y;let z=await X?.getContext();u.debug("[Ads] Fetching ad from server",{hasContext:!!z});let U=await J.getCurrentAd({context:z,excludeAdIds:K},{config:Q,signal:q});if(!U.ok)throw u.error("[Ads] Failed to fetch ad",{error:U.error.message}),Error(U.error.message);if(U.result){if(Y=U.result,K.length>=G)K.shift();K.push(Y.id),u.debug("[Ads] Received ad from server",{adTitle:Y.title,matchType:Y.matchType,matchedPatterns:Y.matchedPatterns,candidateAdPoolCount:Y.candidateAdPoolCount,recentlyShownCount:K.length})}else u.debug("[Ads] No ad available from server");return Y})),J8((q,z)=>q?.id===z?.id))}G0();lj();W2();JD();M2();$L();N8();b6();function xX6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}function bX6(J,Q,Z){if(J.agentMode)return J.agentMode;if(Q?.agentMode){let X=Q.agentMode;if(X==="free"){if(Z?.canUseAmpFree??!1)return"free";return"smart"}return X}return"smart"}G0();JD();import kJ9 from"node:fs";import yX6 from"node:path";function fX6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!yX6.isAbsolute(Q))return null;return u.debug("Extracted image path",{original:J,extracted:Q}),Q}function hX6(J){try{let Q=yX6.extname(J).toLowerCase(),Z=M10(Q);if(!Z)return u.warn("Unsupported image file extension",{ext:Q}),null;try{let X=kJ9.readFileSync(J);return _J9(X,Z)}catch(X){u.error(`Failed to read image file ${J}:`,X)}}catch(Q){u.error("Error handling image file path",{imagePath:J,error:Q})}return null}function _J9(J,Q){if(J.length>_W)return u.warn(`Image file too large: ${J.length} bytes (max: ${_W})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}import{execSync as PK9}from"node:child_process";Fj();G0();import{spawn as xJ9}from"node:child_process";import{promises as bJ9}from"node:fs";function gX6(J){return J.kind==="executable"}function mX6(J){return J.kind==="markdown"}var JB=50000,uX6=300000;async function Kp(J,Q,Z,X={}){let{timeoutMs:Y=uX6,signal:K}=X;try{let G=await Z.getCommand(J);if(!G)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(u.debug("Executing command",{commandName:J,filePath:G.filePath,args:Q}),mX6(G))return await yJ9(G,Q);else if(gX6(G))return await fJ9(G,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(G){return u.error("Failed to execute command",{commandName:J,error:G}),{success:!1,output:"",error:G instanceof Error?G.message:"Unknown error occurred"}}}async function yJ9(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await bJ9.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>JB?Z.slice(0,JB)+`
|
|
6283
6283
|
... (output truncated at ${JB} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function fJ9(J,Q,Z=uX6,X){return new Promise((Y)=>{let[K,G]=hJ9(J,Q);u.debug("Spawning command",{spawnCommand:K,spawnArgs:G.slice(0,10),filePath:J.filePath,timeoutMs:Z});let q=z10(X),z=!1,U=setTimeout(()=>{z=!0,q.abort(),u.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),W=xJ9(K,G,{stdio:["pipe","pipe","pipe"],signal:q.signal,detached:!0}),F=[],H=[],B=0;W.stdout?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=JB)F.push(V);else{let N=JB-(B-V.length);if(N>0)F.push(V.slice(0,N))}}),W.stderr?.on("data",(M)=>{let V=M.toString();if(B+=V.length,B<=JB)H.push(V);else{let N=JB-(B-V.length);if(N>0)H.push(V.slice(0,N))}}),W.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:F.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(q.signal.aborted){Y({success:!1,output:F.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=F.join(""),L=H.join(""),A=N;if(!V&&!N.trim()&&L.trim())A=L;else if(L.trim())A+=N?`
|
|
6284
6284
|
${L}`:L;if(B>JB)A+=`
|
|
6285
|
-
... (output truncated at ${JB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function hJ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return mJ9(Z,X?[...X]:null,Y,Q);else return gJ9(Z,X?[...X]:null,Y,Q)}function gJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function mJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}G0();lj();W2();bB();fX();Oz();b6();C0();var p51={};R6(p51,{scrollUp:()=>GQ9,scrollDown:()=>qQ9,link:()=>BQ9,image:()=>DQ9,iTerm:()=>MQ9,exitAlternativeScreen:()=>FQ9,eraseUp:()=>KQ9,eraseStartLine:()=>XQ9,eraseScreen:()=>Ff1,eraseLines:()=>QQ9,eraseLine:()=>lX6,eraseEndLine:()=>ZQ9,eraseDown:()=>YQ9,enterAlternativeScreen:()=>WQ9,cursorUp:()=>dX6,cursorTo:()=>dJ9,cursorShow:()=>JQ9,cursorSavePosition:()=>aJ9,cursorRestorePosition:()=>rJ9,cursorPrevLine:()=>tJ9,cursorNextLine:()=>oJ9,cursorMove:()=>cJ9,cursorLeft:()=>cX6,cursorHide:()=>eJ9,cursorGetPosition:()=>sJ9,cursorForward:()=>iJ9,cursorDown:()=>lJ9,cursorBackward:()=>nJ9,clearTerminal:()=>UQ9,clearScreen:()=>zQ9,beep:()=>HQ9});import Hf1 from"node:process";var u51=globalThis.window?.document!==void 0,gw2=globalThis.process?.versions?.node!==void 0,mw2=globalThis.process?.versions?.bun!==void 0,uw2=globalThis.Deno?.version?.deno!==void 0,pw2=globalThis.process?.versions?.electron!==void 0,dw2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,cw2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,lw2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,iw2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,nw2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Gp=globalThis.navigator?.userAgentData?.platform,aw2=Gp==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",rw2=Gp==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",sw2=Gp==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",ow2=Gp==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),tw2=Gp==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var j2="\x1B[",zp="\x1B]",IC="\x07",qp=";",pX6=!u51&&Hf1.env.TERM_PROGRAM==="Apple_Terminal",uJ9=!u51&&Hf1.platform==="win32",pJ9=u51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Hf1.cwd,dJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return j2+(J+1)+"G";return j2+(Q+1)+qp+(J+1)+"H"},cJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=j2+-J+"D";else if(J>0)Z+=j2+J+"C";if(Q<0)Z+=j2+-Q+"A";else if(Q>0)Z+=j2+Q+"B";return Z},dX6=(J=1)=>j2+J+"A",lJ9=(J=1)=>j2+J+"B",iJ9=(J=1)=>j2+J+"C",nJ9=(J=1)=>j2+J+"D",cX6=j2+"G",aJ9=pX6?"\x1B7":j2+"s",rJ9=pX6?"\x1B8":j2+"u",sJ9=j2+"6n",oJ9=j2+"E",tJ9=j2+"F",eJ9=j2+"?25l",JQ9=j2+"?25h",QQ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=lX6+(Z<J-1?dX6():"");if(J)Q+=cX6;return Q},ZQ9=j2+"K",XQ9=j2+"1K",lX6=j2+"2K",YQ9=j2+"J",KQ9=j2+"1J",Ff1=j2+"2J",GQ9=j2+"S",qQ9=j2+"T",zQ9="\x1Bc",UQ9=uJ9?`${Ff1}${j2}0f`:`${Ff1}${j2}3J${j2}H`,WQ9=j2+"?1049h",FQ9=j2+"?1049l",HQ9=IC,BQ9=(J,Q)=>[zp,"8",qp,qp,Q,IC,J,zp,"8",qp,qp,IC].join(""),DQ9=(J,Q={})=>{let Z=`${zp}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+IC},MQ9={setCwd:(J=pJ9())=>`${zp}50;CurrentDir=${J}${IC}`,annotation(J,Q={}){let Z=`${zp}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+IC}};var d51=C6(tX6(),1);function ZN(J,Q,{target:Z="stdout",...X}={}){if(!d51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return p51.link(J,Q)}ZN.isSupported=d51.default.stdout;ZN.stderr=(J,Q,Z={})=>ZN(J,Q,{target:"stderr",...Z});ZN.stderr.isSupported=d51.default.stderr;G0();fX();class Up{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1761350495-gee8ea9"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await $a(Q,this.configService)}catch(Q){u.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}import{execFile as l51}from"node:child_process";import{platform as Nf1}from"node:os";import{promisify as AQ9}from"node:util";var c51=AQ9(l51),wQ9=(J)=>`\x1B]52;c;${J}\x1B\\`,RQ9="\x1B]52;c;?\x1B\\",OQ9="\x1B]52;p;?\x1B\\";class eX6{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;setCapabilities(J){this.capabilities=J}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(J){try{return await c51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=l51("pbcopy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`pbcopy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Q=l51("wl-copy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`wl-copy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Q=l51("xclip",["-selection","clipboard"]);return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`xclip exited with code ${Y}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(J){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise)return this.pendingReadPromise;this.pendingReadPromise=new Promise((Z)=>{this.readResolve=Z,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,Z(null)},2000),process.stdout.write(J)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(RQ9)}handleOSC52Response(J){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(J,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:J}=await c51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await c51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await c51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(OQ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Nf1()==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}}return null}async readPrimarySelection(){if(Nf1()==="darwin")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(J){if(this.isOsc52Supported()){let Z=Buffer.from(J).toString("base64"),X=wQ9(Z);process.stdout.write(X);return}if(Nf1()==="darwin"){if(await this.writeToPbcopy(J))return}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return}}}var NY=new eX6;G0();class e9{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function i51(J){if(J instanceof e9)return{title:"Info",description:J.message,type:"info"};return u.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var UN=null,TK9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(UN)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (M51(),Py1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{UN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});UN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{UN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/threads/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => C6(wp(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){u.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new e9(`Continue at ${F}`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}},disconnect:{name:"disconnect",description:"Disconnect from web interface",execute:async(J,Q)=>{if(!UN)return new e9("Not connected to Amp web interface");try{UN.disconnect();let Z=UN.clientID;return UN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new e9(`Disconnected from Amp web interface
|
|
6285
|
+
... (output truncated at ${JB} characters)`;Y({success:V,output:A.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),W.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:F.join(""),error:V})})})}function hJ9(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return mJ9(Z,X?[...X]:null,Y,Q);else return gJ9(Z,X?[...X]:null,Y,Q)}function gJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function mJ9(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}G0();lj();W2();bB();fX();Oz();b6();C0();var p51={};R6(p51,{scrollUp:()=>GQ9,scrollDown:()=>qQ9,link:()=>BQ9,image:()=>DQ9,iTerm:()=>MQ9,exitAlternativeScreen:()=>FQ9,eraseUp:()=>KQ9,eraseStartLine:()=>XQ9,eraseScreen:()=>Ff1,eraseLines:()=>QQ9,eraseLine:()=>lX6,eraseEndLine:()=>ZQ9,eraseDown:()=>YQ9,enterAlternativeScreen:()=>WQ9,cursorUp:()=>dX6,cursorTo:()=>dJ9,cursorShow:()=>JQ9,cursorSavePosition:()=>aJ9,cursorRestorePosition:()=>rJ9,cursorPrevLine:()=>tJ9,cursorNextLine:()=>oJ9,cursorMove:()=>cJ9,cursorLeft:()=>cX6,cursorHide:()=>eJ9,cursorGetPosition:()=>sJ9,cursorForward:()=>iJ9,cursorDown:()=>lJ9,cursorBackward:()=>nJ9,clearTerminal:()=>UQ9,clearScreen:()=>zQ9,beep:()=>HQ9});import Hf1 from"node:process";var u51=globalThis.window?.document!==void 0,gw2=globalThis.process?.versions?.node!==void 0,mw2=globalThis.process?.versions?.bun!==void 0,uw2=globalThis.Deno?.version?.deno!==void 0,pw2=globalThis.process?.versions?.electron!==void 0,dw2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,cw2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,lw2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,iw2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,nw2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,Gp=globalThis.navigator?.userAgentData?.platform,aw2=Gp==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",rw2=Gp==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",sw2=Gp==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",ow2=Gp==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),tw2=Gp==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android";var j2="\x1B[",zp="\x1B]",IC="\x07",qp=";",pX6=!u51&&Hf1.env.TERM_PROGRAM==="Apple_Terminal",uJ9=!u51&&Hf1.platform==="win32",pJ9=u51?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Hf1.cwd,dJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return j2+(J+1)+"G";return j2+(Q+1)+qp+(J+1)+"H"},cJ9=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=j2+-J+"D";else if(J>0)Z+=j2+J+"C";if(Q<0)Z+=j2+-Q+"A";else if(Q>0)Z+=j2+Q+"B";return Z},dX6=(J=1)=>j2+J+"A",lJ9=(J=1)=>j2+J+"B",iJ9=(J=1)=>j2+J+"C",nJ9=(J=1)=>j2+J+"D",cX6=j2+"G",aJ9=pX6?"\x1B7":j2+"s",rJ9=pX6?"\x1B8":j2+"u",sJ9=j2+"6n",oJ9=j2+"E",tJ9=j2+"F",eJ9=j2+"?25l",JQ9=j2+"?25h",QQ9=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=lX6+(Z<J-1?dX6():"");if(J)Q+=cX6;return Q},ZQ9=j2+"K",XQ9=j2+"1K",lX6=j2+"2K",YQ9=j2+"J",KQ9=j2+"1J",Ff1=j2+"2J",GQ9=j2+"S",qQ9=j2+"T",zQ9="\x1Bc",UQ9=uJ9?`${Ff1}${j2}0f`:`${Ff1}${j2}3J${j2}H`,WQ9=j2+"?1049h",FQ9=j2+"?1049l",HQ9=IC,BQ9=(J,Q)=>[zp,"8",qp,qp,Q,IC,J,zp,"8",qp,qp,IC].join(""),DQ9=(J,Q={})=>{let Z=`${zp}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+IC},MQ9={setCwd:(J=pJ9())=>`${zp}50;CurrentDir=${J}${IC}`,annotation(J,Q={}){let Z=`${zp}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+IC}};var d51=C6(tX6(),1);function ZN(J,Q,{target:Z="stdout",...X}={}){if(!d51.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return p51.link(J,Q)}ZN.isSupported=d51.default.stdout;ZN.stderr=(J,Q,Z={})=>ZN(J,Q,{target:"stderr",...Z});ZN.stderr.isSupported=d51.default.stderr;G0();fX();class Up{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Q){this.enabled=J;this.configService=Q;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1761379287-ge22fe5"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await $a(Q,this.configService)}catch(Q){u.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}import{execFile as l51}from"node:child_process";import{platform as Nf1}from"node:os";import{promisify as AQ9}from"node:util";var c51=AQ9(l51),wQ9=(J)=>`\x1B]52;c;${J}\x1B\\`,RQ9="\x1B]52;c;?\x1B\\",OQ9="\x1B]52;p;?\x1B\\";class eX6{capabilities=null;pendingReadPromise=null;readResolve=null;readTimeout=null;setCapabilities(J){this.capabilities=J}isOsc52Supported(){return this.capabilities?.osc52??!1}async commandExists(J){try{return await c51("which",[J]),!0}catch{return!1}}async writeToPbcopy(J){try{let Q=l51("pbcopy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`pbcopy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToWlCopy(J){try{let Q=l51("wl-copy");return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`wl-copy exited with code ${Y}`))})}),!0}catch{return!1}}async writeToXclip(J){try{let Q=l51("xclip",["-selection","clipboard"]);return Q.stdin?.write(J),Q.stdin?.end(),await new Promise((Z,X)=>{Q.on("close",(Y)=>{if(Y===0)Z();else X(Error(`xclip exited with code ${Y}`))})}),!0}catch{return!1}}async readFromOSC52WithQuery(J){if(!this.isOsc52Supported())return null;if(this.pendingReadPromise)return this.pendingReadPromise;this.pendingReadPromise=new Promise((Z)=>{this.readResolve=Z,this.readTimeout=setTimeout(()=>{this.readResolve=null,this.pendingReadPromise=null,Z(null)},2000),process.stdout.write(J)});let Q=await this.pendingReadPromise;return this.pendingReadPromise=null,Q}async readFromOSC52(){return this.readFromOSC52WithQuery(RQ9)}handleOSC52Response(J){if(this.readResolve&&this.readTimeout){clearTimeout(this.readTimeout),this.readTimeout=null;try{let Q=Buffer.from(J,"base64").toString("utf8");this.readResolve(Q)}catch{this.readResolve(null)}this.readResolve=null,this.pendingReadPromise=null}}async readFromPbpaste(){try{let{stdout:J}=await c51("pbpaste");return J}catch{return null}}async readFromWlPaste(J){try{let Q=["--no-newline"];if(J==="primary")Q.push("--primary");let{stdout:Z}=await c51("wl-paste",Q);return Z}catch{return null}}async readFromXclip(J){try{let{stdout:Q}=await c51("xclip",["-selection",J,"-o"]);return Q}catch{return null}}async readFromOSC52Primary(){return this.readFromOSC52WithQuery(OQ9)}async readText(){if(this.isOsc52Supported()){let Q=await this.readFromOSC52();if(Q!==null)return Q}if(Nf1()==="darwin"){let Q=await this.readFromPbpaste();if(Q!==null)return Q}else{if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("clipboard");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("clipboard");if(Q!==null)return Q}}return null}async readPrimarySelection(){if(Nf1()==="darwin")return this.readText();if(this.isOsc52Supported()){let Q=await this.readFromOSC52Primary();if(Q!==null)return Q}if(await this.commandExists("wl-paste")){let Q=await this.readFromWlPaste("primary");if(Q!==null)return Q}if(await this.commandExists("xclip")){let Q=await this.readFromXclip("primary");if(Q!==null)return Q}return null}async writeText(J){if(this.isOsc52Supported()){let Z=Buffer.from(J).toString("base64"),X=wQ9(Z);process.stdout.write(X);return}if(Nf1()==="darwin"){if(await this.writeToPbcopy(J))return}else{if(await this.commandExists("wl-copy")&&await this.writeToWlCopy(J))return;if(await this.commandExists("xclip")&&await this.writeToXclip(J))return}}}var NY=new eX6;G0();class e9{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function i51(J){if(J instanceof e9)return{title:"Info",description:J.message,type:"info"};return u.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var UN=null,TK9={connect:{name:"connect",description:"Connect CLI to web interface for current thread access",execute:async(J,Q)=>{try{if(UN)return Error("Already connected. Use /disconnect first to reconnect.");let{connectedClientsService:Z}=J;await Z.start({clientId:J.clientId,currentThreadID:J.worker.thread.id});let Y=Z.getCurrentStatus().clientID||"unknown",{connectBackground:K}=await Promise.resolve().then(() => (M51(),Py1)),G=await K({worker:J.worker},J.configService,{clientId:J.clientId,onUserDisconnect:()=>{UN=null,Z.sendStatus({connected:!1,enabled:!1,errorMessage:"Disconnected by user via web interface"})}});UN=G,G.promise.then(()=>{Z.sendStatus({connected:!0,errorMessage:void 0})}).catch((M)=>{UN=null,Z.sendStatus({connected:!1,errorMessage:M.message})});let z=(await J.configService.getLatest()).settings.url,U=J.worker.thread.id,W=new URL(`/threads/${U}`,z).toString(),F=new URL("/clients",z).toString(),H="";try{H=await(await Promise.resolve().then(() => C6(wp(),1))).toString(W,{type:"utf8",margin:2,color:{dark:"#000000",light:"#FFFFFF"}})}catch(M){u.error("Failed to generate QR code:",M)}if((process.stdout.rows||24)>=30&&H&&J.onShowQRCodeOverlay)J.onShowQRCodeOverlay({url:F,qrCode:H});else return new e9(`Continue at ${F}`)}catch(Z){return J.connectedClientsService.sendStatus({connected:!1,errorMessage:Z.message}),Error(`Failed to start connection: ${Z.message}`)}}},disconnect:{name:"disconnect",description:"Disconnect from web interface",execute:async(J,Q)=>{if(!UN)return new e9("Not connected to Amp web interface");try{UN.disconnect();let Z=UN.clientID;return UN=null,J.connectedClientsService.sendStatus({connected:!1,enabled:!1,errorMessage:void 0}),new e9(`Disconnected from Amp web interface
|
|
6286
6286
|
Client ID: ${Z}
|
|
6287
6287
|
Server will clean up automatically within 60 seconds`)}catch(Z){return Error(`Failed to disconnect: ${Z.message}`)}}}};class Fh1{configService;commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=AS(),Q){this.configService=Q;this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Z)=>this.latestCustom=Z),this.telemetrySubmitter=new Up(async()=>{try{return(await this.configService.getLatest()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}},this.configService),this.configService.config.pipe(k0((Z)=>EY(Z.settings)),J8()).subscribe((Z)=>{this._initBaseCommands(Z.length>1)})}_initBaseCommands(J){if(this.commands={...CK9},process.env.AMP_CONNECT==="1")Object.assign(this.commands,TK9);if(J)Object.assign(this.commands,SK9)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((q)=>{u.debug("Failed to submit command telemetry",q)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((q)=>q.name===J),G=await Kp(J,Z,this.customRegistry,{signal:X});if(G.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:G.output});return}else{Q.submitMessage(G.output);return}return Error(G.error??`Command '${J}' failed`)}query(J,Q,Z){let X=Object.values(this.commands).filter((K)=>{if(!Q||!K.isVisible)return!0;return K.isVisible(Q,Z)}),Y=this.latestCustom.filter((K)=>K.available).map((K)=>({name:K.name,description:"Custom command",requiresArgs:K.kind==="executable",execute:(G,q)=>this.execute(K.name,G,q??[])}));return[...X,...Y]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}getCustomCommand(J){return this.latestCustom.find((Q)=>Q.name===J)}}var CK9={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${_5} file in the current workspace`,execute:async(J,Q)=>{let Z=await J.configService.getLatest(),X=kQ(Z.settings),K=J.getInMemoryAgentModeOverride()??X;J.worker.handle({type:"user:message",message:{content:[{type:"text",text:Ia}],agentMode:K}});return}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{return J.openInEditor("")}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return BZ("dangerouslyAllowAll",!1),new e9("Amp is now following permissions rules for this session")}catch(K){return u.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return BZ("dangerouslyAllowAll",!0),new e9("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return u.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await QW();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw u.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:QW};await $C(Y);return}catch(Y){u.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return u.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},handoff:{name:"handoff",description:"Draft a new thread with relevant context from current thread: /handoff <your goal>",requiresArgs:!0,execute:async()=>{return},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new e9(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return u.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((q)=>q.type==="text").map((q)=>q.text).join("").trim()}).filter(Boolean).join(`
|
|
6288
6288
|
`).trim();await J.worker.handle({type:"user:message-queue:discard"}),J.editorDispatch({type:"set-input",input:Y})},isVisible:(J)=>(J.queuedMessages?.length??0)>0},share:{name:"share",description:"Set thread visibility - `/share private|workspace|group|public`",execute:async(J,Q)=>{let{thread:Z,threadSyncService:X,ampURL:Y}=J;if(!Q||Q.length===0)return Error("Please specify a visibility option: private, workspace, group, or public");let K=nW(new URL(Y),Z.id).toString(),q=`Thread URL: ${ZN(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"public"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new e9(`${q}
|
|
@@ -6497,7 +6497,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
|
6497
6497
|
`),J.stdout.write(`Thread: ${H}
|
|
6498
6498
|
`),J.stdout.write(`Continue this thread with: amp threads continue ${W}
|
|
6499
6499
|
`)}}function Jp1(J){return J==="smart"?E1.rgb(3,197,97):J==="free"?E1.rgb(0,184,255):SH9(J)}function SH9(J){let Q=0;for(let Y=0;Y<J.length;Y++){let K=J.charCodeAt(Y);Q=(Q<<5)-Q+K,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Z.length;return E1.index(Z[X])}Sh1();if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){QG.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
6500
|
-
`)}var Zp1=Qp1.join(Tl1||Qp1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function bH9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),G=Z||"Warning",q=!1;J.warn(K,{name:G,code:X})}}function cq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")BZ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new c9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${z8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")BZ("experimental.agentMode",Q.agentMode)}async function Yp1(J){try{await kH9(Qp1.dirname(Zp1),{recursive:!0}),await _H9(Zp1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function yH9(){try{return(await OF6(Zp1,"utf-8")).trim()}catch(J){return null}}function fH9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return PS("mcpServers",{global:X,workspace:Q})}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var AF6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??DX,description:`Custom settings file path (overrides the default location ${DX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Ny1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:nK(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:GO}],wF6=(J)=>("deprecated"in J)&&J.deprecated===!0,hH9=(J)=>("hidden"in J)&&J.hidden===!0,gH9=(J)=>("default"in J),mH9=(J)=>("default"in J)?J.default:void 0;function uH9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((q)=>Z.includes(q)||q.includes(Z)),G="Run amp --help for a list of available commands.";if(K.length>0)G=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new c9(iK.unknownCommand(Z),1,G)}}var jF6=null;function Y64(){return jF6}function yQ1(J){return{...J,getThreadEnvironment:U51,vfs:b40({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new f_(J.fileSystem),generateThreadTitle:Bs,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Kp1=w0.file(xH9.homedir()),$F6=process.env.XDG_CONFIG_HOME?w0.file(process.env.XDG_CONFIG_HOME):b0.joinPath(Kp1,".config");async function lq(J,Q){vn1("0.0.
|
|
6500
|
+
`)}var Zp1=Qp1.join(Tl1||Qp1.join(process.env.HOME||process.cwd(),".local","state"),"amp","last-thread-id");function bH9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),G=Z||"Warning",q=!1;J.warn(K,{name:G,code:X})}}function cq(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")BZ("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")throw new c9("The --try-gpt5 flag has been removed.",1,`GPT-5 is now available as the oracle. Read why: ${z8.blue("https://ampcode.com/news/gpt-5-oracle")}`);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")BZ("experimental.agentMode",Q.agentMode)}async function Yp1(J){try{await kH9(Qp1.dirname(Zp1),{recursive:!0}),await _H9(Zp1,J,"utf-8")}catch(Q){u.debug("Failed to save last thread ID",Q)}}async function yH9(){try{return(await OF6(Zp1,"utf-8")).trim()}catch(J){return null}}function fH9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z);return PS("mcpServers",{global:X,workspace:Q})}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}var AF6=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`,deprecated:!0},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??DX,description:`Custom settings file path (overrides the default location ${DX})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(u).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${Ny1})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:nK(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration."},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection."},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"tryGpt5",long:"try-gpt5",type:"switch",default:!1,description:"[DEPRECATED] Try GPT-5 as the primary agent model (see https://ampcode.com/news/gpt-5-oracle)",deprecated:!0},{name:"agentMode",long:"agent-mode",type:"option",description:"Set the experimental agent mode configuration",hidden:!0,choices:GO}],wF6=(J)=>("deprecated"in J)&&J.deprecated===!0,hH9=(J)=>("hidden"in J)&&J.hidden===!0,gH9=(J)=>("default"in J),mH9=(J)=>("default"in J)?J.default:void 0;function uH9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((q)=>Z.includes(q)||q.includes(Z)),G="Run amp --help for a list of available commands.";if(K.length>0)G=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new c9(iK.unknownCommand(Z),1,G)}}var jF6=null;function Y64(){return jF6}function yQ1(J){return{...J,getThreadEnvironment:U51,vfs:b40({os:J.fileSystem},J.configService.config),fileChangeTrackerStorage:new f_(J.fileSystem),generateThreadTitle:Bs,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}var Kp1=w0.file(xH9.homedir()),$F6=process.env.XDG_CONFIG_HOME?w0.file(process.env.XDG_CONFIG_HOME):b0.joinPath(Kp1,".config");async function lq(J,Q){vn1("0.0.1761379287-ge22fe5");let Z=hX1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:e1.of([w0.file(process.cwd())]),defaultAmpURL:J.ampURL,homeDir:Kp1,userConfigDir:$F6}),{initializeCLITelemetry:X}=await Promise.resolve().then(() => (xQ1(),_Q1));X(Z);let Y=await Z.getLatest();u.debug("Global configuration initialized",{settingsKeys:Object.keys(Y.settings)});let K=pa(IO({configService:Z})),G=F40({configService:Z,toolService:K}),q=VO0(K,k9,A11).catch((O)=>{u.warn("Toolbox registration failed, continuing anyway:",O)}),z=G.initialized.catch((O)=>{u.warn("MCP service initialization failed, continuing anyway:",O)});if(J.executeMode)await Promise.all([z,q]);if(Q.jetbrains)CO("JetBrains");else if(Q.ide&&SZ6())CO("VS Code");else if(Q.ide&&vZ6())CO("Neovim");if(J.executeMode)kn1(!0);O26(K,{configService:Z});let U,W=T7.status.pipe(k0((O)=>Boolean(O.connected&&O.authenticated)),J8()).subscribe((O)=>{if(O){if(!U)U=K.registerTool(ms)}else U?.dispose(),U=void 0}),F;if(!J.executeMode)F=new $51(process.cwd(),{},!0);else F=new class extends $51{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(e2.write(`No API key found. Starting login flow...
|
|
6501
6501
|
`),!await pH9(J))await BR(),process.exit(1)}let H=await m40({isDevelopment:!1}),B=new vV1(H),M=new LB1(H,Z,{lazy:!0}),V=Q.notifications!==void 0?Q.notifications:!J.executeMode,N=$26({playNotificationSound:async(O)=>{if(V){j26(O);let j=Th1(),$=Ch1();if((!j||$)&&Y.settings["notifications.system.enabled"]!==!1){if(O==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(O==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:B,configService:Z});u.info("Starting Amp background services");let L=lq0({threadService:B,threadHistoryService:M,configService:Z,isExtensionDevelopment:!1}),A;T7.status.subscribe((O)=>{A=O});let R={codebaseContextService:new fZ1({workspaceRoots:[w0.file(process.cwd())],getCurrentFile:()=>{if(!A?.openFile)return;try{return w0.parse(A.openFile)}catch(O){u.warn("Failed to parse current file URI",{uri:A.openFile,error:O});return}},getOpenFiles:()=>{if(!A?.visibleFiles?.length)return[];let O=A.openFile;return A.visibleFiles.filter((j)=>j!==O).map((j)=>{try{return w0.parse(j)}catch($){return u.warn("Failed to parse visible file URI",{uri:j,error:$}),null}}).filter((j)=>j!==null)}}),configService:Z,toolService:K,mcpService:G,threadService:B,threadHistoryService:M,threadSyncService:L,threadStorage:H,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:F,notificationService:N,fileSystem:Q.jetbrains||Q.ide?k40:k9};return{...R,async asyncDispose(){await R.mcpService.dispose(),await R.threadService.asyncDispose(),R.configService.unsubscribe(),R.toolService.dispose(),R.fuzzyServer.dispose(),R.threadSyncService.dispose(),R.settingsStorage[Symbol.dispose](),W.unsubscribe(),U?.dispose()}}}async function pH9(J){if(!J.executeMode){if(!await Yf1("Would you like to log in to Amp? [(y)es, (n)o]: "))return e2.write(`Login cancelled. Run the command again to retry.
|
|
6502
6502
|
`),!1}return await EF6(J)}async function EF6(J){let Q=vH9(32).toString("hex"),Z=await Xf1(J.ampURL,Q);try{await VY(Z)}catch(Y){u.error("Failed to open browser",{error:Y})}let X=await Xf1(J.ampURL,Q,!1);e2.write(`If your browser did not open automatically, visit:
|
|
6503
6503
|
|
|
@@ -6507,13 +6507,13 @@ ${z8.blue.bold(X)}
|
|
|
6507
6507
|
Login successful! You can now use the Amp CLI.
|
|
6508
6508
|
`),!0}catch(Y){return u.error("Login failed",{error:Y}),QG.write(`
|
|
6509
6509
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
|
6510
|
-
`),!1}}function dH9(){let J=new Bu().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((U)=>{if(U.code==="commander.help"||U.code==="commander.version"||U.exitCode===0)VR(),process.exit(0);let W=U.originalError??U;IQ6(W)}),J.option("-V, --version","output the version number",()=>{e2.write(`0.0.
|
|
6510
|
+
`),!1}}function dH9(){let J=new Bu().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((U)=>{if(U.code==="commander.help"||U.code==="commander.version"||U.exitCode===0)VR(),process.exit(0);let W=U.originalError??U;IQ6(W)}),J.option("-V, --version","output the version number",()=>{e2.write(`0.0.1761379287-ge22fe5 (released 2025-10-25T08:06:47.204Z)
|
|
6511
6511
|
`),process.exit(0)}),J.addHelpText("after",PZ6()),J.configureHelp({formatHelp:TZ6}),J.command("logout").description("Log out by removing stored API key").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);await nH9(H)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);await iH9(H,await ly1(F,H.settings))});let Q=async(U,W,F)=>{hX1({storage:W.settings,secretStorage:W.secrets,workspaceRoots:e1.of([w0.file(process.cwd())]),defaultAmpURL:W.ampURL,homeDir:Kp1,userConfigDir:$F6});let H={...W,executeMode:!1};await Xp1(H,{...U,startWithPicker:!0},F)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);await RF6(F,H,W)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);await eH9(F,H,W)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. By default, shows an interactive picker with the most recently used thread at the top. Use --last to continue the last thread directly without the picker.").option("--last","Continue the last thread directly without showing the picker").option("--pick","Pick a thread interactively from a list (DEPRECATED: picker is now the default)").action(async(U,W,F)=>{let H=F.optsWithGlobals(),B=await NX(H);if(W.pick)QG.write(`${z8.yellow("Warning:")} The --pick flag is deprecated. The picker is now shown by default.
|
|
6512
6512
|
`);if(W.last||U||B.executeMode)await tH9(H,B,U,F);else await Q(H,B,F)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(U,W,F)=>{let H=F.optsWithGlobals(),B=await NX(H);await oH9(H,B,U,F)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);await RF6(F,H,W)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(U,W,F)=>{let H=F.optsWithGlobals(),B=await NX(H);await sH9(H,B,U,F,W.support)}),Z.command("rename <threadId> <newName>").alias("r").summary("Rename a thread").description('Change the title of a thread. Quote names with spaces: amp threads rename T-123 "New thread name"').action(async(U,W,F,H)=>{let B=H.optsWithGlobals(),M=await NX(B);await aH9(B,M,U,W,H)}),Z.command("markdown <threadId>").alias("md").summary("Render thread as markdown").description("Render a thread as markdown. This outputs the entire conversation history in a readable markdown format.").action(async(U,W,F)=>{let H=F.optsWithGlobals(),B=await NX(H);await rH9(H,B,U,F)}),vX6(J,async(U,W)=>{let F=await NX(W);cq(U,W);let H=await lq(F,W);return{context:F,mcpService:H.mcpService,toolService:H.toolService,configService:H.configService,cleanupTerminal:VR,asyncDispose:H.asyncDispose.bind(H)}}),GX6(J),tZ6(J,async(U)=>{let W=await NX(U);return{settings:W.settings,getThreadDeps:async(F)=>{cq(F,U);let H=await lq(W,U);return{mcpService:H.mcpService,asyncDispose:H.asyncDispose.bind(H)}}}}),J.command("connect").description("Connect CLI to web interface for multi-thread management").action(async(U,W)=>{let F=W.optsWithGlobals(),H=await NX(F);cq(W,F);let B=await lq(H,F);try{await Iy1(B,B.configService,{})}finally{await B.asyncDispose(),await VR()}});function X(U,W,F){let B=typeof U.description==="string"?U.description:F===void 0?U.description(!0):U.description(F),M=new dV(W,B),V=mH9(U);if(V)M.default(V);if(M.hidden=hH9(U)||wF6(U),"choices"in U)M.choices([...U.choices]);return M}for(let U of AF6)switch(U.type){case"flag":{J.addOption(X(U,`--${U.long}`)),J.addOption(X(U,`--no-${U.long}`,!1));break}case"switch":{J.addOption(X(U,`--${U.long}`,!0));break}default:{J.addOption(X(U,`--${U.long} <value>`));break}}let Y=new dV("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);J.addOption(Y);let K=new dV("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1).hideHelp();J.addOption(K);let G=new dV("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1);J.addOption(G);let q=new dV("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1);J.addOption(q);let z=new dV("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);if(J.addOption(z),process.env.AMP_CONNECT==="1"){let U=new dV("--client-id <clientId>","Override the client ID for connect functionality (default: amp-<pid>@<hostname>)");J.addOption(U)}return J.action(async(U,W)=>{let F=U,H=await NX(F);if(Object.keys(F).forEach((B)=>{let M=AF6.find((V)=>V.name===B);if(M&&wF6(M)&&!gH9(M))QG.write(z8.yellow(`Warning: '--${B}' flag is deprecated
|
|
6513
6513
|
`))}),W.args.length>0)uH9(H,W);await Xp1(H,F,W)}),iZ6(J),J}async function bQ1(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??Kz(),K=yQ1(J);if(Z)await J.threadStorage.set(Y,Z);let G=await WJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,f51(X));let q=J.threadService.observe(Y).subscribe(async(z)=>{if(o7(z,"assistant"))await Yp1(Y),q.unsubscribe()});return await G.resume(),G}async function Xp1(J,Q,Z){let X=y51(Q);if(X instanceof Error)JG(X.message);let Y,K=null;if(Q.streamJsonInput)Y="";else if(typeof Q.execute==="string"){Y=Q.execute;let R=(await Gf1()).trimEnd();if(R)K=R}else Y=(await Gf1()).trimEnd();if(Q.remote&&!J.executeMode)throw new c9("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new c9("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new c9("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new c9("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if((J.executeMode||Q.streamJson)&&Q.agentMode&&Q.agentMode!=="smart")throw new c9(`Execute mode is not permitted with --agent-mode '${Q.agentMode}'`,1);if(Q.stats&&!J.executeMode)throw new c9("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new c9("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&Y===""&&!Q.streamJsonInput)throw new c9("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
|
6514
6514
|
Or pipe via stdin: echo "your message" | amp --execute`);cq(Z,Q);let G=await lq(J,Q);jF6=G;let q=yQ1(G),z=async(R)=>{let O=await OF6(R,"utf-8"),j=JSON.parse(O);if(!AW(j.id))throw new c9(iK.invalidThreadId);return bQ1(G,{visibility:X,thread:j})},U=async(R)=>{if(!AW(R))throw new c9(iK.invalidThreadId);let O=await G.threadService.get(R)??void 0;if(u.info(`[fetchAndStartThread] Loaded thread ${R}, agentMode: ${O?.agentMode??"undefined"}`),O?.agentMode)u.info(`[fetchAndStartThread] Setting runtime override for agentMode to: ${O.agentMode}`),BZ("experimental.agentMode",O.agentMode);else u.info("[fetchAndStartThread] No agentMode on thread, not setting override");return bQ1(G,{visibility:X,thread:O})},W=async()=>{try{if(Q.threadId)return U(Q.threadId);else return bQ1(G,{visibility:X})}catch(R){if(R instanceof c9)throw R;throw await V51(R,Q.threadId),Error("handleError should have called process.exit()")}},F=async()=>{return bQ1(G,{visibility:X})};if(Q.format==="jsonl")QG.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
6515
|
-
`),await BR(),process.exit(1);if(J.executeMode&&Q.remote)await qX6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await gQ6(H,H.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await nr1();let R=await uB({jetbrainsOnly:Q.jetbrains});if(R.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(R.length===1){let O=R[0];if(O)T7.selectConfig(O)}else B=!0}let V=Qf1("0.0.
|
|
6516
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await FZ6({...J,getHook:process.env.AMP_URL?(G,q)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let G=await eZ6(J.mcpConfig);X=fH9(X,G)}let Y=await X.get("url","global");if(!Y)Y=DZ;if(!PB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=al1(X),await X.get("debug.httpLogging"))ll1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:zX6(await ly1(J,X))}}function cH9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(q,z)=>z.toUpperCase()),G=J[Z+1];if(G&&!G.startsWith("--"))Q[K]=G,Z++}}return Q}async function lH9(){let J=cH9(process.argv);if(zQ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),bH9(u),u.info("Starting Amp CLI.",{version:"0.0.
|
|
6515
|
+
`),await BR(),process.exit(1);if(J.executeMode&&Q.remote)await qX6(Y,K,G.configService),await G.asyncDispose(),process.exit(0);let H=await W();if(J.executeMode)await gQ6(H,H.threadID,Y,K,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let B=!1,M=!1;if(Q.jetbrains||Q.ide){await nr1();let R=await uB({jetbrainsOnly:Q.jetbrains});if(R.length===0){if(Q.jetbrains)M=!await G.configService.get("jetbrains.skipInstall")}else if(R.length===1){let O=R[0];if(O)T7.selectConfig(O)}else B=!0}let V=Qf1("0.0.1761379287-ge22fe5",G.settingsStorage),N=e1.of([w0.file(process.cwd())]),L=AS(void 0,N);if(Y)H.handle({type:"user:message",message:{content:[{type:"text",text:Y}]}});let A;try{A=await YJ.getUserFreeTierStatus({},{config:G.configService})}catch(R){A={ok:!1,error:R}}u.info("User free tier status:",A);let w=await FX6();u.info("Loaded session state:",w),await LF6({codebaseContextService:G.codebaseContextService,stdout:process.stdout,history:new vy1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:H.threadID,worker:H,workerDeps:q,configService:G.configService,internalAPIClient:YJ,ampURL:J.ampURL,startNewThread:F,pickAndContinueThread:async()=>{u.info("Thread picker requested - not yet implemented in TUI")},switchToThread:U,ideClient:T7,connectedClientsService:new vc,commandRegistry:L,showJetBrainsInstaller:M,showIdePicker:B,startWithPicker:Q.startWithPicker,updateService:V,inspector:Q.inspector,inspectorPort:Q.inspectorPort,jetbrainsMode:Q.jetbrains,clientId:Q.clientId,sessionState:w,freeTierStatus:A.ok?A.result:void 0}),await G.asyncDispose(),process.exit(0)}async function NX(J){if(J.interactive)QG.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6516
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=process.stdout.isTTY&&process.stderr.isTTY,X=await FZ6({...J,getHook:process.env.AMP_URL?(G,q)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return q()}:void 0});if(J.mcpConfig){let G=await eZ6(J.mcpConfig);X=fH9(X,G)}let Y=await X.get("url","global");if(!Y)Y=DZ;if(!PB(Y))u.info("Targeting custom Amp server",{ampURL:Y});if(X=al1(X),await X.get("debug.httpLogging"))ll1();return{executeMode:Q,isTTY:Z,ampURL:Y,settings:X,secrets:zX6(await ly1(J,X))}}function cH9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(q,z)=>z.toUpperCase()),G=J[Z+1];if(G&&!G.startsWith("--"))Q[K]=G,Z++}}return Q}async function lH9(){let J=cH9(process.argv);if(zQ6({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),bH9(u),u.info("Starting Amp CLI.",{version:"0.0.1761379287-ge22fe5",buildTimestamp:"2025-10-25T08:06:47.204Z"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new c9(iK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await dH9().parseAsync(process.argv)}lH9().catch(V51);async function iH9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),e2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
6517
6517
|
`);else if(!PB(J.ampURL))e2.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
6518
6518
|
`);let Z=process.env.AMP_API_KEY;if(Z)e2.write(`API key found in environment variable, storing...
|
|
6519
6519
|
`),await Q.set("apiKey",Z,J.ampURL),e2.write(`API key successfully stored.
|
package/package.json
CHANGED