@buoy-gg/mcp 7.0.60 → 7.0.61

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/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use strict";var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf;var __hasOwnProp=Object.prototype.hasOwnProperty;var __commonJS=(e,n)=>function t(){return n||(0,e[__getOwnPropNames(e)[0]])((n={exports:{}}).exports,n),n.exports};var __export=(e,n)=>{for(var t in n)__defProp(e,t,{get:n[t],enumerable:true})};var __copyProps=(e,n,t,r)=>{if(n&&typeof n==="object"||typeof n==="function"){for(let i of __getOwnPropNames(n))if(!__hasOwnProp.call(e,i)&&i!==t)__defProp(e,i,{get:()=>n[i],enumerable:!(r=__getOwnPropDesc(n,i))||r.enumerable})}return e};var __toESM=(e,n,t)=>(t=e!=null?__create(__getProtoOf(e)):{},__copyProps(n||!e||!e.__esModule?__defProp(t,"default",{value:e,enumerable:true}):t,e));var __toCommonJS=e=>__copyProps(__defProp({},"__esModule",{value:true}),e);var require_chunkstream=__commonJS({"../../node_modules/pngjs/lib/chunkstream.js"(e,n){"use strict";var t=require("util");var r=require("stream");var i=n.exports=function(){r.call(this);this._buffers=[];this._buffered=0;this._reads=[];this._paused=false;this._encoding="utf8";this.writable=true};t.inherits(i,r);i.prototype.read=function(o,a){this._reads.push({length:Math.abs(o),allowLess:o<0,func:a});process.nextTick(function(){this._process();if(this._paused&&this._reads&&this._reads.length>0){this._paused=false;this.emit("drain")}}.bind(this))};i.prototype.write=function(o,a){if(!this.writable){this.emit("error",new Error("Stream not writable"));return false}let s;if(Buffer.isBuffer(o)){s=o}else{s=Buffer.from(o,a||this._encoding)}this._buffers.push(s);this._buffered+=s.length;this._process();if(this._reads&&this._reads.length===0){this._paused=true}return this.writable&&!this._paused};i.prototype.end=function(o,a){if(o){this.write(o,a)}this.writable=false;if(!this._buffers){return}if(this._buffers.length===0){this._end()}else{this._buffers.push(null);this._process()}};i.prototype.destroySoon=i.prototype.end;i.prototype._end=function(){if(this._reads.length>0){this.emit("error",new Error("Unexpected end of input"))}this.destroy()};i.prototype.destroy=function(){if(!this._buffers){return}this.writable=false;this._reads=null;this._buffers=null;this.emit("close")};i.prototype._processReadAllowingLess=function(o){this._reads.shift();let a=this._buffers[0];if(a.length>o.length){this._buffered-=o.length;this._buffers[0]=a.slice(o.length);o.func.call(this,a.slice(0,o.length))}else{this._buffered-=a.length;this._buffers.shift();o.func.call(this,a)}};i.prototype._processRead=function(o){this._reads.shift();let a=0;let s=0;let c=Buffer.alloc(o.length);while(a<o.length){let u=this._buffers[s++];let l=Math.min(u.length,o.length-a);u.copy(c,a,0,l);a+=l;if(l!==u.length){this._buffers[--s]=u.slice(l)}}if(s>0){this._buffers.splice(0,s)}this._buffered-=o.length;o.func.call(this,c)};i.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let o=this._reads[0];if(o.allowLess){this._processReadAllowingLess(o)}else if(this._buffered>=o.length){this._processRead(o)}else{break}}if(this._buffers&&!this.writable){this._end()}}catch(o){this.emit("error",o)}}}});var require_interlace=__commonJS({"../../node_modules/pngjs/lib/interlace.js"(e){"use strict";var n=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];e.getImagePasses=function(t,r){let i=[];let o=t%8;let a=r%8;let s=(t-o)/8;let c=(r-a)/8;for(let u=0;u<n.length;u++){let l=n[u];let d=s*l.x.length;let h=c*l.y.length;for(let p=0;p<l.x.length;p++){if(l.x[p]<o){d++}else{break}}for(let p=0;p<l.y.length;p++){if(l.y[p]<a){h++}else{break}}if(d>0&&h>0){i.push({width:d,height:h,index:u})}}return i};e.getInterlaceIterator=function(t){return function(r,i,o){let a=r%n[o].x.length;let s=(r-a)/n[o].x.length*8+n[o].x[a];let c=i%n[o].y.length;let u=(i-c)/n[o].y.length*8+n[o].y[c];return s*4+u*t*4}}}});var require_paeth_predictor=__commonJS({"../../node_modules/pngjs/lib/paeth-predictor.js"(e,n){"use strict";n.exports=function t(r,i,o){let a=r+i-o;let s=Math.abs(a-r);let c=Math.abs(a-i);let u=Math.abs(a-o);if(s<=c&&s<=u){return r}if(c<=u){return i}return o}}});var require_filter_parse=__commonJS({"../../node_modules/pngjs/lib/filter-parse.js"(e,n){"use strict";var t=require_interlace();var r=require_paeth_predictor();function i(a,s,c){let u=a*s;if(c!==8){u=Math.ceil(u/(8/c))}return u}var o=n.exports=function(a,s){let c=a.width;let u=a.height;let l=a.interlace;let d=a.bpp;let h=a.depth;this.read=s.read;this.write=s.write;this.complete=s.complete;this._imageIndex=0;this._images=[];if(l){let p=t.getImagePasses(c,u);for(let m=0;m<p.length;m++){this._images.push({byteWidth:i(p[m].width,d,h),height:p[m].height,lineIndex:0})}}else{this._images.push({byteWidth:i(c,d,h),height:u,lineIndex:0})}if(h===8){this._xComparison=d}else if(h===16){this._xComparison=d*2}else{this._xComparison=1}};o.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};o.prototype._unFilterType1=function(a,s,c){let u=this._xComparison;let l=u-1;for(let d=0;d<c;d++){let h=a[1+d];let p=d>l?s[d-u]:0;s[d]=h+p}};o.prototype._unFilterType2=function(a,s,c){let u=this._lastLine;for(let l=0;l<c;l++){let d=a[1+l];let h=u?u[l]:0;s[l]=d+h}};o.prototype._unFilterType3=function(a,s,c){let u=this._xComparison;let l=u-1;let d=this._lastLine;for(let h=0;h<c;h++){let p=a[1+h];let m=d?d[h]:0;let w=h>l?s[h-u]:0;let g=Math.floor((w+m)/2);s[h]=p+g}};o.prototype._unFilterType4=function(a,s,c){let u=this._xComparison;let l=u-1;let d=this._lastLine;for(let h=0;h<c;h++){let p=a[1+h];let m=d?d[h]:0;let w=h>l?s[h-u]:0;let g=h>l&&d?d[h-u]:0;let f=r(w,m,g);s[h]=p+f}};o.prototype._reverseFilterLine=function(a){let s=a[0];let c;let u=this._images[this._imageIndex];let l=u.byteWidth;if(s===0){c=a.slice(1,l+1)}else{c=Buffer.alloc(l);switch(s){case 1:this._unFilterType1(a,c,l);break;case 2:this._unFilterType2(a,c,l);break;case 3:this._unFilterType3(a,c,l);break;case 4:this._unFilterType4(a,c,l);break;default:throw new Error("Unrecognised filter type - "+s)}}this.write(c);u.lineIndex++;if(u.lineIndex>=u.height){this._lastLine=null;this._imageIndex++;u=this._images[this._imageIndex]}else{this._lastLine=c}if(u){this.read(u.byteWidth+1,this._reverseFilterLine.bind(this))}else{this._lastLine=null;this.complete()}}}});var require_filter_parse_async=__commonJS({"../../node_modules/pngjs/lib/filter-parse-async.js"(e,n){"use strict";var t=require("util");var r=require_chunkstream();var i=require_filter_parse();var o=n.exports=function(a){r.call(this);let s=[];let c=this;this._filter=new i(a,{read:this.read.bind(this),write:function(u){s.push(u)},complete:function(){c.emit("complete",Buffer.concat(s))}});this._filter.start()};t.inherits(o,r)}});var require_constants=__commonJS({"../../node_modules/pngjs/lib/constants.js"(e,n){"use strict";n.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}}});var require_crc=__commonJS({"../../node_modules/pngjs/lib/crc.js"(e,n){"use strict";var t=[];(function(){for(let i=0;i<256;i++){let o=i;for(let a=0;a<8;a++){if(o&1){o=3988292384^o>>>1}else{o=o>>>1}}t[i]=o}})();var r=n.exports=function(){this._crc=-1};r.prototype.write=function(i){for(let o=0;o<i.length;o++){this._crc=t[(this._crc^i[o])&255]^this._crc>>>8}return true};r.prototype.crc32=function(){return this._crc^-1};r.crc32=function(i){let o=-1;for(let a=0;a<i.length;a++){o=t[(o^i[a])&255]^o>>>8}return o^-1}}});var require_parser=__commonJS({"../../node_modules/pngjs/lib/parser.js"(e,n){"use strict";var t=require_constants();var r=require_crc();var i=n.exports=function(o,a){this._options=o;o.checkCRC=o.checkCRC!==false;this._hasIHDR=false;this._hasIEND=false;this._emittedHeadersFinished=false;this._palette=[];this._colorType=0;this._chunks={};this._chunks[t.TYPE_IHDR]=this._handleIHDR.bind(this);this._chunks[t.TYPE_IEND]=this._handleIEND.bind(this);this._chunks[t.TYPE_IDAT]=this._handleIDAT.bind(this);this._chunks[t.TYPE_PLTE]=this._handlePLTE.bind(this);this._chunks[t.TYPE_tRNS]=this._handleTRNS.bind(this);this._chunks[t.TYPE_gAMA]=this._handleGAMA.bind(this);this.read=a.read;this.error=a.error;this.metadata=a.metadata;this.gamma=a.gamma;this.transColor=a.transColor;this.palette=a.palette;this.parsed=a.parsed;this.inflateData=a.inflateData;this.finished=a.finished;this.simpleTransparency=a.simpleTransparency;this.headersFinished=a.headersFinished||function(){}};i.prototype.start=function(){this.read(t.PNG_SIGNATURE.length,this._parseSignature.bind(this))};i.prototype._parseSignature=function(o){let a=t.PNG_SIGNATURE;for(let s=0;s<a.length;s++){if(o[s]!==a[s]){this.error(new Error("Invalid file signature"));return}}this.read(8,this._parseChunkBegin.bind(this))};i.prototype._parseChunkBegin=function(o){let a=o.readUInt32BE(0);let s=o.readUInt32BE(4);let c="";for(let l=4;l<8;l++){c+=String.fromCharCode(o[l])}let u=Boolean(o[4]&32);if(!this._hasIHDR&&s!==t.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}this._crc=new r;this._crc.write(Buffer.from(c));if(this._chunks[s]){return this._chunks[s](a)}if(!u){this.error(new Error("Unsupported critical chunk type "+c));return}this.read(a+4,this._skipChunk.bind(this))};i.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};i.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};i.prototype._parseChunkEnd=function(o){let a=o.readInt32BE(0);let s=this._crc.crc32();if(this._options.checkCRC&&s!==a){this.error(new Error("Crc error - "+a+" - "+s));return}if(!this._hasIEND){this.read(8,this._parseChunkBegin.bind(this))}};i.prototype._handleIHDR=function(o){this.read(o,this._parseIHDR.bind(this))};i.prototype._parseIHDR=function(o){this._crc.write(o);let a=o.readUInt32BE(0);let s=o.readUInt32BE(4);let c=o[8];let u=o[9];let l=o[10];let d=o[11];let h=o[12];if(c!==8&&c!==4&&c!==2&&c!==1&&c!==16){this.error(new Error("Unsupported bit depth "+c));return}if(!(u in t.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(l!==0){this.error(new Error("Unsupported compression method"));return}if(d!==0){this.error(new Error("Unsupported filter method"));return}if(h!==0&&h!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=u;let p=t.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=true;this.metadata({width:a,height:s,depth:c,interlace:Boolean(h),palette:Boolean(u&t.COLORTYPE_PALETTE),color:Boolean(u&t.COLORTYPE_COLOR),alpha:Boolean(u&t.COLORTYPE_ALPHA),bpp:p,colorType:u});this._handleChunkEnd()};i.prototype._handlePLTE=function(o){this.read(o,this._parsePLTE.bind(this))};i.prototype._parsePLTE=function(o){this._crc.write(o);let a=Math.floor(o.length/3);for(let s=0;s<a;s++){this._palette.push([o[s*3],o[s*3+1],o[s*3+2],255])}this.palette(this._palette);this._handleChunkEnd()};i.prototype._handleTRNS=function(o){this.simpleTransparency();this.read(o,this._parseTRNS.bind(this))};i.prototype._parseTRNS=function(o){this._crc.write(o);if(this._colorType===t.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(new Error("Transparency chunk must be after palette"));return}if(o.length>this._palette.length){this.error(new Error("More transparent colors than palette size"));return}for(let a=0;a<o.length;a++){this._palette[a][3]=o[a]}this.palette(this._palette)}if(this._colorType===t.COLORTYPE_GRAYSCALE){this.transColor([o.readUInt16BE(0)])}if(this._colorType===t.COLORTYPE_COLOR){this.transColor([o.readUInt16BE(0),o.readUInt16BE(2),o.readUInt16BE(4)])}this._handleChunkEnd()};i.prototype._handleGAMA=function(o){this.read(o,this._parseGAMA.bind(this))};i.prototype._parseGAMA=function(o){this._crc.write(o);this.gamma(o.readUInt32BE(0)/t.GAMMA_DIVISION);this._handleChunkEnd()};i.prototype._handleIDAT=function(o){if(!this._emittedHeadersFinished){this._emittedHeadersFinished=true;this.headersFinished()}this.read(-o,this._parseIDAT.bind(this,o))};i.prototype._parseIDAT=function(o,a){this._crc.write(a);if(this._colorType===t.COLORTYPE_PALETTE_COLOR&&this._palette.length===0){throw new Error("Expected palette not found")}this.inflateData(a);let s=o-a.length;if(s>0){this._handleIDAT(s)}else{this._handleChunkEnd()}};i.prototype._handleIEND=function(o){this.read(o,this._parseIEND.bind(this))};i.prototype._parseIEND=function(o){this._crc.write(o);this._hasIEND=true;this._handleChunkEnd();if(this.finished){this.finished()}}}});var require_bitmapper=__commonJS({"../../node_modules/pngjs/lib/bitmapper.js"(e){"use strict";var n=require_interlace();var t=[function(){},function(s,c,u,l){if(l===c.length){throw new Error("Ran out of data")}let d=c[l];s[u]=d;s[u+1]=d;s[u+2]=d;s[u+3]=255},function(s,c,u,l){if(l+1>=c.length){throw new Error("Ran out of data")}let d=c[l];s[u]=d;s[u+1]=d;s[u+2]=d;s[u+3]=c[l+1]},function(s,c,u,l){if(l+2>=c.length){throw new Error("Ran out of data")}s[u]=c[l];s[u+1]=c[l+1];s[u+2]=c[l+2];s[u+3]=255},function(s,c,u,l){if(l+3>=c.length){throw new Error("Ran out of data")}s[u]=c[l];s[u+1]=c[l+1];s[u+2]=c[l+2];s[u+3]=c[l+3]}];var r=[function(){},function(s,c,u,l){let d=c[0];s[u]=d;s[u+1]=d;s[u+2]=d;s[u+3]=l},function(s,c,u){let l=c[0];s[u]=l;s[u+1]=l;s[u+2]=l;s[u+3]=c[1]},function(s,c,u,l){s[u]=c[0];s[u+1]=c[1];s[u+2]=c[2];s[u+3]=l},function(s,c,u){s[u]=c[0];s[u+1]=c[1];s[u+2]=c[2];s[u+3]=c[3]}];function i(s,c){let u=[];let l=0;function d(){if(l===s.length){throw new Error("Ran out of data")}let h=s[l];l++;let p,m,w,g,f,v,y,b;switch(c){default:throw new Error("unrecognised depth");case 16:y=s[l];l++;u.push((h<<8)+y);break;case 4:y=h&15;b=h>>4;u.push(b,y);break;case 2:f=h&3;v=h>>2&3;y=h>>4&3;b=h>>6&3;u.push(b,y,v,f);break;case 1:p=h&1;m=h>>1&1;w=h>>2&1;g=h>>3&1;f=h>>4&1;v=h>>5&1;y=h>>6&1;b=h>>7&1;u.push(b,y,v,f,g,w,m,p);break}}return{get:function(h){while(u.length<h){d()}let p=u.slice(0,h);u=u.slice(h);return p},resetAfterLine:function(){u.length=0},end:function(){if(l!==s.length){throw new Error("extra data found")}}}}function o(s,c,u,l,d,h){let p=s.width;let m=s.height;let w=s.index;for(let g=0;g<m;g++){for(let f=0;f<p;f++){let v=u(f,g,w);t[l](c,d,v,h);h+=l}}return h}function a(s,c,u,l,d,h){let p=s.width;let m=s.height;let w=s.index;for(let g=0;g<m;g++){for(let f=0;f<p;f++){let v=d.get(l);let y=u(f,g,w);r[l](c,v,y,h)}d.resetAfterLine()}}e.dataToBitMap=function(s,c){let u=c.width;let l=c.height;let d=c.depth;let h=c.bpp;let p=c.interlace;let m;if(d!==8){m=i(s,d)}let w;if(d<=8){w=Buffer.alloc(u*l*4)}else{w=new Uint16Array(u*l*4)}let g=Math.pow(2,d)-1;let f=0;let v;let y;if(p){v=n.getImagePasses(u,l);y=n.getInterlaceIterator(u,l)}else{let b=0;y=function(){let $=b;b+=4;return $};v=[{width:u,height:l}]}for(let b=0;b<v.length;b++){if(d===8){f=o(v[b],w,y,h,s,f)}else{a(v[b],w,y,h,m,g)}}if(d===8){if(f!==s.length){throw new Error("extra data found")}}else{m.end()}return w}}});var require_format_normaliser=__commonJS({"../../node_modules/pngjs/lib/format-normaliser.js"(e,n){"use strict";function t(o,a,s,c,u){let l=0;for(let d=0;d<c;d++){for(let h=0;h<s;h++){let p=u[o[l]];if(!p){throw new Error("index "+o[l]+" not in palette")}for(let m=0;m<4;m++){a[l+m]=p[m]}l+=4}}}function r(o,a,s,c,u){let l=0;for(let d=0;d<c;d++){for(let h=0;h<s;h++){let p=false;if(u.length===1){if(u[0]===o[l]){p=true}}else if(u[0]===o[l]&&u[1]===o[l+1]&&u[2]===o[l+2]){p=true}if(p){for(let m=0;m<4;m++){a[l+m]=0}}l+=4}}}function i(o,a,s,c,u){let l=255;let d=Math.pow(2,u)-1;let h=0;for(let p=0;p<c;p++){for(let m=0;m<s;m++){for(let w=0;w<4;w++){a[h+w]=Math.floor(o[h+w]*l/d+.5)}h+=4}}}n.exports=function(o,a,s=false){let c=a.depth;let u=a.width;let l=a.height;let d=a.colorType;let h=a.transColor;let p=a.palette;let m=o;if(d===3){t(o,m,u,l,p)}else{if(h){r(o,m,u,l,h)}if(c!==8&&!s){if(c===16){m=Buffer.alloc(u*l*4)}i(o,m,u,l,c)}}return m}}});var require_parser_async=__commonJS({"../../node_modules/pngjs/lib/parser-async.js"(e,n){"use strict";var t=require("util");var r=require("zlib");var i=require_chunkstream();var o=require_filter_parse_async();var a=require_parser();var s=require_bitmapper();var c=require_format_normaliser();var u=n.exports=function(l){i.call(this);this._parser=new a(l,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)});this._options=l;this.writable=true;this._parser.start()};t.inherits(u,i);u.prototype._handleError=function(l){this.emit("error",l);this.writable=false;this.destroy();if(this._inflate&&this._inflate.destroy){this._inflate.destroy()}if(this._filter){this._filter.destroy();this._filter.on("error",function(){})}this.errord=true};u.prototype._inflateData=function(l){if(!this._inflate){if(this._bitmapInfo.interlace){this._inflate=r.createInflate();this._inflate.on("error",this.emit.bind(this,"error"));this._filter.on("complete",this._complete.bind(this));this._inflate.pipe(this._filter)}else{let d=(this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1;let h=d*this._bitmapInfo.height;let p=Math.max(h,r.Z_MIN_CHUNK);this._inflate=r.createInflate({chunkSize:p});let m=h;let w=this.emit.bind(this,"error");this._inflate.on("error",function(f){if(!m){return}w(f)});this._filter.on("complete",this._complete.bind(this));let g=this._filter.write.bind(this._filter);this._inflate.on("data",function(f){if(!m){return}if(f.length>m){f=f.slice(0,m)}m-=f.length;g(f)});this._inflate.on("end",this._filter.end.bind(this._filter))}}this._inflate.write(l)};u.prototype._handleMetaData=function(l){this._metaData=l;this._bitmapInfo=Object.create(l);this._filter=new o(this._bitmapInfo)};u.prototype._handleTransColor=function(l){this._bitmapInfo.transColor=l};u.prototype._handlePalette=function(l){this._bitmapInfo.palette=l};u.prototype._simpleTransparency=function(){this._metaData.alpha=true};u.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};u.prototype._finished=function(){if(this.errord){return}if(!this._inflate){this.emit("error","No Inflate block")}else{this._inflate.end()}};u.prototype._complete=function(l){if(this.errord){return}let d;try{let h=s.dataToBitMap(l,this._bitmapInfo);d=c(h,this._bitmapInfo,this._options.skipRescale);h=null}catch(h){this._handleError(h);return}this.emit("parsed",d)}}});var require_bitpacker=__commonJS({"../../node_modules/pngjs/lib/bitpacker.js"(e,n){"use strict";var t=require_constants();n.exports=function(r,i,o,a){let s=[t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(a.colorType)!==-1;if(a.colorType===a.inputColorType){let f=(function(){let v=new ArrayBuffer(2);new DataView(v).setInt16(0,256,true);return new Int16Array(v)[0]!==256})();if(a.bitDepth===8||a.bitDepth===16&&f){return r}}let c=a.bitDepth!==16?r:new Uint16Array(r.buffer);let u=255;let l=t.COLORTYPE_TO_BPP_MAP[a.inputColorType];if(l===4&&!a.inputHasAlpha){l=3}let d=t.COLORTYPE_TO_BPP_MAP[a.colorType];if(a.bitDepth===16){u=65535;d*=2}let h=Buffer.alloc(i*o*d);let p=0;let m=0;let w=a.bgColor||{};if(w.red===void 0){w.red=u}if(w.green===void 0){w.green=u}if(w.blue===void 0){w.blue=u}function g(){let f;let v;let y;let b=u;switch(a.inputColorType){case t.COLORTYPE_COLOR_ALPHA:b=c[p+3];f=c[p];v=c[p+1];y=c[p+2];break;case t.COLORTYPE_COLOR:f=c[p];v=c[p+1];y=c[p+2];break;case t.COLORTYPE_ALPHA:b=c[p+1];f=c[p];v=f;y=f;break;case t.COLORTYPE_GRAYSCALE:f=c[p];v=f;y=f;break;default:throw new Error("input color type:"+a.inputColorType+" is not supported at present")}if(a.inputHasAlpha){if(!s){b/=u;f=Math.min(Math.max(Math.round((1-b)*w.red+b*f),0),u);v=Math.min(Math.max(Math.round((1-b)*w.green+b*v),0),u);y=Math.min(Math.max(Math.round((1-b)*w.blue+b*y),0),u)}}return{red:f,green:v,blue:y,alpha:b}}for(let f=0;f<o;f++){for(let v=0;v<i;v++){let y=g(c,p);switch(a.colorType){case t.COLORTYPE_COLOR_ALPHA:case t.COLORTYPE_COLOR:if(a.bitDepth===8){h[m]=y.red;h[m+1]=y.green;h[m+2]=y.blue;if(s){h[m+3]=y.alpha}}else{h.writeUInt16BE(y.red,m);h.writeUInt16BE(y.green,m+2);h.writeUInt16BE(y.blue,m+4);if(s){h.writeUInt16BE(y.alpha,m+6)}}break;case t.COLORTYPE_ALPHA:case t.COLORTYPE_GRAYSCALE:{let b=(y.red+y.green+y.blue)/3;if(a.bitDepth===8){h[m]=b;if(s){h[m+1]=y.alpha}}else{h.writeUInt16BE(b,m);if(s){h.writeUInt16BE(y.alpha,m+2)}}break}default:throw new Error("unrecognised color Type "+a.colorType)}p+=l;m+=d}}return h}}});var require_filter_pack=__commonJS({"../../node_modules/pngjs/lib/filter-pack.js"(e,n){"use strict";var t=require_paeth_predictor();function r(w,g,f,v,y){for(let b=0;b<f;b++){v[y+b]=w[g+b]}}function i(w,g,f){let v=0;let y=g+f;for(let b=g;b<y;b++){v+=Math.abs(w[b])}return v}function o(w,g,f,v,y,b){for(let $=0;$<f;$++){let _=$>=b?w[g+$-b]:0;let k=w[g+$]-_;v[y+$]=k}}function a(w,g,f,v){let y=0;for(let b=0;b<f;b++){let $=b>=v?w[g+b-v]:0;let _=w[g+b]-$;y+=Math.abs(_)}return y}function s(w,g,f,v,y){for(let b=0;b<f;b++){let $=g>0?w[g+b-f]:0;let _=w[g+b]-$;v[y+b]=_}}function c(w,g,f){let v=0;let y=g+f;for(let b=g;b<y;b++){let $=g>0?w[b-f]:0;let _=w[b]-$;v+=Math.abs(_)}return v}function u(w,g,f,v,y,b){for(let $=0;$<f;$++){let _=$>=b?w[g+$-b]:0;let k=g>0?w[g+$-f]:0;let T=w[g+$]-(_+k>>1);v[y+$]=T}}function l(w,g,f,v){let y=0;for(let b=0;b<f;b++){let $=b>=v?w[g+b-v]:0;let _=g>0?w[g+b-f]:0;let k=w[g+b]-($+_>>1);y+=Math.abs(k)}return y}function d(w,g,f,v,y,b){for(let $=0;$<f;$++){let _=$>=b?w[g+$-b]:0;let k=g>0?w[g+$-f]:0;let T=g>0&&$>=b?w[g+$-(f+b)]:0;let A=w[g+$]-t(_,k,T);v[y+$]=A}}function h(w,g,f,v){let y=0;for(let b=0;b<f;b++){let $=b>=v?w[g+b-v]:0;let _=g>0?w[g+b-f]:0;let k=g>0&&b>=v?w[g+b-(f+v)]:0;let T=w[g+b]-t($,_,k);y+=Math.abs(T)}return y}var p={0:r,1:o,2:s,3:u,4:d};var m={0:i,1:a,2:c,3:l,4:h};n.exports=function(w,g,f,v,y){let b;if(!("filterType"in v)||v.filterType===-1){b=[0,1,2,3,4]}else if(typeof v.filterType==="number"){b=[v.filterType]}else{throw new Error("unrecognised filter types")}if(v.bitDepth===16){y*=2}let $=g*y;let _=0;let k=0;let T=Buffer.alloc(($+1)*f);let A=b[0];for(let I=0;I<f;I++){if(b.length>1){let C=Infinity;for(let M=0;M<b.length;M++){let S=m[b[M]](w,k,$,y);if(S<C){A=b[M];C=S}}}T[_]=A;_++;p[A](w,k,$,T,_,y);_+=$;k+=$}return T}}});var require_packer=__commonJS({"../../node_modules/pngjs/lib/packer.js"(e,n){"use strict";var t=require_constants();var r=require_crc();var i=require_bitpacker();var o=require_filter_pack();var a=require("zlib");var s=n.exports=function(c){this._options=c;c.deflateChunkSize=c.deflateChunkSize||32*1024;c.deflateLevel=c.deflateLevel!=null?c.deflateLevel:9;c.deflateStrategy=c.deflateStrategy!=null?c.deflateStrategy:3;c.inputHasAlpha=c.inputHasAlpha!=null?c.inputHasAlpha:true;c.deflateFactory=c.deflateFactory||a.createDeflate;c.bitDepth=c.bitDepth||8;c.colorType=typeof c.colorType==="number"?c.colorType:t.COLORTYPE_COLOR_ALPHA;c.inputColorType=typeof c.inputColorType==="number"?c.inputColorType:t.COLORTYPE_COLOR_ALPHA;if([t.COLORTYPE_GRAYSCALE,t.COLORTYPE_COLOR,t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(c.colorType)===-1){throw new Error("option color type:"+c.colorType+" is not supported at present")}if([t.COLORTYPE_GRAYSCALE,t.COLORTYPE_COLOR,t.COLORTYPE_COLOR_ALPHA,t.COLORTYPE_ALPHA].indexOf(c.inputColorType)===-1){throw new Error("option input color type:"+c.inputColorType+" is not supported at present")}if(c.bitDepth!==8&&c.bitDepth!==16){throw new Error("option bit depth:"+c.bitDepth+" is not supported at present")}};s.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};s.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};s.prototype.filterData=function(c,u,l){let d=i(c,u,l,this._options);let h=t.COLORTYPE_TO_BPP_MAP[this._options.colorType];let p=o(d,u,l,this._options,h);return p};s.prototype._packChunk=function(c,u){let l=u?u.length:0;let d=Buffer.alloc(l+12);d.writeUInt32BE(l,0);d.writeUInt32BE(c,4);if(u){u.copy(d,8)}d.writeInt32BE(r.crc32(d.slice(4,d.length-4)),d.length-4);return d};s.prototype.packGAMA=function(c){let u=Buffer.alloc(4);u.writeUInt32BE(Math.floor(c*t.GAMMA_DIVISION),0);return this._packChunk(t.TYPE_gAMA,u)};s.prototype.packIHDR=function(c,u){let l=Buffer.alloc(13);l.writeUInt32BE(c,0);l.writeUInt32BE(u,4);l[8]=this._options.bitDepth;l[9]=this._options.colorType;l[10]=0;l[11]=0;l[12]=0;return this._packChunk(t.TYPE_IHDR,l)};s.prototype.packIDAT=function(c){return this._packChunk(t.TYPE_IDAT,c)};s.prototype.packIEND=function(){return this._packChunk(t.TYPE_IEND,null)}}});var require_packer_async=__commonJS({"../../node_modules/pngjs/lib/packer-async.js"(e,n){"use strict";var t=require("util");var r=require("stream");var i=require_constants();var o=require_packer();var a=n.exports=function(s){r.call(this);let c=s||{};this._packer=new o(c);this._deflate=this._packer.createDeflate();this.readable=true};t.inherits(a,r);a.prototype.pack=function(s,c,u,l){this.emit("data",Buffer.from(i.PNG_SIGNATURE));this.emit("data",this._packer.packIHDR(c,u));if(l){this.emit("data",this._packer.packGAMA(l))}let d=this._packer.filterData(s,c,u);this._deflate.on("error",this.emit.bind(this,"error"));this._deflate.on("data",function(h){this.emit("data",this._packer.packIDAT(h))}.bind(this));this._deflate.on("end",function(){this.emit("data",this._packer.packIEND());this.emit("end")}.bind(this));this._deflate.end(d)}}});var require_sync_inflate=__commonJS({"../../node_modules/pngjs/lib/sync-inflate.js"(e,n){"use strict";var t=require("assert").ok;var r=require("zlib");var i=require("util");var o=require("buffer").kMaxLength;function a(d){if(!(this instanceof a)){return new a(d)}if(d&&d.chunkSize<r.Z_MIN_CHUNK){d.chunkSize=r.Z_MIN_CHUNK}r.Inflate.call(this,d);this._offset=this._offset===void 0?this._outOffset:this._offset;this._buffer=this._buffer||this._outBuffer;if(d&&d.maxLength!=null){this._maxLength=d.maxLength}}function s(d){return new a(d)}function c(d,h){if(h){process.nextTick(h)}if(!d._handle){return}d._handle.close();d._handle=null}a.prototype._processChunk=function(d,h,p){if(typeof p==="function"){return r.Inflate._processChunk.call(this,d,h,p)}let m=this;let w=d&&d.length;let g=this._chunkSize-this._offset;let f=this._maxLength;let v=0;let y=[];let b=0;let $;this.on("error",function(A){$=A});function _(A,I){if(m._hadError){return}let C=g-I;t(C>=0,"have should not go down");if(C>0){let M=m._buffer.slice(m._offset,m._offset+C);m._offset+=C;if(M.length>f){M=M.slice(0,f)}y.push(M);b+=M.length;f-=M.length;if(f===0){return false}}if(I===0||m._offset>=m._chunkSize){g=m._chunkSize;m._offset=0;m._buffer=Buffer.allocUnsafe(m._chunkSize)}if(I===0){v+=w-A;w=A;return true}return false}t(this._handle,"zlib binding closed");let k;do{k=this._handle.writeSync(h,d,v,w,this._buffer,this._offset,g);k=k||this._writeState}while(!this._hadError&&_(k[0],k[1]));if(this._hadError){throw $}if(b>=o){c(this);throw new RangeError("Cannot create final Buffer. It would be larger than 0x"+o.toString(16)+" bytes")}let T=Buffer.concat(y,b);c(this);return T};i.inherits(a,r.Inflate);function u(d,h){if(typeof h==="string"){h=Buffer.from(h)}if(!(h instanceof Buffer)){throw new TypeError("Not a string or buffer")}let p=d._finishFlushFlag;if(p==null){p=r.Z_FINISH}return d._processChunk(h,p)}function l(d,h){return u(new a(h),d)}n.exports=e=l;e.Inflate=a;e.createInflate=s;e.inflateSync=l}});var require_sync_reader=__commonJS({"../../node_modules/pngjs/lib/sync-reader.js"(e,n){"use strict";var t=n.exports=function(r){this._buffer=r;this._reads=[]};t.prototype.read=function(r,i){this._reads.push({length:Math.abs(r),allowLess:r<0,func:i})};t.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let r=this._reads[0];if(this._buffer.length&&(this._buffer.length>=r.length||r.allowLess)){this._reads.shift();let i=this._buffer;this._buffer=i.slice(r.length);r.func.call(this,i.slice(0,r.length))}else{break}}if(this._reads.length>0){throw new Error("There are some read requests waitng on finished stream")}if(this._buffer.length>0){throw new Error("unrecognised content at end of stream")}}}});var require_filter_parse_sync=__commonJS({"../../node_modules/pngjs/lib/filter-parse-sync.js"(e){"use strict";var n=require_sync_reader();var t=require_filter_parse();e.process=function(r,i){let o=[];let a=new n(r);let s=new t(i,{read:a.read.bind(a),write:function(c){o.push(c)},complete:function(){}});s.start();a.process();return Buffer.concat(o)}}});var require_parser_sync=__commonJS({"../../node_modules/pngjs/lib/parser-sync.js"(e,n){"use strict";var t=true;var r=require("zlib");var i=require_sync_inflate();if(!r.deflateSync){t=false}var o=require_sync_reader();var a=require_filter_parse_sync();var s=require_parser();var c=require_bitmapper();var u=require_format_normaliser();n.exports=function(l,d){if(!t){throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0")}let h;function p(x){h=x}let m;function w(x){m=x}function g(x){m.transColor=x}function f(x){m.palette=x}function v(){m.alpha=true}let y;function b(x){y=x}let $=[];function _(x){$.push(x)}let k=new o(l);let T=new s(d,{read:k.read.bind(k),error:p,metadata:w,gamma:b,palette:f,transColor:g,inflateData:_,simpleTransparency:v});T.start();k.process();if(h){throw h}let A=Buffer.concat($);$.length=0;let I;if(m.interlace){I=r.inflateSync(A)}else{let x=(m.width*m.bpp*m.depth+7>>3)+1;let E=x*m.height;I=i(A,{chunkSize:E,maxLength:E})}A=null;if(!I||!I.length){throw new Error("bad png - invalid inflate data response")}let C=a.process(I,m);A=null;let M=c.dataToBitMap(C,m);C=null;let S=u(M,m,d.skipRescale);m.data=S;m.gamma=y||0;return m}}});var require_packer_sync=__commonJS({"../../node_modules/pngjs/lib/packer-sync.js"(e,n){"use strict";var t=true;var r=require("zlib");if(!r.deflateSync){t=false}var i=require_constants();var o=require_packer();n.exports=function(a,s){if(!t){throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0")}let c=s||{};let u=new o(c);let l=[];l.push(Buffer.from(i.PNG_SIGNATURE));l.push(u.packIHDR(a.width,a.height));if(a.gamma){l.push(u.packGAMA(a.gamma))}let d=u.filterData(a.data,a.width,a.height);let h=r.deflateSync(d,u.getDeflateOptions());d=null;if(!h||!h.length){throw new Error("bad png - invalid compressed data response")}l.push(u.packIDAT(h));l.push(u.packIEND());return Buffer.concat(l)}}});var require_png_sync=__commonJS({"../../node_modules/pngjs/lib/png-sync.js"(e){"use strict";var n=require_parser_sync();var t=require_packer_sync();e.read=function(r,i){return n(r,i||{})};e.write=function(r,i){return t(r,i)}}});var require_png=__commonJS({"../../node_modules/pngjs/lib/png.js"(e){"use strict";var n=require("util");var t=require("stream");var r=require_parser_async();var i=require_packer_async();var o=require_png_sync();var a=e.PNG=function(s){t.call(this);s=s||{};this.width=s.width|0;this.height=s.height|0;this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null;if(s.fill&&this.data){this.data.fill(0)}this.gamma=0;this.readable=this.writable=true;this._parser=new r(s);this._parser.on("error",this.emit.bind(this,"error"));this._parser.on("close",this._handleClose.bind(this));this._parser.on("metadata",this._metadata.bind(this));this._parser.on("gamma",this._gamma.bind(this));this._parser.on("parsed",function(c){this.data=c;this.emit("parsed",c)}.bind(this));this._packer=new i(s);this._packer.on("data",this.emit.bind(this,"data"));this._packer.on("end",this.emit.bind(this,"end"));this._parser.on("close",this._handleClose.bind(this));this._packer.on("error",this.emit.bind(this,"error"))};n.inherits(a,t);a.sync=o;a.prototype.pack=function(){if(!this.data||!this.data.length){this.emit("error","No data provided");return this}process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this));return this};a.prototype.parse=function(s,c){if(c){let u,l;u=function(d){this.removeListener("error",l);this.data=d;c(null,this)}.bind(this);l=function(d){this.removeListener("parsed",u);c(d,null)}.bind(this);this.once("parsed",u);this.once("error",l)}this.end(s);return this};a.prototype.write=function(s){this._parser.write(s);return true};a.prototype.end=function(s){this._parser.end(s)};a.prototype._metadata=function(s){this.width=s.width;this.height=s.height;this.emit("metadata",s)};a.prototype._gamma=function(s){this.gamma=s};a.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable){this.emit("close")}};a.bitblt=function(s,c,u,l,d,h,p,m){u|=0;l|=0;d|=0;h|=0;p|=0;m|=0;if(u>s.width||l>s.height||u+d>s.width||l+h>s.height){throw new Error("bitblt reading outside image")}if(p>c.width||m>c.height||p+d>c.width||m+h>c.height){throw new Error("bitblt writing outside image")}for(let w=0;w<h;w++){s.data.copy(c.data,(m+w)*c.width+p<<2,(l+w)*s.width+u<<2,(l+w)*s.width+u+d<<2)}};a.prototype.bitblt=function(s,c,u,l,d,h,p){a.bitblt(this,s,c,u,l,d,h,p);return this};a.adjustGamma=function(s){if(s.gamma){for(let c=0;c<s.height;c++){for(let u=0;u<s.width;u++){let l=s.width*c+u<<2;for(let d=0;d<3;d++){let h=s.data[l+d]/255;h=Math.pow(h,1/2.2/s.gamma);s.data[l+d]=Math.round(h*255)}}}s.gamma=0}};a.prototype.adjustGamma=function(){a.adjustGamma(this)}}});var src_exports={};__export(src_exports,{ALL_DEVICES:()=>ALL_DEVICES,BROKER_PORT:()=>BROKER_PORT,BROKER_URL:()=>BROKER_URL,DASHBOARD_NAME:()=>DASHBOARD_NAME,DEFAULT_ACTION_TIMEOUT_MS:()=>DEFAULT_ACTION_TIMEOUT_MS,DEFAULT_SNAPSHOT_TIMEOUT_MS:()=>DEFAULT_SNAPSHOT_TIMEOUT_MS,PACKAGE_NAME:()=>PACKAGE_NAME,SyncClient:()=>SyncClient,VERSION:()=>VERSION,buildAutomationConfig:()=>buildAutomationConfig,compareReportStats:()=>compareReportStats,createMcpServer:()=>createMcpServer,estimateBatchMs:()=>estimateBatchMs,formatRankingMarkdown:()=>formatRankingMarkdown,getUpdateNotice:()=>getUpdateNotice,rankBatchFromIndex:()=>rankBatchFromIndex,registerConsoleTools:()=>registerConsoleTools,registerEventsTools:()=>registerEventsTools,registerGenericTools:()=>registerGenericTools,registerJotaiTools:()=>registerJotaiTools,registerPerfMonitorTools:()=>registerPerfMonitorTools,registerReactQueryTools:()=>registerReactQueryTools,registerReduxTools:()=>registerReduxTools,registerRoutesTools:()=>registerRoutesTools,registerScreenshotTools:()=>registerScreenshotTools,registerStorageTools:()=>registerStorageTools,registerZustandTools:()=>registerZustandTools,runInit:()=>runInit});module.exports=__toCommonJS(src_exports);var import_node_fs=require("fs");var import_node_path=require("path");var import_node_os=require("os");var import_node_crypto=require("crypto");var import_headless=require("@buoy-gg/license/headless");var KEY_NAMES=["BUOY_LICENSE_KEY","BUOY_KEY","EXPO_PUBLIC_BUOY_KEY","VITE_BUOY_KEY","NEXT_PUBLIC_BUOY_KEY","REACT_APP_BUOY_KEY"];function readProjectKey(e,n=process.env){for(const t of KEY_NAMES)if(n[t]!==void 0)return(0,import_headless.normalizeLicenseKey)(n[t])||null;for(const t of[".env.development.local",".env.local",".env"]){let r;try{r=(0,import_node_fs.readFileSync)((0,import_node_path.join)(e,t),"utf8")}catch{continue}const i=new Map;for(const o of r.split(/\r?\n/)){const a=o.match(/^\s*(?:export\s+)?([A-Z_][A-Z_0-9]*)\s*=\s*(.*)$/);if(!a)continue;const s=a[2].trim();const c=s.match(/^(['"])(.*?)\1\s*(?:#.*)?$/);i.set(a[1],c?c[2]:s.split("#")[0].trim())}for(const o of KEY_NAMES)if(i.has(o))return(0,import_headless.normalizeLicenseKey)(i.get(o))||null}return null}var NodeAccount=class{constructor(e,n={}){this.changed=e;this.key=null;this.cache=null;this.timer=null;this.unsubscribeSession=null;this.generation=0;this.busy=false;this.nextCheck=0;this.retry=0;this.lastAdmission=false;this.hasAccess=()=>this.hasKeyAccess()||this.session?.getStatus().state==="active";this.lastSessionSync=0;this.projectDir=(0,import_node_path.resolve)(n.projectDir??process.env.BUOY_PROJECT_DIR??process.cwd());const t=(0,import_node_crypto.createHash)("sha256").update(this.projectDir).digest("hex").slice(0,20);this.cacheFile=n.cacheFile??(0,import_node_path.join)((0,import_node_os.homedir)(),".buoy",`account-${t}.json`);this.session=n.session!==void 0?n.session:(0,import_headless.createNodeSession)({audience:import_headless.CLI_AUDIENCE,openBrowser:()=>{throw new Error("The MCP does not open a browser. Run `npx buoy login`.")}})}hasKeyAccess(){return(0,import_headless.resolveAccountAccess)({initialized:true,validating:false,key:this.key,tierSource:this.cache?.tier?"key":"none",verifiedAt:this.cache?.cachedAt??null}).status==="admitted"}start(){if(this.timer)return;if(this.session){this.unsubscribeSession=this.session.subscribe(()=>this.notify());void this.session.load().then(()=>this.notify(),()=>{})}try{const e=JSON.parse((0,import_node_fs.readFileSync)(this.cacheFile,"utf8"));if(e.valid&&(0,import_headless.verifyCacheSignature)(e))this.cache=e}catch{}void this.tick();this.timer=setInterval(()=>{void this.tick()},1e3);this.timer.unref()}stop(){++this.generation;this.unsubscribeSession?.();this.unsubscribeSession=null;if(this.timer)clearInterval(this.timer);this.timer=null;this.key=null;this.cache=null;this.notify()}notify(){const e=this.hasAccess();if(e===this.lastAdmission)return;this.lastAdmission=e;this.changed()}async tick(){if(this.session&&Date.now()-this.lastSessionSync>15e3){this.lastSessionSync=Date.now();void this.session.sync().catch(()=>{})}const e=readProjectKey(this.projectDir);if(e!==this.key){++this.generation;this.key=e;if(this.cache?.licenseKey!==e)this.cache=null;this.nextCheck=0;this.retry=0;if(!e)this.removeCache()}this.notify();if(!e||this.busy||Date.now()<this.nextCheck)return;if(this.cache&&this.hasKeyAccess()&&Date.now()-this.cache.lastValidatedAt<import_headless.LICENSE_LAUNCH_VALIDATION_TTL&&this.nextCheck===0){this.nextCheck=this.cache.lastValidatedAt+import_headless.LICENSE_LAUNCH_VALIDATION_TTL;return}this.busy=true;const n=this.generation;try{if((0,import_headless.isDevToken)(e)){const s=(0,import_headless.checkDevToken)(e);if(!s.ok){this.cache=null;this.removeCache()}else{const c=Math.min(Date.now(),s.claims.iat*1e3);const u=s.claims.tier==="free"?"free":"pro";this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`dev:${s.claims.sid}`,valid:true,tier:u,isPro:u==="pro",expiresAt:new Date(s.claims.exp*1e3).toISOString(),cachedAt:c,lastValidatedAt:Date.now()});this.persistCache()}this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}if((0,import_headless.isServiceKey)(e)){const s=await(0,import_headless.exchangeServiceKey)(e,{origin:process.env.BUOY_SITE_URL||"https://buoy.gg"});if(n!==this.generation||readProjectKey(this.projectDir)!==e)return;if(!s.ok){if(s.reason==="rejected"){this.cache=null;this.removeCache();this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL}else{this.nextCheck=Date.now()+(import_headless.LICENSE_TRANSIENT_RETRY_DELAYS[this.retry++]??import_headless.LICENSE_REVALIDATION_INTERVAL)}return}const c=Date.now();const u=s.claims.exp*1e3;this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`service:${s.claims.sid}`,valid:true,tier:"pro",isPro:true,expiresAt:new Date(u).toISOString(),cachedAt:c,lastValidatedAt:c});this.persistCache();this.retry=0;this.nextCheck=Math.max(c+6e4,u-60*60*1e3);return}if((0,import_headless.isBuoyToken)(e)){const s=(0,import_headless.verifyFreeToken)(e);if(!s){this.cache=null;this.removeCache()}else{const c=Date.now();this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:`token:${s.accountHash}`,valid:true,tier:"free",isPro:false,expiresAt:null,cachedAt:c,lastValidatedAt:c});this.persistCache()}this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}const t=await(0,import_headless.validateLicense)(e);if(n!==this.generation||readProjectKey(this.projectDir)!==e)return;const r=t.data?.relationships?.product?.data?.id;const i=t.meta.code==="EXPIRED"&&((0,import_headless.isRecognizedAccount)(t.data)||this.cache?.licenseKey===e);if(r&&r!==import_headless.KEYGEN_CONFIG.productId||!i&&!(0,import_headless.isAcceptedValidation)(t)){this.cache=null;this.removeCache();this.nextCheck=Date.now()+import_headless.LICENSE_REVALIDATION_INTERVAL;return}const o=i?"free":(0,import_headless.resolveTier)(t.data);const a=Date.now();this.cache=(0,import_headless.signCache)({licenseKey:e,licenseId:t.data?.id??"",valid:true,tier:o,isPro:o==="pro",expiresAt:i?null:t.data.attributes.expiry,cachedAt:a,lastValidatedAt:a});this.persistCache();this.retry=0;this.nextCheck=a+import_headless.LICENSE_REVALIDATION_INTERVAL}catch(t){if(n!==this.generation)return;const r=(0,import_headless.isTransientLicenseError)(t)?import_headless.LICENSE_TRANSIENT_RETRY_DELAYS[this.retry++]:void 0;this.nextCheck=Date.now()+(r??import_headless.LICENSE_REVALIDATION_INTERVAL)}finally{this.busy=false;this.notify()}}persistCache(){try{(0,import_node_fs.mkdirSync)((0,import_node_path.dirname)(this.cacheFile),{recursive:true,mode:448});(0,import_node_fs.writeFileSync)(`${this.cacheFile}.tmp`,JSON.stringify(this.cache),{mode:384});(0,import_node_fs.renameSync)(`${this.cacheFile}.tmp`,this.cacheFile)}catch{}}removeCache(){try{(0,import_node_fs.unlinkSync)(this.cacheFile)}catch{}}};var import_node_http=__toESM(require("http"));var import_node_crypto2=require("crypto");var import_socket=require("socket.io-client");var import_sync_broker2=require("@buoy-gg/sync-broker");var import_sync_broker=require("@buoy-gg/sync-broker");var BROKER_PORT=import_sync_broker.DEFAULT_BROKER_PORT;var BROKER_URL=`http://localhost:${BROKER_PORT}`;var DEFAULT_ACTION_TIMEOUT_MS=15e3;var UNRESPONSIVE_ACTION_TIMEOUT_MS=2500;var UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS=1200;var RECOVERY_PROBE_MS=2e4;var UNRESPONSIVE_AFTER_MS=3e4;var DEFAULT_SNAPSHOT_TIMEOUT_MS=5e3;var DEVICE_RETENTION_MS=15*6e4;var DASHBOARD_NAME="Dashboard";var ALL_DEVICES="All";var import_node_child_process=require("child_process");var import_node_util=require("util");var import_node_path2=__toESM(require("path"));var import_node_os2=__toESM(require("os"));var execFileAsync=(0,import_node_util.promisify)(import_node_child_process.execFile);async function devServerRoot(e){let n;try{n=new URL(e)}catch{return null}if(!isLocalHost(n.hostname))return null;const t=n.port||(n.protocol==="https:"?"443":"80");try{const{stdout:r}=await execFileAsync("lsof",["-nP",`-iTCP:${t}`,"-sTCP:LISTEN","-t"],{timeout:3e3});const i=r.split("\n").map(s=>s.trim()).find(Boolean);if(!i)return null;const{stdout:o}=await execFileAsync("lsof",["-a","-p",i,"-d","cwd","-Fn"],{timeout:3e3});const a=o.split("\n").find(s=>s.startsWith("n"));return a?import_node_path2.default.resolve(a.slice(1)):null}catch{return null}}function isLocalHost(e,n=import_node_os2.default.networkInterfaces()){const t=e.replace(/^\[|\]$/g,"").toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="10.0.2.2"||t==="10.0.3.2")return true;return Object.values(n).flat().some(r=>r?.address?.toLowerCase()===t)}function pickByProject(e,n){const t=import_node_path2.default.resolve(n);const r=e.map(a=>({deviceId:a.deviceId,score:a.root?closeness(import_node_path2.default.resolve(a.root),t):-1})).filter(a=>a.score>=0);if(r.length===0)return null;const i=Math.min(...r.map(a=>a.score));const o=r.filter(a=>a.score===i);return o.length===1?o[0].deviceId:null}function closeness(e,n){if(e===n)return 0;const t=import_node_path2.default.relative(e,n);const r=import_node_path2.default.relative(n,e);const i=o=>o&&!o.startsWith("..")&&!import_node_path2.default.isAbsolute(o);if(i(t))return t.split(import_node_path2.default.sep).length;if(i(r))return r.split(import_node_path2.default.sep).length;return-1}function isRecoveryAction(e,n){return e==="app"&&(n==="ping"||n==="reloadApp")}function isUnresponsive(e){return e>=2}function actionTimeoutMs(e){if(isRecoveryAction(e.toolId,e.action)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(!isUnresponsive(e.consecutiveTimeouts)){return{timeoutMs:e.fullMs,usedFullBudget:false}}if(e.now-e.lastFullBudgetAt>e.recoveryProbeMs){return{timeoutMs:e.fullMs,usedFullBudget:true}}return{timeoutMs:e.shortMs,usedFullBudget:false}}function diagnoseCrashed(e){if(e.consecutiveTimeouts>=2)return true;if(e.lastOkAt>0&&e.now-e.lastOkAt>e.unresponsiveAfterMs){return true}return false}var NOT_READY_MARK="Not ready:";var SyncClient=class{constructor(e={}){this.socket=null;this.admitted=false;this.createdAt=Date.now();this.lockedDevices=new Set;this.hostAccount=null;this.broker=null;this.capabilities=new Map;this.devices=[];this.sessionDevice=null;this.snapshots=new Map;this.watching=new Map;this.pendingActions=new Map;this.snapshotWaiters=new Map;this.snapshotAt=new Map;this.health=new Map;this.devServerOrigins=new Map;this.crashSeen=new Map;this.rootLookups=new Set;this.devServerRoots=new Map;this.originProbed=new Set;this.lastSeen=new Map;this.deviceConnections=new Map;this.port=e.port??BROKER_PORT;this.url=e.url??(e.port?`http://localhost:${e.port}`:BROKER_URL);this.actionTimeoutMs=e.actionTimeoutMs??DEFAULT_ACTION_TIMEOUT_MS;this.log=e.log??(n=>process.stderr.write(`[buoy-mcp] ${n}
2
- `));this.autoSpawn=e.autoSpawnBroker??true}async start(){const e=await probeBroker(this.url)||await probeBroker(this.url,8e3);let n="connected";if(!e){if(!this.autoSpawn){throw new Error(`No Buoy broker reachable at ${this.url} and autoSpawnBroker is off. Start the Buoy desktop app, or enable autoSpawnBroker.`)}this.log(`no broker at ${this.url} \u2014 spawning one in-process on :${this.port}`);this.hostAccount=new NodeAccount(()=>this.broker?.refreshAccess());this.hostAccount.start();let t=false;this.broker=(0,import_sync_broker2.createBroker)({canUseDesktop:this.hostAccount.hasAccess,port:this.port,onError:r=>{if(r.code==="EADDRINUSE")t=true;this.log(`broker error: ${r.code??r.message}`)}});await waitForBroker(this.url).catch(r=>{if(!t)throw r});if(!this.broker.httpServer.listening)t=true;if(t){this.log(`another broker holds :${this.port} \u2014 connecting to it as a dashboard`);await this.broker.close().catch(()=>void 0);this.broker=null;this.hostAccount.stop();this.hostAccount=null;await this.connectSocket();return"connected"}try{(0,import_sync_broker2.writeBrokerToken)(this.broker.dashboardToken,(0,import_sync_broker2.brokerTokenPath)(this.port))}catch(r){this.log(`could not write the broker token file: ${r.message}`)}n="spawned"}else{this.log(`found a running broker at ${this.url} \u2014 connecting as a dashboard`)}await this.connectSocket();return n}connectSocket(){return new Promise((e,n)=>{const t=(0,import_socket.io)(this.url,{transports:["websocket"],query:{deviceName:DASHBOARD_NAME},auth:s=>{const c=this.broker?.dashboardToken??(0,import_sync_broker2.readBrokerToken)((0,import_sync_broker2.brokerTokenPath)(this.port));s(c?{dashboardToken:c}:{})},reconnection:true,reconnectionDelay:500,timeout:4e3});this.socket=t;let r=false;const i=()=>{if(r)return;r=true;this.log("connected to broker");e()};const o=setTimeout(()=>{if(r)return;r=true;n(new Error("Broker account is locked or the broker needs an update. Sign in to Buoy Desktop or run npx buoy login for standalone MCP."))},5e3);t.on("buoy:access",s=>{const c=!!s&&typeof s==="object"&&s.protocol===1&&s.ready===true;this.setAdmission(c);if(c){clearTimeout(o);this.rearmWatches();i()}});t.on("connect",()=>{t.emit("buoy:access:request")});t.on("disconnect",()=>this.setAdmission(false,true));const a=s=>s.message===import_sync_broker2.DASHBOARD_TOKEN_REQUIRED;t.once("connect_error",s=>{if(r)return;r=true;clearTimeout(o);n(new Error(a(s)?`The broker at ${this.url} refused this MCP as a dashboard: the token in ${(0,import_sync_broker2.brokerTokenPath)(this.port)} is missing or stale. Update Buoy Desktop, or restart it so it writes the file.`:`failed to connect to broker at ${this.url}: ${s.message}`))});t.on("connect_error",s=>{if(!a(s)||t.active)return;setTimeout(()=>{if(this.socket===t&&!t.connected)t.connect()},1e3).unref?.()});t.on("devtool-capabilities",s=>{if(!this.admitted||this.lockedDevices.has(s.persistentDeviceId))return;this.capabilities.set(s.persistentDeviceId,s);this.trackRootLookup(this.learnDevServerOrigin(s.persistentDeviceId));if(s.tools?.some(c=>c.toolId==="console"))this.ensureWatching("console",s.persistentDeviceId)});t.on("all-devices-update",s=>{if(!this.admitted)return;if(!Array.isArray(s))return;let c=false;for(const l of s){if(l.deviceId&&l.tier==="locked")this.lockDevice(String(l.deviceId));else if(l.deviceId&&(l.tier==="free"||l.tier==="pro")){c=this.lockedDevices.delete(String(l.deviceId))||c}}this.devices=s;const u=Date.now();for(const l of s)if(l.deviceId)this.lastSeen.set(l.deviceId,u);this.pruneStaleDevices();if(c)this.rearmWatches();else this.rearmReconnectedDevices(s)});t.on("devtool-sync",s=>{if(!this.admitted||this.lockedDevices.has(s.persistentDeviceId))return;const c=snapKey(s.persistentDeviceId,s.toolId);this.snapshots.set(c,s.payload);this.snapshotAt.set(c,Date.now());if(s.toolId==="console")this.noteCrashReport(s.persistentDeviceId,s.payload);const u=this.snapshotWaiters.get(c);if(u&&u.length){this.snapshotWaiters.set(c,[]);for(const l of u)l(s.payload)}});t.on("devtool-action-result",s=>{if(!this.admitted)return;const c=this.pendingActions.get(s.requestId);if(!c)return;this.pendingActions.delete(s.requestId);clearTimeout(c.timer);c.resolve(s)})})}requireAdmission(){if(!this.admitted)throw new Error("A verified Buoy account and an updated broker are required. Sign in to Buoy Desktop, or run npx buoy login for standalone MCP.")}setAdmission(e,n=false){this.admitted=e;if(e)return;this.devices=[];this.lockedDevices.clear();this.capabilities.clear();this.snapshots.clear();this.snapshotAt.clear();this.devServerOrigins.clear();this.devServerRoots.clear();this.crashSeen.clear();this.originProbed.clear();this.health.clear();this.lastSeen.clear();if(!n)this.watching.clear();for(const t of this.pendingActions.values()){clearTimeout(t.timer);t.reject(new Error("Buoy account access ended while the action was pending."))}this.pendingActions.clear();for(const t of this.snapshotWaiters.values())for(const r of t)r(void 0);this.snapshotWaiters.clear();if(this.socket)this.socket.sendBuffer=[]}requireDeviceAccount(e){if(this.lockedDevices.has(e))throw new Error("The device's Buoy account access ended. Sign in and verify its key.")}lockDevice(e){this.lockedDevices.add(e);this.capabilities.delete(e);this.health.delete(e);this.devServerOrigins.delete(e);this.devServerRoots.delete(e);this.originProbed.delete(e);const n=`${e}::`;for(const t of this.snapshots.keys())if(t.startsWith(n)){this.snapshots.delete(t);this.snapshotAt.delete(t)}for(const[t,r]of this.snapshotWaiters)if(t.startsWith(n)){this.snapshotWaiters.delete(t);for(const i of r)i(void 0)}for(const[t,r]of this.pendingActions)if(r.target===e||r.target===ALL_DEVICES){clearTimeout(r.timer);this.pendingActions.delete(t);r.reject(new Error("Device account access ended while the action was pending."))}}pruneStaleDevices(){const e=Date.now()-DEVICE_RETENTION_MS;for(const[n,t]of this.lastSeen){if(t>e)continue;if(this.devices.some(i=>i.deviceId===n))continue;this.lastSeen.delete(n);this.capabilities.delete(n);this.health.delete(n);this.devServerOrigins.delete(n);this.devServerRoots.delete(n);this.originProbed.delete(n);const r=`${n}::`;for(const i of[...this.snapshots.keys()]){if(i.startsWith(r)){this.snapshots.delete(i);this.snapshotAt.delete(i)}}for(const i of[...this.watching.keys()]){if(i.startsWith(r))this.watching.delete(i)}}}async stop(){this.setAdmission(false);this.hostAccount?.stop();this.hostAccount=null;for(const[,e]of this.pendingActions){clearTimeout(e.timer);e.reject(new Error("SyncClient stopped"))}this.pendingActions.clear();for(const[,e]of this.snapshotWaiters)for(const n of e)n(void 0);this.snapshotWaiters.clear();this.socket?.close();this.socket=null;if(this.broker){await this.broker.close();this.broker=null}}listDevices(){if(!this.admitted)return[];return this.devices.filter(e=>e.deviceName!==DASHBOARD_NAME&&e.deviceId).map(e=>{const n=this.capabilities.get(e.deviceId);return{deviceId:e.deviceId,deviceName:e.deviceName,platform:e.platform,isConnected:e.isConnected!==false,isPro:e.isPro===true,tier:e.tier==="free"||e.tier==="pro"?e.tier:e.tier===void 0&&e.isPro===true?"pro":"locked",collision:e.collision===true,tools:n?.tools??[]}})}connectedDevices(){return this.listDevices().filter(e=>e.isConnected)}toolActions(e){return this.listDevices().map(n=>{const t=n.tools.find(r=>r.toolId===e);return t?{deviceId:n.deviceId,deviceName:n.deviceName,actions:t.actions}:null}).filter(n=>n!==null)}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const n=(u,l)=>new Error(`${NOT_READY_MARK} "${u}" (${l}) is not connected right now. If it is restarting, it usually takes a few seconds; to use another device, pass deviceId (run list_devices to see them).`);if(this.sessionDevice){const u=this.devices.find(l=>l.deviceId===this.sessionDevice);if(u&&u.isConnected!==false)return this.sessionDevice;throw n(this.sessionDevice,"the device this session was using")}const t=this.connectedDevices();const r=t.filter(u=>!this.lockedDevices.has(u.deviceId));const i=r.filter(u=>u.tools.length>0);const o=process.env.BUOY_PROJECT_ROOT||process.cwd();const a=pickByProject(i.map(u=>({deviceId:u.deviceId,root:this.devServerRoots.get(u.deviceId)})),o);if(a)return this.sessionDevice=a;const s=pickByProject(this.devices.filter(u=>u.deviceId&&u.isConnected===false&&!this.lockedDevices.has(u.deviceId)).map(u=>({deviceId:u.deviceId,root:this.devServerRoots.get(u.deviceId)})),o);if(s)throw n(s,"this project's app");if(r.length===0){if(t.length>0){throw new Error(`Devices are connected (${t.map(u=>u.deviceName).join(", ")}), but the broker has not admitted their accounts. Check app account validation and the account announcement after reconnect; this does not prove the user is signed out.`)}throw new Error("No devices are connected to the broker. Open the app with Buoy devtools running.")}if(r.length===1)return this.sessionDevice=r[0].deviceId;if(i.length===1)return this.sessionDevice=i[0].deviceId;if(i.length===0){const u=r.map(l=>l.deviceName).join(", ");throw new Error(`Connected devices (${u}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const c=i.map(u=>`${u.deviceName} (${u.deviceId})`).join(", ");throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${c}`)}requireProDevice(e){this.requireAdmission();if(e&&e!==ALL_DEVICES)this.sessionDevice=e;const n=o=>{if(!o)return"";return o.tier==="locked"?` The broker has not confirmed account access for "${o.deviceName}"; a locked status does not establish whether a key is configured.`:` The connected app "${o.deviceName}" is on the ${o.tier} tier.`};const t=o=>`Buoy Pro is required to use the MCP.${n(o)} Enter a license in the app, or \u2014 if it runs headless (no on-device UI) \u2014 pass \`licenseKey\` to \`<FloatingDevTools />\`. Run \`list_devices\` to check status.`;if(e===ALL_DEVICES){if(!this.connectedDevices().some(o=>o.isPro))throw new Error(t());return ALL_DEVICES}const r=this.resolveDevice(e);const i=this.connectedDevices().find(o=>o.deviceId===r);if(!i?.isPro){const o=this.accessState(r);if(o==="offline")throw new Error(`${NOT_READY_MARK} "${r}" is not connected right now. If the app is starting or reloading, it usually takes a few seconds. Run list_devices to check.`);if(o==="pending")throw new Error(`${NOT_READY_MARK} account access for "${r}" is still being confirmed (the app just connected). Try again in a moment.`);throw new Error(t(i))}return r}accessState(e){const n=this.devices.find(t=>t.deviceId===e);if(!n||n.isConnected===false)return"offline";if(n.isPro===true)return"ready";return n.tier===void 0?"pending":"denied"}healthOf(e){let n=this.health.get(e);if(!n){n={consecutiveTimeouts:0,lastOkAt:0,lastFullBudgetAt:0};this.health.set(e,n)}return n}noteOk(e){const n=this.healthOf(e);n.consecutiveTimeouts=0;n.lastOkAt=Date.now()}noteTimeout(e){this.healthOf(e).consecutiveTimeouts+=1}isUnresponsive(e){return isUnresponsive(this.healthOf(e).consecutiveTimeouts)}timeoutFor(e,n,t){const r=this.healthOf(e);const{timeoutMs:i,usedFullBudget:o}=actionTimeoutMs({consecutiveTimeouts:r.consecutiveTimeouts,lastFullBudgetAt:r.lastFullBudgetAt,now:Date.now(),fullMs:this.actionTimeoutMs,shortMs:UNRESPONSIVE_ACTION_TIMEOUT_MS,recoveryProbeMs:RECOVERY_PROBE_MS,toolId:n,action:t});if(o)r.lastFullBudgetAt=Date.now();return i}unresponsiveNote(e){const n=this.healthOf(e);const t=n.lastOkAt?Math.round((Date.now()-n.lastOkAt)/1e3):null;const r=diagnoseCrashed({consecutiveTimeouts:n.consecutiveTimeouts,lastOkAt:n.lastOkAt,now:Date.now(),unresponsiveAfterMs:UNRESPONSIVE_AFTER_MS});const i=[`The app on "${e}" is not responding (${n.consecutiveTimeouts} call${n.consecutiveTimeouts===1?"":"s"} unanswered${t!=null?`, last answered ${t}s ago`:""}).`,r?"It is most likely CRASHED \u2014 a fatal render error unmounts the React tree, and the dev tools live in that tree, so nothing on-device can answer until the app is reloaded.":"It may be busy, mid-reload, or crashing."];const o=this.lastFatalFor(e);if(o)i.push(`Last captured error: ${o}`);i.push(o?"Read the crash state with get_console / get_storage (served from the last sync), then reload_app to recover.":"Try get_console (served from the last sync) for the app's last words, then reload_app to recover.");return i.join(" ")}noteCrashReport(e,n){const t=n?.entries;if(!Array.isArray(t)||t.length===0)return;const r=Math.max(...t.map(a=>typeof a?.timestamp==="number"?a.timestamp:-Infinity));const i=this.crashSeen.get(e)??new Set;let o=false;for(const a of t){const s=a?.fatal||/^\[(RENDER ERROR|FATAL)/.test(a?.message??"");if(!s||typeof a.timestamp!=="number")continue;const c=`${a.id??""}|${a.timestamp}|${(a.message??"").slice(0,120)}`;if(i.has(c))continue;i.add(c);if(r-a.timestamp<3e4)o=true}if(i.size>200)for(const a of[...i].slice(0,i.size-200))i.delete(a);this.crashSeen.set(e,i);if(!o)return;if(![...this.pendingActions.values()].some(a=>a.target===e&&a.expire&&!a.cut))return;void this.callAction("app","ping",{},e,{timeoutMs:1500,silent:true}).then(()=>void 0,()=>{const a=Date.now();for(const s of this.pendingActions.values()){if(s.target!==e||!s.expire||s.cut)continue;s.cut=true;if(s.deadline!==void 0&&s.deadline-a<=UNRESPONSIVE_ACTION_TIMEOUT_MS)continue;clearTimeout(s.timer);s.timer=setTimeout(s.expire,UNRESPONSIVE_ACTION_TIMEOUT_MS)}})}lastFatalFor(e){const n=this.snapshots.get(snapKey(e,"console"));const t=n?.entries;if(!Array.isArray(t))return null;for(let r=t.length-1;r>=0;r--){const i=t[r];if(i?.fatal||i?.level==="error"){const o=(i.message??"").split("\n")[0];if(o)return o.length>300?`${o.slice(0,300)}\u2026`:o}}return null}snapshotAgeMs(e,n){this.requireAdmission();const t=this.snapshotAt.get(snapKey(n,e));return t?Date.now()-t:null}noteDevServerOrigin(e,n){if(typeof n==="string"&&/^https?:\/\//.test(n)){const t=this.devServerOrigins.get(e)!==n;this.devServerOrigins.set(e,n);if(t)this.devServerRoots.delete(e);if(t||!this.devServerRoots.has(e)){const r=devServerRoot(n).then(i=>{if(i&&this.devServerOrigins.get(e)===n)this.devServerRoots.set(e,i)});this.trackRootLookup(r)}}}async learnDevServerOrigin(e){if(this.devServerOrigins.has(e)||this.originProbed.has(e))return;this.originProbed.add(e);const n=this.capabilities.get(e)?.tools?.some(t=>t.toolId==="app");if(!n)return;try{const{payload:t}=await this.getSnapshot("app",e,{timeoutMs:4e3,silent:true});this.noteDevServerOrigin(e,t?.devServerOrigin)}catch{}}trackRootLookup(e){const n=e.catch(()=>void 0).finally(()=>this.rootLookups.delete(n));this.rootLookups.add(n)}async awaitBroker(){if(Date.now()-this.createdAt>15e3)return;for(let e=0;!this.admitted&&e<4e3;e+=100)await new Promise(n=>setTimeout(n,100));for(let e=0;this.admitted&&this.devices.length===0&&e<1500;e+=100)await new Promise(n=>setTimeout(n,100))}async settleDeviceChoice(e=1500){await this.awaitBroker();if(this.sessionDevice||this.rootLookups.size===0||this.connectedDevices().length<2)return;await Promise.race([Promise.all([...this.rootLookups]),new Promise(n=>setTimeout(n,e))]);if(this.rootLookups.size)await Promise.race([Promise.all([...this.rootLookups]),new Promise(n=>setTimeout(n,Math.min(800,e)))])}devServerOrigin(e){this.requireAdmission();const n=this.devServerOrigins.get(e);if(n)return n;const t=this.snapshots.get(snapKey(e,"app"));if(typeof t?.devServerOrigin==="string")return t.devServerOrigin;return null}ensureWatching(e,n){const t=snapKey(n,e);if(this.watching.has(t))return;this.watching.set(t,{toolId:e,targetDeviceId:n});this.sendWatch(e,n)}sendWatch(e,n){if(!this.admitted||!this.socket?.connected||this.lockedDevices.has(n))return;this.socket?.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:true,stream:false})}rearmWatches(){for(const{toolId:e,targetDeviceId:n}of this.watching.values()){this.sendWatch(e,n)}}rearmReconnectedDevices(e){for(const n of e){if(!n.deviceId||n.isConnected===false)continue;const t=String(n.deviceId);const r=`${n.id}|${n.connectionNonce??""}`;const i=this.deviceConnections.get(t);this.deviceConnections.set(t,r);if(i===void 0||i===r)continue;for(const{toolId:o,targetDeviceId:a}of this.watching.values()){if(a===t)this.sendWatch(o,a)}}}unwatch(e,n){const t=snapKey(n,e);if(!this.watching.delete(t))return;if(this.admitted&&this.socket?.connected)this.socket.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:false})}cachedSnapshot(e,n){this.requireAdmission();this.requireDeviceAccount(n);return this.snapshots.get(snapKey(n,e))}async getSnapshot(e,n,t={}){const r=this.resolveDevice(n);const i=snapKey(r,e);this.ensureWatching(e,r);let o=t.timeoutMs??DEFAULT_SNAPSHOT_TIMEOUT_MS;if(t.timeoutMs===void 0&&this.isUnresponsive(r)){const u=this.healthOf(r);if(Date.now()-u.lastFullBudgetAt>RECOVERY_PROBE_MS){u.lastFullBudgetAt=Date.now()}else{o=UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS}}const a=this.waitForSnapshot(i,o);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:r});const s=await a;this.requireAdmission();this.requireDeviceAccount(r);if(s!==void 0){if(!t.silent)this.noteOk(r);return{deviceId:r,payload:s}}if(!t.silent)this.noteTimeout(r);const c=this.snapshots.get(i);if(c!==void 0){return{deviceId:r,payload:c,stale:this.staleNote(e,r)}}throw new Error(`Timed out waiting for "${e}" state from ${r} (is the tool active?). ${this.unresponsiveNote(r)}`)}lastSync(e,n){const t=this.snapshots.get(snapKey(e,n));return t===void 0?void 0:{payload:t,ageMs:this.snapshotAgeMs(n,e)}}staleNote(e,n){const t=this.snapshotAgeMs(e,n);const r=t==null?"an earlier sync":`${Math.round(t/1e3)}s ago`;return`\u26A0\uFE0F Served from the last sync (${r}) \u2014 ${this.unresponsiveNote(n)}`}waitForSnapshot(e,n){return new Promise(t=>{const r=this.snapshotWaiters.get(e)??[];const i=setTimeout(()=>{const a=(this.snapshotWaiters.get(e)??[]).filter(s=>s!==o);this.snapshotWaiters.set(e,a);t(void 0)},n);const o=a=>{clearTimeout(i);t(a)};r.push(o);this.snapshotWaiters.set(e,r)})}async callAction(e,n,t,r,i={}){this.requireAdmission();const o=r===ALL_DEVICES?ALL_DEVICES:this.resolveDevice(r);if(!this.socket)throw new Error("SyncClient is not connected");const a=(0,import_node_crypto2.randomUUID)();const s=i.timeoutMs??this.timeoutFor(o,e,n);const c=await new Promise((u,l)=>{const d=Date.now();const h=()=>{this.pendingActions.delete(a);if(o!==ALL_DEVICES&&!i.silent)this.noteTimeout(o);l(new Error(`Action "${e}.${n}" got no answer in ${Date.now()-d}ms. `+(o===ALL_DEVICES?"No device responded.":this.unresponsiveNote(o))))};const p=setTimeout(h,s);this.pendingActions.set(a,{resolve:u,reject:l,timer:p,target:o,expire:h,deadline:d+s});this.socket.emit("devtool-action",{requestId:a,toolId:e,targetDeviceId:o,action:n,params:t??{}})});if(o!==ALL_DEVICES&&!i.silent)this.noteOk(o);if(!c.ok){throw new Error(c.error||`Action "${e}.${n}" failed on device`)}return c.result}};var snapKey=(e,n)=>`${e}::${n}`;function probeBroker(e,n=800){return new Promise(t=>{const r=import_node_http.default.get(e,i=>{i.resume();t((i.statusCode??0)>0)});r.setTimeout(n,()=>{r.destroy();t(false)});r.on("error",()=>t(false))})}async function waitForBroker(e,n=20){for(let t=0;t<n;t++){if(await probeBroker(e,300))return;await delay(50)}throw new Error(`Spawned broker never became reachable at ${e}`)}var delay=e=>new Promise(n=>setTimeout(n,e));var import_mcp=require("@modelcontextprotocol/sdk/server/mcp.js");var import_zod35=require("zod");var import_zod=require("zod");var import_node_fs2=require("fs");var import_node_os3=__toESM(require("os"));var import_node_path3=__toESM(require("path"));var VERSION="7.0.60"?"7.0.60":"0.0.0-dev";var PACKAGE_NAME="@buoy-gg/mcp";var CHECK_TTL_MS=24*60*60*1e3;var FETCH_TIMEOUT_MS=1500;var REGISTRY_URL=`https://registry.npmjs.org/${PACKAGE_NAME}/latest`;var CACHE_FILE=import_node_path3.default.join(import_node_os3.default.tmpdir(),"buoy-mcp-update-check.json");function isNewer(e,n){const t=o=>o.split("-")[0].split(".").map(a=>Number(a)||0);const r=t(e);const i=t(n);for(let o=0;o<3;o++){const a=r[o]??0;const s=i[o]??0;if(a>s)return true;if(a<s)return false}return false}async function readCache(){try{const e=await import_node_fs2.promises.readFile(CACHE_FILE,"utf8");const n=JSON.parse(e);if(typeof n.checkedAt==="number"&&typeof n.latest==="string"){return n}}catch{}return null}async function fetchLatest(e){const n=new AbortController;const t=setTimeout(()=>n.abort(),FETCH_TIMEOUT_MS);try{const r=await fetch(REGISTRY_URL,{signal:n.signal});if(!r.ok)return null;const i=await r.json();const o=typeof i.version==="string"?i.version:null;if(o){await import_node_fs2.promises.writeFile(CACHE_FILE,JSON.stringify({checkedAt:e,latest:o})).catch(()=>{})}return o}catch{return null}finally{clearTimeout(t)}}async function resolveLatest(e){const n=await readCache();if(n&&e-n.checkedAt<CHECK_TTL_MS)return n.latest;return fetchLatest(e)}async function getUpdateNotice(e=Date.now()){if(VERSION==="0.0.0-dev")return null;try{const n=await resolveLatest(e);if(n&&isNewer(n,VERSION)){return`A newer buoy-mcp is available (${n}; you're on ${VERSION}). Update by re-running: npx -y ${PACKAGE_NAME}@latest init \u2014 then restart your editor.`}}catch{}return null}var import_node_child_process2=require("child_process");var import_node_util2=require("util");var import_node_fs3=require("fs");var import_node_os4=__toESM(require("os"));var import_node_path4=__toESM(require("path"));var import_node_crypto3=require("crypto");var execFileAsync2=(0,import_node_util2.promisify)(import_node_child_process2.execFile);var clamp=(e,n,t)=>Math.min(Math.max(e,n),t);function humanizeSimctlError(e){const n=e;if(n?.code==="ENOENT"){return"Xcode command-line tools (xcrun) not found. Install Xcode to capture the iOS Simulator."}const t=String(n?.stderr||n?.message||e);if(/No devices are booted|Unable to find device|current device/i.test(t)){return"No booted iOS Simulator found. Boot the Simulator with your app running, then try again."}return t.trim()||"Failed to capture the iOS Simulator."}function pngSize(e){const n=[137,80,78,71,13,10,26,10];if(e.length<24||!n.every((t,r)=>e[r]===t))return null;return{width:e.readUInt32BE(16),height:e.readUInt32BE(20)}}var WEBVIEW_ID_KEY="@react_buoy_sync_device_id";async function listDir(e){try{return await import_node_fs3.promises.readdir(e)}catch{return[]}}async function webViewInstallIds(e){const n=[];for(const t of await listDir(e))n.push(...await containerWebViewInstallIds(import_node_path4.default.join(e,t)));return n}async function containerWebViewInstallIds(e){const n=[];const t=import_node_path4.default.join(e,"Library","WebKit");for(const r of await listDir(t)){const i=import_node_path4.default.join(t,r,"WebsiteData","Default");for(const o of await listDir(i)){for(const a of await listDir(import_node_path4.default.join(i,o))){const s=import_node_path4.default.join(i,o,a,"LocalStorage","localstorage.sqlite3");try{await import_node_fs3.promises.access(s);const{stdout:c}=await execFileAsync2("sqlite3",["-readonly",s,`SELECT hex(value) FROM ItemTable WHERE key='${WEBVIEW_ID_KEY}' LIMIT 1;`],{timeout:1500});const u=c.trim();if(u)n.push(Buffer.from(u,"hex").toString("utf16le").trim())}catch{}}}}return n}var webViewLookups=new Map;var WEBVIEW_MISS_MS=3e4;async function resolveSimUdid(e){if(process.platform!=="darwin")return{ok:false,error:"Simulator lookup needs macOS."};let n=[];try{const{stdout:r}=await execFileAsync2("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const i=JSON.parse(r).devices;n=Object.entries(i).filter(([o])=>/iOS/.test(o)).flatMap(([,o])=>o.filter(a=>a.state==="Booted"))}catch(r){return{ok:false,error:humanizeSimctlError(r)}}if(n.length===0)return{ok:false,error:"No iOS Simulator is booted."};const t=e?.split("-").pop();if(t){for(const r of n){if(!r.dataPath)continue;const i=import_node_path4.default.join(r.dataPath,"Containers","Data","Application");let o=[];try{o=await import_node_fs3.promises.readdir(i)}catch{continue}for(const a of o){try{const s=(await import_node_fs3.promises.readFile(import_node_path4.default.join(i,a,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(s===t)return{ok:true,udid:r.udid,how:`matched ${e} to "${r.name}"`}}catch{}}}}if(t&&e){const r=n.map(c=>c.udid).sort().join(",");const i=webViewLookups.get(e);const o=i?.booted===r&&(i.udid!==null||Date.now()-i.at<WEBVIEW_MISS_MS);const a=o&&i?.udid?n.find(c=>c.udid===i.udid):void 0;if(a)return{ok:true,udid:a.udid,how:`matched ${e} to "${a.name}" (WebView storage)`};const s=[];if(!o){const c=await Promise.all(n.map(u=>u.dataPath?webViewInstallIds(import_node_path4.default.join(u.dataPath,"Containers","Data","Application")):Promise.resolve([])));c.forEach((u,l)=>{if(u.includes(t))s.push(n[l])});webViewLookups.set(e,{booted:r,udid:s.length===1?s[0].udid:null,at:Date.now()})}if(s.length===1){return{ok:true,udid:s[0].udid,how:`matched ${e} to "${s[0].name}" (WebView storage)`}}if(s.length>1){return{ok:false,error:`${s.length} booted simulators (${s.map(c=>c.name).join(", ")}) hold ${e}. Pass the udid, or shut one down.`}}}if(n.length===1)return{ok:true,udid:n[0].udid,how:`only booted simulator "${n[0].name}"`};return{ok:false,error:`${n.length} iOS Simulators are booted (${n.map(r=>r.name).join(", ")}) and none could be matched to ${e??"this device"}. Shut down the others, or capture from a single booted simulator.`}}async function resolveSims(e){const n=new Map;if(process.platform!=="darwin"||e.length===0)return n;let t=[];try{const{stdout:i}=await execFileAsync2("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const o=JSON.parse(i).devices;t=Object.entries(o).filter(([a])=>/iOS/.test(a)).flatMap(([,a])=>a.filter(s=>s.state==="Booted"))}catch{return n}const r=new Map;for(const i of t){if(!i.dataPath)continue;const o=import_node_path4.default.join(i.dataPath,"Containers","Data","Application");let a=[];try{a=await import_node_fs3.promises.readdir(o)}catch{continue}for(const s of a){try{const c=(await import_node_fs3.promises.readFile(import_node_path4.default.join(o,s,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(c)r.set(c,{name:i.name,udid:i.udid})}catch{}}}for(const i of e){const o=r.get(i.split("-").pop()??"");if(o)n.set(i,o)}return n}async function captureIosFramebuffer(e="booted"){if(process.platform!=="darwin"){return{ok:false,error:"Screenshotting a component requires macOS with Xcode's iOS Simulator (uses `xcrun simctl`)."}}const n=import_node_path4.default.join(import_node_os4.default.tmpdir(),`buoy-mcp-sim-${(0,import_node_crypto3.randomUUID)()}.png`);try{await execFileAsync2("xcrun",["simctl","io",e,"screenshot","--type=png",n],{timeout:15e3})}catch(t){return{ok:false,error:humanizeSimctlError(t)}}try{const t=await import_node_fs3.promises.readFile(n);const r=pngSize(t);if(!r)return{ok:false,error:"Captured file wasn't a valid PNG."};return{ok:true,srcPath:n,width:r.width,height:r.height}}catch(t){return{ok:false,error:`Failed to read screenshot: ${t.message}`}}}async function cropToBuffer(e,n,t){const r=clamp(Math.round(t.x),0,Math.max(0,n.width-1));const i=clamp(Math.round(t.y),0,Math.max(0,n.height-1));const o=clamp(Math.round(t.width),1,n.width-r);const a=clamp(Math.round(t.height),1,n.height-i);const s=import_node_path4.default.join(import_node_os4.default.tmpdir(),`buoy-mcp-crop-${(0,import_node_crypto3.randomUUID)()}.png`);try{await execFileAsync2("sips",["-c",String(a),String(o),"--cropOffset",String(i),String(r),e,"--out",s],{timeout:1e4});const c=await import_node_fs3.promises.readFile(s);return{ok:true,buffer:c,width:o,height:a}}catch(c){const u=c;return{ok:false,error:`Crop failed: ${u?.stderr||u?.message||c}`}}finally{await import_node_fs3.promises.unlink(s).catch(()=>{});await import_node_fs3.promises.unlink(e).catch(()=>{})}}var import_node_child_process7=require("child_process");var import_node_util7=require("util");var import_node_child_process6=require("child_process");var import_node_util6=require("util");var import_node_fs6=require("fs");var import_node_os6=__toESM(require("os"));var import_node_path7=__toESM(require("path"));var import_node_crypto5=require("crypto");var import_pngjs2=__toESM(require_png());var import_node_child_process3=require("child_process");var import_node_util3=require("util");var import_node_fs4=require("fs");var import_node_os5=__toESM(require("os"));var import_node_path5=__toESM(require("path"));var import_node_crypto4=require("crypto");var import_pngjs=__toESM(require_png());var execFileAsync3=(0,import_node_util3.promisify)(import_node_child_process3.execFile);async function devicectl(e,n=3e4){const t=import_node_path5.default.join(import_node_os5.default.tmpdir(),`buoy-devicectl-${(0,import_node_crypto4.randomUUID)()}.json`);try{await execFileAsync3("xcrun",["devicectl",...e,"--quiet","--json-output",t],{timeout:n,maxBuffer:16*1024*1024});return JSON.parse(await import_node_fs4.promises.readFile(t,"utf8"))}catch(r){const i=r;let o=(i.stderr||i.stdout||i.message||"").trim();try{const a=JSON.parse(await import_node_fs4.promises.readFile(t,"utf8"));o=a.error?.userInfo?.NSLocalizedDescription?.string??o}catch{}if(/locked/i.test(o))throw new Error("The iPhone is locked. Unlock it and try again.");throw new Error(`devicectl ${e.slice(0,2).join(" ")} failed: ${o.split("\n").slice(-3).join(" ").slice(0,300)}`)}finally{await import_node_fs4.promises.unlink(t).catch(()=>void 0)}}async function physicalPhones(){if(process.platform!=="darwin")return[];return parsePhones(await devicectl(["list","devices"],15e3).catch(()=>null))}function parsePhones(e){const n=e;return(n?.result?.devices??[]).filter(t=>t.hardwareProperties?.reality==="physical"&&t.hardwareProperties?.platform==="iOS"&&t.connectionProperties?.pairingState==="paired"&&t.connectionProperties?.tunnelState!=="unavailable").map(t=>({udid:t.hardwareProperties.udid,name:t.deviceProperties?.name??"iPhone"})).filter(t=>!!t.udid)}async function developerApps(e){const n=await devicectl(["device","info","apps","--device",e]);return(n.result?.apps??[]).filter(t=>t.bundleIdentifier&&!t.bundleIdentifier.startsWith("com.apple.")&&t.builtByDeveloper!==false).map(t=>({bundleId:t.bundleIdentifier,name:t.name??t.bundleIdentifier,path:t.url?.replace(/^file:\/\//,"")}))}async function readAppFile(e,n,t){const r=await devicectl(["device","info","files","--device",e,"--domain-type","appDataContainer","--domain-identifier",n],2e4);const i=new Set((r.result?.files??[]).map(a=>a.relativePath??a.name??""));if(!i.has(t))return null;const o=import_node_path5.default.join(import_node_os5.default.tmpdir(),`buoy-devfile-${(0,import_node_crypto4.randomUUID)()}`);try{await devicectl(["device","copy","from","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",o],2e4);return await import_node_fs4.promises.readFile(o)}finally{await import_node_fs4.promises.rm(o,{recursive:true,force:true}).catch(()=>void 0)}}async function phoneInstallId(e,n){const t=await readAppFile(e,n,"Documents/react-buoy/@react_buoy_sync_device_id.json").catch(()=>null);const r=t?.toString("utf8").trim().replace(/^"|"$/g,"")??"";return/^[\w-]{4,64}$/.test(r)?r:null}async function phoneScreenshot(e){const n=import_node_path5.default.join(import_node_os5.default.tmpdir(),`buoy-phone-shot-${(0,import_node_crypto4.randomUUID)()}.png`);try{await devicectl(["device","capture","screenshot","--device",e,"--destination",n],3e4);return await import_node_fs4.promises.readFile(n)}finally{await import_node_fs4.promises.unlink(n).catch(()=>void 0)}}var BLACK_PHONE_NOTE="The picture is all black. If the app isn't really showing black, the iPhone's own screen is off: it is asleep, or the Mac shows it in iPhone Mirroring (the phone stays locked then). Quit iPhone Mirroring, unlock the phone and keep its screen on, then try again.";function isAllBlack(e){try{const n=import_pngjs.PNG.sync.read(e);const t=Math.max(1,Math.floor(n.width*n.height/4e3));for(let r=0;r<n.width*n.height;r+=t){const i=r*4;if(n.data[i]>12||n.data[i+1]>12||n.data[i+2]>12)return false}return true}catch{return false}}async function phoneLaunch(e,n,t={}){await devicectl(["device","process","launch","--device",e,...t.terminateExisting?["--terminate-existing"]:[],...t.url?["--payload-url",t.url]:[],n])}async function phoneOpenUrl(e,n){await devicectl(["device","process","openURL","--device",e,n])}async function phoneQuit(e,n){const t=await developerApps(e);const r=t.find(a=>a.bundleId===n)?.path;const i=await devicectl(["device","info","processes","--device",e]);const o=(i.result?.runningProcesses??[]).find(a=>r&&decodeURIComponent(a.executable??"").replace(/^file:\/\//,"").startsWith(r.replace(/\/$/,"")));if(!o?.processIdentifier)return false;await devicectl(["device","process","terminate","--device",e,"--pid",String(o.processIdentifier)]);return true}async function phoneUninstall(e,n){await devicectl(["device","uninstall","app","--device",e,n],12e4)}async function phoneInstall(e,n){await devicectl(["device","install","app","--device",e,n],3e5)}async function writeAppFile(e,n,t,r){await devicectl(["device","copy","to","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",r],3e4)}function phoneRecordArgs(e,n,t){return["devicectl","device","capture","screen-record","--device",e,"--destination",n,"--duration",String(t)]}var coreIds=new Map;async function coreDeviceId(e){const n=coreIds.get(e);if(n)return n;const t=await devicectl(["list","devices"]);const r=t.result?.devices?.find(i=>i.hardwareProperties?.udid===e)?.identifier;if(!r)throw new Error("CoreDevice doesn't list this iPhone right now. Check that it is connected and unlocked.");coreIds.set(e,r);return r}var import_node_child_process5=require("child_process");var import_node_util5=require("util");var import_node_fs5=require("fs");var import_node_path6=__toESM(require("path"));var import_ws=require("ws");var import_node_child_process4=require("child_process");var import_node_util4=require("util");var PLACEHOLDER=/\{\{\s*secret:([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;var MIN_SECRET_LENGTH=6;var used=new Map;var recordingActive=()=>false;function setRecordingProbe(e){recordingActive=e}function hasSecrets(e){PLACEHOLDER.lastIndex=0;return PLACEHOLDER.test(e)}function fillSecrets(e,n=process.env){if(!hasSecrets(e))return e;if(recordingActive()){throw new Error("A screen recording is running, and a video can't hide a typed secret. Stop the recording first (screen_recording stop), then type it.")}const t=[];const r=[];const i=e.replace(PLACEHOLDER,(o,a)=>{const s=n[`BUOY_SECRET_${a}`]??n[a];if(s===void 0||s===""){t.push(a);return""}if(s.length<MIN_SECRET_LENGTH){r.push(a);return""}used.set(a,s);return s});if(t.length){throw new Error(`No value for ${t.map(o=>`{{secret:${o}}}`).join(", ")}. Set ${t.map(o=>`BUOY_SECRET_${o}`).join(", ")} in the environment the MCP server runs in (for example in your editor's MCP config "env").`)}if(r.length){throw new Error(`${r.map(o=>`{{secret:${o}}}`).join(", ")} is shorter than ${MIN_SECRET_LENGTH} characters, so Buoy can't hide it reliably in what it sends back. Use a longer value, or type it as plain text if it isn't sensitive.`)}return i}function knownSecrets(e=process.env){const n=new Map(used);for(const[t,r]of Object.entries(e))if(t.startsWith("BUOY_SECRET_")&&r)n.set(t.slice("BUOY_SECRET_".length),r);return n}var escapeRe=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function scrubSecrets(e){const n=new Map;for(const[i,o]of knownSecrets()){if(o.length<MIN_SECRET_LENGTH)continue;for(const a of[o,JSON.stringify(o).slice(1,-1),encodeURIComponent(o)])n.set(a,i);for(let a=o.length-1;a>=MIN_SECRET_LENGTH;a--){n.set(`${o.slice(0,a)}\u2026`,i);n.set(`${o.slice(0,a)}...`,i);if(a>=8)n.set(o.slice(0,a),i)}}if(n.size===0)return e;const t=[...n.keys()].sort((i,o)=>o.length-i.length);const r=new RegExp(t.map(escapeRe).join("|"),"g");return e.replace(r,(i,o,a)=>{if(/^\d+$/.test(i)){const s=a.slice(Math.max(0,o-8),o);const c=a.slice(o+i.length,o+i.length+8);if(/(\d|\d\.)$/.test(s)||/^(\d|\.\d|[eE][+-]?\d)/.test(c))return i;if(/[:[,]\s*$/.test(s)&&/^\s*([,\]}]|$)/.test(c)&&!insideJsonString(a,o))return`"{{secret:${n.get(i)}}}"`}return`{{secret:${n.get(i)}}}`})}function insideJsonString(e,n){let t=false;for(let r=0;r<n;r++){if(e[r]==="\\")r++;else if(e[r]==='"')t=!t}return t}function typedSecretValues(){return[...used.values()]}function secretValues(){return[...knownSecrets().values()].filter(e=>e.length>=MIN_SECRET_LENGTH)}var execFileAsync4=(0,import_node_util4.promisify)(import_node_child_process4.execFile);var ADB_MISSING="Android control needs adb on this computer (Android SDK platform-tools). Install it, or add it to PATH.";function q(e){return`'${e.replace(/'/g,`'\\''`)}'`}function assertPackage(e){if(!/^[A-Za-z][\w]*(\.[A-Za-z_][\w]*)+$/.test(e))throw new Error(`"${e}" is not a valid Android package name.`);return e}async function adb(e,n,t=15e3){try{const{stdout:r}=await execFileAsync4("adb",e?["-s",e,...n]:n,{timeout:t,maxBuffer:32*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(ADB_MISSING);const o=n[0]==="shell"?`shell ${(n[1]??"").split(" ")[0]}`:n.slice(0,2).join(" ");const a=n[0]==="shell"?i.stderr||(i.killed?"timed out":"no error text"):i.stderr||i.message||"";const s=scrubSecrets(a.replace(/'[^']*'/g,"'\u2026'")).trim().slice(0,300);throw new Error(`adb ${o} failed: ${s}`)}}function adbShell(e,n,t=15e3){return adb(e,["shell",n],t)}async function adbBytes(e,n,t=15e3){try{const{stdout:r}=await execFileAsync4("adb",["-s",e,...n],{timeout:t,encoding:"buffer",maxBuffer:64*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(ADB_MISSING);throw new Error(`adb ${n.slice(0,2).join(" ")} failed: ${i.message.slice(0,300)}`)}}async function adbSerials(){return parseAdbDevices(await adb(null,["devices"]))}function parseAdbDevices(e){return e.split("\n").slice(1).map(n=>n.trim().split(/\s+/)).filter(n=>n[1]==="device").map(n=>n[0])}async function adbScreenSize(e){const n=parseWmSize(await adbShell(e,"wm size"));const t=parseRotation(await adbShell(e,"dumpsys input").catch(()=>""));return t%2===1?{width:n.height,height:n.width}:n}function parseWmSize(e){const n=/Override size:\s*(\d+)x(\d+)/.exec(e);const t=/Physical size:\s*(\d+)x(\d+)/.exec(e);const r=n??t;if(!r)throw new Error(`Could not read the Android screen size (adb said: ${e.trim().slice(0,120)}).`);return{width:Number(r[1]),height:Number(r[2])}}function parseRotation(e){const n=/SurfaceOrientation:\s*(\d)/.exec(e);return n?Number(n[1]):0}async function adbAppFrame(e,n){const t=await adbShell(e,"dumpsys window windows").catch(()=>"");return parseAppFrame(t,n)}function parseAppFrame(e,n){const t=e.split(/\n(?=\s*Window #\d+)/);for(const r of t){if(!r.includes(`${n}/`))continue;const i=/mFrame=\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(r)??/\bframe=\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(r);if(i){const[o,a,s,c]=i.slice(1).map(Number);if(s>o&&c>a)return{x:o,y:a,width:s-o,height:c-a}}}return null}async function adbForegroundPackage(e){return parseForegroundPackage(await adbShell(e,"dumpsys activity activities"))}function parseForegroundPackage(e){const n=/(?:topResumedActivity|mResumedActivity|ResumedActivity)[^\n]*?\s([a-zA-Z][\w.]*)\/[\w.$]+/.exec(e);return n?n[1]:null}async function adbUserPackages(e){const n=await adbShell(e,"pm list packages -3");return n.split("\n").map(t=>t.trim().replace(/^package:/,"")).filter(t=>/^[A-Za-z][\w.]+$/.test(t))}async function adbInstallId(e,n){assertPackage(n);const t=await adbShell(e,`run-as ${q(n)} cat files/react-buoy/@react_buoy_sync_device_id.json 2>/dev/null`,5e3).catch(()=>"");const r=t.trim().replace(/^"|"$/g,"");if(/^[\w-]{4,64}$/.test(r))return r;const i=await adbBytes(e,["exec-out",`run-as ${q(n)} sh -c 'cat app_webview/Default/"Local Storage"/leveldb/*.log app_webview/Default/"Local Storage"/leveldb/*.ldb 2>/dev/null'`],5e3).catch(()=>null);return i?webViewLevelDbInstallId(i):null}function webViewLevelDbInstallId(e){const n=e.toString("latin1");const t=/@react_buoy_sync_device_id([\s\S])\x01([\w-]{4,64})/g;let r=null;for(let i=t.exec(n);i;i=t.exec(n)){const o=i[1].charCodeAt(0)-1;if(o>=4&&o<=i[2].length)r=i[2].slice(0,o)}return r}function escapeAdbText(e){if(/[^\x20-\x7e]/.test(e))throw new Error("adb can only type plain ASCII text. Use tap_element's text for other characters.");return q(e.replace(/ /g,"%s"))}async function adbTap(e,n,t,r){const[i,o]=[Math.round(n),Math.round(t)];if(r)await adbShell(e,`input swipe ${i} ${o} ${i} ${o} ${Math.round(r)}`);else await adbShell(e,`input tap ${i} ${o}`)}async function adbSwipe(e,n,t,r){const i=[...n,...t].map(o=>Math.round(o)).join(" ");await adbShell(e,`input swipe ${i} ${Math.round(r)}`)}async function adbText(e,n){const t=n.replace(/ /g,"\0");for(let r=0;r<t.length;r+=40){const i=t.slice(r,r+40).replace(/\u0000/g," ");await adbShell(e,`input text ${escapeAdbText(i)}`)}}async function adbScreenshot(e){const n=await adbBytes(e,["exec-out","screencap","-p"]);if(n.length<8||n.readUInt32BE(0)!==2303741511)throw new Error("The Android screenshot was not a PNG.");return n}async function adbDemoMode(e,n){if(n){await adbShell(e,"settings put global sysui_demo_allowed 1");for(const t of["-e command enter","-e command clock -e hhmm 0941","-e command battery -e level 100 -e plugged false","-e command network -e wifi show -e level 4","-e command notifications -e visible false"]){await adbShell(e,`am broadcast -a com.android.systemui.demo ${t}`).catch(()=>void 0)}}else{await adbShell(e,"am broadcast -a com.android.systemui.demo -e command exit").catch(()=>void 0)}}async function adbUiNodes(e){const n=await adb(e,["exec-out","uiautomator","dump","/dev/tty"],2e4);return parseUiDump(n)}function parseUiDump(e){const n=[];const t=(r,i)=>{const o=new RegExp(`\\s${i}="([^"]*)"`).exec(r);return o?decodeXml(o[1]):""};for(const r of e.matchAll(/<node\b[^>]*>/g)){const i=r[0];const o=/\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(t(i,"bounds"));if(!o)continue;const[a,s,c,u]=o.slice(1).map(Number);n.push({text:t(i,"text"),desc:t(i,"content-desc"),id:t(i,"resource-id"),cls:t(i,"class"),clickable:t(i,"clickable")==="true",bounds:{x:a,y:s,width:c-a,height:u-s}})}return n}function decodeXml(e){return e.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#(\d+);/g,(n,t)=>String.fromCharCode(Number(t))).replace(/&amp;/g,"&")}function findUiNodes(e,n){const t=n.trim().toLowerCase();const r=c=>{let u=0;for(const l of[c.desc,c.text,c.id.split("/").pop()??""]){const d=l.trim().toLowerCase();if(!d)continue;if(d===t)u=Math.max(u,3);else if(d.startsWith(t))u=Math.max(u,2);else if(d.includes(t))u=Math.max(u,1)}return u};const i=e.filter(c=>c.bounds.width>0&&c.bounds.height>0&&r(c)>0);const o=Math.max(0,...i.map(r));const a=i.filter(c=>r(c)===o);let s=a.filter((c,u)=>a.findIndex(l=>JSON.stringify(l.bounds)===JSON.stringify(c.bounds))===u);if(s.length>1){const c=s.filter(u=>[u.desc,u.text,u.id.split("/").pop()??""].some(l=>l.trim()===n.trim()));if(c.length)s=c}if(s.length>1){const c=s.filter(u=>u.clickable||/EditText|Button/.test(u.cls));if(c.length)s=c}return s}var execFileAsync5=(0,import_node_util5.promisify)(import_node_child_process5.execFile);var WEB_KEEP_KEY=/^(@buoy\/session:|buoy-gg-license|buoy-gg-device-fingerprint$|@react_buoy_sync_device_id$|@react_buoy_install)/;async function listDir2(e){return import_node_fs5.promises.readdir(e).catch(()=>[])}async function containerLocalStorageFiles(e){const n=[];const t=import_node_path6.default.join(e,"Library","WebKit");for(const r of await listDir2(t)){const i=import_node_path6.default.join(t,r,"WebsiteData","Default");for(const o of await listDir2(i)){for(const a of await listDir2(import_node_path6.default.join(i,o))){const s=import_node_path6.default.join(i,o,a);const c=import_node_path6.default.join(s,"LocalStorage","localstorage.sqlite3");if(!await import_node_fs5.promises.access(c).then(()=>true,()=>false))continue;const u=await import_node_fs5.promises.readFile(import_node_path6.default.join(s,"origin")).then(l=>l.toString("hex"),()=>"");if(u)n.push({db:c,origin:u})}}}return n}var sqlite=(e,n,t=true)=>execFileAsync5("sqlite3",[...t?["-readonly"]:[],e,n],{timeout:5e3}).then(r=>r.stdout);async function iosReadWebKeep(e){const n=[];for(const{db:t,origin:r}of await containerLocalStorageFiles(e)){const i=await sqlite(t,"SELECT key, hex(value) FROM ItemTable;");for(const o of i.split("\n")){const a=o.lastIndexOf("|");if(a<0)continue;const s=o.slice(0,a);if(WEB_KEEP_KEY.test(s))n.push({key:s,value:o.slice(a+1),origin:r})}}return n}async function iosWriteWebKeep(e,n){if(!n.length)return false;const t=await containerLocalStorageFiles(e);const r=new Set(n.map(i=>i.origin??""));for(const i of r){const o=i?t.find(s=>s.origin===i):void 0;if(!o)return false;const a=n.filter(s=>(s.origin??"")===i&&/^[0-9A-F]*$/i.test(s.value)).map(s=>`('${s.key.replace(/'/g,"''")}', X'${s.value}')`).join(",");if(a)await sqlite(o.db,`INSERT OR REPLACE INTO ItemTable (key, value) VALUES ${a};`,false)}return true}async function iosWaitForLocalStorage(e,n=15e3){const t=Date.now()+n;while(Date.now()<t){if((await containerLocalStorageFiles(e)).length)return true;await new Promise(r=>setTimeout(r,500))}return false}async function evaluateInWebView(e,n,t){const r=(await adbShell(e,`pidof ${n}`).catch(()=>"")).trim().split(/\s+/)[0];if(!r)throw new Error("the app is not running");const i=(await adb(e,["forward","tcp:0",`localabstract:webview_devtools_remote_${r}`])).trim();try{const o=await(await fetch(`http://127.0.0.1:${i}/json`)).json();const a=o.find(s=>s.type==="page"&&s.webSocketDebuggerUrl);if(!a?.webSocketDebuggerUrl)throw new Error("no debuggable WebView page (needs a debug build)");return await new Promise((s,c)=>{const u=new import_ws.WebSocket(a.webSocketDebuggerUrl);const l=setTimeout(()=>{u.close();c(new Error("the WebView did not answer"))},5e3);u.on("open",()=>u.send(JSON.stringify({id:1,method:"Runtime.evaluate",params:{expression:t,returnByValue:true}})));u.on("message",d=>{const h=JSON.parse(String(d));if(h.id!==1)return;clearTimeout(l);u.close();if(h.result?.exceptionDetails)c(new Error("the WebView script failed"));else s(h.result?.result?.value)});u.on("error",d=>{clearTimeout(l);c(d)})})}finally{await adb(e,["forward","--remove",`tcp:${i}`]).catch(()=>void 0)}}async function evaluateWhenReady(e,n,t,r=15e3){const i=Date.now()+r;let o;while(Date.now()<i){try{return await evaluateInWebView(e,n,t)}catch(a){o=a;await new Promise(s=>setTimeout(s,700))}}throw o instanceof Error?o:new Error("the WebView did not open")}async function androidHasWebViewStorage(e,n){const t=await adbShell(e,`run-as ${n} sh -c 'ls app_webview/Default/"Local Storage"/leveldb 2>/dev/null'`).catch(()=>"");return/CURRENT|\.log/.test(t)}async function androidReadWebKeep(e,n){if(!(await adbShell(e,`pidof ${n}`).catch(()=>"")).trim()){await adbShell(e,`monkey -p ${n} -c android.intent.category.LAUNCHER 1`)}const t=await evaluateWhenReady(e,n,`(() => { const re = ${WEB_KEEP_KEY}; const out = []; for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && re.test(k)) out.push({ key: k, value: localStorage.getItem(k) }); } return out; })()`);return Array.isArray(t)?t.filter(r=>typeof r.key==="string"&&typeof r.value==="string"):[]}async function androidWriteWebKeep(e,n,t){await evaluateWhenReady(e,n,`(() => { for (const r of ${JSON.stringify(t)}) localStorage.setItem(r.key, r.value); setTimeout(() => location.reload(), 50); return true; })()`)}var execFileAsync6=(0,import_node_util6.promisify)(import_node_child_process6.execFile);var hosts=new Map;function rememberedHost(e){return hosts.get(e)}async function sh(e,n,t=2e4){try{const{stdout:r}=await execFileAsync6(e,n,{timeout:t,maxBuffer:16*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(e==="xcrun"?"This needs macOS with Xcode (xcrun simctl).":`${e} is not installed.`);throw new Error(`${e} ${n.slice(0,2).join(" ")} failed: ${(i.stderr||i.message||"").trim().slice(0,300)}`)}}var simctl=(e,n)=>sh("xcrun",["simctl",...e],n);var tailOf=e=>e.split("-").pop()??"";async function simsHolding(e){let n=[];try{const r=JSON.parse(await simctl(["list","devices","booted","-j"])).devices;n=Object.entries(r).filter(([i])=>/iOS/.test(i)).flatMap(([,i])=>i.filter(o=>o.state==="Booted"))}catch{return[]}const t=[];for(const r of n)if(await findIosContainer(e,r.udid))t.push(r);return t}function cloneError(e,n){return new Error(`${n.length} booted simulators hold "${e}" (one is probably a clone): ${n.map(t=>`${t.name} (${t.udid})`).join(", ")}. Pass udid to choose, or shut the extra one down.`)}async function findIosContainer(e,n){const t=tailOf(e);if(!t)return null;let r;try{const a=JSON.parse(await simctl(["list","devices","-j"])).devices;r=Object.values(a).flat().find(s=>s.udid===n)?.dataPath}catch{return null}if(!r)return null;const i=import_node_path7.default.join(r,"Containers","Data","Application");let o=[];try{o=await import_node_fs6.promises.readdir(i)}catch{return null}for(const a of o){const s=import_node_path7.default.join(i,a);if(!await iosContainerHolds(s,t))continue;let c=null;try{c=(await sh("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",import_node_path7.default.join(s,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:s,bundleId:c}}return null}async function iosContainerHolds(e,n){try{if((await import_node_fs6.promises.readFile(import_node_path7.default.join(e,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim()===n)return true}catch{}return(await containerWebViewInstallIds(e).catch(()=>[])).includes(n)}async function findAndroid(e,n){const t=tailOf(e);const r=n.serial?[n.serial]:await adbSerials();if(r.length===0)throw new Error("No Android device or emulator is connected to adb.");for(const i of r){const o=await adbForegroundPackage(i).catch(()=>null);const a=await adbUserPackages(i).catch(()=>[]);const s=[n.bundleId,o,...a].filter((c,u,l)=>!!c&&l.indexOf(c)===u).slice(0,80);for(const c of s){if(await adbInstallId(i,c).catch(()=>null)===t)return{platform:"android",serial:i,packageName:c}}}return null}async function findPhone(e){const n=tailOf(e);for(const t of await physicalPhones()){for(const r of await developerApps(t.udid).catch(()=>[])){if(await phoneInstallId(t.udid,r.bundleId)===n)return{platform:"ios-device",udid:t.udid,name:t.name,bundleId:r.bundleId}}}return null}async function findHost(e,n,t={}){if(e==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');const r=hosts.get(e);if(r&&!t.udid&&!t.serial&&await stillHolds(e,r)){if(r.platform==="ios"&&!r.picked){const c=await simsHolding(e);if(c.length>1)throw cloneError(e,c)}return r}if(r)hosts.delete(e);if(n==="android"){const c=await findAndroid(e,t);if(!c){throw new Error(`Could not prove which Android device and app run "${e}". Buoy checks the app's install id with run-as, which needs a debug build of the app on a device adb can reach${t.serial?` (looked on ${t.serial})`:""}.`)}hosts.set(e,c);return c}if(n&&n!=="ios")throw new Error(`Device control works on iOS Simulators and Android. This app runs on "${n}".`);if(process.platform!=="darwin")throw new Error("iOS control needs macOS with Xcode.");let i=t.udid;let o=i??"";if(!i){const c=await simsHolding(e);if(c.length>1)throw cloneError(e,c);const u=c.length===1?{ok:true,udid:c[0].udid,how:`matched ${e} to "${c[0].name}"`}:await resolveSimUdid(e);if(!u.ok||!/^matched /.test(u.how)){const l=await findPhone(e).catch(()=>null);if(l){hosts.set(e,l);return l}throw new Error(`Could not find which simulator or iPhone runs "${e}": no booted simulator holds its install id, and no connected iPhone has it (an iPhone must be unlocked, paired, and run a development build).`)}i=u.udid;o=/"([^"]+)"/.exec(u.how)?.[1]??i}const a=await findIosContainer(e,i);if(!a&&t.udid)throw new Error(`Simulator ${t.udid} does not hold "${e}".`);const s={platform:"ios",udid:i,name:o,bundleId:t.bundleId??a?.bundleId??null,container:a?.container??null,picked:!!t.udid};hosts.set(e,s);return s}async function verifyHost(e,n){if(n.platform==="ios"&&!n.picked){const t=await simsHolding(e);if(t.length>1)throw cloneError(e,t)}if(await stillHolds(e,n))return n;hosts.delete(e);return findHost(e,n.platform==="android"?"android":"ios",n.platform==="ios"&&n.picked?{udid:n.udid}:{})}async function stillHolds(e,n){const t=tailOf(e);if(n.platform==="android")return await adbInstallId(n.serial,n.packageName).catch(()=>null)===t;if(n.platform==="ios-device")return await phoneInstallId(n.udid,n.bundleId).catch(()=>null)===t;if(n.container)return iosContainerHolds(n.container,t);const r=await resolveSimUdid(e);return r.ok&&r.udid===n.udid&&/^matched /.test(r.how)}function needApp(e){if(e.platform==="android")return assertPackage(e.packageName);if(e.platform==="ios-device")return e.bundleId;if(!e.bundleId)throw new Error("Could not tell which app this is on the simulator (its container has no bundle metadata).");return e.bundleId}async function hostPng(e){if(e.platform==="android")return adbScreenshot(e.serial);if(e.platform==="ios-device")return phoneScreenshot(e.udid);const n=await captureIosFramebuffer(e.udid);if(!n.ok||!n.srcPath)throw new Error(n.error??"Screenshot failed.");try{return await import_node_fs6.promises.readFile(n.srcPath)}finally{await import_node_fs6.promises.unlink(n.srcPath).catch(()=>{})}}async function toSmallImage(e,n=1280){if(process.platform==="darwin"){const i=import_node_path7.default.join(import_node_os6.default.tmpdir(),`buoy-mcp-img-${(0,import_node_crypto5.randomUUID)()}.png`);const o=i.replace(/\.png$/,".jpg");await import_node_fs6.promises.writeFile(i,e);try{await sh("sips",["-Z",String(n),"-s","format","jpeg","-s","formatOptions","70",i,"--out",o],15e3);const a=await sh("sips",["-g","pixelWidth","-g","pixelHeight",o]);return{data:(await import_node_fs6.promises.readFile(o)).toString("base64"),mimeType:"image/jpeg",width:Number(/pixelWidth:\s*(\d+)/.exec(a)?.[1]??0),height:Number(/pixelHeight:\s*(\d+)/.exec(a)?.[1]??0)}}finally{await import_node_fs6.promises.unlink(i).catch(()=>{});await import_node_fs6.promises.unlink(o).catch(()=>{})}}const t=downscalePng(import_pngjs2.PNG.sync.read(e),Math.min(n,1024));const r=import_pngjs2.PNG.sync.write(t,{colorType:2,deflateLevel:9});return{data:r.toString("base64"),mimeType:"image/png",width:t.width,height:t.height}}function downscalePng(e,n){const t=Math.min(1,n/Math.max(e.width,e.height));if(t===1)return e;const r=Math.max(1,Math.round(e.width*t));const i=Math.max(1,Math.round(e.height*t));const o=new import_pngjs2.PNG({width:r,height:i});const a=e.width/r;const s=e.height/i;for(let c=0;c<i;c++){const u=Math.floor(c*s);const l=Math.max(u+1,Math.floor((c+1)*s));for(let d=0;d<r;d++){const h=Math.floor(d*a);const p=Math.max(h+1,Math.floor((d+1)*a));const m=[0,0,0,0];let w=0;for(let f=u;f<l;f++){for(let v=h;v<p;v++){const y=(f*e.width+v)*4;for(let b=0;b<4;b++)m[b]+=e.data[y+b];w++}}const g=(c*r+d)*4;for(let f=0;f<4;f++)o.data[g+f]=Math.round(m[f]/w)}}return o}var steadying=new Set;async function withSteadyStatusBar(e,n){let t=false;try{if(e.platform==="ios"){const r=await simctl(["status_bar",e.udid,"list"]).catch(()=>"");const i=r.split(/^=+$/m).slice(1).join("").trim();if(!i){await simctl(["status_bar",e.udid,"override","--time","9:41","--batteryState","charged","--batteryLevel","100","--wifiBars","3","--cellularBars","4"]);t=true}}else if(e.platform==="android"){const r=(await adbShell(e.serial,"settings get global sysui_demo_allowed").catch(()=>"")).trim();if(r!=="1"&&!steadying.has(e.serial)){steadying.add(e.serial);await adbDemoMode(e.serial,true);t=true}}if(t)await new Promise(r=>setTimeout(r,400))}catch{t=false}try{return{result:await n(),steadied:t}}finally{if(t){if(e.platform==="ios")await simctl(["status_bar",e.udid,"clear"]).catch(()=>void 0);else if(e.platform==="android"){await adbDemoMode(e.serial,false);await adbShell(e.serial,"settings put global sysui_demo_allowed 0").catch(()=>void 0);steadying.delete(e.serial)}}}}async function hostQuit(e){const n=needApp(e);if(e.platform==="ios-device"){const t=await phoneQuit(e.udid,n);return t?`Quit ${n}.`:`${n} was not running.`}if(e.platform==="ios"){await simctl(["terminate",e.udid,n]).catch(t=>{if(!/found nothing to terminate|not running/i.test(String(t)))throw t})}else{await adbShell(e.serial,`am force-stop ${q(n)}`)}return`Quit ${n}.`}async function hostLaunch(e){const n=needApp(e);if(e.platform==="ios")await simctl(["launch",e.udid,n]);else if(e.platform==="ios-device")await phoneLaunch(e.udid,n);else await adbShell(e.serial,`monkey -p ${q(n)} -c android.intent.category.LAUNCHER 1`);return`Launched ${n}.`}async function hostBackground(e){if(e.platform==="ios-device"){await phoneLaunch(e.udid,"com.apple.Preferences");return"Sent to the background for real (Settings opened on top)."}if(e.platform==="ios"){await simctl(["launch",e.udid,"com.apple.Preferences"]);return"Sent to the background for real (Settings opened on top)."}await adbShell(e.serial,"input keyevent 3");return"Sent to the background for real (pressed Home)."}async function hostOpenUrl(e,n){if(!/^[a-zA-Z][\w+.-]*:/.test(n))throw new Error(`"${n}" is not a link with a scheme (like https://\u2026 or myapp://\u2026).`);if(e.platform==="ios-device"){await phoneOpenUrl(e.udid,n);return"Opened through the OS on the iPhone."}if(e.platform==="ios"){await simctl(["openurl",e.udid,n]);return'Opened through the OS. A custom scheme may first show an "Open in" prompt on the simulator.'}await adbShell(e.serial,`am start -a android.intent.action.VIEW -d ${q(n)}`);return"Opened through the OS (an Android VIEW intent)."}var BUOY_KEEP=["buoy-license","react-buoy/@react_buoy_sync_device_id.json","react-buoy/@react_buoy_install.json"];async function appBundleInfo(e){const n=import_node_path7.default.join(e,"Info.plist");const t=a=>sh("plutil",["-extract",a,"raw","-o","-",n]).then(s=>s.trim()).catch(()=>"");const r=await t("CFBundleIdentifier");if(!r)throw new Error(`${e} has no Info.plist with a bundle id. Pass a built .app folder.`);const i=(await sh("plutil",["-extract","CFBundleSupportedPlatforms","json","-o","-",n]).catch(()=>"[]")).toLowerCase();const o=(await t("DTPlatformName")).toLowerCase();return{bundleId:r,simulator:i.includes("iphonesimulator")||o==="iphonesimulator"}}async function apkPackage(e){const n=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT,import_node_path7.default.join(import_node_os6.default.homedir(),"Library","Android","sdk"),import_node_path7.default.join(import_node_os6.default.homedir(),"Android","Sdk")].filter(t=>!!t);for(const t of n){const r=import_node_path7.default.join(t,"build-tools");const i=(await import_node_fs6.promises.readdir(r).catch(()=>[])).sort().reverse();for(const o of i){for(const a of["aapt2","aapt"]){const s=import_node_path7.default.join(r,o,a);try{await import_node_fs6.promises.access(s)}catch{continue}const c=await sh(s,a==="aapt2"?["dump","packagename",e]:["dump","badging",e]).catch(()=>"");const u=a==="aapt2"?c.trim().split("\n")[0]:/package: name='([^']+)'/.exec(c)?.[1]??"";if(u)return u}}}throw new Error("Could not read the APK's package name (needs aapt2 from the Android SDK build-tools). Nothing was changed.")}async function hostReinstall(e,n,t=true){const r=needApp(e);const i=import_node_path7.default.resolve(n);try{await import_node_fs6.promises.access(i)}catch{throw new Error(`No build at ${i}. Pass appPath: the built .app folder (iOS Simulator) or .apk file (Android). Nothing was changed.`)}if(e.platform==="android")return reinstallAndroid(e,r,i,t);if(e.platform==="ios-device")return reinstallPhone(e,r,i,t);if(!/\.app\/?$/i.test(i))throw new Error("On the iOS Simulator, appPath must be a built .app folder. Nothing was changed.");const o=await appBundleInfo(i);if(o.bundleId!==r)throw new Error(`${import_node_path7.default.basename(i)} is ${o.bundleId}, but this app is ${r}. Nothing was changed.`);if(!o.simulator)throw new Error(`${import_node_path7.default.basename(i)} is a device build, not a simulator build. Nothing was changed.`);const a=t?await import_node_fs6.promises.mkdtemp(import_node_path7.default.join(import_node_os6.default.tmpdir(),"buoy-mcp-keep-")):null;try{let s=false;let c=[];if(a){await import_node_fs6.promises.chmod(a,448);const l=(await simctl(["get_app_container",e.udid,r,"data"]).catch(()=>"")).trim();if(l)s=await copyBuoyFiles(import_node_path7.default.join(l,"Documents"),a);if(l&&!s){try{c=await iosReadWebKeep(l)}catch(d){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView storage (${d.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}}await simctl(["terminate",e.udid,r]).catch(()=>void 0);await simctl(["uninstall",e.udid,r]);try{await simctl(["install",e.udid,i],18e4)}catch(l){throw new Error(`The app was removed, but installing ${import_node_path7.default.basename(i)} failed: ${l.message}. Install it again by hand.`)}let u="";if(a&&s){try{const l=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await copyBuoyFiles(a,import_node_path7.default.join(l,"Documents"));e.container=l;u=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(l){u=` Buoy's sign-in could not be restored (${l.message}): sign in to Buoy again in the app.`}}else if(c.length){try{const l=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await simctl(["launch",e.udid,r]);const d=await iosWaitForLocalStorage(l);await simctl(["terminate",e.udid,r]).catch(()=>void 0);if(!d||!await iosWriteWebKeep(l,c))throw new Error("the app made no WebView storage");e.container=l;u=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(l){u=` Buoy's sign-in could not be restored (${l.message}): sign in to Buoy again in the app.`}}else if(t){u=" The old install had no Buoy sign-in to keep."}await simctl(["launch",e.udid,r]);return`Reinstalled ${r} from ${i} and launched it. The app's own data is gone, like a new user.${u}`}finally{if(a)await import_node_fs6.promises.rm(a,{recursive:true,force:true}).catch(()=>void 0)}}async function copyBuoyFiles(e,n){let t=false;for(const r of BUOY_KEEP){const i=import_node_path7.default.join(e,r);try{await import_node_fs6.promises.access(i)}catch{continue}const o=import_node_path7.default.join(n,r);await import_node_fs6.promises.mkdir(import_node_path7.default.dirname(o),{recursive:true});await import_node_fs6.promises.cp(i,o,{recursive:true,force:true});t=true}return t}async function reinstallAndroid(e,n,t,r){if(!/\.apk$/i.test(t))throw new Error("On Android, appPath must be an .apk file. Nothing was changed.");const i=await apkPackage(t);if(i!==n)throw new Error(`${import_node_path7.default.basename(t)} is ${i}, but this app is ${n}. Nothing was changed.`);const o=[];if(r){const c=await adbShell(e.serial,`run-as ${q(n)} find files/buoy-license files/react-buoy -maxdepth 1 -type f 2>/dev/null`).catch(()=>"");const u=c.split("\n").map(l=>l.trim()).filter(l=>l.startsWith("files/buoy-license/")||/react-buoy\/@react_buoy_(sync_device_id|install)\.json$/.test(l));for(const l of u){const d=await adbShell(e.serial,`run-as ${q(n)} base64 ${q(l)}`).catch(()=>"");if(d.trim())o.push({rel:l,data:d.replace(/\s+/g,"")})}}let a=[];if(r&&!o.length&&await androidHasWebViewStorage(e.serial,n)){try{a=await androidReadWebKeep(e.serial,n)}catch(c){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView (${c.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}await adb(e.serial,["install","-r","-d",t],18e4);await adbShell(e.serial,`pm clear ${q(n)}`);let s="";if(a.length){await hostLaunch(e);try{await androidWriteWebKeep(e.serial,n,a);s=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){s=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${s}`}if(o.length){try{for(const c of o){const u=import_node_path7.default.posix.dirname(c.rel);await adbShell(e.serial,`echo ${q(c.data)} | run-as ${q(n)} sh -c ${q(`mkdir -p ${q(u)} && base64 -d > ${q(c.rel)}`)}`)}s=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){s=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}}else if(r){s=" No Buoy sign-in could be read to keep (needs a debug build): sign in to Buoy again in the app."}await hostLaunch(e);return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${s}`}async function reinstallPhone(e,n,t,r){if(!/\.app\/?$/i.test(t))throw new Error("On an iPhone, appPath must be a built .app folder (a device build). Nothing was changed.");const i=await appBundleInfo(t);if(i.bundleId!==n)throw new Error(`${import_node_path7.default.basename(t)} is ${i.bundleId}, but this app is ${n}. Nothing was changed.`);if(i.simulator)throw new Error(`${import_node_path7.default.basename(t)} is a simulator build, not a device build. Nothing was changed.`);const o=["Documents/buoy-license/buoy-gg-license.json","Documents/react-buoy/@react_buoy_sync_device_id.json","Documents/react-buoy/@react_buoy_install.json"];const a=r?await import_node_fs6.promises.mkdtemp(import_node_path7.default.join(import_node_os6.default.tmpdir(),"buoy-mcp-keep-")):null;try{const s=[];if(a){await import_node_fs6.promises.chmod(a,448);for(const u of o){let l;try{l=await readAppFile(e.udid,n,u)}catch(h){throw new Error(`Could not back up Buoy's ${import_node_path7.default.basename(u)} from the iPhone (${h.message}). Nothing was changed.`)}if(!l)continue;const d=import_node_path7.default.join(a,u.replace(/\//g,"__"));await import_node_fs6.promises.writeFile(d,l,{mode:384});s.push({rel:u,local:d})}}await phoneQuit(e.udid,n).catch(()=>false);await phoneUninstall(e.udid,n);try{await phoneInstall(e.udid,t)}catch(u){throw new Error(`The app was removed, but installing ${import_node_path7.default.basename(t)} failed: ${u.message}. Install it again from Xcode.`)}let c="";if(s.length){try{for(const d of s)await writeAppFile(e.udid,n,d.local,d.rel);const u=s.some(d=>d.rel.includes("buoy-license"));const l=s.some(d=>d.rel.includes("sync_device_id"));c=u?` Kept Buoy's sign-in${l?" and device id, so the same deviceId still works":""}.`:` Kept the device id; there was no Buoy sign-in to keep, so sign in to Buoy in the app.`}catch(u){c=` Buoy's sign-in could not be restored (${u.message}): sign in to Buoy again in the app.`}}else if(r)c=" The old install had no Buoy sign-in to keep.";await phoneLaunch(e.udid,n);return`Reinstalled ${n} on the iPhone and launched it. The app's own data is gone, like a new user.${c}`}finally{if(a)await import_node_fs6.promises.rm(a,{recursive:true,force:true}).catch(()=>void 0)}}async function bootSimulator(e){const n=JSON.parse(await simctl(["list","devices","available","-j"])).devices;const t=Object.entries(n).filter(([s])=>/iOS/.test(s)).flatMap(([,s])=>s);const r=e.trim().toLowerCase();const i=t.filter(s=>s.udid.toLowerCase()===r||s.name.toLowerCase()===r);const o=i.length?i:t.filter(s=>s.name.toLowerCase().includes(r));if(o.length===0)throw new Error(`No iOS Simulator matches "${e}". Run \`xcrun simctl list devices available\` to see them.`);if(o.length>1)throw new Error(`${o.length} simulators match "${e}": ${o.map(s=>`${s.name} (${s.udid})`).join(", ")}. Pass the udid.`);const a=o[0];if(a.state!=="Booted")await simctl(["boot",a.udid],12e4);await sh("open",["-a","Simulator","--args","-CurrentDeviceUDID",a.udid]).catch(()=>void 0);return a.state==="Booted"?`${a.name} (${a.udid}) was already booted.`:`Booted ${a.name} (${a.udid}).`}var execFileAsync7=(0,import_node_util7.promisify)(import_node_child_process7.execFile);async function hostTarget(e,n,t={},r={}){if(n==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');let i;let o=true;try{i=e.requireProDevice(n)}catch(c){const u=c instanceof Error?c.message:String(c);const l=u.startsWith(NOT_READY_MARK)&&/is not connected right now/.test(u)?/"([^"]+)"/.exec(u)?.[1]:void 0;const d=l?e.listDevices().some(h=>h.deviceId===l&&h.isPro):false;if(!r.allowOffline||!l||!d)throw c;i=l;o=false}const a=e.listDevices().find(c=>c.deviceId===i)?.platform;let s=await findHost(i,a,t);if(r.changesApp&&rememberedHost(i)===s)s=await verifyHost(i,s);return{id:i,host:s,online:o}}function hostLabel(e){if(e.platform==="ios")return`simulator "${e.name}"`;if(e.platform==="ios-device")return`iPhone "${e.name}"`;return`Android device ${e.serial}`}var onPath=new Map;function has(e){if(!onPath.has(e))onPath.set(e,execFileAsync7("which",[e],{timeout:3e3}).then(()=>true,()=>false));return onPath.get(e)}async function hostSummary(e,n){let t=n;if(e.platform==="android"){const i=rememberedHost(e.deviceId);const o=i??(e.isConnected?await Promise.race([findHost(e.deviceId,"android").catch(()=>void 0),new Promise(s=>setTimeout(()=>s(void 0),3e3))]):void 0);const a=await has("adb");return{kind:"android",...o&&o.platform==="android"?{id:o.serial,name:o.packageName}:{},can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall","real lifecycle events","native_tap/type/swipe"],...!a?{missing:["adb (Android SDK platform-tools)"]}:!o?{missing:["proof of which phone runs it (needs a debug build reachable by adb)"]}:{}}}if(e.platform!=="ios")return{kind:e.platform??"unknown",can:[],missing:["host control works on iOS and Android apps"]};let r=rememberedHost(e.deviceId);if(!r&&!t&&e.isConnected){r=await Promise.race([findHost(e.deviceId,"ios").catch(()=>void 0),new Promise(i=>setTimeout(()=>i(void 0),4e3))])}if(!t&&r?.platform==="ios")t={name:r.name,udid:r.udid};if(r?.platform==="ios-device"){return{kind:"physical iPhone",id:r.udid,name:r.name,can:["screenshot","screen_recording (if this iPhone supports it)","baseline diffs","quit/launch/reinstall","open_url","native_tap/type/swipe (by query, testID, nativeTag or x/y; not label)"]}}if(t){const i=await has("idb");return{kind:"ios simulator",id:t.udid,name:t.name,can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall/boot","real lifecycle events",...i?["native_tap/type/swipe"]:[]],...i?{}:{missing:["idb for real touches (brew install facebook/fb/idb-companion && pipx install fb-idb)"]}}}return void 0}function json(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function fail(e){return{isError:true,content:[{type:"text",text:e}]}}function registerGenericTools(e,n){e.registerTool("list_devices",{description:"List the apps connected to Buoy: id, name, platform, whether it is connected and has MCP access, the simulator or phone it runs on with the host controls that work there (screenshot, recording, app control, real touches) and anything missing, and the Buoy tools it exposes. Start here. Pass details:true for every tool's action names.",inputSchema:{details:import_zod.z.boolean().optional().describe("Also list every action of every tool. Default false (tool names only); list_tool_actions gives one tool's actions."),includeDisconnected:import_zod.z.boolean().optional().describe("Also list apps that were seen before but are not connected now. Default false.")}},async(t={})=>{const r=await getUpdateNotice();let i=n.listDevices();for(let p=0;i.length===0&&p<10;p++){await new Promise(m=>setTimeout(m,200));i=n.listDevices()}if(i.length===0){return json({devices:[],hint:"No devices connected. Open the app with Buoy devtools running, then retry.",...r?{updateAvailable:r}:{}})}const o=t.includeDisconnected?0:i.filter(p=>!p.isConnected).length;if(!t.includeDisconnected)i=i.filter(p=>p.isConnected);if(i.length===0){return json({devices:[],hint:`No app is connected right now${o?` (${o} seen before; pass includeDisconnected:true to list them)`:""}. Open the app with Buoy devtools running, then retry.`,...r?{updateAvailable:r}:{}})}const a=await resolveSims(i.filter(p=>p.platform==="ios").map(p=>p.deviceId)).catch(()=>new Map);const s=i.filter(p=>p.isConnected);const c=s.some(p=>p.isPro);const u=s.some(p=>p.tier!=="locked");const l=s.filter(p=>p.collision);const d=await Promise.all(i.map(p=>p.isConnected?hostSummary(p,a.get(p.deviceId)).catch(()=>void 0):void 0));const h=i.map((p,m)=>{const w=a.get(p.deviceId);const g=d[m];return{deviceId:p.deviceId,deviceName:p.deviceName,platform:p.platform,isConnected:p.isConnected,isPro:p.isPro,tier:p.tier,access:n.accessState(p.deviceId),...w?{simulator:w}:{},...g?{host:g}:{},...p.collision?{collision:true}:{},tools:t.details?p.tools:p.tools.map(f=>f.toolId)}});return json({devices:h,...t.details?{}:{note:`Tool names only. Pass details:true, or list_tool_actions({toolId}), for action names.${o?` ${o} apps seen before but not connected now are left out (includeDisconnected:true lists them).`:""}`},...l.length>0?{warning:`${l.map(p=>`"${p.deviceId}"`).join(", ")}: more than one app is registered under this id, so actions sent to it land on an arbitrary device. Give each device its own externalSync.deviceId (or leave it unset for a per-install default) before mutating anything.`}:{},...c?{}:{hint:u?"The Buoy MCP is a Pro feature \u2014 the connected device is signed in on the free tier, so data/action tools are blocked. Upgrade to Buoy Pro in the app, or pass `licenseKey` to `<FloatingDevTools />` if it runs headless.":"The broker has not confirmed account access for the connected devices, so data/action tools are blocked. A locked status can mean missing configuration, pending/failed validation, or a missing account announcement after reconnect; it does not prove the user is signed out. Check app account status and broker compatibility."},...r?{updateAvailable:r}:{}})});e.registerTool("list_tool_actions",{description:"List the actions a tool exposes, and which connected devices offer it. Leave toolId out to list every tool's actions. Use the action names with call_action.",inputSchema:{toolId:import_zod.z.string().optional().describe('The tool id, e.g. "perf-monitor", "network", "react-query". Leave out for every tool.'),tool:import_zod.z.string().optional().describe("Same as toolId."),deviceId:import_zod.z.string().optional().describe("Only list what this device offers.")}},async({toolId:t,tool:r,deviceId:i})=>{const o=t??r;if(!o){const c=n.connectedDevices().filter(l=>!i||l.deviceId===i);if(c.length===0)return fail(i?`No connected device "${i}". Call list_devices.`:"No devices are connected. Call list_devices.");const u=c.map(l=>[`**${l.deviceName}** (${l.deviceId})`,...l.tools.map(d=>`- ${d.toolId}: ${d.actions.join(", ")}`)].join("\n"));return{content:[{type:"text",text:`${u.join("\n\n")}
2
+ `));this.autoSpawn=e.autoSpawnBroker??true}async start(){const e=await probeBroker(this.url)||await probeBroker(this.url,8e3);let n="connected";if(!e){if(!this.autoSpawn){throw new Error(`No Buoy broker reachable at ${this.url} and autoSpawnBroker is off. Start the Buoy desktop app, or enable autoSpawnBroker.`)}this.log(`no broker at ${this.url} \u2014 spawning one in-process on :${this.port}`);this.hostAccount=new NodeAccount(()=>this.broker?.refreshAccess());this.hostAccount.start();let t=false;this.broker=(0,import_sync_broker2.createBroker)({canUseDesktop:this.hostAccount.hasAccess,port:this.port,onError:r=>{if(r.code==="EADDRINUSE")t=true;this.log(`broker error: ${r.code??r.message}`)}});await waitForBroker(this.url).catch(r=>{if(!t)throw r});if(!this.broker.httpServer.listening)t=true;if(t){this.log(`another broker holds :${this.port} \u2014 connecting to it as a dashboard`);await this.broker.close().catch(()=>void 0);this.broker=null;this.hostAccount.stop();this.hostAccount=null;await this.connectSocket();return"connected"}try{(0,import_sync_broker2.writeBrokerToken)(this.broker.dashboardToken,(0,import_sync_broker2.brokerTokenPath)(this.port))}catch(r){this.log(`could not write the broker token file: ${r.message}`)}n="spawned"}else{this.log(`found a running broker at ${this.url} \u2014 connecting as a dashboard`)}await this.connectSocket();return n}connectSocket(){return new Promise((e,n)=>{const t=(0,import_socket.io)(this.url,{transports:["websocket"],query:{deviceName:DASHBOARD_NAME},auth:s=>{const c=this.broker?.dashboardToken??(0,import_sync_broker2.readBrokerToken)((0,import_sync_broker2.brokerTokenPath)(this.port));s(c?{dashboardToken:c}:{})},reconnection:true,reconnectionDelay:500,timeout:4e3});this.socket=t;let r=false;const i=()=>{if(r)return;r=true;this.log("connected to broker");e()};const o=setTimeout(()=>{if(r)return;r=true;n(new Error("Broker account is locked or the broker needs an update. Sign in to Buoy Desktop or run npx buoy login for standalone MCP."))},5e3);t.on("buoy:access",s=>{const c=!!s&&typeof s==="object"&&s.protocol===1&&s.ready===true;this.setAdmission(c);if(c){clearTimeout(o);this.rearmWatches();i()}});t.on("connect",()=>{t.emit("buoy:access:request")});t.on("disconnect",()=>this.setAdmission(false,true));const a=s=>s.message===import_sync_broker2.DASHBOARD_TOKEN_REQUIRED;t.once("connect_error",s=>{if(r)return;r=true;clearTimeout(o);n(new Error(a(s)?`The broker at ${this.url} refused this MCP as a dashboard: the token in ${(0,import_sync_broker2.brokerTokenPath)(this.port)} is missing or stale. Update Buoy Desktop, or restart it so it writes the file.`:`failed to connect to broker at ${this.url}: ${s.message}`))});t.on("connect_error",s=>{if(!a(s)||t.active)return;setTimeout(()=>{if(this.socket===t&&!t.connected)t.connect()},1e3).unref?.()});t.on("devtool-capabilities",s=>{if(!this.admitted||this.lockedDevices.has(s.persistentDeviceId))return;this.capabilities.set(s.persistentDeviceId,s);this.trackRootLookup(this.learnDevServerOrigin(s.persistentDeviceId));if(s.tools?.some(c=>c.toolId==="console"))this.ensureWatching("console",s.persistentDeviceId)});t.on("all-devices-update",s=>{if(!this.admitted)return;if(!Array.isArray(s))return;let c=false;for(const l of s){if(l.deviceId&&l.tier==="locked")this.lockDevice(String(l.deviceId));else if(l.deviceId&&(l.tier==="free"||l.tier==="pro")){c=this.lockedDevices.delete(String(l.deviceId))||c}}this.devices=s;const u=Date.now();for(const l of s)if(l.deviceId)this.lastSeen.set(l.deviceId,u);this.pruneStaleDevices();if(c)this.rearmWatches();else this.rearmReconnectedDevices(s)});t.on("devtool-sync",s=>{if(!this.admitted||this.lockedDevices.has(s.persistentDeviceId))return;const c=snapKey(s.persistentDeviceId,s.toolId);this.snapshots.set(c,s.payload);this.snapshotAt.set(c,Date.now());if(s.toolId==="console")this.noteCrashReport(s.persistentDeviceId,s.payload);const u=this.snapshotWaiters.get(c);if(u&&u.length){this.snapshotWaiters.set(c,[]);for(const l of u)l(s.payload)}});t.on("devtool-action-result",s=>{if(!this.admitted)return;const c=this.pendingActions.get(s.requestId);if(!c)return;this.pendingActions.delete(s.requestId);clearTimeout(c.timer);c.resolve(s)})})}requireAdmission(){if(!this.admitted)throw new Error("A verified Buoy account and an updated broker are required. Sign in to Buoy Desktop, or run npx buoy login for standalone MCP.")}setAdmission(e,n=false){this.admitted=e;if(e)return;this.devices=[];this.lockedDevices.clear();this.capabilities.clear();this.snapshots.clear();this.snapshotAt.clear();this.devServerOrigins.clear();this.devServerRoots.clear();this.crashSeen.clear();this.originProbed.clear();this.health.clear();this.lastSeen.clear();if(!n)this.watching.clear();for(const t of this.pendingActions.values()){clearTimeout(t.timer);t.reject(new Error("Buoy account access ended while the action was pending."))}this.pendingActions.clear();for(const t of this.snapshotWaiters.values())for(const r of t)r(void 0);this.snapshotWaiters.clear();if(this.socket)this.socket.sendBuffer=[]}requireDeviceAccount(e){if(this.lockedDevices.has(e))throw new Error("The device's Buoy account access ended. Sign in and verify its key.")}lockDevice(e){this.lockedDevices.add(e);this.capabilities.delete(e);this.health.delete(e);this.devServerOrigins.delete(e);this.devServerRoots.delete(e);this.originProbed.delete(e);const n=`${e}::`;for(const t of this.snapshots.keys())if(t.startsWith(n)){this.snapshots.delete(t);this.snapshotAt.delete(t)}for(const[t,r]of this.snapshotWaiters)if(t.startsWith(n)){this.snapshotWaiters.delete(t);for(const i of r)i(void 0)}for(const[t,r]of this.pendingActions)if(r.target===e||r.target===ALL_DEVICES){clearTimeout(r.timer);this.pendingActions.delete(t);r.reject(new Error("Device account access ended while the action was pending."))}}pruneStaleDevices(){const e=Date.now()-DEVICE_RETENTION_MS;for(const[n,t]of this.lastSeen){if(t>e)continue;if(this.devices.some(i=>i.deviceId===n))continue;this.lastSeen.delete(n);this.capabilities.delete(n);this.health.delete(n);this.devServerOrigins.delete(n);this.devServerRoots.delete(n);this.originProbed.delete(n);const r=`${n}::`;for(const i of[...this.snapshots.keys()]){if(i.startsWith(r)){this.snapshots.delete(i);this.snapshotAt.delete(i)}}for(const i of[...this.watching.keys()]){if(i.startsWith(r))this.watching.delete(i)}}}async stop(){this.setAdmission(false);this.hostAccount?.stop();this.hostAccount=null;for(const[,e]of this.pendingActions){clearTimeout(e.timer);e.reject(new Error("SyncClient stopped"))}this.pendingActions.clear();for(const[,e]of this.snapshotWaiters)for(const n of e)n(void 0);this.snapshotWaiters.clear();this.socket?.close();this.socket=null;if(this.broker){await this.broker.close();this.broker=null}}listDevices(){if(!this.admitted)return[];return this.devices.filter(e=>e.deviceName!==DASHBOARD_NAME&&e.deviceId).map(e=>{const n=this.capabilities.get(e.deviceId);return{deviceId:e.deviceId,deviceName:e.deviceName,platform:e.platform,isConnected:e.isConnected!==false,isPro:e.isPro===true,tier:e.tier==="free"||e.tier==="pro"?e.tier:e.tier===void 0&&e.isPro===true?"pro":"locked",collision:e.collision===true,tools:n?.tools??[]}})}connectedDevices(){return this.listDevices().filter(e=>e.isConnected)}toolActions(e){return this.listDevices().map(n=>{const t=n.tools.find(r=>r.toolId===e);return t?{deviceId:n.deviceId,deviceName:n.deviceName,actions:t.actions}:null}).filter(n=>n!==null)}resolveDevice(e){this.requireAdmission();if(e){this.requireDeviceAccount(e);return e}const n=(u,l)=>new Error(`${NOT_READY_MARK} "${u}" (${l}) is not connected right now. If it is restarting, it usually takes a few seconds; to use another device, pass deviceId (run list_devices to see them).`);if(this.sessionDevice){const u=this.devices.find(l=>l.deviceId===this.sessionDevice);if(u&&u.isConnected!==false)return this.sessionDevice;throw n(this.sessionDevice,"the device this session was using")}const t=this.connectedDevices();const r=t.filter(u=>!this.lockedDevices.has(u.deviceId));const i=r.filter(u=>u.tools.length>0);const o=process.env.BUOY_PROJECT_ROOT||process.cwd();const a=pickByProject(i.map(u=>({deviceId:u.deviceId,root:this.devServerRoots.get(u.deviceId)})),o);if(a)return this.sessionDevice=a;const s=pickByProject(this.devices.filter(u=>u.deviceId&&u.isConnected===false&&!this.lockedDevices.has(u.deviceId)).map(u=>({deviceId:u.deviceId,root:this.devServerRoots.get(u.deviceId)})),o);if(s)throw n(s,"this project's app");if(r.length===0){if(t.length>0){throw new Error(`Devices are connected (${t.map(u=>u.deviceName).join(", ")}), but the broker has not admitted their accounts. Check app account validation and the account announcement after reconnect; this does not prove the user is signed out.`)}throw new Error("No devices are connected to the broker. Open the app with Buoy devtools running.")}if(r.length===1)return this.sessionDevice=r[0].deviceId;if(i.length===1)return this.sessionDevice=i[0].deviceId;if(i.length===0){const u=r.map(l=>l.deviceName).join(", ");throw new Error(`Connected devices (${u}) are not exposing any Buoy tools yet. Make sure the app is in the foreground with devtools mounted, then retry.`)}const c=i.map(u=>`${u.deviceName} (${u.deviceId})`).join(", ");throw new Error(`Multiple devices connected \u2014 specify deviceId. Connected: ${c}`)}requireProDevice(e){this.requireAdmission();if(e&&e!==ALL_DEVICES)this.sessionDevice=e;const n=o=>{if(!o)return"";return o.tier==="locked"?` The broker has not confirmed account access for "${o.deviceName}"; a locked status does not establish whether a key is configured.`:` The connected app "${o.deviceName}" is on the ${o.tier} tier.`};const t=o=>`Buoy Pro is required to use the MCP.${n(o)} Enter a license in the app, or \u2014 if it runs headless (no on-device UI) \u2014 pass \`licenseKey\` to \`<FloatingDevTools />\`. Run \`list_devices\` to check status.`;if(e===ALL_DEVICES){if(!this.connectedDevices().some(o=>o.isPro))throw new Error(t());return ALL_DEVICES}const r=this.resolveDevice(e);const i=this.connectedDevices().find(o=>o.deviceId===r);if(!i?.isPro){const o=this.accessState(r);if(o==="offline")throw new Error(`${NOT_READY_MARK} "${r}" is not connected right now. If the app is starting or reloading, it usually takes a few seconds. Run list_devices to check.`);if(o==="pending")throw new Error(`${NOT_READY_MARK} account access for "${r}" is still being confirmed (the app just connected). Try again in a moment.`);throw new Error(t(i))}return r}accessState(e){const n=this.devices.find(t=>t.deviceId===e);if(!n||n.isConnected===false)return"offline";if(n.isPro===true)return"ready";return n.tier===void 0?"pending":"denied"}healthOf(e){let n=this.health.get(e);if(!n){n={consecutiveTimeouts:0,lastOkAt:0,lastFullBudgetAt:0};this.health.set(e,n)}return n}noteOk(e){const n=this.healthOf(e);n.consecutiveTimeouts=0;n.lastOkAt=Date.now()}noteTimeout(e){this.healthOf(e).consecutiveTimeouts+=1}isUnresponsive(e){return isUnresponsive(this.healthOf(e).consecutiveTimeouts)}timeoutFor(e,n,t){const r=this.healthOf(e);const{timeoutMs:i,usedFullBudget:o}=actionTimeoutMs({consecutiveTimeouts:r.consecutiveTimeouts,lastFullBudgetAt:r.lastFullBudgetAt,now:Date.now(),fullMs:this.actionTimeoutMs,shortMs:UNRESPONSIVE_ACTION_TIMEOUT_MS,recoveryProbeMs:RECOVERY_PROBE_MS,toolId:n,action:t});if(o)r.lastFullBudgetAt=Date.now();return i}unresponsiveNote(e){const n=this.healthOf(e);const t=n.lastOkAt?Math.round((Date.now()-n.lastOkAt)/1e3):null;const r=diagnoseCrashed({consecutiveTimeouts:n.consecutiveTimeouts,lastOkAt:n.lastOkAt,now:Date.now(),unresponsiveAfterMs:UNRESPONSIVE_AFTER_MS});const i=[`The app on "${e}" is not responding (${n.consecutiveTimeouts} call${n.consecutiveTimeouts===1?"":"s"} unanswered${t!=null?`, last answered ${t}s ago`:""}).`,r?"It is most likely CRASHED \u2014 a fatal render error unmounts the React tree, and the dev tools live in that tree, so nothing on-device can answer until the app is reloaded.":"It may be busy, mid-reload, or crashing."];const o=this.lastFatalFor(e);if(o)i.push(`Last captured error: ${o}`);i.push(o?"Read the crash state with get_console / get_storage (served from the last sync), then reload_app to recover.":"Try get_console (served from the last sync) for the app's last words, then reload_app to recover.");return i.join(" ")}noteCrashReport(e,n){const t=n?.entries;if(!Array.isArray(t)||t.length===0)return;const r=Math.max(...t.map(a=>typeof a?.timestamp==="number"?a.timestamp:-Infinity));const i=this.crashSeen.get(e)??new Set;let o=false;for(const a of t){const s=a?.fatal||/^\[(RENDER ERROR|FATAL)/.test(a?.message??"");if(!s||typeof a.timestamp!=="number")continue;const c=`${a.id??""}|${a.timestamp}|${(a.message??"").slice(0,120)}`;if(i.has(c))continue;i.add(c);if(r-a.timestamp<3e4)o=true}if(i.size>200)for(const a of[...i].slice(0,i.size-200))i.delete(a);this.crashSeen.set(e,i);if(!o)return;if(![...this.pendingActions.values()].some(a=>a.target===e&&a.expire&&!a.cut))return;void this.callAction("app","ping",{},e,{timeoutMs:1500,silent:true}).then(()=>void 0,()=>{const a=Date.now();for(const s of this.pendingActions.values()){if(s.target!==e||!s.expire||s.cut)continue;s.cut=true;if(s.deadline!==void 0&&s.deadline-a<=UNRESPONSIVE_ACTION_TIMEOUT_MS)continue;clearTimeout(s.timer);s.timer=setTimeout(s.expire,UNRESPONSIVE_ACTION_TIMEOUT_MS)}})}lastFatalFor(e){const n=this.snapshots.get(snapKey(e,"console"));const t=n?.entries;if(!Array.isArray(t))return null;for(let r=t.length-1;r>=0;r--){const i=t[r];if(i?.fatal||i?.level==="error"){const o=(i.message??"").split("\n")[0];if(o)return o.length>300?`${o.slice(0,300)}\u2026`:o}}return null}snapshotAgeMs(e,n){this.requireAdmission();const t=this.snapshotAt.get(snapKey(n,e));return t?Date.now()-t:null}noteDevServerOrigin(e,n){if(typeof n==="string"&&/^https?:\/\//.test(n)){const t=this.devServerOrigins.get(e)!==n;this.devServerOrigins.set(e,n);if(t)this.devServerRoots.delete(e);if(t||!this.devServerRoots.has(e)){const r=devServerRoot(n).then(i=>{if(i&&this.devServerOrigins.get(e)===n)this.devServerRoots.set(e,i)});this.trackRootLookup(r)}}}async learnDevServerOrigin(e){if(this.devServerOrigins.has(e)||this.originProbed.has(e))return;this.originProbed.add(e);const n=this.capabilities.get(e)?.tools?.some(t=>t.toolId==="app");if(!n)return;try{const{payload:t}=await this.getSnapshot("app",e,{timeoutMs:4e3,silent:true});this.noteDevServerOrigin(e,t?.devServerOrigin)}catch{}}trackRootLookup(e){const n=e.catch(()=>void 0).finally(()=>this.rootLookups.delete(n));this.rootLookups.add(n)}async awaitBroker(){if(Date.now()-this.createdAt>15e3)return;for(let e=0;!this.admitted&&e<4e3;e+=100)await new Promise(n=>setTimeout(n,100));for(let e=0;this.admitted&&this.devices.length===0&&e<1500;e+=100)await new Promise(n=>setTimeout(n,100))}async settleDeviceChoice(e=1500){await this.awaitBroker();if(this.sessionDevice||this.rootLookups.size===0||this.connectedDevices().length<2)return;await Promise.race([Promise.all([...this.rootLookups]),new Promise(n=>setTimeout(n,e))]);if(this.rootLookups.size)await Promise.race([Promise.all([...this.rootLookups]),new Promise(n=>setTimeout(n,Math.min(800,e)))])}devServerOrigin(e){this.requireAdmission();const n=this.devServerOrigins.get(e);if(n)return n;const t=this.snapshots.get(snapKey(e,"app"));if(typeof t?.devServerOrigin==="string")return t.devServerOrigin;return null}ensureWatching(e,n){const t=snapKey(n,e);if(this.watching.has(t))return;this.watching.set(t,{toolId:e,targetDeviceId:n});this.sendWatch(e,n)}sendWatch(e,n){if(!this.admitted||!this.socket?.connected||this.lockedDevices.has(n))return;this.socket?.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:true,stream:false})}rearmWatches(){for(const{toolId:e,targetDeviceId:n}of this.watching.values()){this.sendWatch(e,n)}}rearmReconnectedDevices(e){for(const n of e){if(!n.deviceId||n.isConnected===false)continue;const t=String(n.deviceId);const r=`${n.id}|${n.connectionNonce??""}`;const i=this.deviceConnections.get(t);this.deviceConnections.set(t,r);if(i===void 0||i===r)continue;for(const{toolId:o,targetDeviceId:a}of this.watching.values()){if(a===t)this.sendWatch(o,a)}}}unwatch(e,n){const t=snapKey(n,e);if(!this.watching.delete(t))return;if(this.admitted&&this.socket?.connected)this.socket.emit("devtool-watch",{toolId:e,targetDeviceId:n,watching:false})}cachedSnapshot(e,n){this.requireAdmission();this.requireDeviceAccount(n);return this.snapshots.get(snapKey(n,e))}async getSnapshot(e,n,t={}){const r=this.resolveDevice(n);const i=snapKey(r,e);this.ensureWatching(e,r);let o=t.timeoutMs??DEFAULT_SNAPSHOT_TIMEOUT_MS;if(t.timeoutMs===void 0&&this.isUnresponsive(r)){const u=this.healthOf(r);if(Date.now()-u.lastFullBudgetAt>RECOVERY_PROBE_MS){u.lastFullBudgetAt=Date.now()}else{o=UNRESPONSIVE_SNAPSHOT_TIMEOUT_MS}}const a=this.waitForSnapshot(i,o);this.socket?.emit("request-devtool-state",{toolId:e,targetDeviceId:r});const s=await a;this.requireAdmission();this.requireDeviceAccount(r);if(s!==void 0){if(!t.silent)this.noteOk(r);return{deviceId:r,payload:s}}if(!t.silent)this.noteTimeout(r);const c=this.snapshots.get(i);if(c!==void 0){return{deviceId:r,payload:c,stale:this.staleNote(e,r)}}throw new Error(`Timed out waiting for "${e}" state from ${r} (is the tool active?). ${this.unresponsiveNote(r)}`)}lastSync(e,n){const t=this.snapshots.get(snapKey(e,n));return t===void 0?void 0:{payload:t,ageMs:this.snapshotAgeMs(n,e)}}staleNote(e,n){const t=this.snapshotAgeMs(e,n);const r=t==null?"an earlier sync":`${Math.round(t/1e3)}s ago`;return`\u26A0\uFE0F Served from the last sync (${r}) \u2014 ${this.unresponsiveNote(n)}`}waitForSnapshot(e,n){return new Promise(t=>{const r=this.snapshotWaiters.get(e)??[];const i=setTimeout(()=>{const a=(this.snapshotWaiters.get(e)??[]).filter(s=>s!==o);this.snapshotWaiters.set(e,a);t(void 0)},n);const o=a=>{clearTimeout(i);t(a)};r.push(o);this.snapshotWaiters.set(e,r)})}async callAction(e,n,t,r,i={}){this.requireAdmission();const o=r===ALL_DEVICES?ALL_DEVICES:this.resolveDevice(r);if(!this.socket)throw new Error("SyncClient is not connected");const a=(0,import_node_crypto2.randomUUID)();const s=i.timeoutMs??this.timeoutFor(o,e,n);const c=await new Promise((u,l)=>{const d=Date.now();const h=()=>{this.pendingActions.delete(a);if(o!==ALL_DEVICES&&!i.silent)this.noteTimeout(o);l(new Error(`Action "${e}.${n}" got no answer in ${Date.now()-d}ms. `+(o===ALL_DEVICES?"No device responded.":this.unresponsiveNote(o))))};const p=setTimeout(h,s);this.pendingActions.set(a,{resolve:u,reject:l,timer:p,target:o,expire:h,deadline:d+s});this.socket.emit("devtool-action",{requestId:a,toolId:e,targetDeviceId:o,action:n,params:t??{}})});if(o!==ALL_DEVICES&&!i.silent)this.noteOk(o);if(!c.ok){throw new Error(c.error||`Action "${e}.${n}" failed on device`)}return c.result}};var snapKey=(e,n)=>`${e}::${n}`;function probeBroker(e,n=800){return new Promise(t=>{const r=import_node_http.default.get(e,i=>{i.resume();t((i.statusCode??0)>0)});r.setTimeout(n,()=>{r.destroy();t(false)});r.on("error",()=>t(false))})}async function waitForBroker(e,n=20){for(let t=0;t<n;t++){if(await probeBroker(e,300))return;await delay(50)}throw new Error(`Spawned broker never became reachable at ${e}`)}var delay=e=>new Promise(n=>setTimeout(n,e));var import_mcp=require("@modelcontextprotocol/sdk/server/mcp.js");var import_zod35=require("zod");var import_zod=require("zod");var import_node_fs2=require("fs");var import_node_os3=__toESM(require("os"));var import_node_path3=__toESM(require("path"));var VERSION="7.0.61"?"7.0.61":"0.0.0-dev";var PACKAGE_NAME="@buoy-gg/mcp";var CHECK_TTL_MS=24*60*60*1e3;var FETCH_TIMEOUT_MS=1500;var REGISTRY_URL=`https://registry.npmjs.org/${PACKAGE_NAME}/latest`;var CACHE_FILE=import_node_path3.default.join(import_node_os3.default.tmpdir(),"buoy-mcp-update-check.json");function isNewer(e,n){const t=o=>o.split("-")[0].split(".").map(a=>Number(a)||0);const r=t(e);const i=t(n);for(let o=0;o<3;o++){const a=r[o]??0;const s=i[o]??0;if(a>s)return true;if(a<s)return false}return false}async function readCache(){try{const e=await import_node_fs2.promises.readFile(CACHE_FILE,"utf8");const n=JSON.parse(e);if(typeof n.checkedAt==="number"&&typeof n.latest==="string"){return n}}catch{}return null}async function fetchLatest(e){const n=new AbortController;const t=setTimeout(()=>n.abort(),FETCH_TIMEOUT_MS);try{const r=await fetch(REGISTRY_URL,{signal:n.signal});if(!r.ok)return null;const i=await r.json();const o=typeof i.version==="string"?i.version:null;if(o){await import_node_fs2.promises.writeFile(CACHE_FILE,JSON.stringify({checkedAt:e,latest:o})).catch(()=>{})}return o}catch{return null}finally{clearTimeout(t)}}async function resolveLatest(e){const n=await readCache();if(n&&e-n.checkedAt<CHECK_TTL_MS)return n.latest;return fetchLatest(e)}async function getUpdateNotice(e=Date.now()){if(VERSION==="0.0.0-dev")return null;try{const n=await resolveLatest(e);if(n&&isNewer(n,VERSION)){return`A newer buoy-mcp is available (${n}; you're on ${VERSION}). Update by re-running: npx -y ${PACKAGE_NAME}@latest init \u2014 then restart your editor.`}}catch{}return null}var import_node_child_process2=require("child_process");var import_node_util2=require("util");var import_node_fs3=require("fs");var import_node_os4=__toESM(require("os"));var import_node_path4=__toESM(require("path"));var import_node_crypto3=require("crypto");var execFileAsync2=(0,import_node_util2.promisify)(import_node_child_process2.execFile);var clamp=(e,n,t)=>Math.min(Math.max(e,n),t);function humanizeSimctlError(e){const n=e;if(n?.code==="ENOENT"){return"Xcode command-line tools (xcrun) not found. Install Xcode to capture the iOS Simulator."}const t=String(n?.stderr||n?.message||e);if(/No devices are booted|Unable to find device|current device/i.test(t)){return"No booted iOS Simulator found. Boot the Simulator with your app running, then try again."}return t.trim()||"Failed to capture the iOS Simulator."}function pngSize(e){const n=[137,80,78,71,13,10,26,10];if(e.length<24||!n.every((t,r)=>e[r]===t))return null;return{width:e.readUInt32BE(16),height:e.readUInt32BE(20)}}var WEBVIEW_ID_KEY="@react_buoy_sync_device_id";async function listDir(e){try{return await import_node_fs3.promises.readdir(e)}catch{return[]}}async function webViewInstallIds(e){const n=[];for(const t of await listDir(e))n.push(...await containerWebViewInstallIds(import_node_path4.default.join(e,t)));return n}async function containerWebViewInstallIds(e){const n=[];const t=import_node_path4.default.join(e,"Library","WebKit");for(const r of await listDir(t)){const i=import_node_path4.default.join(t,r,"WebsiteData","Default");for(const o of await listDir(i)){for(const a of await listDir(import_node_path4.default.join(i,o))){const s=import_node_path4.default.join(i,o,a,"LocalStorage","localstorage.sqlite3");try{await import_node_fs3.promises.access(s);const{stdout:c}=await execFileAsync2("sqlite3",["-readonly",s,`SELECT hex(value) FROM ItemTable WHERE key='${WEBVIEW_ID_KEY}' LIMIT 1;`],{timeout:1500});const u=c.trim();if(u)n.push(Buffer.from(u,"hex").toString("utf16le").trim())}catch{}}}}return n}var webViewLookups=new Map;var WEBVIEW_MISS_MS=3e4;async function resolveSimUdid(e){if(process.platform!=="darwin")return{ok:false,error:"Simulator lookup needs macOS."};let n=[];try{const{stdout:r}=await execFileAsync2("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const i=JSON.parse(r).devices;n=Object.entries(i).filter(([o])=>/iOS/.test(o)).flatMap(([,o])=>o.filter(a=>a.state==="Booted"))}catch(r){return{ok:false,error:humanizeSimctlError(r)}}if(n.length===0)return{ok:false,error:"No iOS Simulator is booted."};const t=e?.split("-").pop();if(t){for(const r of n){if(!r.dataPath)continue;const i=import_node_path4.default.join(r.dataPath,"Containers","Data","Application");let o=[];try{o=await import_node_fs3.promises.readdir(i)}catch{continue}for(const a of o){try{const s=(await import_node_fs3.promises.readFile(import_node_path4.default.join(i,a,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(s===t)return{ok:true,udid:r.udid,how:`matched ${e} to "${r.name}"`}}catch{}}}}if(t&&e){const r=n.map(c=>c.udid).sort().join(",");const i=webViewLookups.get(e);const o=i?.booted===r&&(i.udid!==null||Date.now()-i.at<WEBVIEW_MISS_MS);const a=o&&i?.udid?n.find(c=>c.udid===i.udid):void 0;if(a)return{ok:true,udid:a.udid,how:`matched ${e} to "${a.name}" (WebView storage)`};const s=[];if(!o){const c=await Promise.all(n.map(u=>u.dataPath?webViewInstallIds(import_node_path4.default.join(u.dataPath,"Containers","Data","Application")):Promise.resolve([])));c.forEach((u,l)=>{if(u.includes(t))s.push(n[l])});webViewLookups.set(e,{booted:r,udid:s.length===1?s[0].udid:null,at:Date.now()})}if(s.length===1){return{ok:true,udid:s[0].udid,how:`matched ${e} to "${s[0].name}" (WebView storage)`}}if(s.length>1){return{ok:false,error:`${s.length} booted simulators (${s.map(c=>c.name).join(", ")}) hold ${e}. Pass the udid, or shut one down.`}}}if(n.length===1)return{ok:true,udid:n[0].udid,how:`only booted simulator "${n[0].name}"`};return{ok:false,error:`${n.length} iOS Simulators are booted (${n.map(r=>r.name).join(", ")}) and none could be matched to ${e??"this device"}. Shut down the others, or capture from a single booted simulator.`}}async function resolveSims(e){const n=new Map;if(process.platform!=="darwin"||e.length===0)return n;let t=[];try{const{stdout:i}=await execFileAsync2("xcrun",["simctl","list","devices","booted","-j"],{timeout:1e4});const o=JSON.parse(i).devices;t=Object.entries(o).filter(([a])=>/iOS/.test(a)).flatMap(([,a])=>a.filter(s=>s.state==="Booted"))}catch{return n}const r=new Map;for(const i of t){if(!i.dataPath)continue;const o=import_node_path4.default.join(i.dataPath,"Containers","Data","Application");let a=[];try{a=await import_node_fs3.promises.readdir(o)}catch{continue}for(const s of a){try{const c=(await import_node_fs3.promises.readFile(import_node_path4.default.join(o,s,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim();if(c)r.set(c,{name:i.name,udid:i.udid})}catch{}}}for(const i of e){const o=r.get(i.split("-").pop()??"");if(o)n.set(i,o)}return n}async function captureIosFramebuffer(e="booted"){if(process.platform!=="darwin"){return{ok:false,error:"Screenshotting a component requires macOS with Xcode's iOS Simulator (uses `xcrun simctl`)."}}const n=import_node_path4.default.join(import_node_os4.default.tmpdir(),`buoy-mcp-sim-${(0,import_node_crypto3.randomUUID)()}.png`);try{await execFileAsync2("xcrun",["simctl","io",e,"screenshot","--type=png",n],{timeout:15e3})}catch(t){return{ok:false,error:humanizeSimctlError(t)}}try{const t=await import_node_fs3.promises.readFile(n);const r=pngSize(t);if(!r)return{ok:false,error:"Captured file wasn't a valid PNG."};return{ok:true,srcPath:n,width:r.width,height:r.height}}catch(t){return{ok:false,error:`Failed to read screenshot: ${t.message}`}}}async function cropToBuffer(e,n,t){const r=clamp(Math.round(t.x),0,Math.max(0,n.width-1));const i=clamp(Math.round(t.y),0,Math.max(0,n.height-1));const o=clamp(Math.round(t.width),1,n.width-r);const a=clamp(Math.round(t.height),1,n.height-i);const s=import_node_path4.default.join(import_node_os4.default.tmpdir(),`buoy-mcp-crop-${(0,import_node_crypto3.randomUUID)()}.png`);try{await execFileAsync2("sips",["-c",String(a),String(o),"--cropOffset",String(i),String(r),e,"--out",s],{timeout:1e4});const c=await import_node_fs3.promises.readFile(s);return{ok:true,buffer:c,width:o,height:a}}catch(c){const u=c;return{ok:false,error:`Crop failed: ${u?.stderr||u?.message||c}`}}finally{await import_node_fs3.promises.unlink(s).catch(()=>{});await import_node_fs3.promises.unlink(e).catch(()=>{})}}var import_node_child_process7=require("child_process");var import_node_util7=require("util");var import_node_child_process6=require("child_process");var import_node_util6=require("util");var import_node_fs6=require("fs");var import_node_os6=__toESM(require("os"));var import_node_path7=__toESM(require("path"));var import_node_crypto5=require("crypto");var import_pngjs2=__toESM(require_png());var import_node_child_process3=require("child_process");var import_node_util3=require("util");var import_node_fs4=require("fs");var import_node_os5=__toESM(require("os"));var import_node_path5=__toESM(require("path"));var import_node_crypto4=require("crypto");var import_pngjs=__toESM(require_png());var execFileAsync3=(0,import_node_util3.promisify)(import_node_child_process3.execFile);async function devicectl(e,n=3e4){const t=import_node_path5.default.join(import_node_os5.default.tmpdir(),`buoy-devicectl-${(0,import_node_crypto4.randomUUID)()}.json`);try{await execFileAsync3("xcrun",["devicectl",...e,"--quiet","--json-output",t],{timeout:n,maxBuffer:16*1024*1024});return JSON.parse(await import_node_fs4.promises.readFile(t,"utf8"))}catch(r){const i=r;let o=(i.stderr||i.stdout||i.message||"").trim();try{const a=JSON.parse(await import_node_fs4.promises.readFile(t,"utf8"));o=a.error?.userInfo?.NSLocalizedDescription?.string??o}catch{}if(/locked/i.test(o))throw new Error("The iPhone is locked. Unlock it and try again.");throw new Error(`devicectl ${e.slice(0,2).join(" ")} failed: ${o.split("\n").slice(-3).join(" ").slice(0,300)}`)}finally{await import_node_fs4.promises.unlink(t).catch(()=>void 0)}}async function physicalPhones(){if(process.platform!=="darwin")return[];return parsePhones(await devicectl(["list","devices"],15e3).catch(()=>null))}function parsePhones(e){const n=e;return(n?.result?.devices??[]).filter(t=>t.hardwareProperties?.reality==="physical"&&t.hardwareProperties?.platform==="iOS"&&t.connectionProperties?.pairingState==="paired"&&t.connectionProperties?.tunnelState!=="unavailable").map(t=>({udid:t.hardwareProperties.udid,name:t.deviceProperties?.name??"iPhone"})).filter(t=>!!t.udid)}async function developerApps(e){const n=await devicectl(["device","info","apps","--device",e]);return(n.result?.apps??[]).filter(t=>t.bundleIdentifier&&!t.bundleIdentifier.startsWith("com.apple.")&&t.builtByDeveloper!==false).map(t=>({bundleId:t.bundleIdentifier,name:t.name??t.bundleIdentifier,path:t.url?.replace(/^file:\/\//,"")}))}async function readAppFile(e,n,t){const r=await devicectl(["device","info","files","--device",e,"--domain-type","appDataContainer","--domain-identifier",n],2e4);const i=new Set((r.result?.files??[]).map(a=>a.relativePath??a.name??""));if(!i.has(t))return null;const o=import_node_path5.default.join(import_node_os5.default.tmpdir(),`buoy-devfile-${(0,import_node_crypto4.randomUUID)()}`);try{await devicectl(["device","copy","from","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",o],2e4);return await import_node_fs4.promises.readFile(o)}finally{await import_node_fs4.promises.rm(o,{recursive:true,force:true}).catch(()=>void 0)}}async function phoneInstallId(e,n){const t=await readAppFile(e,n,"Documents/react-buoy/@react_buoy_sync_device_id.json").catch(()=>null);const r=t?.toString("utf8").trim().replace(/^"|"$/g,"")??"";return/^[\w-]{4,64}$/.test(r)?r:null}async function phoneScreenshot(e){const n=import_node_path5.default.join(import_node_os5.default.tmpdir(),`buoy-phone-shot-${(0,import_node_crypto4.randomUUID)()}.png`);try{await devicectl(["device","capture","screenshot","--device",e,"--destination",n],3e4);return await import_node_fs4.promises.readFile(n)}finally{await import_node_fs4.promises.unlink(n).catch(()=>void 0)}}var BLACK_PHONE_NOTE="The picture is all black. If the app isn't really showing black, the iPhone's own screen is off: it is asleep, or the Mac shows it in iPhone Mirroring (the phone stays locked then). Quit iPhone Mirroring, unlock the phone and keep its screen on, then try again.";function isAllBlack(e){try{const n=import_pngjs.PNG.sync.read(e);const t=Math.max(1,Math.floor(n.width*n.height/4e3));for(let r=0;r<n.width*n.height;r+=t){const i=r*4;if(n.data[i]>12||n.data[i+1]>12||n.data[i+2]>12)return false}return true}catch{return false}}async function phoneLaunch(e,n,t={}){await devicectl(["device","process","launch","--device",e,...t.terminateExisting?["--terminate-existing"]:[],...t.url?["--payload-url",t.url]:[],n])}async function phoneOpenUrl(e,n){await devicectl(["device","process","openURL","--device",e,n])}async function phoneQuit(e,n){const t=await developerApps(e);const r=t.find(a=>a.bundleId===n)?.path;const i=await devicectl(["device","info","processes","--device",e]);const o=(i.result?.runningProcesses??[]).find(a=>r&&decodeURIComponent(a.executable??"").replace(/^file:\/\//,"").startsWith(r.replace(/\/$/,"")));if(!o?.processIdentifier)return false;await devicectl(["device","process","terminate","--device",e,"--pid",String(o.processIdentifier)]);return true}async function phoneUninstall(e,n){await devicectl(["device","uninstall","app","--device",e,n],12e4)}async function phoneInstall(e,n){await devicectl(["device","install","app","--device",e,n],3e5)}async function writeAppFile(e,n,t,r){await devicectl(["device","copy","to","--device",e,"--domain-type","appDataContainer","--domain-identifier",n,"--source",t,"--destination",r],3e4)}function phoneRecordArgs(e,n,t){return["devicectl","device","capture","screen-record","--device",e,"--destination",n,"--duration",String(t)]}var coreIds=new Map;async function coreDeviceId(e){const n=coreIds.get(e);if(n)return n;const t=await devicectl(["list","devices"]);const r=t.result?.devices?.find(i=>i.hardwareProperties?.udid===e)?.identifier;if(!r)throw new Error("CoreDevice doesn't list this iPhone right now. Check that it is connected and unlocked.");coreIds.set(e,r);return r}var import_node_child_process5=require("child_process");var import_node_util5=require("util");var import_node_fs5=require("fs");var import_node_path6=__toESM(require("path"));var import_ws=require("ws");var import_node_child_process4=require("child_process");var import_node_util4=require("util");var PLACEHOLDER=/\{\{\s*secret:([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;var MIN_SECRET_LENGTH=6;var used=new Map;var recordingActive=()=>false;function setRecordingProbe(e){recordingActive=e}function hasSecrets(e){PLACEHOLDER.lastIndex=0;return PLACEHOLDER.test(e)}function fillSecrets(e,n=process.env){if(!hasSecrets(e))return e;if(recordingActive()){throw new Error("A screen recording is running, and a video can't hide a typed secret. Stop the recording first (screen_recording stop), then type it.")}const t=[];const r=[];const i=e.replace(PLACEHOLDER,(o,a)=>{const s=n[`BUOY_SECRET_${a}`]??n[a];if(s===void 0||s===""){t.push(a);return""}if(s.length<MIN_SECRET_LENGTH){r.push(a);return""}used.set(a,s);return s});if(t.length){throw new Error(`No value for ${t.map(o=>`{{secret:${o}}}`).join(", ")}. Set ${t.map(o=>`BUOY_SECRET_${o}`).join(", ")} in the environment the MCP server runs in (for example in your editor's MCP config "env").`)}if(r.length){throw new Error(`${r.map(o=>`{{secret:${o}}}`).join(", ")} is shorter than ${MIN_SECRET_LENGTH} characters, so Buoy can't hide it reliably in what it sends back. Use a longer value, or type it as plain text if it isn't sensitive.`)}return i}function knownSecrets(e=process.env){const n=new Map(used);for(const[t,r]of Object.entries(e))if(t.startsWith("BUOY_SECRET_")&&r)n.set(t.slice("BUOY_SECRET_".length),r);return n}var escapeRe=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function scrubSecrets(e){const n=new Map;for(const[i,o]of knownSecrets()){if(o.length<MIN_SECRET_LENGTH)continue;for(const a of[o,JSON.stringify(o).slice(1,-1),encodeURIComponent(o)])n.set(a,i);for(let a=o.length-1;a>=MIN_SECRET_LENGTH;a--){n.set(`${o.slice(0,a)}\u2026`,i);n.set(`${o.slice(0,a)}...`,i);if(a>=8)n.set(o.slice(0,a),i)}}if(n.size===0)return e;const t=[...n.keys()].sort((i,o)=>o.length-i.length);const r=new RegExp(t.map(escapeRe).join("|"),"g");return e.replace(r,(i,o,a)=>{if(/^\d+$/.test(i)){const s=a.slice(Math.max(0,o-8),o);const c=a.slice(o+i.length,o+i.length+8);if(/(\d|\d\.)$/.test(s)||/^(\d|\.\d|[eE][+-]?\d)/.test(c))return i;if(/[:[,]\s*$/.test(s)&&/^\s*([,\]}]|$)/.test(c)&&!insideJsonString(a,o))return`"{{secret:${n.get(i)}}}"`}return`{{secret:${n.get(i)}}}`})}function insideJsonString(e,n){let t=false;for(let r=0;r<n;r++){if(e[r]==="\\")r++;else if(e[r]==='"')t=!t}return t}function typedSecretValues(){return[...used.values()]}function secretValues(){return[...knownSecrets().values()].filter(e=>e.length>=MIN_SECRET_LENGTH)}var execFileAsync4=(0,import_node_util4.promisify)(import_node_child_process4.execFile);var ADB_MISSING="Android control needs adb on this computer (Android SDK platform-tools). Install it, or add it to PATH.";function q(e){return`'${e.replace(/'/g,`'\\''`)}'`}function assertPackage(e){if(!/^[A-Za-z][\w]*(\.[A-Za-z_][\w]*)+$/.test(e))throw new Error(`"${e}" is not a valid Android package name.`);return e}async function adb(e,n,t=15e3){try{const{stdout:r}=await execFileAsync4("adb",e?["-s",e,...n]:n,{timeout:t,maxBuffer:32*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(ADB_MISSING);const o=n[0]==="shell"?`shell ${(n[1]??"").split(" ")[0]}`:n.slice(0,2).join(" ");const a=n[0]==="shell"?i.stderr||(i.killed?"timed out":"no error text"):i.stderr||i.message||"";const s=scrubSecrets(a.replace(/'[^']*'/g,"'\u2026'")).trim().slice(0,300);throw new Error(`adb ${o} failed: ${s}`)}}function adbShell(e,n,t=15e3){return adb(e,["shell",n],t)}async function adbBytes(e,n,t=15e3){try{const{stdout:r}=await execFileAsync4("adb",["-s",e,...n],{timeout:t,encoding:"buffer",maxBuffer:64*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(ADB_MISSING);throw new Error(`adb ${n.slice(0,2).join(" ")} failed: ${i.message.slice(0,300)}`)}}async function adbSerials(){return parseAdbDevices(await adb(null,["devices"]))}function parseAdbDevices(e){return e.split("\n").slice(1).map(n=>n.trim().split(/\s+/)).filter(n=>n[1]==="device").map(n=>n[0])}async function adbScreenSize(e){const n=parseWmSize(await adbShell(e,"wm size"));const t=parseRotation(await adbShell(e,"dumpsys input").catch(()=>""));return t%2===1?{width:n.height,height:n.width}:n}function parseWmSize(e){const n=/Override size:\s*(\d+)x(\d+)/.exec(e);const t=/Physical size:\s*(\d+)x(\d+)/.exec(e);const r=n??t;if(!r)throw new Error(`Could not read the Android screen size (adb said: ${e.trim().slice(0,120)}).`);return{width:Number(r[1]),height:Number(r[2])}}function parseRotation(e){const n=/SurfaceOrientation:\s*(\d)/.exec(e);return n?Number(n[1]):0}async function adbAppFrame(e,n){const t=await adbShell(e,"dumpsys window windows").catch(()=>"");return parseAppFrame(t,n)}function parseAppFrame(e,n){const t=e.split(/\n(?=\s*Window #\d+)/);for(const r of t){if(!r.includes(`${n}/`))continue;const i=/mFrame=\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(r)??/\bframe=\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(r);if(i){const[o,a,s,c]=i.slice(1).map(Number);if(s>o&&c>a)return{x:o,y:a,width:s-o,height:c-a}}}return null}async function adbForegroundPackage(e){return parseForegroundPackage(await adbShell(e,"dumpsys activity activities"))}function parseForegroundPackage(e){const n=/(?:topResumedActivity|mResumedActivity|ResumedActivity)[^\n]*?\s([a-zA-Z][\w.]*)\/[\w.$]+/.exec(e);return n?n[1]:null}async function adbUserPackages(e){const n=await adbShell(e,"pm list packages -3");return n.split("\n").map(t=>t.trim().replace(/^package:/,"")).filter(t=>/^[A-Za-z][\w.]+$/.test(t))}async function adbInstallId(e,n){assertPackage(n);const t=await adbShell(e,`run-as ${q(n)} cat files/react-buoy/@react_buoy_sync_device_id.json 2>/dev/null`,5e3).catch(()=>"");const r=t.trim().replace(/^"|"$/g,"");if(/^[\w-]{4,64}$/.test(r))return r;const i=await adbBytes(e,["exec-out",`run-as ${q(n)} sh -c 'cat app_webview/Default/"Local Storage"/leveldb/*.log app_webview/Default/"Local Storage"/leveldb/*.ldb 2>/dev/null'`],5e3).catch(()=>null);return i?webViewLevelDbInstallId(i):null}function webViewLevelDbInstallId(e){const n=e.toString("latin1");const t=/@react_buoy_sync_device_id([\s\S])\x01([\w-]{4,64})/g;let r=null;for(let i=t.exec(n);i;i=t.exec(n)){const o=i[1].charCodeAt(0)-1;if(o>=4&&o<=i[2].length)r=i[2].slice(0,o)}return r}function escapeAdbText(e){if(/[^\x20-\x7e]/.test(e))throw new Error("adb can only type plain ASCII text. Use tap_element's text for other characters.");return q(e.replace(/ /g,"%s"))}async function adbTap(e,n,t,r){const[i,o]=[Math.round(n),Math.round(t)];if(r)await adbShell(e,`input swipe ${i} ${o} ${i} ${o} ${Math.round(r)}`);else await adbShell(e,`input tap ${i} ${o}`)}async function adbSwipe(e,n,t,r){const i=[...n,...t].map(o=>Math.round(o)).join(" ");await adbShell(e,`input swipe ${i} ${Math.round(r)}`)}async function adbText(e,n){const t=n.replace(/ /g,"\0");for(let r=0;r<t.length;r+=40){const i=t.slice(r,r+40).replace(/\u0000/g," ");await adbShell(e,`input text ${escapeAdbText(i)}`)}}async function adbScreenshot(e){const n=await adbBytes(e,["exec-out","screencap","-p"]);if(n.length<8||n.readUInt32BE(0)!==2303741511)throw new Error("The Android screenshot was not a PNG.");return n}async function adbDemoMode(e,n){if(n){await adbShell(e,"settings put global sysui_demo_allowed 1");for(const t of["-e command enter","-e command clock -e hhmm 0941","-e command battery -e level 100 -e plugged false","-e command network -e wifi show -e level 4","-e command notifications -e visible false"]){await adbShell(e,`am broadcast -a com.android.systemui.demo ${t}`).catch(()=>void 0)}}else{await adbShell(e,"am broadcast -a com.android.systemui.demo -e command exit").catch(()=>void 0)}}async function adbUiNodes(e){const n=await adb(e,["exec-out","uiautomator","dump","/dev/tty"],2e4);return parseUiDump(n)}function parseUiDump(e){const n=[];const t=(r,i)=>{const o=new RegExp(`\\s${i}="([^"]*)"`).exec(r);return o?decodeXml(o[1]):""};for(const r of e.matchAll(/<node\b[^>]*>/g)){const i=r[0];const o=/\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/.exec(t(i,"bounds"));if(!o)continue;const[a,s,c,u]=o.slice(1).map(Number);n.push({text:t(i,"text"),desc:t(i,"content-desc"),id:t(i,"resource-id"),cls:t(i,"class"),clickable:t(i,"clickable")==="true",bounds:{x:a,y:s,width:c-a,height:u-s}})}return n}function decodeXml(e){return e.replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#(\d+);/g,(n,t)=>String.fromCharCode(Number(t))).replace(/&amp;/g,"&")}function findUiNodes(e,n){const t=n.trim().toLowerCase();const r=c=>{let u=0;for(const l of[c.desc,c.text,c.id.split("/").pop()??""]){const d=l.trim().toLowerCase();if(!d)continue;if(d===t)u=Math.max(u,3);else if(d.startsWith(t))u=Math.max(u,2);else if(d.includes(t))u=Math.max(u,1)}return u};const i=e.filter(c=>c.bounds.width>0&&c.bounds.height>0&&r(c)>0);const o=Math.max(0,...i.map(r));const a=i.filter(c=>r(c)===o);let s=a.filter((c,u)=>a.findIndex(l=>JSON.stringify(l.bounds)===JSON.stringify(c.bounds))===u);if(s.length>1){const c=s.filter(u=>[u.desc,u.text,u.id.split("/").pop()??""].some(l=>l.trim()===n.trim()));if(c.length)s=c}if(s.length>1){const c=s.filter(u=>u.clickable||/EditText|Button/.test(u.cls));if(c.length)s=c}return s}var execFileAsync5=(0,import_node_util5.promisify)(import_node_child_process5.execFile);var WEB_KEEP_KEY=/^(@buoy\/session:|buoy-gg-license|buoy-gg-device-fingerprint$|@react_buoy_sync_device_id$|@react_buoy_install)/;async function listDir2(e){return import_node_fs5.promises.readdir(e).catch(()=>[])}async function containerLocalStorageFiles(e){const n=[];const t=import_node_path6.default.join(e,"Library","WebKit");for(const r of await listDir2(t)){const i=import_node_path6.default.join(t,r,"WebsiteData","Default");for(const o of await listDir2(i)){for(const a of await listDir2(import_node_path6.default.join(i,o))){const s=import_node_path6.default.join(i,o,a);const c=import_node_path6.default.join(s,"LocalStorage","localstorage.sqlite3");if(!await import_node_fs5.promises.access(c).then(()=>true,()=>false))continue;const u=await import_node_fs5.promises.readFile(import_node_path6.default.join(s,"origin")).then(l=>l.toString("hex"),()=>"");if(u)n.push({db:c,origin:u})}}}return n}var sqlite=(e,n,t=true)=>execFileAsync5("sqlite3",[...t?["-readonly"]:[],e,n],{timeout:5e3}).then(r=>r.stdout);async function iosReadWebKeep(e){const n=[];for(const{db:t,origin:r}of await containerLocalStorageFiles(e)){const i=await sqlite(t,"SELECT key, hex(value) FROM ItemTable;");for(const o of i.split("\n")){const a=o.lastIndexOf("|");if(a<0)continue;const s=o.slice(0,a);if(WEB_KEEP_KEY.test(s))n.push({key:s,value:o.slice(a+1),origin:r})}}return n}async function iosWriteWebKeep(e,n){if(!n.length)return false;const t=await containerLocalStorageFiles(e);const r=new Set(n.map(i=>i.origin??""));for(const i of r){const o=i?t.find(s=>s.origin===i):void 0;if(!o)return false;const a=n.filter(s=>(s.origin??"")===i&&/^[0-9A-F]*$/i.test(s.value)).map(s=>`('${s.key.replace(/'/g,"''")}', X'${s.value}')`).join(",");if(a)await sqlite(o.db,`INSERT OR REPLACE INTO ItemTable (key, value) VALUES ${a};`,false)}return true}async function iosWaitForLocalStorage(e,n=15e3){const t=Date.now()+n;while(Date.now()<t){if((await containerLocalStorageFiles(e)).length)return true;await new Promise(r=>setTimeout(r,500))}return false}async function evaluateInWebView(e,n,t){const r=(await adbShell(e,`pidof ${n}`).catch(()=>"")).trim().split(/\s+/)[0];if(!r)throw new Error("the app is not running");const i=(await adb(e,["forward","tcp:0",`localabstract:webview_devtools_remote_${r}`])).trim();try{const o=await(await fetch(`http://127.0.0.1:${i}/json`)).json();const a=o.find(s=>s.type==="page"&&s.webSocketDebuggerUrl);if(!a?.webSocketDebuggerUrl)throw new Error("no debuggable WebView page (needs a debug build)");return await new Promise((s,c)=>{const u=new import_ws.WebSocket(a.webSocketDebuggerUrl);const l=setTimeout(()=>{u.close();c(new Error("the WebView did not answer"))},5e3);u.on("open",()=>u.send(JSON.stringify({id:1,method:"Runtime.evaluate",params:{expression:t,returnByValue:true}})));u.on("message",d=>{const h=JSON.parse(String(d));if(h.id!==1)return;clearTimeout(l);u.close();if(h.result?.exceptionDetails)c(new Error("the WebView script failed"));else s(h.result?.result?.value)});u.on("error",d=>{clearTimeout(l);c(d)})})}finally{await adb(e,["forward","--remove",`tcp:${i}`]).catch(()=>void 0)}}async function evaluateWhenReady(e,n,t,r=15e3){const i=Date.now()+r;let o;while(Date.now()<i){try{return await evaluateInWebView(e,n,t)}catch(a){o=a;await new Promise(s=>setTimeout(s,700))}}throw o instanceof Error?o:new Error("the WebView did not open")}async function androidHasWebViewStorage(e,n){const t=await adbShell(e,`run-as ${n} sh -c 'ls app_webview/Default/"Local Storage"/leveldb 2>/dev/null'`).catch(()=>"");return/CURRENT|\.log/.test(t)}async function androidReadWebKeep(e,n){if(!(await adbShell(e,`pidof ${n}`).catch(()=>"")).trim()){await adbShell(e,`monkey -p ${n} -c android.intent.category.LAUNCHER 1`)}const t=await evaluateWhenReady(e,n,`(() => { const re = ${WEB_KEEP_KEY}; const out = []; for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k && re.test(k)) out.push({ key: k, value: localStorage.getItem(k) }); } return out; })()`);return Array.isArray(t)?t.filter(r=>typeof r.key==="string"&&typeof r.value==="string"):[]}async function androidWriteWebKeep(e,n,t){await evaluateWhenReady(e,n,`(() => { for (const r of ${JSON.stringify(t)}) localStorage.setItem(r.key, r.value); setTimeout(() => location.reload(), 50); return true; })()`)}var execFileAsync6=(0,import_node_util6.promisify)(import_node_child_process6.execFile);var hosts=new Map;function rememberedHost(e){return hosts.get(e)}async function sh(e,n,t=2e4){try{const{stdout:r}=await execFileAsync6(e,n,{timeout:t,maxBuffer:16*1024*1024});return r}catch(r){const i=r;if(i.code==="ENOENT")throw new Error(e==="xcrun"?"This needs macOS with Xcode (xcrun simctl).":`${e} is not installed.`);throw new Error(`${e} ${n.slice(0,2).join(" ")} failed: ${(i.stderr||i.message||"").trim().slice(0,300)}`)}}var simctl=(e,n)=>sh("xcrun",["simctl",...e],n);var tailOf=e=>e.split("-").pop()??"";async function simsHolding(e){let n=[];try{const r=JSON.parse(await simctl(["list","devices","booted","-j"])).devices;n=Object.entries(r).filter(([i])=>/iOS/.test(i)).flatMap(([,i])=>i.filter(o=>o.state==="Booted"))}catch{return[]}const t=[];for(const r of n)if(await findIosContainer(e,r.udid))t.push(r);return t}function cloneError(e,n){return new Error(`${n.length} booted simulators hold "${e}" (one is probably a clone): ${n.map(t=>`${t.name} (${t.udid})`).join(", ")}. Pass udid to choose, or shut the extra one down.`)}async function findIosContainer(e,n){const t=tailOf(e);if(!t)return null;let r;try{const a=JSON.parse(await simctl(["list","devices","-j"])).devices;r=Object.values(a).flat().find(s=>s.udid===n)?.dataPath}catch{return null}if(!r)return null;const i=import_node_path7.default.join(r,"Containers","Data","Application");let o=[];try{o=await import_node_fs6.promises.readdir(i)}catch{return null}for(const a of o){const s=import_node_path7.default.join(i,a);if(!await iosContainerHolds(s,t))continue;let c=null;try{c=(await sh("plutil",["-extract","MCMMetadataIdentifier","raw","-o","-",import_node_path7.default.join(s,".com.apple.mobile_container_manager.metadata.plist")])).trim()||null}catch{}return{container:s,bundleId:c}}return null}async function iosContainerHolds(e,n){try{if((await import_node_fs6.promises.readFile(import_node_path7.default.join(e,"Documents","react-buoy","@react_buoy_sync_device_id.json"),"utf8")).trim()===n)return true}catch{}return(await containerWebViewInstallIds(e).catch(()=>[])).includes(n)}async function findAndroid(e,n){const t=tailOf(e);const r=n.serial?[n.serial]:await adbSerials();if(r.length===0)throw new Error("No Android device or emulator is connected to adb.");for(const i of r){const o=await adbForegroundPackage(i).catch(()=>null);const a=await adbUserPackages(i).catch(()=>[]);const s=[n.bundleId,o,...a].filter((c,u,l)=>!!c&&l.indexOf(c)===u).slice(0,80);for(const c of s){if(await adbInstallId(i,c).catch(()=>null)===t)return{platform:"android",serial:i,packageName:c}}}return null}async function findPhone(e){const n=tailOf(e);for(const t of await physicalPhones()){for(const r of await developerApps(t.udid).catch(()=>[])){if(await phoneInstallId(t.udid,r.bundleId)===n)return{platform:"ios-device",udid:t.udid,name:t.name,bundleId:r.bundleId}}}return null}async function findHost(e,n,t={}){if(e==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');const r=hosts.get(e);if(r&&!t.udid&&!t.serial&&await stillHolds(e,r)){if(r.platform==="ios"&&!r.picked){const c=await simsHolding(e);if(c.length>1)throw cloneError(e,c)}return r}if(r)hosts.delete(e);if(n==="android"){const c=await findAndroid(e,t);if(!c){throw new Error(`Could not prove which Android device and app run "${e}". Buoy checks the app's install id with run-as, which needs a debug build of the app on a device adb can reach${t.serial?` (looked on ${t.serial})`:""}.`)}hosts.set(e,c);return c}if(n&&n!=="ios")throw new Error(`Device control works on iOS Simulators and Android. This app runs on "${n}".`);if(process.platform!=="darwin")throw new Error("iOS control needs macOS with Xcode.");let i=t.udid;let o=i??"";if(!i){const c=await simsHolding(e);if(c.length>1)throw cloneError(e,c);const u=c.length===1?{ok:true,udid:c[0].udid,how:`matched ${e} to "${c[0].name}"`}:await resolveSimUdid(e);if(!u.ok||!/^matched /.test(u.how)){const l=await findPhone(e).catch(()=>null);if(l){hosts.set(e,l);return l}throw new Error(`Could not find which simulator or iPhone runs "${e}": no booted simulator holds its install id, and no connected iPhone has it (an iPhone must be unlocked, paired, and run a development build).`)}i=u.udid;o=/"([^"]+)"/.exec(u.how)?.[1]??i}const a=await findIosContainer(e,i);if(!a&&t.udid)throw new Error(`Simulator ${t.udid} does not hold "${e}".`);const s={platform:"ios",udid:i,name:o,bundleId:t.bundleId??a?.bundleId??null,container:a?.container??null,picked:!!t.udid};hosts.set(e,s);return s}async function verifyHost(e,n){if(n.platform==="ios"&&!n.picked){const t=await simsHolding(e);if(t.length>1)throw cloneError(e,t)}if(await stillHolds(e,n))return n;hosts.delete(e);return findHost(e,n.platform==="android"?"android":"ios",n.platform==="ios"&&n.picked?{udid:n.udid}:{})}async function stillHolds(e,n){const t=tailOf(e);if(n.platform==="android")return await adbInstallId(n.serial,n.packageName).catch(()=>null)===t;if(n.platform==="ios-device")return await phoneInstallId(n.udid,n.bundleId).catch(()=>null)===t;if(n.container)return iosContainerHolds(n.container,t);const r=await resolveSimUdid(e);return r.ok&&r.udid===n.udid&&/^matched /.test(r.how)}function needApp(e){if(e.platform==="android")return assertPackage(e.packageName);if(e.platform==="ios-device")return e.bundleId;if(!e.bundleId)throw new Error("Could not tell which app this is on the simulator (its container has no bundle metadata).");return e.bundleId}async function hostPng(e){if(e.platform==="android")return adbScreenshot(e.serial);if(e.platform==="ios-device")return phoneScreenshot(e.udid);const n=await captureIosFramebuffer(e.udid);if(!n.ok||!n.srcPath)throw new Error(n.error??"Screenshot failed.");try{return await import_node_fs6.promises.readFile(n.srcPath)}finally{await import_node_fs6.promises.unlink(n.srcPath).catch(()=>{})}}async function toSmallImage(e,n=1280){if(process.platform==="darwin"){const i=import_node_path7.default.join(import_node_os6.default.tmpdir(),`buoy-mcp-img-${(0,import_node_crypto5.randomUUID)()}.png`);const o=i.replace(/\.png$/,".jpg");await import_node_fs6.promises.writeFile(i,e);try{await sh("sips",["-Z",String(n),"-s","format","jpeg","-s","formatOptions","70",i,"--out",o],15e3);const a=await sh("sips",["-g","pixelWidth","-g","pixelHeight",o]);return{data:(await import_node_fs6.promises.readFile(o)).toString("base64"),mimeType:"image/jpeg",width:Number(/pixelWidth:\s*(\d+)/.exec(a)?.[1]??0),height:Number(/pixelHeight:\s*(\d+)/.exec(a)?.[1]??0)}}finally{await import_node_fs6.promises.unlink(i).catch(()=>{});await import_node_fs6.promises.unlink(o).catch(()=>{})}}const t=downscalePng(import_pngjs2.PNG.sync.read(e),Math.min(n,1024));const r=import_pngjs2.PNG.sync.write(t,{colorType:2,deflateLevel:9});return{data:r.toString("base64"),mimeType:"image/png",width:t.width,height:t.height}}function downscalePng(e,n){const t=Math.min(1,n/Math.max(e.width,e.height));if(t===1)return e;const r=Math.max(1,Math.round(e.width*t));const i=Math.max(1,Math.round(e.height*t));const o=new import_pngjs2.PNG({width:r,height:i});const a=e.width/r;const s=e.height/i;for(let c=0;c<i;c++){const u=Math.floor(c*s);const l=Math.max(u+1,Math.floor((c+1)*s));for(let d=0;d<r;d++){const h=Math.floor(d*a);const p=Math.max(h+1,Math.floor((d+1)*a));const m=[0,0,0,0];let w=0;for(let f=u;f<l;f++){for(let v=h;v<p;v++){const y=(f*e.width+v)*4;for(let b=0;b<4;b++)m[b]+=e.data[y+b];w++}}const g=(c*r+d)*4;for(let f=0;f<4;f++)o.data[g+f]=Math.round(m[f]/w)}}return o}var steadying=new Set;async function withSteadyStatusBar(e,n){let t=false;try{if(e.platform==="ios"){const r=await simctl(["status_bar",e.udid,"list"]).catch(()=>"");const i=r.split(/^=+$/m).slice(1).join("").trim();if(!i){await simctl(["status_bar",e.udid,"override","--time","9:41","--batteryState","charged","--batteryLevel","100","--wifiBars","3","--cellularBars","4"]);t=true}}else if(e.platform==="android"){const r=(await adbShell(e.serial,"settings get global sysui_demo_allowed").catch(()=>"")).trim();if(r!=="1"&&!steadying.has(e.serial)){steadying.add(e.serial);await adbDemoMode(e.serial,true);t=true}}if(t)await new Promise(r=>setTimeout(r,400))}catch{t=false}try{return{result:await n(),steadied:t}}finally{if(t){if(e.platform==="ios")await simctl(["status_bar",e.udid,"clear"]).catch(()=>void 0);else if(e.platform==="android"){await adbDemoMode(e.serial,false);await adbShell(e.serial,"settings put global sysui_demo_allowed 0").catch(()=>void 0);steadying.delete(e.serial)}}}}async function hostQuit(e){const n=needApp(e);if(e.platform==="ios-device"){const t=await phoneQuit(e.udid,n);return t?`Quit ${n}.`:`${n} was not running.`}if(e.platform==="ios"){await simctl(["terminate",e.udid,n]).catch(t=>{if(!/found nothing to terminate|not running/i.test(String(t)))throw t})}else{await adbShell(e.serial,`am force-stop ${q(n)}`)}return`Quit ${n}.`}async function hostLaunch(e){const n=needApp(e);if(e.platform==="ios")await simctl(["launch",e.udid,n]);else if(e.platform==="ios-device")await phoneLaunch(e.udid,n);else await adbShell(e.serial,`monkey -p ${q(n)} -c android.intent.category.LAUNCHER 1`);return`Launched ${n}.`}async function hostBackground(e){if(e.platform==="ios-device"){await phoneLaunch(e.udid,"com.apple.Preferences");return"Sent to the background for real (Settings opened on top)."}if(e.platform==="ios"){await simctl(["launch",e.udid,"com.apple.Preferences"]);return"Sent to the background for real (Settings opened on top)."}await adbShell(e.serial,"input keyevent 3");return"Sent to the background for real (pressed Home)."}async function hostOpenUrl(e,n){if(!/^[a-zA-Z][\w+.-]*:/.test(n))throw new Error(`"${n}" is not a link with a scheme (like https://\u2026 or myapp://\u2026).`);if(e.platform==="ios-device"){await phoneOpenUrl(e.udid,n);return"Opened through the OS on the iPhone."}if(e.platform==="ios"){await simctl(["openurl",e.udid,n]);return'Opened through the OS. A custom scheme may first show an "Open in" prompt on the simulator.'}await adbShell(e.serial,`am start -a android.intent.action.VIEW -d ${q(n)}`);return"Opened through the OS (an Android VIEW intent)."}var BUOY_KEEP=["buoy-license","react-buoy/@react_buoy_sync_device_id.json","react-buoy/@react_buoy_install.json"];async function appBundleInfo(e){const n=import_node_path7.default.join(e,"Info.plist");const t=a=>sh("plutil",["-extract",a,"raw","-o","-",n]).then(s=>s.trim()).catch(()=>"");const r=await t("CFBundleIdentifier");if(!r)throw new Error(`${e} has no Info.plist with a bundle id. Pass a built .app folder.`);const i=(await sh("plutil",["-extract","CFBundleSupportedPlatforms","json","-o","-",n]).catch(()=>"[]")).toLowerCase();const o=(await t("DTPlatformName")).toLowerCase();return{bundleId:r,simulator:i.includes("iphonesimulator")||o==="iphonesimulator"}}async function apkPackage(e){const n=[process.env.ANDROID_HOME,process.env.ANDROID_SDK_ROOT,import_node_path7.default.join(import_node_os6.default.homedir(),"Library","Android","sdk"),import_node_path7.default.join(import_node_os6.default.homedir(),"Android","Sdk")].filter(t=>!!t);for(const t of n){const r=import_node_path7.default.join(t,"build-tools");const i=(await import_node_fs6.promises.readdir(r).catch(()=>[])).sort().reverse();for(const o of i){for(const a of["aapt2","aapt"]){const s=import_node_path7.default.join(r,o,a);try{await import_node_fs6.promises.access(s)}catch{continue}const c=await sh(s,a==="aapt2"?["dump","packagename",e]:["dump","badging",e]).catch(()=>"");const u=a==="aapt2"?c.trim().split("\n")[0]:/package: name='([^']+)'/.exec(c)?.[1]??"";if(u)return u}}}throw new Error("Could not read the APK's package name (needs aapt2 from the Android SDK build-tools). Nothing was changed.")}async function hostReinstall(e,n,t=true){const r=needApp(e);const i=import_node_path7.default.resolve(n);try{await import_node_fs6.promises.access(i)}catch{throw new Error(`No build at ${i}. Pass appPath: the built .app folder (iOS Simulator) or .apk file (Android). Nothing was changed.`)}if(e.platform==="android")return reinstallAndroid(e,r,i,t);if(e.platform==="ios-device")return reinstallPhone(e,r,i,t);if(!/\.app\/?$/i.test(i))throw new Error("On the iOS Simulator, appPath must be a built .app folder. Nothing was changed.");const o=await appBundleInfo(i);if(o.bundleId!==r)throw new Error(`${import_node_path7.default.basename(i)} is ${o.bundleId}, but this app is ${r}. Nothing was changed.`);if(!o.simulator)throw new Error(`${import_node_path7.default.basename(i)} is a device build, not a simulator build. Nothing was changed.`);const a=t?await import_node_fs6.promises.mkdtemp(import_node_path7.default.join(import_node_os6.default.tmpdir(),"buoy-mcp-keep-")):null;try{let s=false;let c=[];if(a){await import_node_fs6.promises.chmod(a,448);const l=(await simctl(["get_app_container",e.udid,r,"data"]).catch(()=>"")).trim();if(l)s=await copyBuoyFiles(import_node_path7.default.join(l,"Documents"),a);if(l&&!s){try{c=await iosReadWebKeep(l)}catch(d){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView storage (${d.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}}await simctl(["terminate",e.udid,r]).catch(()=>void 0);await simctl(["uninstall",e.udid,r]);try{await simctl(["install",e.udid,i],18e4)}catch(l){throw new Error(`The app was removed, but installing ${import_node_path7.default.basename(i)} failed: ${l.message}. Install it again by hand.`)}let u="";if(a&&s){try{const l=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await copyBuoyFiles(a,import_node_path7.default.join(l,"Documents"));e.container=l;u=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(l){u=` Buoy's sign-in could not be restored (${l.message}): sign in to Buoy again in the app.`}}else if(c.length){try{const l=(await simctl(["get_app_container",e.udid,r,"data"])).trim();await simctl(["launch",e.udid,r]);const d=await iosWaitForLocalStorage(l);await simctl(["terminate",e.udid,r]).catch(()=>void 0);if(!d||!await iosWriteWebKeep(l,c))throw new Error("the app made no WebView storage");e.container=l;u=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(l){u=` Buoy's sign-in could not be restored (${l.message}): sign in to Buoy again in the app.`}}else if(t){u=" The old install had no Buoy sign-in to keep."}await simctl(["launch",e.udid,r]);return`Reinstalled ${r} from ${i} and launched it. The app's own data is gone, like a new user.${u}`}finally{if(a)await import_node_fs6.promises.rm(a,{recursive:true,force:true}).catch(()=>void 0)}}async function copyBuoyFiles(e,n){let t=false;for(const r of BUOY_KEEP){const i=import_node_path7.default.join(e,r);try{await import_node_fs6.promises.access(i)}catch{continue}const o=import_node_path7.default.join(n,r);await import_node_fs6.promises.mkdir(import_node_path7.default.dirname(o),{recursive:true});await import_node_fs6.promises.cp(i,o,{recursive:true,force:true});t=true}return t}async function reinstallAndroid(e,n,t,r){if(!/\.apk$/i.test(t))throw new Error("On Android, appPath must be an .apk file. Nothing was changed.");const i=await apkPackage(t);if(i!==n)throw new Error(`${import_node_path7.default.basename(t)} is ${i}, but this app is ${n}. Nothing was changed.`);const o=[];if(r){const c=await adbShell(e.serial,`run-as ${q(n)} find files/buoy-license files/react-buoy -maxdepth 1 -type f 2>/dev/null`).catch(()=>"");const u=c.split("\n").map(l=>l.trim()).filter(l=>l.startsWith("files/buoy-license/")||/react-buoy\/@react_buoy_(sync_device_id|install)\.json$/.test(l));for(const l of u){const d=await adbShell(e.serial,`run-as ${q(n)} base64 ${q(l)}`).catch(()=>"");if(d.trim())o.push({rel:l,data:d.replace(/\s+/g,"")})}}let a=[];if(r&&!o.length&&await androidHasWebViewStorage(e.serial,n)){try{a=await androidReadWebKeep(e.serial,n)}catch(c){throw new Error(`Couldn't read Buoy's sign-in from the app's WebView (${c.message}). Nothing was changed. Pass keepBuoy: false to reinstall anyway.`)}}await adb(e.serial,["install","-r","-d",t],18e4);await adbShell(e.serial,`pm clear ${q(n)}`);let s="";if(a.length){await hostLaunch(e);try{await androidWriteWebKeep(e.serial,n,a);s=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){s=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${s}`}if(o.length){try{for(const c of o){const u=import_node_path7.default.posix.dirname(c.rel);await adbShell(e.serial,`echo ${q(c.data)} | run-as ${q(n)} sh -c ${q(`mkdir -p ${q(u)} && base64 -d > ${q(c.rel)}`)}`)}s=" Kept Buoy's sign-in and device id, so the same deviceId still works."}catch(c){s=` Buoy's sign-in could not be restored (${c.message}): sign in to Buoy again in the app.`}}else if(r){s=" No Buoy sign-in could be read to keep (needs a debug build): sign in to Buoy again in the app."}await hostLaunch(e);return`Reinstalled ${n} from ${t} and launched it. The app's data is gone, like a new user.${s}`}async function reinstallPhone(e,n,t,r){if(!/\.app\/?$/i.test(t))throw new Error("On an iPhone, appPath must be a built .app folder (a device build). Nothing was changed.");const i=await appBundleInfo(t);if(i.bundleId!==n)throw new Error(`${import_node_path7.default.basename(t)} is ${i.bundleId}, but this app is ${n}. Nothing was changed.`);if(i.simulator)throw new Error(`${import_node_path7.default.basename(t)} is a simulator build, not a device build. Nothing was changed.`);const o=["Documents/buoy-license/buoy-gg-license.json","Documents/react-buoy/@react_buoy_sync_device_id.json","Documents/react-buoy/@react_buoy_install.json"];const a=r?await import_node_fs6.promises.mkdtemp(import_node_path7.default.join(import_node_os6.default.tmpdir(),"buoy-mcp-keep-")):null;try{const s=[];if(a){await import_node_fs6.promises.chmod(a,448);for(const u of o){let l;try{l=await readAppFile(e.udid,n,u)}catch(h){throw new Error(`Could not back up Buoy's ${import_node_path7.default.basename(u)} from the iPhone (${h.message}). Nothing was changed.`)}if(!l)continue;const d=import_node_path7.default.join(a,u.replace(/\//g,"__"));await import_node_fs6.promises.writeFile(d,l,{mode:384});s.push({rel:u,local:d})}}await phoneQuit(e.udid,n).catch(()=>false);await phoneUninstall(e.udid,n);try{await phoneInstall(e.udid,t)}catch(u){throw new Error(`The app was removed, but installing ${import_node_path7.default.basename(t)} failed: ${u.message}. Install it again from Xcode.`)}let c="";if(s.length){try{for(const d of s)await writeAppFile(e.udid,n,d.local,d.rel);const u=s.some(d=>d.rel.includes("buoy-license"));const l=s.some(d=>d.rel.includes("sync_device_id"));c=u?` Kept Buoy's sign-in${l?" and device id, so the same deviceId still works":""}.`:` Kept the device id; there was no Buoy sign-in to keep, so sign in to Buoy in the app.`}catch(u){c=` Buoy's sign-in could not be restored (${u.message}): sign in to Buoy again in the app.`}}else if(r)c=" The old install had no Buoy sign-in to keep.";await phoneLaunch(e.udid,n);return`Reinstalled ${n} on the iPhone and launched it. The app's own data is gone, like a new user.${c}`}finally{if(a)await import_node_fs6.promises.rm(a,{recursive:true,force:true}).catch(()=>void 0)}}async function bootSimulator(e){const n=JSON.parse(await simctl(["list","devices","available","-j"])).devices;const t=Object.entries(n).filter(([s])=>/iOS/.test(s)).flatMap(([,s])=>s);const r=e.trim().toLowerCase();const i=t.filter(s=>s.udid.toLowerCase()===r||s.name.toLowerCase()===r);const o=i.length?i:t.filter(s=>s.name.toLowerCase().includes(r));if(o.length===0)throw new Error(`No iOS Simulator matches "${e}". Run \`xcrun simctl list devices available\` to see them.`);if(o.length>1)throw new Error(`${o.length} simulators match "${e}": ${o.map(s=>`${s.name} (${s.udid})`).join(", ")}. Pass the udid.`);const a=o[0];if(a.state!=="Booted")await simctl(["boot",a.udid],12e4);await sh("open",["-a","Simulator","--args","-CurrentDeviceUDID",a.udid]).catch(()=>void 0);return a.state==="Booted"?`${a.name} (${a.udid}) was already booted.`:`Booted ${a.name} (${a.udid}).`}var execFileAsync7=(0,import_node_util7.promisify)(import_node_child_process7.execFile);async function hostTarget(e,n,t={},r={}){if(n==="All")throw new Error('Device control acts on one app. Pass its deviceId, not "All".');let i;let o=true;try{i=e.requireProDevice(n)}catch(c){const u=c instanceof Error?c.message:String(c);const l=u.startsWith(NOT_READY_MARK)&&/is not connected right now/.test(u)?/"([^"]+)"/.exec(u)?.[1]:void 0;const d=l?e.listDevices().some(h=>h.deviceId===l&&h.isPro):false;if(!r.allowOffline||!l||!d)throw c;i=l;o=false}const a=e.listDevices().find(c=>c.deviceId===i)?.platform;let s=await findHost(i,a,t);if(r.changesApp&&rememberedHost(i)===s)s=await verifyHost(i,s);return{id:i,host:s,online:o}}function hostLabel(e){if(e.platform==="ios")return`simulator "${e.name}"`;if(e.platform==="ios-device")return`iPhone "${e.name}"`;return`Android device ${e.serial}`}var onPath=new Map;function has(e){if(!onPath.has(e))onPath.set(e,execFileAsync7("which",[e],{timeout:3e3}).then(()=>true,()=>false));return onPath.get(e)}async function hostSummary(e,n){let t=n;if(e.platform==="android"){const i=rememberedHost(e.deviceId);const o=i??(e.isConnected?await Promise.race([findHost(e.deviceId,"android").catch(()=>void 0),new Promise(s=>setTimeout(()=>s(void 0),3e3))]):void 0);const a=await has("adb");return{kind:"android",...o&&o.platform==="android"?{id:o.serial,name:o.packageName}:{},can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall","real lifecycle events","native_tap/type/swipe"],...!a?{missing:["adb (Android SDK platform-tools)"]}:!o?{missing:["proof of which phone runs it (needs a debug build reachable by adb)"]}:{}}}if(e.platform!=="ios")return{kind:e.platform??"unknown",can:[],missing:["host control works on iOS and Android apps"]};let r=rememberedHost(e.deviceId);if(!r&&!t&&e.isConnected){r=await Promise.race([findHost(e.deviceId,"ios").catch(()=>void 0),new Promise(i=>setTimeout(()=>i(void 0),4e3))])}if(!t&&r?.platform==="ios")t={name:r.name,udid:r.udid};if(r?.platform==="ios-device"){return{kind:"physical iPhone",id:r.udid,name:r.name,can:["screenshot","screen_recording (if this iPhone supports it)","baseline diffs","quit/launch/reinstall","open_url","native_tap/type/swipe (by query, testID, nativeTag or x/y; not label)"]}}if(t){const i=await has("idb");return{kind:"ios simulator",id:t.udid,name:t.name,can:["screenshot","screen_recording","baseline diffs","quit/launch/reinstall/boot","real lifecycle events",...i?["native_tap/type/swipe"]:[]],...i?{}:{missing:["idb for real touches (brew install facebook/fb/idb-companion && pipx install fb-idb)"]}}}return void 0}function json(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}function fail(e){return{isError:true,content:[{type:"text",text:e}]}}function registerGenericTools(e,n){e.registerTool("list_devices",{description:"List the apps connected to Buoy: id, name, platform, whether it is connected and has MCP access, the simulator or phone it runs on with the host controls that work there (screenshot, recording, app control, real touches) and anything missing, and the Buoy tools it exposes. Start here. Pass details:true for every tool's action names.",inputSchema:{details:import_zod.z.boolean().optional().describe("Also list every action of every tool. Default false (tool names only); list_tool_actions gives one tool's actions."),includeDisconnected:import_zod.z.boolean().optional().describe("Also list apps that were seen before but are not connected now. Default false.")}},async(t={})=>{const r=await getUpdateNotice();let i=n.listDevices();for(let p=0;i.length===0&&p<10;p++){await new Promise(m=>setTimeout(m,200));i=n.listDevices()}if(i.length===0){return json({devices:[],hint:"No devices connected. Open the app with Buoy devtools running, then retry.",...r?{updateAvailable:r}:{}})}const o=t.includeDisconnected?0:i.filter(p=>!p.isConnected).length;if(!t.includeDisconnected)i=i.filter(p=>p.isConnected);if(i.length===0){return json({devices:[],hint:`No app is connected right now${o?` (${o} seen before; pass includeDisconnected:true to list them)`:""}. Open the app with Buoy devtools running, then retry.`,...r?{updateAvailable:r}:{}})}const a=await resolveSims(i.filter(p=>p.platform==="ios").map(p=>p.deviceId)).catch(()=>new Map);const s=i.filter(p=>p.isConnected);const c=s.some(p=>p.isPro);const u=s.some(p=>p.tier!=="locked");const l=s.filter(p=>p.collision);const d=await Promise.all(i.map(p=>p.isConnected?hostSummary(p,a.get(p.deviceId)).catch(()=>void 0):void 0));const h=i.map((p,m)=>{const w=a.get(p.deviceId);const g=d[m];return{deviceId:p.deviceId,deviceName:p.deviceName,platform:p.platform,isConnected:p.isConnected,isPro:p.isPro,tier:p.tier,access:n.accessState(p.deviceId),...w?{simulator:w}:{},...g?{host:g}:{},...p.collision?{collision:true}:{},tools:t.details?p.tools:p.tools.map(f=>f.toolId)}});return json({devices:h,...t.details?{}:{note:`Tool names only. Pass details:true, or list_tool_actions({toolId}), for action names.${o?` ${o} apps seen before but not connected now are left out (includeDisconnected:true lists them).`:""}`},...l.length>0?{warning:`${l.map(p=>`"${p.deviceId}"`).join(", ")}: more than one app is registered under this id, so actions sent to it land on an arbitrary device. Give each device its own externalSync.deviceId (or leave it unset for a per-install default) before mutating anything.`}:{},...c?{}:{hint:u?"The Buoy MCP is a Pro feature \u2014 the connected device is signed in on the free tier, so data/action tools are blocked. Upgrade to Buoy Pro in the app, or pass `licenseKey` to `<FloatingDevTools />` if it runs headless.":"The broker has not confirmed account access for the connected devices, so data/action tools are blocked. A locked status can mean missing configuration, pending/failed validation, or a missing account announcement after reconnect; it does not prove the user is signed out. Check app account status and broker compatibility."},...r?{updateAvailable:r}:{}})});e.registerTool("list_tool_actions",{description:"List the actions a tool exposes, and which connected devices offer it. Leave toolId out to list every tool's actions. Use the action names with call_action.",inputSchema:{toolId:import_zod.z.string().optional().describe('The tool id, e.g. "perf-monitor", "network", "react-query". Leave out for every tool.'),tool:import_zod.z.string().optional().describe("Same as toolId."),deviceId:import_zod.z.string().optional().describe("Only list what this device offers.")}},async({toolId:t,tool:r,deviceId:i})=>{const o=t??r;if(!o){const c=n.connectedDevices().filter(l=>!i||l.deviceId===i);if(c.length===0)return fail(i?`No connected device "${i}". Call list_devices.`:"No devices are connected. Call list_devices.");const u=c.map(l=>[`**${l.deviceName}** (${l.deviceId})`,...l.tools.map(d=>`- ${d.toolId}: ${d.actions.join(", ")}`)].join("\n"));return{content:[{type:"text",text:`${u.join("\n\n")}
3
3
 
4
4
  Call one with call_action({toolId, action, params}).`}]}}const a=new Set(n.connectedDevices().map(c=>c.deviceId));const s=n.toolActions(o).filter(c=>a.has(c.deviceId)&&(!i||c.deviceId===i));if(s.length===0){const c=[...new Set(n.connectedDevices().flatMap(u=>u.tools.map(l=>l.toolId)))].sort();return fail(`No connected device exposes tool "${o}". Tool ids: ${c.join(", ")||"(none connected)"}. MCP tool names like "${o}" are not tool ids.`)}return json({toolId:o,offerings:s})});e.registerTool("get_snapshot",{description:"Read a tool's current state (its sync snapshot) from a device. Starts watching the tool and returns the next fresh snapshot.",inputSchema:{toolId:import_zod.z.string().optional().describe("The tool id to read state from."),tool:import_zod.z.string().optional().describe("Same as toolId."),deviceId:import_zod.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out."),timeoutMs:import_zod.z.number().optional().describe("How long to wait for a fresh snapshot before falling back to the cached one.")}},async({toolId:t,tool:r,deviceId:i,timeoutMs:o})=>{try{const a=t??r;if(!a)return fail("get_snapshot needs toolId (see list_tool_actions).");const s=n.requireProDevice(i);const{payload:c,stale:u}=await n.getSnapshot(a,s,{timeoutMs:o});return json({toolId:a,deviceId:s,...u?{stale:u}:{},snapshot:c})}catch(a){return fail(errMsg(a))}});e.registerTool("call_action",{description:"Invoke any action a tool exposes (see list_tool_actions) and return its result. This is the generic escape hatch that works for every Buoy tool.",inputSchema:{toolId:import_zod.z.string().optional().describe('The tool id, e.g. "perf-monitor".'),tool:import_zod.z.string().optional().describe("Same as toolId."),action:import_zod.z.string().describe('The action name, e.g. "startRecording", "clearAll".'),params:import_zod.z.union([import_zod.z.record(import_zod.z.unknown()),import_zod.z.string()]).optional().describe("JSON params object for the action (shape depends on the action)."),args:import_zod.z.union([import_zod.z.record(import_zod.z.unknown()),import_zod.z.string()]).optional().describe("Same as params."),deviceId:import_zod.z.string().optional().describe('The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out. Or "All" to broadcast.'),timeoutMs:import_zod.z.number().optional().describe("Max time to wait for the device's result.")}},async({toolId:t,tool:r,action:i,params:o,args:a,deviceId:s,timeoutMs:c})=>{try{const u=t??r;if(!u)return fail("call_action needs toolId (see list_tool_actions).");const l=actionParams(o??a);const d=n.requireProDevice(s);const h=await n.callAction(u,i,l,d,{timeoutMs:c});return json({toolId:u,action:i,ok:true,result:h??null})}catch(u){return fail(errMsg(u))}})}function actionParams(e){if(e===void 0||typeof e==="object")return e;const n=e.trim();if(!n)return void 0;let t;try{t=JSON.parse(n)}catch{throw new Error('params is a string but not JSON. Pass an object, e.g. {"user": {...}}.')}if(!t||typeof t!=="object"||Array.isArray(t))throw new Error("params must be a JSON object.");return t}function errMsg(e){return e instanceof Error?e.message:String(e)}var import_zod3=require("zod");var import_zod2=require("zod");var text=e=>({content:[{type:"text",text:e}]});var fail2=e=>({isError:true,content:[{type:"text",text:e}]});var errMsg2=e=>e instanceof Error?e.message:String(e);var deviceIdInput=import_zod2.z.string().optional().describe("The device to act on: its id from list_devices or from your instructions. Pass it whenever more than one app may be connected. Once a call names a device, later calls in this session use it when deviceId is left out.");function clampLimit(e,n){return typeof e==="number"&&e>0?e:n}function staleHeader(e){return e?`${e}
5
5
 
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{createRequire as e}from"module";const L=e(import.meta.url);import{runInit as r}from"./chunk-HKTKHDRR.mjs";import{ALL_DEVICES as o,BROKER_PORT as t,BROKER_URL as i,DASHBOARD_NAME as s,DEFAULT_ACTION_TIMEOUT_MS as a,DEFAULT_SNAPSHOT_TIMEOUT_MS as T,PACKAGE_NAME as n,SyncClient as m,VERSION as g,buildAutomationConfig as l,compareReportStats as R,createMcpServer as E,estimateBatchMs as _,formatRankingMarkdown as c,getUpdateNotice as p,rankBatchFromIndex as u,registerConsoleTools as A,registerEventsTools as S,registerGenericTools as M,registerJotaiTools as O,registerPerfMonitorTools as C,registerReactQueryTools as I,registerReduxTools as d,registerRoutesTools as f,registerScreenshotTools as N,registerStorageTools as U,registerZustandTools as B}from"./chunk-4LPT4F4I.mjs";import"./chunk-6EOB4FHJ.mjs";import"./chunk-OPHPYPJD.mjs";import"./chunk-MTTWR4T7.mjs";export{o as ALL_DEVICES,t as BROKER_PORT,i as BROKER_URL,s as DASHBOARD_NAME,a as DEFAULT_ACTION_TIMEOUT_MS,T as DEFAULT_SNAPSHOT_TIMEOUT_MS,n as PACKAGE_NAME,m as SyncClient,g as VERSION,l as buildAutomationConfig,R as compareReportStats,E as createMcpServer,_ as estimateBatchMs,c as formatRankingMarkdown,p as getUpdateNotice,u as rankBatchFromIndex,A as registerConsoleTools,S as registerEventsTools,M as registerGenericTools,O as registerJotaiTools,C as registerPerfMonitorTools,I as registerReactQueryTools,d as registerReduxTools,f as registerRoutesTools,N as registerScreenshotTools,U as registerStorageTools,B as registerZustandTools,r as runInit};
1
+ import{createRequire as e}from"module";const L=e(import.meta.url);import{runInit as r}from"./chunk-QBPXMMWS.mjs";import{ALL_DEVICES as o,BROKER_PORT as t,BROKER_URL as i,DASHBOARD_NAME as s,DEFAULT_ACTION_TIMEOUT_MS as a,DEFAULT_SNAPSHOT_TIMEOUT_MS as T,PACKAGE_NAME as n,SyncClient as m,VERSION as g,buildAutomationConfig as l,compareReportStats as R,createMcpServer as E,estimateBatchMs as _,formatRankingMarkdown as c,getUpdateNotice as p,rankBatchFromIndex as u,registerConsoleTools as A,registerEventsTools as S,registerGenericTools as M,registerJotaiTools as O,registerPerfMonitorTools as C,registerReactQueryTools as I,registerReduxTools as d,registerRoutesTools as f,registerScreenshotTools as N,registerStorageTools as U,registerZustandTools as B}from"./chunk-CRYV6OHD.mjs";import"./chunk-6EOB4FHJ.mjs";import"./chunk-OPHPYPJD.mjs";import"./chunk-MTTWR4T7.mjs";export{o as ALL_DEVICES,t as BROKER_PORT,i as BROKER_URL,s as DASHBOARD_NAME,a as DEFAULT_ACTION_TIMEOUT_MS,T as DEFAULT_SNAPSHOT_TIMEOUT_MS,n as PACKAGE_NAME,m as SyncClient,g as VERSION,l as buildAutomationConfig,R as compareReportStats,E as createMcpServer,_ as estimateBatchMs,c as formatRankingMarkdown,p as getUpdateNotice,u as rankBatchFromIndex,A as registerConsoleTools,S as registerEventsTools,M as registerGenericTools,O as registerJotaiTools,C as registerPerfMonitorTools,I as registerReactQueryTools,d as registerReduxTools,f as registerRoutesTools,N as registerScreenshotTools,U as registerStorageTools,B as registerZustandTools,r as runInit};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@buoy-gg/mcp",
3
3
  "mcpName": "io.github.Buoy-gg/mcp",
4
- "version": "7.0.60",
4
+ "version": "7.0.61",
5
5
  "buoy": {
6
6
  "dashboardAuthVersion": 1
7
7
  },
@@ -35,8 +35,8 @@
35
35
  "socket.io-client": "^4.8.1",
36
36
  "ws": "^8.18.0",
37
37
  "zod": "^3.25.0",
38
- "@buoy-gg/license": "^7.0.60",
39
- "@buoy-gg/sync-broker": "^7.0.60"
38
+ "@buoy-gg/license": "^7.0.61",
39
+ "@buoy-gg/sync-broker": "^7.0.61"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@types/node": "^22.0.0",